{"text":"#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_proximity_list\n\n#include \n#include \"proximity_list\/proximity_list.h\"\n#include \"proximity_list\/proximitylist_api.h\"\n#include \"type\/data.h\"\n#include \"georef\/georef.h\"\n\nusing namespace navitia::type;\nusing namespace navitia::proximitylist;\n\nBOOST_AUTO_TEST_CASE(distances_grand_cercle)\n{\n GeographicalCoord a(0,0);\n GeographicalCoord b(0,0);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n BOOST_CHECK_CLOSE(a.distance_to(b), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(a), 0, 1e-6);\n\n GeographicalCoord nantes(-1.57, 47.22);\n GeographicalCoord paris(2.36, 48.85);\n BOOST_CHECK_CLOSE(nantes.distance_to(paris), 340000, 10);\n BOOST_CHECK_CLOSE(paris.distance_to(nantes), 340000, 10);\n\n a.set_lon(180);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n\n a.set_lon(84); a.set_lat(89.999);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n\n\n a.set_lon(34); a.set_lat(-89.999);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n\n\n a.set_lon(0); a.set_lat(45);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000\/4,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000\/4,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(approx_distance){\n GeographicalCoord canaltp(2.3921, 48.8296);\n GeographicalCoord tour_eiffel(2.29447,48.85834);\n double coslat = ::cos(canaltp.lat() * 0.0174532925199432958);\n BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1);\n BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1);\n BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1);\n BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1);\n}\n\nBOOST_AUTO_TEST_CASE(find_nearest){\n constexpr double M_TO_DEG = 1.0\/111320.0;\n typedef std::pair p;\n ProximityList pl;\n\n GeographicalCoord c;\n std::vector coords;\n\n \/\/ Exemple d'illustration issu de wikipedia\n c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3); pl.add(c, 1); coords.push_back(c);\n c.set_lon(M_TO_DEG *5); c.set_lat(M_TO_DEG *4); pl.add(c, 2); coords.push_back(c);\n c.set_lon(M_TO_DEG *9); c.set_lat(M_TO_DEG *6); pl.add(c, 3); coords.push_back(c);\n c.set_lon(M_TO_DEG *4); c.set_lat(M_TO_DEG *7); pl.add(c, 4); coords.push_back(c);\n c.set_lon(M_TO_DEG *8); c.set_lat(M_TO_DEG *1); pl.add(c, 5); coords.push_back(c);\n c.set_lon(M_TO_DEG *7); c.set_lat(M_TO_DEG *2); pl.add(c, 6); coords.push_back(c);\n\n pl.build();\n\n std::vector expected {1,4,2,6,5,3};\n for(size_t i=0; i < expected.size(); ++i)\n BOOST_CHECK_EQUAL(pl.items[i].element, expected[i]);\n\n\n c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3);\n BOOST_CHECK_EQUAL(pl.find_nearest(c), 1);\n\n c.set_lon(M_TO_DEG *7.1); c.set_lat(M_TO_DEG *1.9);\n BOOST_CHECK_EQUAL(pl.find_nearest(c), 6);\n\n c.set_lon(M_TO_DEG *100); c.set_lat(M_TO_DEG *6);\n BOOST_CHECK_EQUAL(pl.find_nearest(c), 3);\n\n c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *4);\n\n expected = {1};\n auto tmp1 = pl.find_within(c, 1.1);\n std::vector tmp;\n for(auto p : tmp1) tmp.push_back(p.first);\n BOOST_CHECK_EQUAL(tmp1[0].second, coords[0]);\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2};\n tmp1 = pl.find_within(c, 3.1);\n tmp.clear();\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,4};\n tmp.clear();\n tmp1 = pl.find_within(c, 3.7);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,4,6};\n tmp.clear();\n tmp1 = pl.find_within(c, 5.4);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,4,5,6};\n tmp.clear();\n tmp1 = pl.find_within(c, 6.8);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,3,4,5,6};\n tmp.clear();\n tmp1 = pl.find_within(c, 7.3);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n}\nKraken : Add idx to stop_areas in proximity_list tests#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_proximity_list\n\n#include \n#include \"proximity_list\/proximity_list.h\"\n#include \"proximity_list\/proximitylist_api.h\"\n#include \"type\/data.h\"\n#include \"georef\/georef.h\"\n\nusing namespace navitia::type;\nusing namespace navitia::proximitylist;\n\nBOOST_AUTO_TEST_CASE(distances_grand_cercle)\n{\n GeographicalCoord a(0,0);\n GeographicalCoord b(0,0);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n BOOST_CHECK_CLOSE(a.distance_to(b), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(a), 0, 1e-6);\n\n GeographicalCoord nantes(-1.57, 47.22);\n GeographicalCoord paris(2.36, 48.85);\n BOOST_CHECK_CLOSE(nantes.distance_to(paris), 340000, 10);\n BOOST_CHECK_CLOSE(paris.distance_to(nantes), 340000, 10);\n\n a.set_lon(180);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n\n a.set_lon(84); a.set_lat(89.999);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n\n\n a.set_lon(34); a.set_lat(-89.999);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000\/2,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n\n\n a.set_lon(0); a.set_lat(45);\n BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000\/4,1);\n BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000\/4,1);\n BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6);\n BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6);\n}\n\nBOOST_AUTO_TEST_CASE(approx_distance){\n GeographicalCoord canaltp(2.3921, 48.8296);\n GeographicalCoord tour_eiffel(2.29447,48.85834);\n double coslat = ::cos(canaltp.lat() * 0.0174532925199432958);\n BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1);\n BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1);\n BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1);\n BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1);\n}\n\nBOOST_AUTO_TEST_CASE(find_nearest){\n constexpr double M_TO_DEG = 1.0\/111320.0;\n typedef std::pair p;\n ProximityList pl;\n\n GeographicalCoord c;\n std::vector coords;\n\n \/\/ Exemple d'illustration issu de wikipedia\n c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3); pl.add(c, 1); coords.push_back(c);\n c.set_lon(M_TO_DEG *5); c.set_lat(M_TO_DEG *4); pl.add(c, 2); coords.push_back(c);\n c.set_lon(M_TO_DEG *9); c.set_lat(M_TO_DEG *6); pl.add(c, 3); coords.push_back(c);\n c.set_lon(M_TO_DEG *4); c.set_lat(M_TO_DEG *7); pl.add(c, 4); coords.push_back(c);\n c.set_lon(M_TO_DEG *8); c.set_lat(M_TO_DEG *1); pl.add(c, 5); coords.push_back(c);\n c.set_lon(M_TO_DEG *7); c.set_lat(M_TO_DEG *2); pl.add(c, 6); coords.push_back(c);\n\n pl.build();\n\n std::vector expected {1,4,2,6,5,3};\n for(size_t i=0; i < expected.size(); ++i)\n BOOST_CHECK_EQUAL(pl.items[i].element, expected[i]);\n\n\n c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3);\n BOOST_CHECK_EQUAL(pl.find_nearest(c), 1);\n\n c.set_lon(M_TO_DEG *7.1); c.set_lat(M_TO_DEG *1.9);\n BOOST_CHECK_EQUAL(pl.find_nearest(c), 6);\n\n c.set_lon(M_TO_DEG *100); c.set_lat(M_TO_DEG *6);\n BOOST_CHECK_EQUAL(pl.find_nearest(c), 3);\n\n c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *4);\n\n expected = {1};\n auto tmp1 = pl.find_within(c, 1.1);\n std::vector tmp;\n for(auto p : tmp1) tmp.push_back(p.first);\n BOOST_CHECK_EQUAL(tmp1[0].second, coords[0]);\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2};\n tmp1 = pl.find_within(c, 3.1);\n tmp.clear();\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,4};\n tmp.clear();\n tmp1 = pl.find_within(c, 3.7);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,4,6};\n tmp.clear();\n tmp1 = pl.find_within(c, 5.4);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,4,5,6};\n tmp.clear();\n tmp1 = pl.find_within(c, 6.8);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n\n expected={1,2,3,4,5,6};\n tmp.clear();\n tmp1 = pl.find_within(c, 7.3);\n for(auto p : tmp1) tmp.push_back(p.first);\n std::sort(tmp.begin(), tmp.end());\n BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end());\n}\n\nBOOST_AUTO_TEST_CASE(test_api) {\n navitia::type::Data data;\n \/\/Everything in the range\n auto sa = new navitia::type::StopArea();\n sa->coord.set_lon(-1.554514);\n sa->coord.set_lat(47.218515);\n sa->idx = 0;\n data.pt_data.stop_areas.push_back(sa);\n sa = new navitia::type::StopArea();\n sa->coord.set_lon(-1.552044);\n sa->coord.set_lat(47.212516);\n sa->idx = 1;\n data.pt_data.stop_areas.push_back(sa);\n data.build_proximity_list();\n navitia::type::GeographicalCoord c;\n c.set_lon(-1.554514);\n c.set_lat(47.218515);\n auto result = find(c, 700,\n {navitia::type::Type_e::StopArea, navitia::type::Type_e::POI},\n \"\", 1, 10, 0, data);\n BOOST_CHECK_EQUAL(result.places_nearby().size(), 2);\n \/\/One object out of the range\n}\n\nBOOST_AUTO_TEST_CASE(test_api_type) {\n \/\/Everything of the same type in the range\n \/\/Everything of the same type and one out of the range\n \/\/Two types and everything in the range\n \/\/Two types and one out of the range\n}\n\nBOOST_AUTO_TEST_CASE(test_filter) {\n \/\/We ask for a stop_area inside the range\n \/\/We ask for a stop_area outside the range\n\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"aio_private.h\"\n\n#define EVEN_DISTRIBUTE\n\nconst int MAX_BUF_REQS = 1024 * 3;\n\n\/* \n * each file gets the same number of outstanding requests.\n *\/\n#ifdef EVEN_DISTRIBUTE\n#define MAX_OUTSTANDING_NREQS (AIO_DEPTH \/ num_open_files())\n#define ALLOW_DROP\n#endif\n\nclass extended_io_request: public io_request\n{\n\tchar *orig_embedded_bufs[NUM_EMBEDDED_IOVECS];\n\tchar **orig_bufs;\n\tslab_allocator *allocator;\n\n\tvoid assign_extended(extended_io_request &req) {\n\t\tthis->allocator = req.allocator;\n\t\tif (req.orig_bufs == req.orig_embedded_bufs) {\n\t\t\tthis->orig_bufs = this->orig_embedded_bufs;\n\t\t\tmemcpy(this->orig_embedded_bufs, req.orig_embedded_bufs,\n\t\t\t\t\tsizeof(orig_embedded_bufs));\n\t\t}\n\t\telse {\n\t\t\tthis->orig_bufs = req.orig_bufs;\n\t\t\treq.orig_bufs = NULL;\n\t\t}\n\t}\npublic:\n\textended_io_request() {\n\t\torig_bufs = NULL;\n\t\tallocator = NULL;\n\t\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\t}\n\n\t\/**\n\t * The buffers in the IO request are allocated in a different NUMA node\n\t * than the SSDs are connected to, and allocate buffers on the local node.\n\t *\/\n\textended_io_request(io_request &req, slab_allocator *allocator) {\n\t\tinit(req, allocator);\n\t}\n\n\t\/**\n\t * The buffers are allocated in the same NUMA node as the SSDs\n\t * are connected to.\n\t *\/\n\textended_io_request(io_request &req): io_request(req) {\n\t\tallocator = NULL;\n\t\torig_bufs = NULL;\n\t\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\t}\n\n\textended_io_request(extended_io_request &req) {\n\t\tio_request::assign(req);\n\t\tassign_extended(req);\n\t}\n\n\t~extended_io_request() {\n\t\treset();\n\t}\n\n\textended_io_request &operator=(io_request &req) {\n\t\tio_request::assign(req);\n\t\torig_bufs = NULL;\n\t\tallocator = NULL;\n\t\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\t\treturn *this;\n\t}\n\n\textended_io_request &operator=(extended_io_request &req) {\n\t\tio_request::assign(req);\n\t\tassign_extended(req);\n\t\treturn *this;\n\t}\n\n\tvoid reset();\n\tvoid init(io_request &req, slab_allocator *allocator);\n\n\tbool is_replaced() const {\n\t\treturn orig_bufs != NULL;\n\t}\n\n\tvoid use_orig_bufs();\n};\n\nvoid extended_io_request::use_orig_bufs()\n{\n\tfor (int i = 0; i < get_num_bufs(); i++) {\n\t\tchar *buf = get_buf(i);\n\t\t\/\/ This memory copy can significantly decrease the performance.\n\t\t\/\/ But it seems there isn't a better way to avoid it.\n\t\tmemcpy(orig_bufs[i], buf, get_buf_size(i));\n\t\tset_buf(i, orig_bufs[i]);\n\t\tif (this->get_buf_size(i) <= PAGE_SIZE)\n\t\t\tallocator->free(&buf, 1);\n\t\telse\n\t\t\tfree(buf);\n\t}\n\t\/\/ We have to reset orig_bufs because all original buffers\n\t\/\/ will be destroyed when the object is destructed.\n\tif (orig_bufs != orig_embedded_bufs)\n\t\tdelete orig_bufs;\n\torig_bufs = NULL;\n}\n\nvoid extended_io_request::init(io_request &req, slab_allocator *allocator)\n{\n\tio_request::assign(req);\n\tthis->allocator = allocator;\n\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\tif (this->get_num_bufs() > NUM_EMBEDDED_IOVECS)\n\t\torig_bufs = new char *[this->get_num_bufs()];\n\telse\n\t\torig_bufs = orig_embedded_bufs;\n\tfor (int i = 0; i < this->get_num_bufs(); i++) {\n\t\tchar *remote_buf = this->get_buf(i);\n\t\tchar *local_buf;\n\t\tif (this->get_buf_size(i) <= PAGE_SIZE) {\n\t\t\tint ret = allocator->alloc(&local_buf, 1);\n\t\t\tassert(ret == 1);\n\t\t}\n\t\telse\n\t\t\tlocal_buf = (char *) valloc(this->get_buf_size(i));\n\t\tthis->set_buf(i, local_buf);\n\t\torig_bufs[i] = remote_buf;\n\t}\n}\n\nvoid extended_io_request::reset()\n{\n\tif (orig_bufs) {\n\t\tchar *local_pages[get_num_bufs()];\n\t\tfor (int i = 0; i < get_num_bufs(); i++) {\n\t\t\tlocal_pages[i] = get_buf(i);\n\t\t}\n\t\tallocator->free(local_pages, get_num_bufs());\n\t\tif (orig_bufs != orig_embedded_bufs)\n\t\t\tdelete orig_bufs;\n\t\torig_bufs = NULL;\n\t}\n}\n\nstruct thread_callback_s\n{\n\tstruct io_callback_s cb;\n\tasync_io *aio;\n\textended_io_request req;\n};\n\nvoid aio_callback(io_context_t ctx, struct iocb* iocb[],\n\t\tvoid *cbs[], long res[], long res2[], int num) {\n\tasync_io *aio = NULL;\n\tthread_callback_s *tcbs[num];\n\tfor (int i = 0; i < num; i++) {\n\t\tassert(res2[i] == 0);\n\t\ttcbs[i] = (thread_callback_s *) cbs[i];\n\t\tif (aio == NULL)\n\t\t\taio = tcbs[i]->aio;\n\t\t\/\/ This is true when disks are only accessed by disk access threads.\n\t\tassert(aio == tcbs[i]->aio);\n\t}\n\n\taio->return_cb(tcbs, num);\n}\n\nasync_io::async_io(const logical_file_partition &partition, long size,\n\t\tint aio_depth_per_file, int node_id): buffered_io(partition, size,\n\t\t\tnode_id, O_DIRECT | O_RDWR), AIO_DEPTH(aio_depth_per_file *\n\t\t\t\tpartition.get_num_files()), allocator(PAGE_SIZE,\n\t\t\t\tAIO_DEPTH * PAGE_SIZE, INT_MAX, node_id)\n{\n\tprintf(\"aio is used\\n\");\n\tbuf_idx = 0;\n\tctx = create_aio_ctx(AIO_DEPTH);\n\tfor (int i = 0; i < AIO_DEPTH * 5; i++) {\n\t\tcbs.push_back(new thread_callback_s());\n\t}\n\tcb = NULL;\n\tnum_iowait = 0;\n}\n\nvoid async_io::cleanup()\n{\n\tint slot = max_io_slot(ctx);\n\n\twhile (slot < AIO_DEPTH) {\n\t\tio_wait(ctx, NULL);\n\t\tslot = max_io_slot(ctx);\n\t}\n\tbuffered_io::cleanup();\n}\n\nasync_io::~async_io()\n{\n\tcleanup();\n}\n\nstruct iocb *async_io::construct_req(io_request &io_req, callback_t cb_func)\n{\n\tif (cbs.empty()) {\n\t\tfprintf(stderr, \"no callback object left\\n\");\n\t\treturn NULL;\n\t}\n\n\tthread_callback_s *tcb = cbs.front();\n\tio_callback_s *cb = (io_callback_s *) tcb;\n\tcbs.pop_front();\n\n\tcb->func = cb_func;\n\tif (get_node_id() == io_req.get_node_id() || get_node_id() == -1)\n\t\ttcb->req = io_req;\n\telse\n\t\ttcb->req.init(io_req, &allocator);\n\ttcb->aio = this;\n\n\tassert(tcb->req.get_size() >= MIN_BLOCK_SIZE);\n\tassert(tcb->req.get_size() % MIN_BLOCK_SIZE == 0);\n\tassert(tcb->req.get_offset() % MIN_BLOCK_SIZE == 0);\n\tassert((long) tcb->req.get_buf() % MIN_BLOCK_SIZE == 0);\n\tint io_type = tcb->req.get_access_method() == READ ? A_READ : A_WRITE;\n\tblock_identifier bid;\n\tget_partition().map(tcb->req.get_offset() \/ PAGE_SIZE, bid);\n\tif (tcb->req.get_num_bufs() == 1)\n\t\treturn make_io_request(ctx, get_fd(tcb->req.get_offset()),\n\t\t\t\ttcb->req.get_size(), bid.off * PAGE_SIZE, tcb->req.get_buf(),\n\t\t\t\tio_type, cb);\n\telse {\n\t\tint num_bufs = tcb->req.get_num_bufs();\n\t\tfor (int i = 0; i < num_bufs; i++) {\n\t\t\tassert((long) tcb->req.get_buf(i) % MIN_BLOCK_SIZE == 0);\n\t\t\tassert(tcb->req.get_buf_size(i) % MIN_BLOCK_SIZE == 0);\n\t\t}\n\t\treturn make_io_request(ctx, get_fd(tcb->req.get_offset()),\n\t\t\t\t\/* \n\t\t\t\t * iocb only contains a pointer to the io vector.\n\t\t\t\t * the space for the IO vector is stored\n\t\t\t\t * in the callback structure.\n\t\t\t\t *\/\n\t\t\t\ttcb->req.get_vec(), num_bufs, bid.off * PAGE_SIZE,\n\t\t\t\tio_type, cb);\n\t}\n}\n\nssize_t async_io::access(io_request *requests, int num)\n{\n\tssize_t ret = 0;\n\n\twhile (num > 0) {\n\t\tint slot = max_io_slot(ctx);\n\t\tif (slot == 0) {\n\t\t\t\/*\n\t\t\t * To achieve the best performance, we need to submit requests\n\t\t\t * as long as there is a slot available.\n\t\t\t *\/\n\t\t\tnum_iowait++;\n\t\t\tio_wait(ctx, NULL, 1);\n\t\t\tslot = max_io_slot(ctx);\n\t\t}\n\t\tstruct iocb *reqs[slot];\n\t\tint min = slot > num ? num : slot;\n\t\tfor (int i = 0; i < min; i++) {\n\t\t\tret += requests->get_size();\n\t\t\treqs[i] = construct_req(*requests, aio_callback);\n\t\t\trequests++;\n\t\t}\n\t\tsubmit_io_request(ctx, reqs, min);\n\t\tnum -= min;\n\t}\n\treturn ret;\n}\n\nvoid async_io::return_cb(thread_callback_s *tcbs[], int num)\n{\n\tio_request *reqs[num];\n\tfor (int i = 0; i < num; i++) {\n\t\tthread_callback_s *tcb = tcbs[i];\n\t\tif (tcb->req.is_replaced())\n\t\t\ttcb->req.use_orig_bufs();\n\t\treqs[i] = &tcb->req;\n\t}\n\tif (this->cb) {\n\t\tthis->cb->invoke(reqs, num);\n\t}\n\tfor (int i = 0; i < num; i++) {\n\t\tthread_callback_s *tcb = tcbs[i];\n\t\ttcb->req.reset();\n\t\tcbs.push_back(tcb);\n\t}\n}\nFix a bug in aio for writing data to a remote SSD.#include \n\n#include \"aio_private.h\"\n\n#define EVEN_DISTRIBUTE\n\nconst int MAX_BUF_REQS = 1024 * 3;\n\n\/* \n * each file gets the same number of outstanding requests.\n *\/\n#ifdef EVEN_DISTRIBUTE\n#define MAX_OUTSTANDING_NREQS (AIO_DEPTH \/ num_open_files())\n#define ALLOW_DROP\n#endif\n\nclass extended_io_request: public io_request\n{\n\tchar *orig_embedded_bufs[NUM_EMBEDDED_IOVECS];\n\tchar **orig_bufs;\n\tslab_allocator *allocator;\n\n\tvoid assign_extended(extended_io_request &req) {\n\t\tthis->allocator = req.allocator;\n\t\tif (req.orig_bufs == req.orig_embedded_bufs) {\n\t\t\tthis->orig_bufs = this->orig_embedded_bufs;\n\t\t\tmemcpy(this->orig_embedded_bufs, req.orig_embedded_bufs,\n\t\t\t\t\tsizeof(orig_embedded_bufs));\n\t\t}\n\t\telse {\n\t\t\tthis->orig_bufs = req.orig_bufs;\n\t\t\treq.orig_bufs = NULL;\n\t\t}\n\t}\npublic:\n\textended_io_request() {\n\t\torig_bufs = NULL;\n\t\tallocator = NULL;\n\t\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\t}\n\n\t\/**\n\t * The buffers in the IO request are allocated in a different NUMA node\n\t * than the SSDs are connected to, and allocate buffers on the local node.\n\t *\/\n\textended_io_request(io_request &req, slab_allocator *allocator) {\n\t\tinit(req, allocator);\n\t}\n\n\t\/**\n\t * The buffers are allocated in the same NUMA node as the SSDs\n\t * are connected to.\n\t *\/\n\textended_io_request(io_request &req): io_request(req) {\n\t\tallocator = NULL;\n\t\torig_bufs = NULL;\n\t\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\t}\n\n\textended_io_request(extended_io_request &req) {\n\t\tio_request::assign(req);\n\t\tassign_extended(req);\n\t}\n\n\t~extended_io_request() {\n\t\treset();\n\t}\n\n\textended_io_request &operator=(io_request &req) {\n\t\tio_request::assign(req);\n\t\torig_bufs = NULL;\n\t\tallocator = NULL;\n\t\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\t\treturn *this;\n\t}\n\n\textended_io_request &operator=(extended_io_request &req) {\n\t\tio_request::assign(req);\n\t\tassign_extended(req);\n\t\treturn *this;\n\t}\n\n\tvoid reset();\n\tvoid init(io_request &req, slab_allocator *allocator);\n\n\tbool is_replaced() const {\n\t\treturn orig_bufs != NULL;\n\t}\n\n\tvoid use_orig_bufs();\n};\n\nvoid extended_io_request::use_orig_bufs()\n{\n\tfor (int i = 0; i < get_num_bufs(); i++) {\n\t\tchar *buf = get_buf(i);\n\t\t\/\/ This memory copy can significantly decrease the performance.\n\t\t\/\/ But it seems there isn't a better way to avoid it.\n\t\tif (this->get_access_method() == READ)\n\t\t\tmemcpy(orig_bufs[i], buf, get_buf_size(i));\n\t\tset_buf(i, orig_bufs[i]);\n\t\tif (this->get_buf_size(i) <= PAGE_SIZE)\n\t\t\tallocator->free(&buf, 1);\n\t\telse\n\t\t\tfree(buf);\n\t}\n\t\/\/ We have to reset orig_bufs because all original buffers\n\t\/\/ will be destroyed when the object is destructed.\n\tif (orig_bufs != orig_embedded_bufs)\n\t\tdelete orig_bufs;\n\torig_bufs = NULL;\n}\n\nvoid extended_io_request::init(io_request &req, slab_allocator *allocator)\n{\n\tio_request::assign(req);\n\tthis->allocator = allocator;\n\tmemset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs));\n\tif (this->get_num_bufs() > NUM_EMBEDDED_IOVECS)\n\t\torig_bufs = new char *[this->get_num_bufs()];\n\telse\n\t\torig_bufs = orig_embedded_bufs;\n\tfor (int i = 0; i < this->get_num_bufs(); i++) {\n\t\tchar *remote_buf = this->get_buf(i);\n\t\tchar *local_buf;\n\t\tif (this->get_buf_size(i) <= PAGE_SIZE) {\n\t\t\tint ret = allocator->alloc(&local_buf, 1);\n\t\t\tassert(ret == 1);\n\t\t}\n\t\telse\n\t\t\tlocal_buf = (char *) valloc(this->get_buf_size(i));\n\t\tif (this->get_access_method() == WRITE)\n\t\t\tmemcpy(local_buf, remote_buf, this->get_buf_size(i));\n\t\tthis->set_buf(i, local_buf);\n\t\torig_bufs[i] = remote_buf;\n\t}\n}\n\nvoid extended_io_request::reset()\n{\n\tif (orig_bufs) {\n\t\tchar *local_pages[get_num_bufs()];\n\t\tfor (int i = 0; i < get_num_bufs(); i++) {\n\t\t\tlocal_pages[i] = get_buf(i);\n\t\t}\n\t\tallocator->free(local_pages, get_num_bufs());\n\t\tif (orig_bufs != orig_embedded_bufs)\n\t\t\tdelete orig_bufs;\n\t\torig_bufs = NULL;\n\t}\n}\n\nstruct thread_callback_s\n{\n\tstruct io_callback_s cb;\n\tasync_io *aio;\n\textended_io_request req;\n};\n\nvoid aio_callback(io_context_t ctx, struct iocb* iocb[],\n\t\tvoid *cbs[], long res[], long res2[], int num) {\n\tasync_io *aio = NULL;\n\tthread_callback_s *tcbs[num];\n\tfor (int i = 0; i < num; i++) {\n\t\tassert(res2[i] == 0);\n\t\ttcbs[i] = (thread_callback_s *) cbs[i];\n\t\tif (aio == NULL)\n\t\t\taio = tcbs[i]->aio;\n\t\t\/\/ This is true when disks are only accessed by disk access threads.\n\t\tassert(aio == tcbs[i]->aio);\n\t}\n\n\taio->return_cb(tcbs, num);\n}\n\nasync_io::async_io(const logical_file_partition &partition, long size,\n\t\tint aio_depth_per_file, int node_id): buffered_io(partition, size,\n\t\t\tnode_id, O_DIRECT | O_RDWR), AIO_DEPTH(aio_depth_per_file *\n\t\t\t\tpartition.get_num_files()), allocator(PAGE_SIZE,\n\t\t\t\tAIO_DEPTH * PAGE_SIZE, INT_MAX, node_id)\n{\n\tprintf(\"aio is used\\n\");\n\tbuf_idx = 0;\n\tctx = create_aio_ctx(AIO_DEPTH);\n\tfor (int i = 0; i < AIO_DEPTH * 5; i++) {\n\t\tcbs.push_back(new thread_callback_s());\n\t}\n\tcb = NULL;\n\tnum_iowait = 0;\n}\n\nvoid async_io::cleanup()\n{\n\tint slot = max_io_slot(ctx);\n\n\twhile (slot < AIO_DEPTH) {\n\t\tio_wait(ctx, NULL);\n\t\tslot = max_io_slot(ctx);\n\t}\n\tbuffered_io::cleanup();\n}\n\nasync_io::~async_io()\n{\n\tcleanup();\n}\n\nstruct iocb *async_io::construct_req(io_request &io_req, callback_t cb_func)\n{\n\tif (cbs.empty()) {\n\t\tfprintf(stderr, \"no callback object left\\n\");\n\t\treturn NULL;\n\t}\n\n\tthread_callback_s *tcb = cbs.front();\n\tio_callback_s *cb = (io_callback_s *) tcb;\n\tcbs.pop_front();\n\n\tcb->func = cb_func;\n\tif (get_node_id() == io_req.get_node_id() || get_node_id() == -1)\n\t\ttcb->req = io_req;\n\telse\n\t\ttcb->req.init(io_req, &allocator);\n\ttcb->aio = this;\n\n\tassert(tcb->req.get_size() >= MIN_BLOCK_SIZE);\n\tassert(tcb->req.get_size() % MIN_BLOCK_SIZE == 0);\n\tassert(tcb->req.get_offset() % MIN_BLOCK_SIZE == 0);\n\tassert((long) tcb->req.get_buf() % MIN_BLOCK_SIZE == 0);\n\tint io_type = tcb->req.get_access_method() == READ ? A_READ : A_WRITE;\n\tblock_identifier bid;\n\tget_partition().map(tcb->req.get_offset() \/ PAGE_SIZE, bid);\n\tif (tcb->req.get_num_bufs() == 1)\n\t\treturn make_io_request(ctx, get_fd(tcb->req.get_offset()),\n\t\t\t\ttcb->req.get_size(), bid.off * PAGE_SIZE, tcb->req.get_buf(),\n\t\t\t\tio_type, cb);\n\telse {\n\t\tint num_bufs = tcb->req.get_num_bufs();\n\t\tfor (int i = 0; i < num_bufs; i++) {\n\t\t\tassert((long) tcb->req.get_buf(i) % MIN_BLOCK_SIZE == 0);\n\t\t\tassert(tcb->req.get_buf_size(i) % MIN_BLOCK_SIZE == 0);\n\t\t}\n\t\treturn make_io_request(ctx, get_fd(tcb->req.get_offset()),\n\t\t\t\t\/* \n\t\t\t\t * iocb only contains a pointer to the io vector.\n\t\t\t\t * the space for the IO vector is stored\n\t\t\t\t * in the callback structure.\n\t\t\t\t *\/\n\t\t\t\ttcb->req.get_vec(), num_bufs, bid.off * PAGE_SIZE,\n\t\t\t\tio_type, cb);\n\t}\n}\n\nssize_t async_io::access(io_request *requests, int num)\n{\n\tssize_t ret = 0;\n\n\twhile (num > 0) {\n\t\tint slot = max_io_slot(ctx);\n\t\tif (slot == 0) {\n\t\t\t\/*\n\t\t\t * To achieve the best performance, we need to submit requests\n\t\t\t * as long as there is a slot available.\n\t\t\t *\/\n\t\t\tnum_iowait++;\n\t\t\tio_wait(ctx, NULL, 1);\n\t\t\tslot = max_io_slot(ctx);\n\t\t}\n\t\tstruct iocb *reqs[slot];\n\t\tint min = slot > num ? num : slot;\n\t\tfor (int i = 0; i < min; i++) {\n\t\t\tret += requests->get_size();\n\t\t\treqs[i] = construct_req(*requests, aio_callback);\n\t\t\trequests++;\n\t\t}\n\t\tsubmit_io_request(ctx, reqs, min);\n\t\tnum -= min;\n\t}\n\treturn ret;\n}\n\nvoid async_io::return_cb(thread_callback_s *tcbs[], int num)\n{\n\tio_request *reqs[num];\n\tfor (int i = 0; i < num; i++) {\n\t\tthread_callback_s *tcb = tcbs[i];\n\t\tif (tcb->req.is_replaced())\n\t\t\ttcb->req.use_orig_bufs();\n\t\treqs[i] = &tcb->req;\n\t}\n\tif (this->cb) {\n\t\tthis->cb->invoke(reqs, num);\n\t}\n\tfor (int i = 0; i < num; i++) {\n\t\tthread_callback_s *tcb = tcbs[i];\n\t\ttcb->req.reset();\n\t\tcbs.push_back(tcb);\n\t}\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\r\n**\r\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n**\r\n** This file is part of the Qt Mobility Components.\r\n**\r\n** $QT_BEGIN_LICENSE:LGPL$\r\n** No Commercial Usage\r\n** This file contains pre-release code and may not be distributed.\r\n** You may use this file in accordance with the terms and conditions\r\n** contained in the Technology Preview License Agreement accompanying\r\n** this package.\r\n**\r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file. Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\r\n**\r\n** In addition, as a special exception, Nokia gives you certain additional\r\n** rights. These rights are described in the Nokia Qt LGPL Exception\r\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\r\n**\r\n** If you have questions regarding the use of this file, please contact\r\n** Nokia at qt-info@nokia.com.\r\n**\r\n**\r\n**\r\n**\r\n**\r\n**\r\n**\r\n**\r\n** $QT_END_LICENSE$\r\n**\r\n****************************************************************************\/\r\n\r\n#include \"S60mediarecognizer.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nS60MediaRecognizer::S60MediaRecognizer(QObject *parent) : QObject(parent)\r\n{\r\n m_recognizer = NULL;\r\n TRAP(m_error, m_recognizer = CMPMediaRecognizer::NewL());\r\n}\r\n\r\nS60MediaRecognizer::~S60MediaRecognizer()\r\n{\r\n delete m_recognizer;\r\n m_recognizer = NULL;\r\n}\r\n\/*\r\n * Checks if Url is valid or not.\n *\/\r\nbool S60MediaRecognizer::checkUrl(const QUrl& url)\r\n{\r\n TBool validUrl = false;\r\n if (m_recognizer) {\r\n TPtrC myDesc (static_cast(url.toString().utf16()), url.toString().length());\r\n validUrl = m_recognizer->ValidUrl(myDesc);\r\n }\r\n \r\n return validUrl;\r\n}\r\n\r\nS60MediaRecognizer::MediaType S60MediaRecognizer::IdentifyMediaType(const QUrl& url)\r\n{\r\n CMPMediaRecognizer::TMPMediaType type;\r\n QString filePath = QDir::toNativeSeparators(url.toLocalFile());\r\n TPtrC16 urlPtr(reinterpret_cast(filePath.utf16()));\r\n MediaType mediaType = NotSupported;\r\n TRAP(m_error, type = m_recognizer->IdentifyMediaTypeL(urlPtr, EFalse));\r\n \r\n if (!m_error) {\r\n switch (type) {\r\n case CMPMediaRecognizer::ELocalAudioFile:\r\n mediaType = Audio;\r\n break;\r\n case CMPMediaRecognizer::ELocalVideoFile:\r\n mediaType = Video;\r\n break;\r\n case CMPMediaRecognizer::ELocalAudioPlaylist:\r\n case CMPMediaRecognizer::EUrl:\r\n\/\/ TODO: Must be considered when streams will be implemented\r\n case CMPMediaRecognizer::ELocalRamFile:\r\n case CMPMediaRecognizer::ELocalSdpFile:\r\n case CMPMediaRecognizer::EProgressiveDownload:\r\n case CMPMediaRecognizer::EUnidentified:\r\n default:\r\n break;\r\n }\r\n }\r\n return mediaType; \r\n}\r\nExclude EProgressiveDownload from switch.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"S60mediarecognizer.h\"\n#include \n#include \n#include \n#include \n#include \n\nS60MediaRecognizer::S60MediaRecognizer(QObject *parent) : QObject(parent)\n{\n m_recognizer = NULL;\n TRAP(m_error, m_recognizer = CMPMediaRecognizer::NewL());\n}\n\nS60MediaRecognizer::~S60MediaRecognizer()\n{\n delete m_recognizer;\n m_recognizer = NULL;\n}\n\/*\n * Checks if Url is valid or not.\n *\/\nbool S60MediaRecognizer::checkUrl(const QUrl& url)\n{\n TBool validUrl = false;\n if (m_recognizer) {\n TPtrC myDesc (static_cast(url.toString().utf16()), url.toString().length());\n validUrl = m_recognizer->ValidUrl(myDesc);\n }\n \n return validUrl;\n}\n\nS60MediaRecognizer::MediaType S60MediaRecognizer::IdentifyMediaType(const QUrl& url)\n{\n CMPMediaRecognizer::TMPMediaType type;\n QString filePath = QDir::toNativeSeparators(url.toLocalFile());\n TPtrC16 urlPtr(reinterpret_cast(filePath.utf16()));\n MediaType mediaType = NotSupported;\n TRAP(m_error, type = m_recognizer->IdentifyMediaTypeL(urlPtr, EFalse));\n \n if (!m_error) {\n switch (type) {\n case CMPMediaRecognizer::ELocalAudioFile:\n mediaType = Audio;\n break;\n case CMPMediaRecognizer::ELocalVideoFile:\n mediaType = Video;\n break;\n case CMPMediaRecognizer::ELocalAudioPlaylist:\n case CMPMediaRecognizer::EUrl:\n\/\/ TODO: Must be considered when streams will be implemented\n case CMPMediaRecognizer::ELocalRamFile:\n case CMPMediaRecognizer::ELocalSdpFile:\n\/\/ case CMPMediaRecognizer::EProgressiveDownload:\n case CMPMediaRecognizer::EUnidentified:\n default:\n break;\n }\n }\n return mediaType; \n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ yas_db_model.cpp\n\/\/\n\n#include \n#include \n#include \"yas_db_model.h\"\n#include \"yas_db_entity.h\"\n#include \"yas_db_index.h\"\n#include \"yas_db_attribute.h\"\n#include \"yas_db_relation.h\"\n\nusing namespace yas;\n\nnamespace yas::db {\nstatic std::string const version_key = \"version\";\nstatic std::string const entities_key = \"entities\";\nstatic std::string const indices_key = \"indices\";\nstatic std::string const attributes_key = \"attributes\";\nstatic std::string const relations_key = \"relations\";\n\nstatic std::unordered_map make_inverse_relation_names(\n std::vector const &enitity_args_vec) {\n std::unordered_map entity_inv_rel_names;\n\n for (db::entity_args const &entity : enitity_args_vec) {\n std::string const &entity_name = entity.name;\n for (db::relation_args const &relation : entity.relations) {\n std::string const &tgt_entity_name = relation.target;\n\n if (entity_inv_rel_names.count(tgt_entity_name) == 0) {\n entity_inv_rel_names.insert(std::make_pair(tgt_entity_name, db::string_set_map_t{}));\n }\n\n auto &inv_rel_names = entity_inv_rel_names.at(tgt_entity_name);\n if (inv_rel_names.count(entity_name) == 0) {\n inv_rel_names.insert(std::make_pair(entity_name, db::string_set_t{}));\n }\n\n inv_rel_names.at(entity_name).insert(relation.name);\n }\n }\n\n return entity_inv_rel_names;\n}\n}\n\nstruct db::model::impl : base::impl {\n struct args {\n yas::version const version;\n db::entity_map_t const entities;\n db::index_map_t const indices;\n };\n\n args _args;\n\n static db::model::impl::args to_args(model_args &&args) {\n auto entity_inv_rel_names = make_inverse_relation_names(args.entities);\n\n db::entity_map_t entities;\n entities.reserve(args.entities.size());\n\n for (db::entity_args &entity_args : args.entities) {\n db::string_set_map_t inv_rel_names;\n if (entity_inv_rel_names.count(entity_args.name)) {\n inv_rel_names = std::move(entity_inv_rel_names.at(entity_args.name));\n }\n\n std::string name = entity_args.name;\n entities.emplace(std::move(name), db::entity{{.name = std::move(entity_args.name),\n .attributes = std::move(entity_args.attributes),\n .relations = std::move(entity_args.relations)},\n std::move(inv_rel_names)});\n }\n\n db::index_map_t indices;\n indices.reserve(args.indices.size());\n\n for (db::index_args &index_args : args.indices) {\n std::string name = index_args.name;\n indices.emplace(std::move(name), db::index{std::move(index_args)});\n }\n\n return {.version = std::move(args.version), .entities = std::move(entities), .indices = std::move(indices)};\n }\n\n impl(model_args &&args) : _args(to_args(std::move(args))) {\n }\n};\n\ndb::model::model(model_args args) : base(std::make_shared(std::move(args))) {\n}\n\ndb::model::model(std::nullptr_t) : base(nullptr) {\n}\n\nyas::version const &db::model::version() const {\n return impl_ptr()->_args.version;\n}\n\ndb::entity_map_t const &db::model::entities() const {\n return impl_ptr()->_args.entities;\n}\n\ndb::index_map_t const &db::model::indices() const {\n return impl_ptr()->_args.indices;\n}\n\ndb::entity const &db::model::entity(std::string const &entity) const {\n return this->entities().at(entity);\n}\n\ndb::attribute_map_t const &db::model::attributes(std::string const &entity) const {\n return this->entities().at(entity).all_attributes;\n}\n\ndb::attribute_map_t const &db::model::custom_attributes(std::string const &entity) const {\n return this->entities().at(entity).custom_attributes;\n}\n\ndb::relation_map_t const &db::model::relations(std::string const &entity) const {\n return this->entities().at(entity).relations;\n}\n\ndb::attribute const &db::model::attribute(std::string const &entity, std::string const &attr_name) const {\n return this->entities().at(entity).all_attributes.at(attr_name);\n}\n\ndb::relation const &db::model::relation(std::string const &entity, std::string const &rel_name) const {\n return this->entities().at(entity).relations.at(rel_name);\n}\n\ndb::index const &db::model::index(std::string const &index_name) const {\n return this->indices().at(index_name);\n}\n\nbool db::model::entity_exists(std::string const &entity) const {\n return this->entities().count(entity) > 0;\n}\n\nbool db::model::attribute_exists(std::string const &entity, std::string const &attr_name) const {\n if (this->entity_exists(entity)) {\n if (this->entities().at(entity).all_attributes.count(attr_name) > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool db::model::relation_exists(std::string const &entity, std::string const &rel_name) const {\n if (this->entity_exists(entity)) {\n if (this->entities().at(entity).relations.count(rel_name) > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool db::model::index_exists(std::string const &index_name) const {\n return this->indices().count(index_name) > 0;\n}\nremove key\/\/\n\/\/ yas_db_model.cpp\n\/\/\n\n#include \n#include \n#include \"yas_db_model.h\"\n#include \"yas_db_entity.h\"\n#include \"yas_db_index.h\"\n#include \"yas_db_attribute.h\"\n#include \"yas_db_relation.h\"\n\nusing namespace yas;\n\nnamespace yas::db {\nstatic std::unordered_map make_inverse_relation_names(\n std::vector const &enitity_args_vec) {\n std::unordered_map entity_inv_rel_names;\n\n for (db::entity_args const &entity : enitity_args_vec) {\n std::string const &entity_name = entity.name;\n for (db::relation_args const &relation : entity.relations) {\n std::string const &tgt_entity_name = relation.target;\n\n if (entity_inv_rel_names.count(tgt_entity_name) == 0) {\n entity_inv_rel_names.insert(std::make_pair(tgt_entity_name, db::string_set_map_t{}));\n }\n\n auto &inv_rel_names = entity_inv_rel_names.at(tgt_entity_name);\n if (inv_rel_names.count(entity_name) == 0) {\n inv_rel_names.insert(std::make_pair(entity_name, db::string_set_t{}));\n }\n\n inv_rel_names.at(entity_name).insert(relation.name);\n }\n }\n\n return entity_inv_rel_names;\n}\n}\n\nstruct db::model::impl : base::impl {\n struct args {\n yas::version const version;\n db::entity_map_t const entities;\n db::index_map_t const indices;\n };\n\n args _args;\n\n static db::model::impl::args to_args(model_args &&args) {\n auto entity_inv_rel_names = make_inverse_relation_names(args.entities);\n\n db::entity_map_t entities;\n entities.reserve(args.entities.size());\n\n for (db::entity_args &entity_args : args.entities) {\n db::string_set_map_t inv_rel_names;\n if (entity_inv_rel_names.count(entity_args.name)) {\n inv_rel_names = std::move(entity_inv_rel_names.at(entity_args.name));\n }\n\n std::string name = entity_args.name;\n entities.emplace(std::move(name), db::entity{{.name = std::move(entity_args.name),\n .attributes = std::move(entity_args.attributes),\n .relations = std::move(entity_args.relations)},\n std::move(inv_rel_names)});\n }\n\n db::index_map_t indices;\n indices.reserve(args.indices.size());\n\n for (db::index_args &index_args : args.indices) {\n std::string name = index_args.name;\n indices.emplace(std::move(name), db::index{std::move(index_args)});\n }\n\n return {.version = std::move(args.version), .entities = std::move(entities), .indices = std::move(indices)};\n }\n\n impl(model_args &&args) : _args(to_args(std::move(args))) {\n }\n};\n\ndb::model::model(model_args args) : base(std::make_shared(std::move(args))) {\n}\n\ndb::model::model(std::nullptr_t) : base(nullptr) {\n}\n\nyas::version const &db::model::version() const {\n return impl_ptr()->_args.version;\n}\n\ndb::entity_map_t const &db::model::entities() const {\n return impl_ptr()->_args.entities;\n}\n\ndb::index_map_t const &db::model::indices() const {\n return impl_ptr()->_args.indices;\n}\n\ndb::entity const &db::model::entity(std::string const &entity) const {\n return this->entities().at(entity);\n}\n\ndb::attribute_map_t const &db::model::attributes(std::string const &entity) const {\n return this->entities().at(entity).all_attributes;\n}\n\ndb::attribute_map_t const &db::model::custom_attributes(std::string const &entity) const {\n return this->entities().at(entity).custom_attributes;\n}\n\ndb::relation_map_t const &db::model::relations(std::string const &entity) const {\n return this->entities().at(entity).relations;\n}\n\ndb::attribute const &db::model::attribute(std::string const &entity, std::string const &attr_name) const {\n return this->entities().at(entity).all_attributes.at(attr_name);\n}\n\ndb::relation const &db::model::relation(std::string const &entity, std::string const &rel_name) const {\n return this->entities().at(entity).relations.at(rel_name);\n}\n\ndb::index const &db::model::index(std::string const &index_name) const {\n return this->indices().at(index_name);\n}\n\nbool db::model::entity_exists(std::string const &entity) const {\n return this->entities().count(entity) > 0;\n}\n\nbool db::model::attribute_exists(std::string const &entity, std::string const &attr_name) const {\n if (this->entity_exists(entity)) {\n if (this->entities().at(entity).all_attributes.count(attr_name) > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool db::model::relation_exists(std::string const &entity, std::string const &rel_name) const {\n if (this->entity_exists(entity)) {\n if (this->entities().at(entity).relations.count(rel_name) > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool db::model::index_exists(std::string const &index_name) const {\n return this->indices().count(index_name) > 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Pavel Kirienko \n *\/\n\n#include \n#include \n#include \n#include \n\nnamespace uavcan\n{\n\/**\n * Frame\n *\/\nconst uint8_t Frame::MaxIndexForService;\nconst uint8_t Frame::MaxIndexForMessage;\n\nuint_fast8_t Frame::getMaxIndexForTransferType(const TransferType type)\n{\n if (type == TransferTypeMessageBroadcast ||\n type == TransferTypeMessageUnicast)\n {\n return MaxIndexForMessage;\n }\n else if (type == TransferTypeServiceRequest ||\n type == TransferTypeServiceResponse)\n {\n return MaxIndexForService;\n }\n else\n {\n UAVCAN_ASSERT(0);\n return 0;\n }\n}\n\nvoid Frame::setPriority(const TransferPriority priority)\n{\n UAVCAN_ASSERT(priority < NumTransferPriorities);\n if (transfer_type_ == TransferTypeMessageBroadcast ||\n transfer_type_ == TransferTypeMessageUnicast)\n {\n if (priority != TransferPriorityService)\n {\n transfer_priority_ = priority;\n }\n else\n {\n UAVCAN_ASSERT(0);\n }\n }\n else\n {\n UAVCAN_ASSERT(0);\n }\n}\n\nint Frame::getMaxPayloadLen() const\n{\n switch (getTransferType())\n {\n case TransferTypeMessageBroadcast:\n {\n return int(sizeof(payload_));\n }\n case TransferTypeServiceResponse:\n case TransferTypeServiceRequest:\n case TransferTypeMessageUnicast:\n {\n return int(sizeof(payload_)) - 1;\n }\n default:\n {\n UAVCAN_ASSERT(0);\n return -ErrLogic;\n }\n }\n}\n\nint Frame::setPayload(const uint8_t* data, unsigned len)\n{\n const int maxlen = getMaxPayloadLen();\n if (maxlen < 0)\n {\n return maxlen;\n }\n len = min(unsigned(maxlen), len);\n (void)copy(data, data + len, payload_);\n payload_len_ = uint_fast8_t(len);\n return int(len);\n}\n\ntemplate \ninline static uint32_t bitunpack(uint32_t val)\n{\n StaticAssert<(OFFSET >= 0)>::check();\n StaticAssert<(WIDTH > 0)>::check();\n StaticAssert<((OFFSET + WIDTH) <= 29)>::check();\n return (val >> OFFSET) & ((1UL << WIDTH) - 1);\n}\n\nbool Frame::parse(const CanFrame& can_frame)\n{\n if (can_frame.isErrorFrame() || can_frame.isRemoteTransmissionRequest() || !can_frame.isExtended())\n {\n return false;\n }\n\n if (can_frame.dlc > sizeof(can_frame.data))\n {\n UAVCAN_ASSERT(0); \/\/ This is not a protocol error, so UAVCAN_ASSERT() is ok\n return false;\n }\n\n \/*\n * CAN ID parsing\n *\/\n const uint32_t id = can_frame.id & CanFrame::MaskExtID;\n transfer_id_ = uint8_t(bitunpack<0, 3>(id));\n last_frame_ = bitunpack<3, 1>(id) != 0;\n \/\/ TT-specific fields skipped\n transfer_priority_ = TransferPriority(bitunpack<27, 2>(id));\n\n if (transfer_priority_ == TransferPriorityService)\n {\n frame_index_ = uint_fast8_t(bitunpack<4, 6>(id));\n src_node_id_ = uint8_t(bitunpack<10, 7>(id));\n data_type_id_ = uint16_t(bitunpack<17, 9>(id));\n \/\/ RequestNotResponse\n transfer_type_ = (bitunpack<26, 1>(id) == 1U) ? TransferTypeServiceRequest : TransferTypeServiceResponse;\n }\n else\n {\n frame_index_ = uint_fast8_t(bitunpack<4, 4>(id));\n \/\/ BroadcastNotUnicast\n transfer_type_ = (bitunpack<8, 1>(id) == 1U) ? TransferTypeMessageBroadcast : TransferTypeMessageUnicast;\n src_node_id_ = uint8_t(bitunpack<9, 7>(id));\n data_type_id_ = uint16_t(bitunpack<16, 11>(id));\n }\n\n \/*\n * CAN payload parsing\n *\/\n switch (transfer_type_)\n {\n case TransferTypeMessageBroadcast:\n {\n dst_node_id_ = NodeID::Broadcast;\n payload_len_ = can_frame.dlc;\n (void)copy(can_frame.data, can_frame.data + can_frame.dlc, payload_);\n break;\n }\n case TransferTypeServiceResponse:\n case TransferTypeServiceRequest:\n case TransferTypeMessageUnicast:\n {\n if (can_frame.dlc < 1)\n {\n return false;\n }\n if (can_frame.data[0] & 0x80) \/\/ RESERVED, must be zero\n {\n return false;\n }\n dst_node_id_ = can_frame.data[0] & 0x7F;\n payload_len_ = uint8_t(can_frame.dlc - 1);\n (void)copy(can_frame.data + 1, can_frame.data + can_frame.dlc, payload_);\n break;\n }\n default:\n {\n return false;\n }\n }\n\n \/*\n * Special case for anonymous transfers - trailing 8 bits of CAN ID must be ignored\n * - Transfer ID (assumed zero)\n * - Last Frame (assumed true)\n * - Frame Index (assumed zero)\n *\/\n if (src_node_id_.isBroadcast())\n {\n transfer_id_ = TransferID(0);\n last_frame_ = true;\n frame_index_ = 0;\n }\n\n return isValid();\n}\n\ntemplate \ninline static uint32_t bitpack(uint32_t field)\n{\n StaticAssert<(OFFSET >= 0)>::check();\n StaticAssert<(WIDTH > 0)>::check();\n StaticAssert<((OFFSET + WIDTH) <= 29)>::check();\n UAVCAN_ASSERT((field & ((1UL << WIDTH) - 1)) == field);\n return uint32_t((field & ((1UL << WIDTH) - 1)) << OFFSET);\n}\n\nbool Frame::compile(CanFrame& out_can_frame) const\n{\n if (!isValid())\n {\n UAVCAN_ASSERT(0); \/\/ This is an application error, so we need to maximize it.\n return false;\n }\n\n \/*\n * Setting CAN ID field\n *\/\n \/\/ Common fields for messages and services\n out_can_frame.id =\n CanFrame::FlagEFF |\n bitpack<0, 3>(transfer_id_.get()) |\n bitpack<3, 1>(last_frame_) |\n \/* TT-specific fields skipped *\/\n bitpack<27, 2>(transfer_priority_);\n\n if (transfer_type_ == TransferTypeServiceRequest ||\n transfer_type_ == TransferTypeServiceResponse)\n {\n out_can_frame.id |=\n bitpack<4, 6>(frame_index_) |\n bitpack<10, 7>(src_node_id_.get()) |\n bitpack<17, 9>(data_type_id_.get()) |\n bitpack<26, 1>((transfer_type_ == TransferTypeServiceRequest) ? 1U : 0U);\n }\n else if (transfer_type_ == TransferTypeMessageBroadcast ||\n transfer_type_ == TransferTypeMessageUnicast)\n {\n out_can_frame.id |=\n bitpack<4, 4>(frame_index_) |\n bitpack<8, 1>((transfer_type_ == TransferTypeMessageBroadcast) ? 1U : 0U) |\n bitpack<9, 7>(src_node_id_.get()) |\n bitpack<16, 11>(data_type_id_.get());\n }\n else\n {\n UAVCAN_ASSERT(0);\n return false;\n }\n\n \/*\n * Setting payload\n *\/\n switch (transfer_type_)\n {\n case TransferTypeMessageBroadcast:\n {\n out_can_frame.dlc = uint8_t(payload_len_);\n (void)copy(payload_, payload_ + payload_len_, out_can_frame.data);\n break;\n }\n case TransferTypeServiceResponse:\n case TransferTypeServiceRequest:\n case TransferTypeMessageUnicast:\n {\n UAVCAN_ASSERT((payload_len_ + 1U) <= sizeof(out_can_frame.data));\n out_can_frame.data[0] = dst_node_id_.get();\n out_can_frame.dlc = uint8_t(payload_len_ + 1);\n (void)copy(payload_, payload_ + payload_len_, out_can_frame.data + 1);\n break;\n }\n default:\n {\n UAVCAN_ASSERT(0);\n return false;\n }\n }\n\n \/*\n * Setting trailing bits of CAN ID for anonymous message\n * This overrides the following fields:\n * - Transfer ID (assumed zero)\n * - Last Frame (assumed true)\n * - Frame Index (assumed zero)\n *\/\n if (src_node_id_.isBroadcast())\n {\n uint8_t sum = 0;\n out_can_frame.id &= ~bitpack<0, 8>(sum); \/\/ Clearing bits\n for (uint_fast8_t i = 0; i < payload_len_; i++)\n {\n sum = static_cast(sum + payload_[i]);\n }\n out_can_frame.id |= bitpack<0, 8>(sum); \/\/ Setting the checksum\n }\n\n return true;\n}\n\nbool Frame::isValid() const\n{\n \/*\n * Frame index\n *\/\n if (frame_index_ > getMaxIndex())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if ((frame_index_ == getMaxIndex()) && !last_frame_)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Node ID\n *\/\n if (!src_node_id_.isValid() ||\n !dst_node_id_.isValid())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if (src_node_id_.isUnicast() &&\n (src_node_id_ == dst_node_id_))\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Transfer type\n *\/\n if (transfer_type_ >= NumTransferTypes)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if ((transfer_type_ == TransferTypeMessageBroadcast) != dst_node_id_.isBroadcast())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/\/ Anonymous transfers\n if (src_node_id_.isBroadcast() &&\n (!last_frame_ || (frame_index_ > 0) || (transfer_type_ != TransferTypeMessageBroadcast)))\n {\n return false;\n }\n\n \/*\n * Payload\n *\/\n if (static_cast(payload_len_) > getMaxPayloadLen())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Data type ID\n *\/\n if (!data_type_id_.isValidForDataTypeKind(getDataTypeKindForTransferType(transfer_type_)))\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Priority\n *\/\n if (transfer_priority_ >= NumTransferPriorities)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if (transfer_type_ == TransferTypeServiceRequest ||\n transfer_type_ == TransferTypeServiceResponse)\n {\n if (transfer_priority_ != TransferPriorityService)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n }\n\n return true;\n}\n\nbool Frame::operator==(const Frame& rhs) const\n{\n return\n (transfer_priority_ == rhs.transfer_priority_) &&\n (transfer_type_ == rhs.transfer_type_) &&\n (data_type_id_ == rhs.data_type_id_) &&\n (src_node_id_ == rhs.src_node_id_) &&\n (dst_node_id_ == rhs.dst_node_id_) &&\n (frame_index_ == rhs.frame_index_) &&\n (transfer_id_ == rhs.transfer_id_) &&\n (last_frame_ == rhs.last_frame_) &&\n (payload_len_ == rhs.payload_len_) &&\n equal(payload_, payload_ + payload_len_, rhs.payload_);\n}\n\n#if UAVCAN_TOSTRING\nstd::string Frame::toString() const\n{\n \/*\n * - Priority\n * - Data Type ID\n * - Transfer Type\n * - Source Node ID\n * - Frame Index\n * - Last Frame\n * - Transfer ID\n *\/\n static const int BUFLEN = 100;\n char buf[BUFLEN];\n int ofs = snprintf(buf, BUFLEN, \"prio=%d dtid=%d tt=%d snid=%d dnid=%d idx=%d last=%d tid=%d payload=[\",\n int(transfer_priority_), int(data_type_id_.get()), int(transfer_type_), int(src_node_id_.get()),\n int(dst_node_id_.get()), int(frame_index_), int(last_frame_), int(transfer_id_.get()));\n\n for (unsigned i = 0; i < payload_len_; i++)\n {\n ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), \"%02x\", payload_[i]);\n if ((i + 1) < payload_len_)\n {\n ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), \" \");\n }\n }\n (void)snprintf(buf + ofs, unsigned(BUFLEN - ofs), \"]\");\n return std::string(buf);\n}\n#endif\n\n\/**\n * RxFrame\n *\/\nbool RxFrame::parse(const CanRxFrame& can_frame)\n{\n if (!Frame::parse(can_frame))\n {\n return false;\n }\n if (can_frame.ts_mono.isZero()) \/\/ Monotonic timestamps are mandatory.\n {\n UAVCAN_ASSERT(0); \/\/ If it is not set, it's a driver failure.\n return false;\n }\n ts_mono_ = can_frame.ts_mono;\n ts_utc_ = can_frame.ts_utc;\n iface_index_ = can_frame.iface_index;\n return true;\n}\n\n#if UAVCAN_TOSTRING\nstd::string RxFrame::toString() const\n{\n std::string out = Frame::toString();\n out.reserve(128);\n out += \" ts_m=\" + ts_mono_.toString();\n out += \" ts_utc=\" + ts_utc_.toString();\n out += \" iface=\";\n out += char('0' + iface_index_);\n return out;\n}\n#endif\n\n}\nCoverity 1304848\/*\n * Copyright (C) 2014 Pavel Kirienko \n *\/\n\n#include \n#include \n#include \n#include \n\nnamespace uavcan\n{\n\/**\n * Frame\n *\/\nconst uint8_t Frame::MaxIndexForService;\nconst uint8_t Frame::MaxIndexForMessage;\n\nuint_fast8_t Frame::getMaxIndexForTransferType(const TransferType type)\n{\n if (type == TransferTypeMessageBroadcast ||\n type == TransferTypeMessageUnicast)\n {\n return MaxIndexForMessage;\n }\n else if (type == TransferTypeServiceRequest ||\n type == TransferTypeServiceResponse)\n {\n return MaxIndexForService;\n }\n else\n {\n UAVCAN_ASSERT(0);\n return 0;\n }\n}\n\nvoid Frame::setPriority(const TransferPriority priority)\n{\n UAVCAN_ASSERT(priority < NumTransferPriorities);\n if (transfer_type_ == TransferTypeMessageBroadcast ||\n transfer_type_ == TransferTypeMessageUnicast)\n {\n if (priority != TransferPriorityService)\n {\n transfer_priority_ = priority;\n }\n else\n {\n UAVCAN_ASSERT(0);\n }\n }\n else\n {\n UAVCAN_ASSERT(0);\n }\n}\n\nint Frame::getMaxPayloadLen() const\n{\n switch (getTransferType())\n {\n case TransferTypeMessageBroadcast:\n {\n return int(sizeof(payload_));\n }\n case TransferTypeServiceResponse:\n case TransferTypeServiceRequest:\n case TransferTypeMessageUnicast:\n {\n return int(sizeof(payload_)) - 1;\n }\n default:\n {\n UAVCAN_ASSERT(0);\n return -ErrLogic;\n }\n }\n}\n\nint Frame::setPayload(const uint8_t* data, unsigned len)\n{\n const int maxlen = getMaxPayloadLen();\n if (maxlen < 0)\n {\n return maxlen;\n }\n len = min(unsigned(maxlen), len);\n (void)copy(data, data + len, payload_);\n payload_len_ = uint_fast8_t(len);\n return int(len);\n}\n\ntemplate \ninline static uint32_t bitunpack(uint32_t val)\n{\n StaticAssert<(OFFSET >= 0)>::check();\n StaticAssert<(WIDTH > 0)>::check();\n StaticAssert<((OFFSET + WIDTH) <= 29)>::check();\n return (val >> OFFSET) & ((1UL << WIDTH) - 1);\n}\n\nbool Frame::parse(const CanFrame& can_frame)\n{\n if (can_frame.isErrorFrame() || can_frame.isRemoteTransmissionRequest() || !can_frame.isExtended())\n {\n return false;\n }\n\n if (can_frame.dlc > sizeof(can_frame.data))\n {\n UAVCAN_ASSERT(0); \/\/ This is not a protocol error, so UAVCAN_ASSERT() is ok\n return false;\n }\n\n \/*\n * CAN ID parsing\n *\/\n const uint32_t id = can_frame.id & CanFrame::MaskExtID;\n transfer_id_ = uint8_t(bitunpack<0, 3>(id));\n last_frame_ = bitunpack<3, 1>(id) != 0;\n \/\/ TT-specific fields skipped\n transfer_priority_ = TransferPriority(bitunpack<27, 2>(id));\n\n if (transfer_priority_ == TransferPriorityService)\n {\n frame_index_ = uint_fast8_t(bitunpack<4, 6>(id));\n src_node_id_ = uint8_t(bitunpack<10, 7>(id));\n data_type_id_ = uint16_t(bitunpack<17, 9>(id));\n \/\/ RequestNotResponse\n transfer_type_ = (bitunpack<26, 1>(id) == 1U) ? TransferTypeServiceRequest : TransferTypeServiceResponse;\n }\n else\n {\n frame_index_ = uint_fast8_t(bitunpack<4, 4>(id));\n \/\/ BroadcastNotUnicast\n transfer_type_ = (bitunpack<8, 1>(id) == 1U) ? TransferTypeMessageBroadcast : TransferTypeMessageUnicast;\n src_node_id_ = uint8_t(bitunpack<9, 7>(id));\n data_type_id_ = uint16_t(bitunpack<16, 11>(id));\n }\n\n \/*\n * CAN payload parsing\n *\/\n switch (transfer_type_)\n {\n case TransferTypeMessageBroadcast:\n {\n dst_node_id_ = NodeID::Broadcast;\n payload_len_ = can_frame.dlc;\n (void)copy(can_frame.data, can_frame.data + can_frame.dlc, payload_);\n break;\n }\n case TransferTypeServiceResponse:\n case TransferTypeServiceRequest:\n case TransferTypeMessageUnicast:\n {\n if (can_frame.dlc < 1)\n {\n return false;\n }\n if (can_frame.data[0] & 0x80) \/\/ RESERVED, must be zero\n {\n return false;\n }\n dst_node_id_ = can_frame.data[0] & 0x7F;\n payload_len_ = uint8_t(can_frame.dlc - 1);\n (void)copy(can_frame.data + 1, can_frame.data + can_frame.dlc, payload_);\n break;\n }\n default:\n {\n return false;\n }\n }\n\n \/*\n * Special case for anonymous transfers - trailing 8 bits of CAN ID must be ignored\n * - Transfer ID (assumed zero)\n * - Last Frame (assumed true)\n * - Frame Index (assumed zero)\n *\/\n if (src_node_id_.isBroadcast())\n {\n transfer_id_ = TransferID(0);\n last_frame_ = true;\n frame_index_ = 0;\n }\n\n return isValid();\n}\n\ntemplate \ninline static uint32_t bitpack(uint32_t field)\n{\n StaticAssert<(OFFSET >= 0)>::check();\n StaticAssert<(WIDTH > 0)>::check();\n StaticAssert<((OFFSET + WIDTH) <= 29)>::check();\n UAVCAN_ASSERT((field & ((1UL << WIDTH) - 1)) == field);\n return uint32_t((field & ((1UL << WIDTH) - 1)) << OFFSET);\n}\n\nbool Frame::compile(CanFrame& out_can_frame) const\n{\n if (!isValid())\n {\n UAVCAN_ASSERT(0); \/\/ This is an application error, so we need to maximize it.\n return false;\n }\n\n \/*\n * Setting CAN ID field\n *\/\n \/\/ Common fields for messages and services\n out_can_frame.id =\n CanFrame::FlagEFF |\n bitpack<0, 3>(transfer_id_.get()) |\n bitpack<3, 1>(last_frame_) |\n \/* TT-specific fields skipped *\/\n bitpack<27, 2>(transfer_priority_);\n\n if (transfer_type_ == TransferTypeServiceRequest ||\n transfer_type_ == TransferTypeServiceResponse)\n {\n out_can_frame.id |=\n bitpack<4, 6>(frame_index_) |\n bitpack<10, 7>(src_node_id_.get()) |\n bitpack<17, 9>(data_type_id_.get()) |\n bitpack<26, 1>((transfer_type_ == TransferTypeServiceRequest) ? 1U : 0U);\n }\n else if (transfer_type_ == TransferTypeMessageBroadcast ||\n transfer_type_ == TransferTypeMessageUnicast)\n {\n out_can_frame.id |=\n bitpack<4, 4>(frame_index_) |\n bitpack<8, 1>((transfer_type_ == TransferTypeMessageBroadcast) ? 1U : 0U) |\n bitpack<9, 7>(src_node_id_.get()) |\n bitpack<16, 11>(data_type_id_.get());\n }\n else\n {\n UAVCAN_ASSERT(0);\n return false;\n }\n\n \/*\n * Setting payload\n *\/\n switch (transfer_type_)\n {\n case TransferTypeMessageBroadcast:\n {\n out_can_frame.dlc = uint8_t(payload_len_);\n (void)copy(payload_, payload_ + payload_len_, out_can_frame.data);\n break;\n }\n case TransferTypeServiceResponse:\n case TransferTypeServiceRequest:\n case TransferTypeMessageUnicast:\n {\n UAVCAN_ASSERT((payload_len_ + 1U) <= sizeof(out_can_frame.data));\n out_can_frame.data[0] = dst_node_id_.get();\n out_can_frame.dlc = uint8_t(payload_len_ + 1);\n (void)copy(payload_, payload_ + payload_len_, out_can_frame.data + 1);\n break;\n }\n default:\n {\n UAVCAN_ASSERT(0);\n return false;\n }\n }\n\n \/*\n * Setting trailing bits of CAN ID for anonymous message\n * This overrides the following fields:\n * - Transfer ID (assumed zero)\n * - Last Frame (assumed true)\n * - Frame Index (assumed zero)\n *\/\n if (src_node_id_.isBroadcast())\n {\n uint8_t sum = 0;\n out_can_frame.id &= ~bitpack<0, 8>(sum); \/\/ Clearing bits\n for (uint_fast8_t i = 0; i < payload_len_; i++)\n {\n sum = static_cast(sum + payload_[i]);\n }\n out_can_frame.id |= bitpack<0, 8>(sum); \/\/ Setting the checksum\n }\n\n return true;\n}\n\nbool Frame::isValid() const\n{\n \/*\n * Frame index\n *\/\n if (frame_index_ > getMaxIndex())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if ((frame_index_ == getMaxIndex()) && !last_frame_)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Node ID\n *\/\n if (!src_node_id_.isValid() ||\n !dst_node_id_.isValid())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if (src_node_id_.isUnicast() &&\n (src_node_id_ == dst_node_id_))\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Transfer type\n *\/\n if (transfer_type_ >= NumTransferTypes)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if ((transfer_type_ == TransferTypeMessageBroadcast) != dst_node_id_.isBroadcast())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/\/ Anonymous transfers\n if (src_node_id_.isBroadcast() &&\n (!last_frame_ || (frame_index_ > 0) || (transfer_type_ != TransferTypeMessageBroadcast)))\n {\n return false;\n }\n\n \/*\n * Payload\n *\/\n if (static_cast(payload_len_) > getMaxPayloadLen())\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Data type ID\n *\/\n if (!data_type_id_.isValidForDataTypeKind(getDataTypeKindForTransferType(transfer_type_)))\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n \/*\n * Priority\n *\/\n if (transfer_priority_ >= NumTransferPriorities)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n\n if (transfer_type_ == TransferTypeServiceRequest ||\n transfer_type_ == TransferTypeServiceResponse)\n {\n if (transfer_priority_ != TransferPriorityService)\n {\n UAVCAN_TRACE(\"Frame\", \"Validness check failed at line %d\", __LINE__);\n return false;\n }\n }\n\n return true;\n}\n\nbool Frame::operator==(const Frame& rhs) const\n{\n return\n (transfer_priority_ == rhs.transfer_priority_) &&\n (transfer_type_ == rhs.transfer_type_) &&\n (data_type_id_ == rhs.data_type_id_) &&\n (src_node_id_ == rhs.src_node_id_) &&\n (dst_node_id_ == rhs.dst_node_id_) &&\n (frame_index_ == rhs.frame_index_) &&\n (transfer_id_ == rhs.transfer_id_) &&\n (last_frame_ == rhs.last_frame_) &&\n (payload_len_ == rhs.payload_len_) &&\n equal(payload_, payload_ + payload_len_, rhs.payload_);\n}\n\n#if UAVCAN_TOSTRING\nstd::string Frame::toString() const\n{\n \/*\n * - Priority\n * - Data Type ID\n * - Transfer Type\n * - Source Node ID\n * - Frame Index\n * - Last Frame\n * - Transfer ID\n *\/\n static const int BUFLEN = 100;\n char buf[BUFLEN];\n int ofs = snprintf(buf, BUFLEN, \"prio=%d dtid=%d tt=%d snid=%d dnid=%d idx=%d last=%d tid=%d payload=[\",\n int(transfer_priority_), int(data_type_id_.get()), int(transfer_type_), int(src_node_id_.get()),\n int(dst_node_id_.get()), int(frame_index_), int(last_frame_), int(transfer_id_.get()));\n\n for (unsigned i = 0; i < payload_len_; i++)\n {\n \/\/ Coverity Scan complains about payload_ being not default initialized. This is OK.\n \/\/ coverity[read_parm_fld]\n ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), \"%02x\", payload_[i]);\n if ((i + 1) < payload_len_)\n {\n ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), \" \");\n }\n }\n (void)snprintf(buf + ofs, unsigned(BUFLEN - ofs), \"]\");\n return std::string(buf);\n}\n#endif\n\n\/**\n * RxFrame\n *\/\nbool RxFrame::parse(const CanRxFrame& can_frame)\n{\n if (!Frame::parse(can_frame))\n {\n return false;\n }\n if (can_frame.ts_mono.isZero()) \/\/ Monotonic timestamps are mandatory.\n {\n UAVCAN_ASSERT(0); \/\/ If it is not set, it's a driver failure.\n return false;\n }\n ts_mono_ = can_frame.ts_mono;\n ts_utc_ = can_frame.ts_utc;\n iface_index_ = can_frame.iface_index;\n return true;\n}\n\n#if UAVCAN_TOSTRING\nstd::string RxFrame::toString() const\n{\n std::string out = Frame::toString();\n out.reserve(128);\n out += \" ts_m=\" + ts_mono_.toString();\n out += \" ts_utc=\" + ts_utc_.toString();\n out += \" iface=\";\n out += char('0' + iface_index_);\n return out;\n}\n#endif\n\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \"vast\/system\/pivot_command.hpp\"\n\n#include \"vast\/defaults.hpp\"\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/detail\/make_io_stream.hpp\"\n#include \"vast\/error.hpp\"\n#include \"vast\/format\/csv.hpp\"\n#include \"vast\/format\/json.hpp\"\n#include \"vast\/format\/pcap.hpp\"\n#include \"vast\/format\/zeek.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/scope_linked.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/system\/read_query.hpp\"\n#include \"vast\/system\/signal_monitor.hpp\"\n#include \"vast\/system\/sink.hpp\"\n#include \"vast\/system\/sink_command.hpp\"\n#include \"vast\/system\/spawn_or_connect_to_node.hpp\"\n#include \"vast\/system\/tracker.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace std::chrono_literals;\n\nnamespace vast::system {\n\nnamespace {\n\ntemplate \ncaf::expected\nmake_writer(caf::actor_system& sys, const caf::settings& options) {\n using defaults = typename Writer::defaults;\n using ostream_ptr = std::unique_ptr;\n std::string category = defaults::category;\n if constexpr (std::is_constructible_v) {\n auto output = get_or(options, category + \".write\", defaults::write);\n auto uds = get_or(options, category + \".uds\", false);\n auto out = detail::make_output_stream(output, uds);\n if (!out)\n return out.error();\n Writer writer{std::move(*out)};\n return sys.spawn(sink, std::move(writer), max_events);\n } else {\n Writer writer;\n return sys.spawn(sink, std::move(writer), max_events);\n }\n}\n\n} \/\/ namespace\n\ncaf::message\npivot_command(const command::invocation& invocation, caf::actor_system& sys) {\n VAST_TRACE(invocation);\n \/\/ Read query from input file, STDIN or CLI arguments.\n auto query = read_query(invocation, \"export.read\", size_t{1});\n if (!query)\n return caf::make_message(std::move(query.error()));\n auto& options = invocation.options;\n auto& target = invocation.arguments[0];\n \/\/ using caf::get_or;\n auto limit\n = get_or(options, \"export.max-events\", defaults::export_::max_events);\n caf::actor writer;\n if (detail::starts_with(target, \"pcap\")) {\n using defaults_t = defaults::export_::pcap;\n std::string category = defaults_t::category;\n auto output = get_or(options, category + \".write\", defaults_t::write);\n auto flush = get_or(options, category + \".flush-interval\",\n defaults_t::flush_interval);\n format::pcap::writer w{output, flush};\n writer = sys.spawn(sink, std::move(w), limit);\n } else if (detail::starts_with(target, \"suricata\")) {\n auto w = make_writer(sys, invocation.options);\n if (!w)\n return make_message(w.error());\n writer = *w;\n } else if (detail::starts_with(target, \"zeek\")) {\n auto w = make_writer(sys, invocation.options);\n if (!w)\n return make_message(w.error());\n writer = *w;\n } else\n return make_message(make_error(ec::unimplemented, \"pivoting is only \"\n \"implemented for pcap, \"\n \"suricata and zeek\"));\n caf::scoped_actor self{sys};\n \/\/ Get VAST node.\n auto node_opt\n = spawn_or_connect_to_node(self, invocation.options, content(sys.config()));\n if (auto err = caf::get_if(&node_opt))\n return caf::make_message(std::move(*err));\n auto& node = caf::holds_alternative(node_opt)\n ? caf::get(node_opt)\n : caf::get(node_opt).get();\n VAST_ASSERT(node != nullptr);\n \/\/ TODO(ch9412): Factor guard into a function.\n \/\/ Start signal monitor.\n std::thread sig_mon_thread;\n auto guard = signal_monitor::run_guarded(sig_mon_thread, sys, 750ms, self);\n \/\/ Spawn exporter at the node.\n caf::actor exp;\n auto exporter_invocation\n = command::invocation{invocation.options, \"spawn exporter\", {*query}};\n VAST_DEBUG(invocation.full_name,\n \"spawns exporter with parameters:\", exporter_invocation);\n error err;\n self->request(node, caf::infinite, std::move(exporter_invocation))\n .receive(\n [&](caf::actor& a) {\n exp = std::move(a);\n if (!exp)\n err = make_error(ec::invalid_result, \"remote spawn returned nullptr\");\n },\n [&](error& e) { err = std::move(e); });\n if (err) {\n self->send_exit(writer, caf::exit_reason::user_shutdown);\n return caf::make_message(std::move(err));\n }\n \/\/ Spawn pivoter at the node.\n caf::actor piv;\n auto pivoter_invocation = command::invocation{\n invocation.options, \"spawn pivoter\", {invocation.arguments[0], *query}};\n VAST_DEBUG(invocation.full_name,\n \"spawns exporter with parameters:\", pivoter_invocation);\n self->request(node, caf::infinite, std::move(pivoter_invocation))\n .receive(\n [&](caf::actor& a) {\n piv = std::move(a);\n if (!piv)\n err = make_error(ec::invalid_result, \"remote spawn returned nullptr\");\n },\n [&](error& e) { err = std::move(e); });\n if (err) {\n self->send_exit(exp, caf::exit_reason::user_shutdown);\n self->send_exit(writer, caf::exit_reason::user_shutdown);\n return caf::make_message(std::move(err));\n }\n self->request(node, caf::infinite, get_atom::value)\n .receive(\n [&](const std::string& id, system::registry& reg) {\n \/\/ Assign accountant to sink.\n VAST_DEBUG(invocation.full_name, \"assigns accountant from node\", id,\n \"to new sink\");\n auto er = reg.components[id].find(\"accountant\");\n if (er != reg.components[id].end()) {\n auto accountant = er->second.actor;\n self->send(writer, caf::actor_cast(accountant));\n }\n },\n [&](error& e) { err = std::move(e); });\n if (err) {\n self->send_exit(writer, caf::exit_reason::user_shutdown);\n return caf::make_message(std::move(err));\n }\n self->monitor(writer);\n self->monitor(piv);\n \/\/ Start the exporter.\n self->send(exp, system::sink_atom::value, piv);\n \/\/ (Ab)use query_statistics as done message.\n self->send(exp, system::statistics_atom::value, piv);\n self->send(piv, system::sink_atom::value, writer);\n self->send(exp, system::run_atom::value);\n auto stop = false;\n self\n ->do_receive(\n [&](caf::down_msg& msg) {\n if (msg.source == node) {\n VAST_DEBUG_ANON(__func__, \"received DOWN from node\");\n self->send_exit(writer, caf::exit_reason::user_shutdown);\n self->send_exit(exp, caf::exit_reason::user_shutdown);\n self->send_exit(piv, caf::exit_reason::user_shutdown);\n } else if (msg.source == piv) {\n VAST_DEBUG(invocation.full_name, \"received DOWN from pivoter\");\n self->send_exit(exp, caf::exit_reason::user_shutdown);\n self->send_exit(writer, caf::exit_reason::user_shutdown);\n } else if (msg.source == writer) {\n VAST_DEBUG(invocation.full_name, \"received DOWN from sink\");\n self->send_exit(exp, caf::exit_reason::user_shutdown);\n self->send_exit(piv, caf::exit_reason::user_shutdown);\n } else {\n VAST_ASSERT(!\"received DOWN from inexplicable actor\");\n }\n if (msg.reason) {\n VAST_WARNING(invocation.full_name, \"received error message:\",\n self->system().render(msg.reason));\n err = std::move(msg.reason);\n }\n stop = true;\n },\n [&](system::signal_atom, int signal) {\n VAST_DEBUG(invocation.full_name, \"got \" << ::strsignal(signal));\n if (signal == SIGINT || signal == SIGTERM) {\n self->send_exit(exp, caf::exit_reason::user_shutdown);\n self->send_exit(piv, caf::exit_reason::user_shutdown);\n self->send_exit(writer, caf::exit_reason::user_shutdown);\n }\n })\n .until([&] { return stop; });\n if (err)\n return caf::make_message(std::move(err));\n return caf::none;\n}\n\n} \/\/ namespace vast::system\nUse node control functions in pivoter command\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \"vast\/system\/pivot_command.hpp\"\n\n#include \"vast\/defaults.hpp\"\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/detail\/make_io_stream.hpp\"\n#include \"vast\/error.hpp\"\n#include \"vast\/format\/csv.hpp\"\n#include \"vast\/format\/json.hpp\"\n#include \"vast\/format\/pcap.hpp\"\n#include \"vast\/format\/zeek.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/scope_linked.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/system\/node_control.hpp\"\n#include \"vast\/system\/read_query.hpp\"\n#include \"vast\/system\/signal_monitor.hpp\"\n#include \"vast\/system\/sink.hpp\"\n#include \"vast\/system\/sink_command.hpp\"\n#include \"vast\/system\/spawn_or_connect_to_node.hpp\"\n#include \"vast\/system\/tracker.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace std::chrono_literals;\n\nnamespace vast::system {\n\nnamespace {\n\ntemplate \ncaf::expected\nmake_writer(caf::actor_system& sys, const caf::settings& options) {\n using defaults = typename Writer::defaults;\n using ostream_ptr = std::unique_ptr;\n std::string category = defaults::category;\n if constexpr (std::is_constructible_v) {\n auto output = get_or(options, category + \".write\", defaults::write);\n auto uds = get_or(options, category + \".uds\", false);\n auto out = detail::make_output_stream(output, uds);\n if (!out)\n return out.error();\n Writer writer{std::move(*out)};\n return sys.spawn(sink, std::move(writer), max_events);\n } else {\n Writer writer;\n return sys.spawn(sink, std::move(writer), max_events);\n }\n}\n\n} \/\/ namespace\n\ncaf::message\npivot_command(const command::invocation& invocation, caf::actor_system& sys) {\n VAST_TRACE(invocation);\n \/\/ Read query from input file, STDIN or CLI arguments.\n auto query = read_query(invocation, \"export.read\", size_t{1});\n if (!query)\n return caf::make_message(std::move(query.error()));\n auto& options = invocation.options;\n auto& target = invocation.arguments[0];\n \/\/ using caf::get_or;\n auto limit\n = get_or(options, \"export.max-events\", defaults::export_::max_events);\n caf::actor writer;\n if (detail::starts_with(target, \"pcap\")) {\n using defaults_t = defaults::export_::pcap;\n std::string category = defaults_t::category;\n auto output = get_or(options, category + \".write\", defaults_t::write);\n auto flush = get_or(options, category + \".flush-interval\",\n defaults_t::flush_interval);\n format::pcap::writer w{output, flush};\n writer = sys.spawn(sink, std::move(w), limit);\n } else if (detail::starts_with(target, \"suricata\")) {\n auto w = make_writer(sys, invocation.options);\n if (!w)\n return make_message(w.error());\n writer = *w;\n } else if (detail::starts_with(target, \"zeek\")) {\n auto w = make_writer(sys, invocation.options);\n if (!w)\n return make_message(w.error());\n writer = *w;\n } else\n return make_message(make_error(ec::unimplemented, \"pivoting is only \"\n \"implemented for pcap, \"\n \"suricata and zeek\"));\n caf::scoped_actor self{sys};\n auto writer_guard = caf::detail::make_scope_guard(\n [&] { self->send_exit(writer, caf::exit_reason::user_shutdown); });\n \/\/ Get VAST node.\n auto node_opt\n = spawn_or_connect_to_node(self, invocation.options, content(sys.config()));\n if (auto err = caf::get_if(&node_opt))\n return caf::make_message(std::move(*err));\n auto& node = caf::holds_alternative(node_opt)\n ? caf::get(node_opt)\n : caf::get(node_opt).get();\n VAST_ASSERT(node != nullptr);\n \/\/ TODO(ch9412): Factor guard into a function.\n \/\/ Start signal monitor.\n std::thread sig_mon_thread;\n auto signal_guard\n = signal_monitor::run_guarded(sig_mon_thread, sys, 750ms, self);\n \/\/ Spawn exporter at the node.\n auto spawn_exporter\n = command::invocation{invocation.options, \"spawn exporter\", {*query}};\n VAST_DEBUG(&invocation, \"spawns exporter with parameters:\", spawn_exporter);\n auto exp = spawn_at_node(self, node, spawn_exporter);\n if (!exp)\n return caf::make_message(std::move(exp.error()));\n auto exp_guard = caf::detail::make_scope_guard(\n [&] { self->send_exit(*exp, caf::exit_reason::user_shutdown); });\n \/\/ Spawn pivoter at the node.\n auto spawn_pivoter = command::invocation{\n invocation.options, \"spawn pivoter\", {invocation.arguments[0], *query}};\n VAST_DEBUG(&invocation, \"spawns pivoter with parameters:\", spawn_pivoter);\n auto piv = spawn_at_node(self, node, spawn_pivoter);\n if (!piv)\n return caf::make_message(std::move(piv.error()));\n auto piv_guard = caf::detail::make_scope_guard(\n [&] { self->send_exit(*piv, caf::exit_reason::user_shutdown); });\n \/\/ Register the accountant at the Sink.\n auto components = get_node_component(self, node);\n if (!components)\n return caf::make_message(std::move(components.error()));\n auto& [accountant] = *components;\n if (accountant) {\n VAST_DEBUG(invocation.full_name, \"assigns accountant to writer\");\n self->send(writer, caf::actor_cast(*accountant));\n }\n caf::error err;\n self->monitor(writer);\n self->monitor(*piv);\n \/\/ Start the exporter.\n self->send(*exp, system::sink_atom::value, *piv);\n \/\/ (Ab)use query_statistics as done message.\n self->send(*exp, system::statistics_atom::value, *piv);\n self->send(*piv, system::sink_atom::value, writer);\n self->send(*exp, system::run_atom::value);\n auto stop = false;\n self\n ->do_receive(\n [&](caf::down_msg& msg) {\n if (msg.source == node) {\n VAST_DEBUG(invocation.full_name, \"received DOWN from node\");\n } else if (msg.source == *piv) {\n VAST_DEBUG(invocation.full_name, \"received DOWN from pivoter\");\n piv_guard.disable();\n } else if (msg.source == writer) {\n VAST_DEBUG(invocation.full_name, \"received DOWN from sink\");\n writer_guard.disable();\n } else {\n VAST_ASSERT(!\"received DOWN from inexplicable actor\");\n }\n if (msg.reason) {\n VAST_WARNING(invocation.full_name, \"received error message:\",\n self->system().render(msg.reason));\n err = std::move(msg.reason);\n }\n stop = true;\n },\n [&](system::signal_atom, int signal) {\n VAST_DEBUG(invocation.full_name, \"got \" << ::strsignal(signal));\n if (signal == SIGINT || signal == SIGTERM) {\n stop = true;\n }\n })\n .until([&] { return stop; });\n if (err)\n return caf::make_message(std::move(err));\n return caf::none;\n}\n\n} \/\/ namespace vast::system\n<|endoftext|>"} {"text":"\/*************************************************************************\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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sal.hxx\"\n\n#include \"system.h\"\n#include \n#include \n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\/\/ Prototypes for initialization and deinitialization of SAL library\n\nvoid SAL_CALL sal_detail_initialize(int argc, char ** argv)\n{\n WSADATA wsaData;\n int error;\n WORD wVersionRequested;\n\n wVersionRequested = MAKEWORD(1, 1);\n\n error = WSAStartup(wVersionRequested, &wsaData);\n if ( 0 == error )\n {\n WORD wMajorVersionRequired = 1;\n WORD wMinorVersionRequired = 1;\n\n if ((LOBYTE(wsaData.wVersion) < wMajorVersionRequired) ||\n (LOBYTE(wsaData.wVersion) == wMajorVersionRequired) &&\n ((HIBYTE(wsaData.wVersion) < wMinorVersionRequired)))\n {\n \/\/ How to handle a very unlikely error ???\n }\n }\n else\n {\n \/\/ How to handle a very unlikely error ???\n }\n\n osl_setCommandArgs(argc, argv);\n}\n\nvoid SAL_CALL sal_detail_deinitialize()\n{\n if ( SOCKET_ERROR == WSACleanup() )\n {\n \/\/ We should never reach this point or we did wrong elsewhere\n }\n}\n\n\n\n#ifdef __cplusplus\n} \/\/ extern \"C\"\n#endif\nmhu23 #i113531# use recommended Windows linker flags and DLL search path.\/*************************************************************************\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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sal.hxx\"\n\n#include \"system.h\"\n#include \n#include \n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\/\/ Prototypes for initialization and deinitialization of SAL library\n\nvoid SAL_CALL sal_detail_initialize(int argc, char ** argv)\n{\n \/\/ SetProcessDEPPolicy(PROCESS_DEP_ENABLE);\n \/\/ SetDllDirectoryW(L\"\");\n \/\/ SetSearchPathMode(\n \/\/ BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT);\n HMODULE h = GetModuleHandleW(L\"kernel32.dll\");\n if (h != 0) {\n FARPROC p = GetProcAddress(h, \"SetProcessDEPPolicy\");\n if (p != 0) {\n reinterpret_cast< BOOL (WINAPI *)(DWORD) >(p)(0x00000001);\n }\n p = GetProcAddress(h, \"SetDllDirectoryW\");\n if (p != 0) {\n reinterpret_cast< BOOL (WINAPI *)(LPCWSTR) >(p)(L\"\");\n }\n p = GetProcAddress(h, \"SetSearchPathMode\");\n if (p != 0) {\n reinterpret_cast< BOOL (WINAPI *)(DWORD) >(p)(0x8001);\n }\n }\n\n WSADATA wsaData;\n int error;\n WORD wVersionRequested;\n\n wVersionRequested = MAKEWORD(1, 1);\n\n error = WSAStartup(wVersionRequested, &wsaData);\n if ( 0 == error )\n {\n WORD wMajorVersionRequired = 1;\n WORD wMinorVersionRequired = 1;\n\n if ((LOBYTE(wsaData.wVersion) < wMajorVersionRequired) ||\n (LOBYTE(wsaData.wVersion) == wMajorVersionRequired) &&\n ((HIBYTE(wsaData.wVersion) < wMinorVersionRequired)))\n {\n \/\/ How to handle a very unlikely error ???\n }\n }\n else\n {\n \/\/ How to handle a very unlikely error ???\n }\n\n osl_setCommandArgs(argc, argv);\n}\n\nvoid SAL_CALL sal_detail_deinitialize()\n{\n if ( SOCKET_ERROR == WSACleanup() )\n {\n \/\/ We should never reach this point or we did wrong elsewhere\n }\n}\n\n\n\n#ifdef __cplusplus\n} \/\/ extern \"C\"\n#endif\n<|endoftext|>"} {"text":"\/*\n alm_cui.cpp\n\n Copyright (c) 2014, 2015, 2016 Terumasa Tadano\n\n This file is distributed under the terms of the MIT license.\n Please see the file 'LICENCE.txt' in the root directory\n or http:\/\/opensource.org\/licenses\/mit-license.php for information.\n*\/\n\n#include \"alm_cui.h\"\n#include \"alm.h\"\n#include \"input_parser.h\"\n#include \"timer.h\"\n#include \"version.h\"\n#include \"writer.h\"\n#include \n#include \n\n#ifdef _OPENMP\n\n#include \n\n#endif\n\nusing namespace ALM_NS;\n\nALMCUI::ALMCUI() {}\n\nALMCUI::~ALMCUI() {}\n\nvoid ALMCUI::run(const int narg,\n char **arg) const\n{\n auto alm = new ALM();\n\n \/\/ alm->mode is set herein.\n auto input_parser = new InputParser();\n input_parser->run(alm, narg, arg);\n auto run_mode = input_parser->get_run_mode();\n delete input_parser;\n\n if (alm->get_verbosity() > 0) {\n std::cout << \" +-----------------------------------------------------------------+\" << std::endl;\n std::cout << \" + Program ALM +\" << std::endl;\n std::cout << \" + Ver.\";\n std::cout << std::setw(7) << ALAMODE_VERSION;\n std::cout << \" +\" << std::endl;\n std::cout << \" +-----------------------------------------------------------------+\" << std::endl;\n std::cout << std::endl;\n#ifdef _OPENMP\n std::cout << \" Number of OpenMP threads = \"\n << omp_get_max_threads() << std::endl << std::endl;\n#endif\n\n std::cout << \" Job started at \" << alm->timer->DateAndTime() << std::endl;\n }\n\n auto writer = new Writer();\n\n if (alm->get_verbosity() > 0) {\n writer->write_input_vars(alm, run_mode);\n }\n\n alm->init_fc_table();\n\n if (run_mode == \"optimize\") {\n alm->run_optimize();\n if (alm->get_optimizer_control().linear_model == 1 ||\n (alm->get_optimizer_control().linear_model >= 2\n && alm->get_optimizer_control().cross_validation == 0)) {\n writer->writeall(alm);\n }\n } else if (run_mode == \"suggest\") {\n alm->run_suggest();\n writer->write_displacement_pattern(alm);\n }\n delete writer;\n\n if (alm->get_verbosity() > 0) {\n std::cout << std::endl << \" Job finished at \"\n << alm->timer->DateAndTime() << std::endl;\n }\n\n delete alm;\n}\nMinor output formatting\/*\n alm_cui.cpp\n\n Copyright (c) 2014, 2015, 2016 Terumasa Tadano\n\n This file is distributed under the terms of the MIT license.\n Please see the file 'LICENCE.txt' in the root directory\n or http:\/\/opensource.org\/licenses\/mit-license.php for information.\n*\/\n\n#include \"alm_cui.h\"\n#include \"alm.h\"\n#include \"input_parser.h\"\n#include \"timer.h\"\n#include \"version.h\"\n#include \"writer.h\"\n#include \n#include \n\n#ifdef _OPENMP\n\n#include \n\n#endif\n\nusing namespace ALM_NS;\n\nALMCUI::ALMCUI() {}\n\nALMCUI::~ALMCUI() {}\n\nvoid ALMCUI::run(const int narg,\n char **arg) const\n{\n auto alm = new ALM();\n\n \/\/ alm->mode is set herein.\n auto input_parser = new InputParser();\n input_parser->run(alm, narg, arg);\n auto run_mode = input_parser->get_run_mode();\n delete input_parser;\n\n if (alm->get_verbosity() > 0) {\n std::cout << \" +-----------------------------------------------------------------+\" << std::endl;\n std::cout << \" + Program ALM +\" << std::endl;\n std::cout << \" + Ver.\";\n std::cout << std::setw(7) << ALAMODE_VERSION;\n std::cout << \" +\" << std::endl;\n std::cout << \" +-----------------------------------------------------------------+\" << std::endl;\n std::cout << std::endl;\n#ifdef _OPENMP\n std::cout << \" Number of OpenMP threads = \"\n << omp_get_max_threads() << std::endl << std::endl;\n#endif\n\n std::cout << \" Job started at \" << alm->timer->DateAndTime() << std::endl;\n }\n\n auto writer = new Writer();\n\n if (alm->get_verbosity() > 0) {\n writer->write_input_vars(alm, run_mode);\n }\n\n alm->init_fc_table();\n\n if (run_mode == \"optimize\") {\n alm->run_optimize();\n if (alm->get_optimizer_control().linear_model == 1 ||\n (alm->get_optimizer_control().linear_model >= 2\n && alm->get_optimizer_control().cross_validation == 0)) {\n writer->writeall(alm);\n }\n } else if (run_mode == \"suggest\") {\n alm->run_suggest();\n writer->write_displacement_pattern(alm);\n }\n delete writer;\n\n if (alm->get_verbosity() > 0) {\n std::cout << std::endl << \" Job finished at \"\n << alm->timer->DateAndTime() << std::endl;\n }\n\n delete alm;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: KWSys - Kitware System Library\n Module: DynamicLoader.cxx\n\n Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"kwsysPrivate.h\"\n#include KWSYS_HEADER(DynamicLoader.hxx)\n\n#include KWSYS_HEADER(Configure.hxx)\n\n\/\/ Work-around CMake dependency scanning limitation. This must\n\/\/ duplicate the above list of headers.\n#if 0\n# include \"DynamicLoader.hxx.in\"\n# include \"Configure.hxx.in\"\n#endif\n\n\/\/ This file is actually 3 different implementations.\n\/\/ 1. HP machines which uses shl_load\n\/\/ 2. Power PC MAC which uses GetSharedLibrary\n\/\/ 3. Windows which uses LoadLibrary\n\/\/ 4. Most unix systems which use dlopen (default )\n\/\/ Each part of the ifdef contains a complete implementation for\n\/\/ the static methods of DynamicLoader. \n\nnamespace KWSYS_NAMESPACE\n{\n\n\/\/----------------------------------------------------------------------------\nDynamicLoader::DynamicLoader()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoader::~DynamicLoader()\n{\n}\n\n}\n\n\/\/ ---------------------------------------------------------------\n\/\/ 1. Implementation for HPUX machines\n#ifdef __hpux\n#include \n#define DYNAMICLOADER_DEFINED 1\n\nnamespace KWSYS_NAMESPACE\n{\n\n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname )\n{\n return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary(LibHandle lib)\n{\n return !shl_unload(lib);\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction\nDynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)\n{ \n void* addr;\n int status;\n \n status = shl_findsym (&lib, sym, TYPE_PROCEDURE, &addr);\n void* result = (status < 0) ? (void*)0 : addr;\n \n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"lib\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".sl\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n \/\/ TODO: Need implementation with errno\/strerror\n \/* If successful, shl_findsym returns an integer (int) value zero. If \n * shl_findsym cannot find sym, it returns -1 and sets errno to zero. \n * If any other errors occur, shl_findsym returns -1 and sets errno to one \n * of these values (defined in ):\n * ENOEXEC\n * A format error was detected in the specified library.\n * ENOSYM\n * A symbol on which sym depends could not be found.\n * EINVAL\n * The specified handle is invalid.\n *\/\n\n return 0;\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif \/\/__hpux\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ 2. Implementation for Mac OS X 10.2.x and earlier\n#ifdef __APPLE__\n#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030\n#include \n#define DYNAMICLOADER_DEFINED 1\n\nnamespace KWSYS_NAMESPACE\n{\n\n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname )\n{\n NSObjectFileImageReturnCode rc;\n NSObjectFileImage image = 0;\n \n rc = NSCreateObjectFileImageFromFile(libname, &image);\n if(!image)\n {\n return 0;\n }\n return NSLinkModule(image, libname, NSLINKMODULE_OPTION_BINDNOW);\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary( LibHandle lib)\n{\n DYLD_BOOL success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE);\n return success;\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle \/* lib *\/, const char* sym)\n{ \n void *result=0;\n if(NSIsSymbolNameDefined(sym))\n {\n NSSymbol symbol= NSLookupAndBindSymbol(sym);\n if(symbol)\n {\n result = NSAddressOfSymbol(symbol);\n }\n }\n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".dylib\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n return 0;\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif \/\/MAC_OS_X_VERSION_MIN_REQUIRED < 1030\n#endif \/\/ __APPLE__\n\n\/\/ ---------------------------------------------------------------\n\/\/ 3. Implementation for Windows win32 code\n#ifdef _WIN32\n#include \n#define DYNAMICLOADER_DEFINED 1\n\nnamespace KWSYS_NAMESPACE\n{\n \n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname)\n{\n LibHandle lh;\n#ifdef UNICODE\n wchar_t libn[MB_CUR_MAX];\n mbstowcs(libn, libname, MB_CUR_MAX);\n lh = LoadLibrary(libn);\n#else\n lh = LoadLibrary(libname);\n#endif\n return lh;\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary(LibHandle lib)\n{\n return (int)FreeLibrary(lib);\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)\n{ \n void *result;\n#ifdef UNICODE\n wchar_t wsym[MB_CUR_MAX];\n mbstowcs(wsym, sym, MB_CUR_MAX);\n result = GetProcAddress(lib, wsym);\n#else\n result = (void*)GetProcAddress(lib, sym);\n#endif\n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".dll\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n LPVOID lpMsgBuf;\n\n FormatMessage( \n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL,\n GetLastError(),\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ Default language\n (LPTSTR) &lpMsgBuf,\n 0,\n NULL \n );\n \n static char* str = 0;\n delete [] str;\n str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);\n \/\/ Free the buffer.\n LocalFree( lpMsgBuf );\n return str;\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif \/\/_WIN32\n\n\/\/ ---------------------------------------------------------------\n\/\/ 4. Implementation for default UNIX machines.\n\/\/ if nothing has been defined then use this\n#ifndef DYNAMICLOADER_DEFINED\n#define DYNAMICLOADER_DEFINED 1\n\/\/ Setup for most unix machines\n#include \n\nnamespace KWSYS_NAMESPACE\n{\n \n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname )\n{\n return dlopen(libname, RTLD_LAZY);\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary(LibHandle lib)\n{\n if (lib)\n {\n \/\/ The function dlclose() returns 0 on success, and non-zero on error.\n return !(int)dlclose(lib);\n }\n \/\/ else\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)\n{ \n void* result = dlsym(lib, sym);\n \n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"lib\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".so\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n return dlerror(); \n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif\nCOMP: Fix compilation on MacOSX\/*=========================================================================\n\n Program: KWSys - Kitware System Library\n Module: DynamicLoader.cxx\n\n Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"kwsysPrivate.h\"\n#include KWSYS_HEADER(DynamicLoader.hxx)\n\n#include KWSYS_HEADER(Configure.hxx)\n\n\/\/ Work-around CMake dependency scanning limitation. This must\n\/\/ duplicate the above list of headers.\n#if 0\n# include \"DynamicLoader.hxx.in\"\n# include \"Configure.hxx.in\"\n#endif\n\n\/\/ This file is actually 3 different implementations.\n\/\/ 1. HP machines which uses shl_load\n\/\/ 2. Power PC MAC which uses GetSharedLibrary\n\/\/ 3. Windows which uses LoadLibrary\n\/\/ 4. Most unix systems which use dlopen (default )\n\/\/ Each part of the ifdef contains a complete implementation for\n\/\/ the static methods of DynamicLoader. \n\nnamespace KWSYS_NAMESPACE\n{\n\n\/\/----------------------------------------------------------------------------\nDynamicLoader::DynamicLoader()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoader::~DynamicLoader()\n{\n}\n\n}\n\n\/\/ ---------------------------------------------------------------\n\/\/ 1. Implementation for HPUX machines\n#ifdef __hpux\n#include \n#define DYNAMICLOADER_DEFINED 1\n\nnamespace KWSYS_NAMESPACE\n{\n\n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname )\n{\n return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary(LibHandle lib)\n{\n return !shl_unload(lib);\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction\nDynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)\n{ \n void* addr;\n int status;\n \n status = shl_findsym (&lib, sym, TYPE_PROCEDURE, &addr);\n void* result = (status < 0) ? (void*)0 : addr;\n \n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"lib\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".sl\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n \/\/ TODO: Need implementation with errno\/strerror\n \/* If successful, shl_findsym returns an integer (int) value zero. If \n * shl_findsym cannot find sym, it returns -1 and sets errno to zero. \n * If any other errors occur, shl_findsym returns -1 and sets errno to one \n * of these values (defined in ):\n * ENOEXEC\n * A format error was detected in the specified library.\n * ENOSYM\n * A symbol on which sym depends could not be found.\n * EINVAL\n * The specified handle is invalid.\n *\/\n\n return 0;\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif \/\/__hpux\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ 2. Implementation for Mac OS X 10.2.x and earlier\n#ifdef __APPLE__\n#if MAC_OS_X_VERSION_MIN_REQUIRED < 1030\n#include \n#define DYNAMICLOADER_DEFINED 1\n\nnamespace KWSYS_NAMESPACE\n{\n\n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname )\n{\n NSObjectFileImageReturnCode rc;\n NSObjectFileImage image = 0;\n \n rc = NSCreateObjectFileImageFromFile(libname, &image);\n if(!image)\n {\n return 0;\n }\n return NSLinkModule(image, libname, NSLINKMODULE_OPTION_BINDNOW);\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary( LibHandle lib)\n{\n bool success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE);\n return success;\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle \/* lib *\/, const char* sym)\n{ \n void *result=0;\n if(NSIsSymbolNameDefined(sym))\n {\n NSSymbol symbol= NSLookupAndBindSymbol(sym);\n if(symbol)\n {\n result = NSAddressOfSymbol(symbol);\n }\n }\n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".dylib\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n return 0;\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif \/\/MAC_OS_X_VERSION_MIN_REQUIRED < 1030\n#endif \/\/ __APPLE__\n\n\/\/ ---------------------------------------------------------------\n\/\/ 3. Implementation for Windows win32 code\n#ifdef _WIN32\n#include \n#define DYNAMICLOADER_DEFINED 1\n\nnamespace KWSYS_NAMESPACE\n{\n \n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname)\n{\n LibHandle lh;\n#ifdef UNICODE\n wchar_t libn[MB_CUR_MAX];\n mbstowcs(libn, libname, MB_CUR_MAX);\n lh = LoadLibrary(libn);\n#else\n lh = LoadLibrary(libname);\n#endif\n return lh;\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary(LibHandle lib)\n{\n return (int)FreeLibrary(lib);\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)\n{ \n void *result;\n#ifdef UNICODE\n wchar_t wsym[MB_CUR_MAX];\n mbstowcs(wsym, sym, MB_CUR_MAX);\n result = GetProcAddress(lib, wsym);\n#else\n result = (void*)GetProcAddress(lib, sym);\n#endif\n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".dll\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n LPVOID lpMsgBuf;\n\n FormatMessage( \n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n NULL,\n GetLastError(),\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ Default language\n (LPTSTR) &lpMsgBuf,\n 0,\n NULL \n );\n \n static char* str = 0;\n delete [] str;\n str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);\n \/\/ Free the buffer.\n LocalFree( lpMsgBuf );\n return str;\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif \/\/_WIN32\n\n\/\/ ---------------------------------------------------------------\n\/\/ 4. Implementation for default UNIX machines.\n\/\/ if nothing has been defined then use this\n#ifndef DYNAMICLOADER_DEFINED\n#define DYNAMICLOADER_DEFINED 1\n\/\/ Setup for most unix machines\n#include \n\nnamespace KWSYS_NAMESPACE\n{\n \n\/\/----------------------------------------------------------------------------\nLibHandle DynamicLoader::OpenLibrary(const char* libname )\n{\n return dlopen(libname, RTLD_LAZY);\n}\n\n\/\/----------------------------------------------------------------------------\nint DynamicLoader::CloseLibrary(LibHandle lib)\n{\n if (lib)\n {\n \/\/ The function dlclose() returns 0 on success, and non-zero on error.\n return !(int)dlclose(lib);\n }\n \/\/ else\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nDynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym)\n{ \n void* result = dlsym(lib, sym);\n \n \/\/ Hack to cast pointer-to-data to pointer-to-function.\n return *reinterpret_cast(&result);\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibPrefix()\n{ \n return \"lib\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LibExtension()\n{\n return \".so\";\n}\n\n\/\/----------------------------------------------------------------------------\nconst char* DynamicLoader::LastError()\n{\n return dlerror(); \n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Terminal.cpp -- source file\n\/*\n *\n * Author: septimomend (Ivan Chapkailo)\n *\n * 30.06.2017\n *\n *\/\n\n#include \"stdafx.h\"\n#include \"Terminal.h\"\n\nTerminal::Terminal() \/\/ cstr\n{\n}\n\nvoid Terminal::emergencyDestruction(const char* str)\n{\n write(STDOUT_FILENO, \"\\x1b[2J\", 4); \/\/ write clr code to file\n write(STDOUT_FILENO, \"\\x1b[H\", 3);\n\n perror(str);\n exit(1); \/\/ exit with error\n}\n\nvoid Terminal::rowModeOff()\n{\n \/\/ the change will occur after all output written to STDIN_FILENO is transmitted,\n \/\/ and all input so far received but not read will be discarded before the change is made\n if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &configObj.baseTermiosObj) == -1)\n emergencyDestruction(\"tcsetattr\");\n}\n\nvoid Terminal::rowModeOn()\n{\n if (tcgetattr(STDIN_FILENO, &configObj.baseTermiosObj) == -1)\n emergencyDestruction(\"tcgetattr\");\n atexit(rowModeOff);\n\n struct termios raw = configObj.baseTermiosObj;\n \/\/ setting flags\n \/\/\n raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);\n raw.c_oflag &= ~(OPOST); \/\/ Post-process output\n raw.c_cflag |= (CS8); \/\/ Character size 8 bits\n raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n raw.c_cc[VMIN] = 0;\n raw.c_cc[VTIME] = 1;\n}\n\nint Terminal::whatKey() \/\/ defines key pressing\n{\n \/\/ TODO\n}\n\nint Terminal::getCursorPosition(int *row, int *column) \/\/ returns cursor position\n{\n \/\/ TODO\n}\n\nint Terminal::getWindowSize(int *row, int *column) \/\/ returns size of window\n{\n \/\/ TODO\n}\nfixed inheritance errors\/\/ Terminal.cpp -- source file\n\/*\n *\n * Author: septimomend (Ivan Chapkailo)\n *\n * 30.06.2017\n *\n *\/\n\n#include \"stdafx.h\"\n#include \"Terminal.h\"\n\nTerminal::Terminal() \/\/ cstr\n{\n}\n\nvoid Terminal::emergencyDestruction(const char* str)\n{\n write(STDOUT_FILENO, \"\\x1b[2J\", 4); \/\/ write clr code to file\n write(STDOUT_FILENO, \"\\x1b[H\", 3);\n\n perror(str);\n exit(1); \/\/ exit with error\n}\n\nvoid Terminal::rowModeOff()\n{\n AllControllers all;\n ConfigurationController* configObj = all.getConfigObj();\n struct termios* termObj = configObj->getTermios();\n\n \/\/ the change will occur after all output written to STDIN_FILENO is transmitted,\n \/\/ and all input so far received but not read will be discarded before the change is made\n if (tcsetattr(STDIN_FILENO, TCSAFLUSH, termObj) == -1)\n emergencyDestruction(\"tcsetattr\");\n}\n\nvoid Terminal::rowModeOn()\n{\n AllControllers all;\n ConfigurationController* configObj = all.getConfigObj();\n struct termios* termObj = configObj->getTermios();\n\n if (tcgetattr(STDIN_FILENO, termObj) == -1)\n emergencyDestruction(\"tcgetattr\");\n atexit(rowModeOff);\n\n struct termios raw = *termObj;\n \/\/ setting flags\n \/\/\n raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);\n raw.c_oflag &= ~(OPOST); \/\/ Post-process output\n raw.c_cflag |= (CS8); \/\/ Character size 8 bits\n raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);\n raw.c_cc[VMIN] = 0;\n raw.c_cc[VTIME] = 1;\n}\n\nint Terminal::whatKey() \/\/ defines key pressing\n{\n \/\/ TODO\n}\n\nint Terminal::getCursorPosition(int *row, int *column) \/\/ returns cursor position\n{\n \/\/ TODO\n}\n\nint Terminal::getWindowSize(int *row, int *column) \/\/ returns size of window\n{\n \/\/ TODO\n}\n<|endoftext|>"} {"text":"SIMD componentProduct<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"exceptions\/exceptions.hh\"\n\nenum class compressor {\n none,\n lz4,\n snappy,\n deflate,\n};\n\nclass compression_parameters {\npublic:\n static constexpr int32_t DEFAULT_CHUNK_LENGTH = 64 * 1024;\n static constexpr double DEFAULT_CRC_CHECK_CHANCE = 1.0;\n\n static constexpr auto SSTABLE_COMPRESSION = \"sstable_compression\";\n static constexpr auto CHUNK_LENGTH_KB = \"chunk_length_kb\";\n static constexpr auto CRC_CHECK_CHANCE = \"crc_check_chance\";\nprivate:\n compressor _compressor = compressor::none;\n int _chunk_length = DEFAULT_CHUNK_LENGTH;\n double _crc_check_chance = DEFAULT_CRC_CHECK_CHANCE;\npublic:\n compression_parameters() = default;\n compression_parameters(compressor c) : _compressor(c) { }\n compression_parameters(const std::map& options) {\n validate_options(options);\n\n const auto& compressor_class = options.at(SSTABLE_COMPRESSION);\n if (compressor_class == \"LZ4Compressor\") {\n _compressor = compressor::lz4;\n } else if (compressor_class == \"SnappyCompressor\") {\n _compressor = compressor::snappy;\n } else if (compressor_class == \"DeflateCompressor\") {\n _compressor = compressor::deflate;\n } else {\n throw exceptions::configuration_exception(sstring(\"Unsupported compression class '\") + compressor_class + \"'.\");\n }\n auto chunk_length = options.find(CHUNK_LENGTH_KB);\n if (chunk_length != options.end()) {\n try {\n _chunk_length = std::stoi(chunk_length->second) * 1024;\n } catch (const std::exception& e) {\n throw exceptions::syntax_exception(sstring(\"Invalid integer value \") + chunk_length->second + \" for \" + CHUNK_LENGTH_KB);\n }\n }\n auto crc_chance = options.find(CRC_CHECK_CHANCE);\n if (crc_chance != options.end()) {\n try {\n _crc_check_chance = std::stod(crc_chance->second);\n } catch (const std::exception& e) {\n throw exceptions::syntax_exception(sstring(\"Invalid double value \") + crc_chance->second + \"for \" + CRC_CHECK_CHANCE);\n }\n }\n }\n\n compressor get_compressor() const { return _compressor; }\n int32_t chunk_length() const { return _chunk_length; }\n double crc_check_chance() const { return _crc_check_chance; }\n\n void validate() {\n if (_chunk_length <= 0) {\n throw exceptions::configuration_exception(sstring(\"Invalid negative or null \") + CHUNK_LENGTH_KB);\n }\n \/\/ _chunk_length must be a power of two\n if (_chunk_length & (_chunk_length - 1)) {\n throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + \" must be a power of 2.\");\n }\n if (_crc_check_chance < 0.0 || _crc_check_chance > 1.0) {\n throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + \" must be between 0.0 and 1.0.\");\n }\n }\nprivate:\n void validate_options(const std::map& options) {\n \/\/ currently, there are no options specific to a particular compressor\n static std::set keywords({\n sstring(SSTABLE_COMPRESSION),\n sstring(CHUNK_LENGTH_KB),\n sstring(CRC_CHECK_CHANCE),\n });\n for (auto&& opt : options) {\n if (!keywords.count(opt.first)) {\n throw exceptions::configuration_exception(sprint(\"Unknown compression option '%s'.\", opt.first));\n }\n }\n }\n};\ncompress: accept both qualified and unqualified class names\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"exceptions\/exceptions.hh\"\n\nenum class compressor {\n none,\n lz4,\n snappy,\n deflate,\n};\n\nclass compression_parameters {\npublic:\n static constexpr int32_t DEFAULT_CHUNK_LENGTH = 64 * 1024;\n static constexpr double DEFAULT_CRC_CHECK_CHANCE = 1.0;\n\n static constexpr auto SSTABLE_COMPRESSION = \"sstable_compression\";\n static constexpr auto CHUNK_LENGTH_KB = \"chunk_length_kb\";\n static constexpr auto CRC_CHECK_CHANCE = \"crc_check_chance\";\nprivate:\n compressor _compressor = compressor::none;\n int _chunk_length = DEFAULT_CHUNK_LENGTH;\n double _crc_check_chance = DEFAULT_CRC_CHECK_CHANCE;\npublic:\n compression_parameters() = default;\n compression_parameters(compressor c) : _compressor(c) { }\n compression_parameters(const std::map& options) {\n validate_options(options);\n\n const auto& compressor_class = options.at(SSTABLE_COMPRESSION);\n if (is_compressor_class(compressor_class, \"LZ4Compressor\")) {\n _compressor = compressor::lz4;\n } else if (is_compressor_class(compressor_class, \"SnappyCompressor\")) {\n _compressor = compressor::snappy;\n } else if (is_compressor_class(compressor_class, \"DeflateCompressor\")) {\n _compressor = compressor::deflate;\n } else {\n throw exceptions::configuration_exception(sstring(\"Unsupported compression class '\") + compressor_class + \"'.\");\n }\n auto chunk_length = options.find(CHUNK_LENGTH_KB);\n if (chunk_length != options.end()) {\n try {\n _chunk_length = std::stoi(chunk_length->second) * 1024;\n } catch (const std::exception& e) {\n throw exceptions::syntax_exception(sstring(\"Invalid integer value \") + chunk_length->second + \" for \" + CHUNK_LENGTH_KB);\n }\n }\n auto crc_chance = options.find(CRC_CHECK_CHANCE);\n if (crc_chance != options.end()) {\n try {\n _crc_check_chance = std::stod(crc_chance->second);\n } catch (const std::exception& e) {\n throw exceptions::syntax_exception(sstring(\"Invalid double value \") + crc_chance->second + \"for \" + CRC_CHECK_CHANCE);\n }\n }\n }\n\n compressor get_compressor() const { return _compressor; }\n int32_t chunk_length() const { return _chunk_length; }\n double crc_check_chance() const { return _crc_check_chance; }\n\n void validate() {\n if (_chunk_length <= 0) {\n throw exceptions::configuration_exception(sstring(\"Invalid negative or null \") + CHUNK_LENGTH_KB);\n }\n \/\/ _chunk_length must be a power of two\n if (_chunk_length & (_chunk_length - 1)) {\n throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + \" must be a power of 2.\");\n }\n if (_crc_check_chance < 0.0 || _crc_check_chance > 1.0) {\n throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + \" must be between 0.0 and 1.0.\");\n }\n }\nprivate:\n void validate_options(const std::map& options) {\n \/\/ currently, there are no options specific to a particular compressor\n static std::set keywords({\n sstring(SSTABLE_COMPRESSION),\n sstring(CHUNK_LENGTH_KB),\n sstring(CRC_CHECK_CHANCE),\n });\n for (auto&& opt : options) {\n if (!keywords.count(opt.first)) {\n throw exceptions::configuration_exception(sprint(\"Unknown compression option '%s'.\", opt.first));\n }\n }\n }\n bool is_compressor_class(const sstring& value, const sstring& class_name) {\n static const sstring namespace_prefix = \"org.apache.cassandra.io.compress.\";\n return value == class_name || value == namespace_prefix + class_name;\n }\n};\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 Vicente Romero Calero\n\/\/\n\/\/ Distributed under the MIT software license, see the file LICENSE\n\/\/\n\/\/ Author: Vicente Romero \n\n#include \"compress.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"bpe.h\"\n#include \"endian.h\"\n\nusing namespace std;\n\nstruct BytePairOccurs\n{\n uint8_t byte1;\n uint8_t byte2;\n int occurs;\n};\n\nextern Config config;\n\nstatic void replaceBytes(\n uint8_t byte,\n uint8_t bytepair1,\n uint8_t bytepair2,\n list &byte_block,\n vector > &byte_pairs,\n BytePairOccurs &best_byte_pair)\n{\n list::iterator it1 = byte_block.begin();\n list::iterator it2 = next(it1);\n list::iterator prev_it, next_it;\n\n best_byte_pair.occurs = 0;\n\n while(it2 != byte_block.end())\n {\n if((*it1 == bytepair1) && (*it2 == bytepair2))\n {\n \/\/ Update byte pairs\n prev_it = prev(it1);\n next_it = next(it2);\n\n --byte_pairs[bytepair1][bytepair2];\n\n if(prev_it != byte_block.end())\n {\n --byte_pairs[*prev_it][bytepair1];\n int occurs = ++byte_pairs[*prev_it][byte];\n if(occurs > best_byte_pair.occurs)\n {\n best_byte_pair.byte1 = *prev_it;\n best_byte_pair.byte2 = byte;\n best_byte_pair.occurs = occurs;\n }\n }\n\n if(next_it != byte_block.end())\n {\n --byte_pairs[bytepair2][*next_it];\n int occurs = ++byte_pairs[byte][*next_it];\n if(occurs > best_byte_pair.occurs)\n {\n best_byte_pair.byte1 = byte;\n best_byte_pair.byte2 = *next_it;\n best_byte_pair.occurs = occurs;\n }\n }\n\n \/\/ Perform the replacement\n it1 = byte_block.erase(it1, next_it);\n byte_block.insert(it1, byte);\n\n it2 = next(it1);\n }\n else\n {\n ++it1;\n ++it2;\n }\n }\n}\n\nstatic void compressBlock(\n uint8_t *buffer,\n int len,\n list &byte_block,\n vector > &dictionary)\n{\n unordered_set unused_bytes;\n unordered_set::iterator it_set;\n vector > byte_pairs(256, vector(256, 0));\n BytePairOccurs best_byte_pair;\n uint8_t byte;\n\n best_byte_pair.byte1 = 0;\n best_byte_pair.byte2 = 0;\n best_byte_pair.occurs = 0;\n\n for(int i=0; i<256; ++i)\n unused_bytes.emplace(i);\n\n for(int i=0; i best_byte_pair.occurs)\n {\n best_byte_pair.byte1 = buffer[i];\n best_byte_pair.byte2 = buffer[i + 1];\n best_byte_pair.occurs = occurs;\n }\n }\n }\n\n while(!unused_bytes.empty())\n {\n if(best_byte_pair.occurs < 4)\n break;\n\n it_set = unused_bytes.begin();\n byte = *it_set;\n\n dictionary.push_back(make_pair(byte, (best_byte_pair.byte1 << 8) | best_byte_pair.byte2));\n\n replaceBytes(\n byte,\n best_byte_pair.byte1,\n best_byte_pair.byte2,\n byte_block,\n byte_pairs,\n best_byte_pair);\n\n unused_bytes.erase(it_set);\n }\n}\n\nstatic int writeBlock(\n FILE *outfile,\n const list &byte_block,\n const vector > &dictionary)\n{\n uint8_t dict_size = dictionary.size();\n uint16_t data_size = byte_block.size();\n uint8_t buffer[data_size];\n int block_size = 3 + 3 * dict_size + data_size;\n\n fwrite(&dict_size, 1, 1, outfile);\n\n for(int i=dict_size-1; i>=0; --i)\n {\n fwrite(&(dictionary[i].first), 1, 1, outfile);\n fwrite16(dictionary[i].second, outfile);\n }\n\n fwrite16(data_size, outfile);\n\n copy(byte_block.begin(), byte_block.end(), buffer);\n fwrite(buffer, 1, data_size, outfile);\n\n return block_size;\n}\n\nvoid compress()\n{\n int num_blocks = 0;\n uint8_t buffer[config.block_size];\n size_t read_size;\n long long total_size=0, total_compressed_size=0;\n\n FILE *infile = fopen(config.infile, \"rb\");\n if(infile == NULL)\n {\n perror(config.infile);\n exit(1);\n }\n\n FILE *outfile = NULL;\n if(config.stdout_opt)\n {\n outfile = stdout;\n }\n else\n {\n outfile = fopen(config.outfile, \"wb\");\n if(outfile == NULL)\n {\n perror(config.outfile);\n exit(1);\n }\n }\n\n do\n {\n read_size = fread(buffer, sizeof(uint8_t), config.block_size, infile);\n total_size += read_size;\n\n list byte_block;\n vector > dictionary;\n compressBlock(buffer, read_size, byte_block, dictionary);\n\n total_compressed_size += writeBlock(outfile, byte_block, dictionary);\n\n num_blocks++;\n\n } while(!feof(infile));\n\n if(config.verbose_opt)\n {\n double reduction = (total_size - total_compressed_size) \/ (double)total_size;\n fprintf(stderr, \"Reduction: %.2f%%\\n\", reduction * 100.0);\n }\n\n fclose(infile);\n\n if(!config.stdout_opt)\n {\n fclose(outfile);\n\n remove(config.infile);\n }\n}\ndeleted unused variable\/\/ Copyright (c) 2014 Vicente Romero Calero\n\/\/\n\/\/ Distributed under the MIT software license, see the file LICENSE\n\/\/\n\/\/ Author: Vicente Romero \n\n#include \"compress.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"bpe.h\"\n#include \"endian.h\"\n\nusing namespace std;\n\nstruct BytePairOccurs\n{\n uint8_t byte1;\n uint8_t byte2;\n int occurs;\n};\n\nextern Config config;\n\nstatic void replaceBytes(\n uint8_t byte,\n uint8_t bytepair1,\n uint8_t bytepair2,\n list &byte_block,\n vector > &byte_pairs,\n BytePairOccurs &best_byte_pair)\n{\n list::iterator it1 = byte_block.begin();\n list::iterator it2 = next(it1);\n list::iterator prev_it, next_it;\n\n best_byte_pair.occurs = 0;\n\n while(it2 != byte_block.end())\n {\n if((*it1 == bytepair1) && (*it2 == bytepair2))\n {\n \/\/ Update byte pairs\n prev_it = prev(it1);\n next_it = next(it2);\n\n --byte_pairs[bytepair1][bytepair2];\n\n if(prev_it != byte_block.end())\n {\n --byte_pairs[*prev_it][bytepair1];\n int occurs = ++byte_pairs[*prev_it][byte];\n if(occurs > best_byte_pair.occurs)\n {\n best_byte_pair.byte1 = *prev_it;\n best_byte_pair.byte2 = byte;\n best_byte_pair.occurs = occurs;\n }\n }\n\n if(next_it != byte_block.end())\n {\n --byte_pairs[bytepair2][*next_it];\n int occurs = ++byte_pairs[byte][*next_it];\n if(occurs > best_byte_pair.occurs)\n {\n best_byte_pair.byte1 = byte;\n best_byte_pair.byte2 = *next_it;\n best_byte_pair.occurs = occurs;\n }\n }\n\n \/\/ Perform the replacement\n it1 = byte_block.erase(it1, next_it);\n byte_block.insert(it1, byte);\n\n it2 = next(it1);\n }\n else\n {\n ++it1;\n ++it2;\n }\n }\n}\n\nstatic void compressBlock(\n uint8_t *buffer,\n int len,\n list &byte_block,\n vector > &dictionary)\n{\n unordered_set unused_bytes;\n unordered_set::iterator it_set;\n vector > byte_pairs(256, vector(256, 0));\n BytePairOccurs best_byte_pair;\n uint8_t byte;\n\n best_byte_pair.byte1 = 0;\n best_byte_pair.byte2 = 0;\n best_byte_pair.occurs = 0;\n\n for(int i=0; i<256; ++i)\n unused_bytes.emplace(i);\n\n for(int i=0; i best_byte_pair.occurs)\n {\n best_byte_pair.byte1 = buffer[i];\n best_byte_pair.byte2 = buffer[i + 1];\n best_byte_pair.occurs = occurs;\n }\n }\n }\n\n while(!unused_bytes.empty())\n {\n if(best_byte_pair.occurs < 4)\n break;\n\n it_set = unused_bytes.begin();\n byte = *it_set;\n\n dictionary.push_back(make_pair(byte, (best_byte_pair.byte1 << 8) | best_byte_pair.byte2));\n\n replaceBytes(\n byte,\n best_byte_pair.byte1,\n best_byte_pair.byte2,\n byte_block,\n byte_pairs,\n best_byte_pair);\n\n unused_bytes.erase(it_set);\n }\n}\n\nstatic int writeBlock(\n FILE *outfile,\n const list &byte_block,\n const vector > &dictionary)\n{\n uint8_t dict_size = dictionary.size();\n uint16_t data_size = byte_block.size();\n uint8_t buffer[data_size];\n int block_size = 3 + 3 * dict_size + data_size;\n\n fwrite(&dict_size, 1, 1, outfile);\n\n for(int i=dict_size-1; i>=0; --i)\n {\n fwrite(&(dictionary[i].first), 1, 1, outfile);\n fwrite16(dictionary[i].second, outfile);\n }\n\n fwrite16(data_size, outfile);\n\n copy(byte_block.begin(), byte_block.end(), buffer);\n fwrite(buffer, 1, data_size, outfile);\n\n return block_size;\n}\n\nvoid compress()\n{\n uint8_t buffer[config.block_size];\n size_t read_size;\n long long total_size=0, total_compressed_size=0;\n\n FILE *infile = fopen(config.infile, \"rb\");\n if(infile == NULL)\n {\n perror(config.infile);\n exit(1);\n }\n\n FILE *outfile = NULL;\n if(config.stdout_opt)\n {\n outfile = stdout;\n }\n else\n {\n outfile = fopen(config.outfile, \"wb\");\n if(outfile == NULL)\n {\n perror(config.outfile);\n exit(1);\n }\n }\n\n do\n {\n read_size = fread(buffer, sizeof(uint8_t), config.block_size, infile);\n total_size += read_size;\n\n list byte_block;\n vector > dictionary;\n compressBlock(buffer, read_size, byte_block, dictionary);\n\n total_compressed_size += writeBlock(outfile, byte_block, dictionary);\n\n } while(!feof(infile));\n\n if(config.verbose_opt)\n {\n double reduction = (total_size - total_compressed_size) \/ (double)total_size;\n fprintf(stderr, \"Reduction: %.2f%%\\n\", reduction * 100.0);\n }\n\n fclose(infile);\n\n if(!config.stdout_opt)\n {\n fclose(outfile);\n\n remove(config.infile);\n }\n}\n<|endoftext|>"} {"text":"\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2005 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n#ifndef GEOMETRY_HH\n#define GEOMETRY_HH\n\n#include \"vertex_vector.hh\"\n#include \"vertex_transform.hh\"\n#include \"ctrans.hh\"\n#include \"ptr.hh\"\n\nnamespace mapnik\n{\n enum {\n \tPoint = 1,\n \tLineString = 2,\n \tPolygon = 3,\n };\n \n template class Container=vertex_vector>\n class geometry\n { \n public:\n\ttypedef T vertex_type;\n\ttypedef typename vertex_type::type value_type;\n\ttypedef Container container_type;\n private:\n\tint srid_;\n\tmutable unsigned itr_;\n protected:\n\tcontainer_type cont_;\n public:\n\tgeometry (int srid=-1)\n\t : srid_(srid),\n\t itr_(0),\n\t cont_() {}\t\n\t\n\tvirtual int type() const=0;\n\t\n\tvirtual bool hit_test(value_type x,value_type y) const=0;\n\t\n\tint srid() const\n\t{\n\t return srid_;\n\t}\n\t\n\tvoid move_to(value_type x,value_type y)\n\t{\n\t cont_.push_back(x,y,SEG_MOVETO);\n\t}\n\n\tvoid line_to(value_type x,value_type y)\n\t{\n\t cont_.push_back(x,y,SEG_LINETO);\n\t}\n\t\n\t\/\/unsigned vertex(double* x, double* y)\n\t\/\/\t{\n\t\/\/ return cont_.get_vertex(itr_++,x,y);\n\t\/\/\t}\n\t\n\t\/\/void rewind(unsigned )\n\t\/\/\t{\n\t\/\/ itr_=0;\n\t\/\/\t}\n\ttemplate \n\tclass path_iterator\n\t{\n\t typedef vertex vertex_type;\n\t const container_type* cont_;\n\t unsigned pos_;\n\t unsigned cmd_;\n\t vertex_type vertex_; \n\t \n\tprivate:\n\n\t void advance () \n\t {\n\t\tif (pos_ < cont_->size())\n\t\t{\n\t\t value_type x,y;\n\t\t vertex_.cmd=cont_->get_vertex(pos_,&x,&y);\n\t\t vertex_.x=Transform::apply(x);\n\t\t vertex_.y=Transform::apply(y);\n\t\t}\n\t\telse \n\t\t{\n\t\t vertex_.cmd=SEG_END;\n\t\t vertex_.x=0;\n\t\t vertex_.y=0;\n\t\t}\n\t\t++pos_;\n\t } \n\n\tpublic:\n\n\t path_iterator()\n\t\t: cont_(0),\n\t\t pos_(0),\n\t\t cmd_(SEG_END),\n\t\t vertex_(0,0,cmd_) {}\n\n\t explicit path_iterator(const container_type& cont)\n\t\t: cont_(&cont),\n\t\t pos_(0),\n\t\t cmd_(SEG_MOVETO),\n\t\t vertex_(0,0,cmd_)\n\t {\n\t\tadvance();\n\t }\n\n\t path_iterator& operator++()\n\t {\n\t\tadvance();\n\t\treturn *this;\n\t }\n\t \n\t const vertex_type& operator*() const\n\t {\n\t\treturn vertex_;\n\t }\n\t \n\t const vertex_type* operator->() const\n\t {\n\t\treturn &vertex_;\n\t }\n\t \n\t bool operator !=(const path_iterator& itr)\n\t {\n\t\treturn vertex_.cmd !=itr.vertex_.cmd;\n\t }\n\t};\n\t\n\ttemplate \n\tpath_iterator begin() const \n\t{\n\t return path_iterator(cont_);\n\t}\n\t\n\ttemplate \n\tpath_iterator end() const \n\t{\n\t return path_iterator();\n\t}\n\n\tvoid transform(const mapnik::CoordTransform& t)\n\t{\n\t for (unsigned pos=0;pos class Container=vertex_vector>\n class point : public geometry\n {\n\ttypedef typename geometry::value_type value_type;\n\tusing geometry::cont_;\n public:\n\tpoint(int srid)\n\t : geometry(srid)\n\t{}\n\t \n\tint type() const \n\t{\n\t return Point;\n\t}\n\tbool hit_test(value_type x,value_type y) const\n\t{\n\t return point_on_points(x,y,*this);\n\t}\n };\n\n template class Container=vertex_vector>\n class polygon : public geometry\n {\n\ttypedef geometry geometry_base;\n\ttypedef typename geometry_base::value_type value_type;\n\ttypedef typename geometry_base::template path_iterator path_iterator;\n public:\n\tpolygon(int srid)\n\t : geometry_base(srid)\n\t{}\n\n\tint type() const \n\t{\n\t return Polygon;\n\t}\n\t\n\tbool hit_test(value_type x,value_type y) const\n\t{\t \n\t path_iterator start = geometry_base::template begin();\n\t path_iterator end = geometry_base::template end();\n\t return point_inside_path(start,end,x,y);\n\t} \n };\n \n template class Container=vertex_vector>\n class line_string : public geometry\n {\n\ttypedef typename geometry::value_type value_type; \n public:\n\tline_string(int srid)\n\t : geometry(srid)\n\t{}\n\t\n\tint type() const \n\t{\n\t return LineString;\n\t}\n\t\n\tbool hit_test(value_type x,value_type y) const\n\t{\n\t return point_on_path(x,y,*this);\n\t}\n };\n\n typedef point point_impl;\n typedef line_string line_string_impl;\n typedef polygon polygon_impl;\n \n typedef geometry geometry_type;\n typedef ref_ptr geometry_ptr;\n}\n\n#endif \/\/GEOMETRY_HH\nmoved typedef typename geometry_base::template path_iterator path_iterator\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2005 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n#ifndef GEOMETRY_HH\n#define GEOMETRY_HH\n\n#include \"vertex_vector.hh\"\n#include \"vertex_transform.hh\"\n#include \"ctrans.hh\"\n#include \"ptr.hh\"\n\nnamespace mapnik\n{\n enum {\n \tPoint = 1,\n \tLineString = 2,\n \tPolygon = 3,\n };\n \n template class Container=vertex_vector>\n class geometry\n { \n public:\n\ttypedef T vertex_type;\n\ttypedef typename vertex_type::type value_type;\n\ttypedef Container container_type;\n private:\n\tint srid_;\n\tmutable unsigned itr_;\n protected:\n\tcontainer_type cont_;\n public:\n\tgeometry (int srid=-1)\n\t : srid_(srid),\n\t itr_(0),\n\t cont_() {}\t\n\t\n\tvirtual int type() const=0;\n\t\n\tvirtual bool hit_test(value_type x,value_type y) const=0;\n\t\n\tint srid() const\n\t{\n\t return srid_;\n\t}\n\t\n\tvoid move_to(value_type x,value_type y)\n\t{\n\t cont_.push_back(x,y,SEG_MOVETO);\n\t}\n\n\tvoid line_to(value_type x,value_type y)\n\t{\n\t cont_.push_back(x,y,SEG_LINETO);\n\t}\n\t\n\t\/\/unsigned vertex(double* x, double* y)\n\t\/\/\t{\n\t\/\/ return cont_.get_vertex(itr_++,x,y);\n\t\/\/\t}\n\t\n\t\/\/void rewind(unsigned )\n\t\/\/\t{\n\t\/\/ itr_=0;\n\t\/\/\t}\n\ttemplate \n\tclass path_iterator\n\t{\n\t typedef vertex vertex_type;\n\t const container_type* cont_;\n\t unsigned pos_;\n\t unsigned cmd_;\n\t vertex_type vertex_; \n\t \n\tprivate:\n\n\t void advance () \n\t {\n\t\tif (pos_ < cont_->size())\n\t\t{\n\t\t value_type x,y;\n\t\t vertex_.cmd=cont_->get_vertex(pos_,&x,&y);\n\t\t vertex_.x=Transform::apply(x);\n\t\t vertex_.y=Transform::apply(y);\n\t\t}\n\t\telse \n\t\t{\n\t\t vertex_.cmd=SEG_END;\n\t\t vertex_.x=0;\n\t\t vertex_.y=0;\n\t\t}\n\t\t++pos_;\n\t } \n\n\tpublic:\n\n\t path_iterator()\n\t\t: cont_(0),\n\t\t pos_(0),\n\t\t cmd_(SEG_END),\n\t\t vertex_(0,0,cmd_) {}\n\n\t explicit path_iterator(const container_type& cont)\n\t\t: cont_(&cont),\n\t\t pos_(0),\n\t\t cmd_(SEG_MOVETO),\n\t\t vertex_(0,0,cmd_)\n\t {\n\t\tadvance();\n\t }\n\n\t path_iterator& operator++()\n\t {\n\t\tadvance();\n\t\treturn *this;\n\t }\n\t \n\t const vertex_type& operator*() const\n\t {\n\t\treturn vertex_;\n\t }\n\t \n\t const vertex_type* operator->() const\n\t {\n\t\treturn &vertex_;\n\t }\n\t \n\t bool operator !=(const path_iterator& itr)\n\t {\n\t\treturn vertex_.cmd !=itr.vertex_.cmd;\n\t }\n\t};\n\t\n\ttemplate \n\tpath_iterator begin() const \n\t{\n\t return path_iterator(cont_);\n\t}\n\t\n\ttemplate \n\tpath_iterator end() const \n\t{\n\t return path_iterator();\n\t}\n\n\tvoid transform(const mapnik::CoordTransform& t)\n\t{\n\t for (unsigned pos=0;pos class Container=vertex_vector>\n class point : public geometry\n {\n\ttypedef typename geometry::value_type value_type;\n\tusing geometry::cont_;\n public:\n\tpoint(int srid)\n\t : geometry(srid)\n\t{}\n\t \n\tint type() const \n\t{\n\t return Point;\n\t}\n\tbool hit_test(value_type x,value_type y) const\n\t{\n\t return point_on_points(x,y,*this);\n\t}\n };\n\n template class Container=vertex_vector>\n class polygon : public geometry\n {\n\ttypedef geometry geometry_base;\n\ttypedef typename geometry_base::value_type value_type;\n\t\n public:\n\tpolygon(int srid)\n\t : geometry_base(srid)\n\t{}\n\n\tint type() const \n\t{\n\t return Polygon;\n\t}\n\t\n\tbool hit_test(value_type x,value_type y) const\n\t{\t \n\t typedef typename geometry_base::template path_iterator path_iterator;\n\t path_iterator start = geometry_base::template begin();\n\t path_iterator end = geometry_base::template end();\n\t return point_inside_path(start,end,x,y);\n\t} \n };\n \n template class Container=vertex_vector>\n class line_string : public geometry\n {\n\ttypedef typename geometry::value_type value_type; \n public:\n\tline_string(int srid)\n\t : geometry(srid)\n\t{}\n\t\n\tint type() const \n\t{\n\t return LineString;\n\t}\n\t\n\tbool hit_test(value_type x,value_type y) const\n\t{\n\t return point_on_path(x,y,*this);\n\t}\n };\n\n typedef point point_impl;\n typedef line_string line_string_impl;\n typedef polygon polygon_impl;\n \n typedef geometry geometry_type;\n typedef ref_ptr geometry_ptr;\n}\n\n#endif \/\/GEOMETRY_HH\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \/\/ TODO\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"read-queries\/entwine.hpp\"\n#include \"read-queries\/unindexed.hpp\"\n#include \"types\/paths.hpp\"\n#include \"util\/buffer-pool.hpp\"\n\n#include \"session.hpp\"\n\nnamespace\n{\n \/\/ TODO Put this somewhere else - platform dependent code.\n std::vector resolve(\n const std::vector& dirs,\n const std::string& name)\n {\n glob_t buffer;\n for (std::size_t i(0); i < dirs.size(); ++i)\n {\n auto flags(GLOB_NOSORT | GLOB_TILDE);\n if (i) flags |= GLOB_APPEND;\n\n glob((dirs[i] + \"\/\" + name + \"*\").c_str(), flags, 0, &buffer);\n }\n\n std::vector results;\n for (std::size_t i(0); i < buffer.gl_pathc; ++i)\n {\n results.push_back(buffer.gl_pathv[i]);\n }\n\n globfree(&buffer);\n\n return results;\n }\n}\n\nSession::Session(\n pdal::StageFactory& stageFactory,\n std::mutex& factoryMutex)\n : m_stageFactory(stageFactory)\n , m_factoryMutex(factoryMutex)\n , m_initOnce()\n , m_source()\n , m_entwine()\n , m_name()\n , m_paths()\n , m_arbiter()\n{ }\n\nSession::~Session()\n{ }\n\nbool Session::initialize(\n const std::string& name,\n const Paths& paths,\n std::shared_ptr arbiter)\n{\n m_initOnce.ensure([this, &name, &paths, arbiter]()\n {\n std::cout << \"Discovering \" << name << std::endl;\n\n m_name = name;\n m_paths.reset(new Paths(paths));\n m_arbiter = arbiter;\n\n resolveSource();\n resolveIndex();\n\n std::cout << \"Source for \" << name << \": \" <<\n (sourced() ? \"FOUND\" : \"NOT found\") << std::endl;\n\n std::cout << \"Index for \" << name << \": \" <<\n (indexed() ? \"FOUND\" : \"NOT found\") << std::endl;\n });\n\n return sourced() || indexed();\n}\n\nstd::size_t Session::getNumPoints()\n{\n if (indexed()) return m_entwine->numPoints();\n else return m_source->numPoints();\n}\n\nstd::string Session::getStats()\n{\n \/\/ TODO\n return \"{ }\";\n}\n\nstd::string Session::getSrs()\n{\n return \"\";\n}\n\nentwine::BBox Session::getBounds()\n{\n if (resolveIndex())\n {\n return m_entwine->bbox();\n }\n else\n {\n throw std::runtime_error(\"No index found for \" + m_name);\n }\n}\n\nstd::shared_ptr Session::query(\n const entwine::Schema& schema,\n const bool compress)\n{\n if (resolveSource())\n {\n return std::shared_ptr(\n new UnindexedReadQuery(\n schema,\n compress,\n *m_source));\n }\n else\n {\n return std::shared_ptr();\n }\n}\n\nstd::shared_ptr Session::query(\n const entwine::Schema& schema,\n bool compress,\n const entwine::BBox& bbox,\n std::size_t depthBegin,\n std::size_t depthEnd)\n{\n if (resolveIndex())\n {\n std::vector results(\n m_entwine->query(\n bbox.exists() ? bbox : m_entwine->bbox(),\n depthBegin,\n depthEnd));\n\n return std::shared_ptr(\n new EntwineReadQuery(\n schema,\n compress,\n false,\n *m_entwine,\n results));\n }\n else\n {\n return std::shared_ptr();\n }\n}\n\nstd::shared_ptr Session::query(\n const entwine::Schema& schema,\n bool compress,\n const entwine::BBox& bbox,\n std::size_t rasterize,\n RasterMeta& rasterMeta)\n{\n throw std::runtime_error(\"TODO - Session::query (rastered)\");\n return std::shared_ptr();\n}\n\nconst entwine::Schema& Session::schema()\n{\n if (indexed()) return m_entwine->schema();\n else return m_source->schema();\n}\n\nbool Session::sourced()\n{\n std::lock_guard lock(m_sourceMutex);\n return m_source.get() != 0;\n}\n\nbool Session::indexed()\n{\n std::lock_guard lock(m_indexMutex);\n return m_entwine.get() != 0;\n}\n\nbool Session::resolveSource()\n{\n \/\/ TODO For now only works for local paths. Support any Source the Arbiter\n \/\/ contains.\n std::lock_guard lock(m_sourceMutex);\n if (!m_source)\n {\n const auto sources(resolve(m_paths->inputs, m_name));\n\n if (sources.size() > 1)\n {\n std::cout << \"Found competing sources for \" << m_name << std::endl;\n }\n\n if (sources.size())\n {\n std::size_t i(0);\n\n while (!m_source && i < sources.size())\n {\n const std::string path(sources[i++]);\n\n std::unique_lock lock(m_factoryMutex);\n const std::string driver(\n m_stageFactory.inferReaderDriver(path));\n lock.unlock();\n\n if (driver.size())\n {\n try\n {\n m_source.reset(\n new SourceManager(\n m_stageFactory,\n m_factoryMutex,\n path,\n driver));\n }\n catch (...)\n {\n std::cout << \"Bad source: \" << path << std::endl;\n m_source.reset(0);\n }\n }\n }\n }\n }\n\n return m_source.get() != 0;\n}\n\nbool Session::resolveIndex()\n{\n std::lock_guard lock(m_indexMutex);\n if (!m_entwine)\n {\n std::vector searchPaths(m_paths->inputs);\n searchPaths.push_back(m_paths->output);\n searchPaths.push_back(\"s3:\/\/\");\n\n for (std::string path : searchPaths)\n {\n try\n {\n if (path.size() && path.back() != '\/') path.push_back('\/');\n\n entwine::Source source(m_arbiter->getSource(path + m_name));\n\n \/\/ TODO Specify via config.\n m_entwine.reset(new entwine::Reader(source, 128, 128));\n }\n catch (...)\n {\n m_entwine.reset(0);\n }\n\n if (m_entwine) break;\n }\n }\n\n return m_entwine.get() != 0;\n}\n\nAdd failure logging to indexed Reader creation loop.#include \n#include \n\n#include \/\/ TODO\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"read-queries\/entwine.hpp\"\n#include \"read-queries\/unindexed.hpp\"\n#include \"types\/paths.hpp\"\n#include \"util\/buffer-pool.hpp\"\n\n#include \"session.hpp\"\n\nnamespace\n{\n \/\/ TODO Put this somewhere else - platform dependent code.\n std::vector resolve(\n const std::vector& dirs,\n const std::string& name)\n {\n glob_t buffer;\n for (std::size_t i(0); i < dirs.size(); ++i)\n {\n auto flags(GLOB_NOSORT | GLOB_TILDE);\n if (i) flags |= GLOB_APPEND;\n\n glob((dirs[i] + \"\/\" + name + \"*\").c_str(), flags, 0, &buffer);\n }\n\n std::vector results;\n for (std::size_t i(0); i < buffer.gl_pathc; ++i)\n {\n results.push_back(buffer.gl_pathv[i]);\n }\n\n globfree(&buffer);\n\n return results;\n }\n}\n\nSession::Session(\n pdal::StageFactory& stageFactory,\n std::mutex& factoryMutex)\n : m_stageFactory(stageFactory)\n , m_factoryMutex(factoryMutex)\n , m_initOnce()\n , m_source()\n , m_entwine()\n , m_name()\n , m_paths()\n , m_arbiter()\n{ }\n\nSession::~Session()\n{ }\n\nbool Session::initialize(\n const std::string& name,\n const Paths& paths,\n std::shared_ptr arbiter)\n{\n m_initOnce.ensure([this, &name, &paths, arbiter]()\n {\n std::cout << \"Discovering \" << name << std::endl;\n\n m_name = name;\n m_paths.reset(new Paths(paths));\n m_arbiter = arbiter;\n\n resolveSource();\n resolveIndex();\n\n std::cout << \"Source for \" << name << \": \" <<\n (sourced() ? \"FOUND\" : \"NOT found\") << std::endl;\n\n std::cout << \"Index for \" << name << \": \" <<\n (indexed() ? \"FOUND\" : \"NOT found\") << std::endl;\n });\n\n return sourced() || indexed();\n}\n\nstd::size_t Session::getNumPoints()\n{\n if (indexed()) return m_entwine->numPoints();\n else return m_source->numPoints();\n}\n\nstd::string Session::getStats()\n{\n \/\/ TODO\n return \"{ }\";\n}\n\nstd::string Session::getSrs()\n{\n return \"\";\n}\n\nentwine::BBox Session::getBounds()\n{\n if (resolveIndex())\n {\n return m_entwine->bbox();\n }\n else\n {\n throw std::runtime_error(\"No index found for \" + m_name);\n }\n}\n\nstd::shared_ptr Session::query(\n const entwine::Schema& schema,\n const bool compress)\n{\n if (resolveSource())\n {\n return std::shared_ptr(\n new UnindexedReadQuery(\n schema,\n compress,\n *m_source));\n }\n else\n {\n return std::shared_ptr();\n }\n}\n\nstd::shared_ptr Session::query(\n const entwine::Schema& schema,\n bool compress,\n const entwine::BBox& bbox,\n std::size_t depthBegin,\n std::size_t depthEnd)\n{\n if (resolveIndex())\n {\n std::vector results(\n m_entwine->query(\n bbox.exists() ? bbox : m_entwine->bbox(),\n depthBegin,\n depthEnd));\n\n return std::shared_ptr(\n new EntwineReadQuery(\n schema,\n compress,\n false,\n *m_entwine,\n results));\n }\n else\n {\n return std::shared_ptr();\n }\n}\n\nstd::shared_ptr Session::query(\n const entwine::Schema& schema,\n bool compress,\n const entwine::BBox& bbox,\n std::size_t rasterize,\n RasterMeta& rasterMeta)\n{\n throw std::runtime_error(\"TODO - Session::query (rastered)\");\n return std::shared_ptr();\n}\n\nconst entwine::Schema& Session::schema()\n{\n if (indexed()) return m_entwine->schema();\n else return m_source->schema();\n}\n\nbool Session::sourced()\n{\n std::lock_guard lock(m_sourceMutex);\n return m_source.get() != 0;\n}\n\nbool Session::indexed()\n{\n std::lock_guard lock(m_indexMutex);\n return m_entwine.get() != 0;\n}\n\nbool Session::resolveSource()\n{\n \/\/ TODO For now only works for local paths. Support any Source the Arbiter\n \/\/ contains.\n std::lock_guard lock(m_sourceMutex);\n if (!m_source)\n {\n const auto sources(resolve(m_paths->inputs, m_name));\n\n if (sources.size() > 1)\n {\n std::cout << \"Found competing sources for \" << m_name << std::endl;\n }\n\n if (sources.size())\n {\n std::size_t i(0);\n\n while (!m_source && i < sources.size())\n {\n const std::string path(sources[i++]);\n\n std::unique_lock lock(m_factoryMutex);\n const std::string driver(\n m_stageFactory.inferReaderDriver(path));\n lock.unlock();\n\n if (driver.size())\n {\n try\n {\n m_source.reset(\n new SourceManager(\n m_stageFactory,\n m_factoryMutex,\n path,\n driver));\n }\n catch (...)\n {\n std::cout << \"Bad source: \" << path << std::endl;\n m_source.reset(0);\n }\n }\n }\n }\n }\n\n return m_source.get() != 0;\n}\n\nbool Session::resolveIndex()\n{\n std::lock_guard lock(m_indexMutex);\n if (!m_entwine)\n {\n std::vector searchPaths(m_paths->inputs);\n searchPaths.push_back(m_paths->output);\n searchPaths.push_back(\"s3:\/\/\");\n\n for (std::string path : searchPaths)\n {\n try\n {\n if (path.size() && path.back() != '\/') path.push_back('\/');\n\n entwine::Source source(m_arbiter->getSource(path + m_name));\n\n \/\/ TODO Specify via config.\n m_entwine.reset(new entwine::Reader(source, 128, 128));\n }\n catch (std::runtime_error& e)\n {\n std::cout << \"At \" << path << \": \" <<\n e.what() << \"\\n\" << std::endl;\n }\n catch (...)\n {\n m_entwine.reset(0);\n }\n\n if (m_entwine) break;\n }\n }\n\n return m_entwine.get() != 0;\n}\n\n<|endoftext|>"} {"text":"#include \"BLITSaw_vst3.h\"\r\n#include \"BLITSaw_vst3_guids.h\"\r\n#include \"pluginterfaces\/base\/ibstream.h\"\r\n#include \"pluginterfaces\/vst\/ivstparameterchanges.h\"\r\n#include \"pluginterfaces\/vst\/ivstevents.h\"\r\n#include \r\n\r\nnamespace Steinberg { namespace Vst {\r\n\r\n\/\/-------------------------------------------------------------------------\r\n\/\/ BLITSaw_vst3 Implementation\r\n\/\/-------------------------------------------------------------------------\r\nBLITSaw_vst3::BLITSaw_vst3()\r\n{\r\n\tsetControllerClass(AGainControllerUID);\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\nFUnknown* BLITSaw_vst3::createInstance(void* context)\r\n{\r\n\treturn (IAudioProcessor*)new BLITSaw_vst3();\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\ntresult PLUGIN_API BLITSaw_vst3::initialize(FUnknown* context)\r\n{\r\n\t\/*親クラス初期化処理*\/\r\n\ttresult result = AudioEffect::initialize(context);\r\n\tif(result != kResultOk)\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\r\n\t\/*バスの設定*\/\r\n\taddAudioOutput(STR16(\"Stereo Out\"), SpeakerArr::kStereo);\r\n\taddEventInput (STR16 (\"Event Input\"), 1);\r\n\r\n\treturn kResultOk;\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\ntresult PLUGIN_API BLITSaw_vst3::setBusArrangements(\r\n\tSpeakerArrangement* inputs,\r\n\tint32 numIns,\r\n\tSpeakerArrangement* outputs,\r\n\tint32 numOuts\r\n){\r\n\tif (numIns == 0 && numOuts == 1 && outputs[0] == SpeakerArr::kStereo)\r\n\t{\r\n\t\treturn AudioEffect::setBusArrangements (inputs, numIns, outputs, numOuts);\r\n\t}\r\n\treturn kResultFalse;\r\n}\r\n\r\ntresult PLUGIN_API BLITSaw_vst3::setProcessing (TBool state)\r\n{\r\n\t\/\/ state 起動1 終了0\r\n\tif( state == 1 )\r\n\t{\r\n\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t{\r\n\t\t\tnote->setSampleRate( processSetup.sampleRate );\r\n\t\t}\r\n\r\n\t\t_filter.setSampleRate( processSetup.sampleRate );\r\n\t}\r\n\r\n\treturn kResultOk;\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\ntresult PLUGIN_API BLITSaw_vst3::process(ProcessData& data)\r\n{\r\n\t\/\/ update parameters\r\n\tif( data.inputParameterChanges )\r\n\t{\r\n\t\tint32 numParamsChanged = data.inputParameterChanges->getParameterCount();\r\n\t\tfor( int32 ii = 0; ii < numParamsChanged; ii++ )\r\n\t\t{\r\n\t\t\tIParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(ii);\r\n\t\t\tif( paramQueue )\r\n\t\t\t{\r\n\t\t\t\tint32 offsetSamples;\r\n\t\t\t\tdouble value;\r\n\t\t\t\t\/\/ 末尾の値を取得\r\n\t\t\t\tif(paramQueue->getPoint(paramQueue->getPointCount() - 1, offsetSamples, value) == kResultTrue)\r\n\t\t\t\t{\r\n\t\t\t\t\tParamID id = paramQueue->getParameterId();\r\n\t\t\t\t\tif( id == feedback )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ -> [0.99, 1.0]\r\n\t\t\t\t\t\tdouble feedback = 0.99 + 0.01 * value; \r\n\t\t\t\t\t\tblit.setFeedback(feedback);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == coarse )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble coarse_pitch = static_cast( 48 * value + 0.5 ) - 24;\r\n\r\n\t\t\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnote->setCorasePitch( coarse_pitch );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == fine )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble finepitch = static_cast( 200 * value + 0.5 ) - 100;\r\n\t\t\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnote->setFinePitch( finepitch );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == attack )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble attack_time = value * 0.2; \/\/ [0, 0.2]\r\n\t\t\t\t\t\tblit.setAttackTime( attack_time, processSetup.sampleRate );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == release )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble release_time = value * 0.2; \/\/ [0, 0.2]\r\n\t\t\t\t\t\tblit.setReleaseTime( release_time, processSetup.sampleRate );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == cutoff )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble cutoff_freq = 200.0 * pow(20.0, (double)value); \/\/ [200, 4000]\r\n\t\t\t\t\t\t_filter.setCutoff( cutoff_freq );\r\n\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == resonance )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble q = 0.70710678118654757274 * (1.0 - value) + 20.0*value;\r\n\t\t\t\t\t\t_filter.setResonance( q );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == high )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t_filter.setHigh( value );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == band )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t_filter.setBand( value );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == low )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t_filter.setLow( value );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t\/\/ process events\r\n\tif( data.inputEvents )\r\n\t{\r\n\t\tint nEventCount = data.inputEvents->getEventCount();\r\n\r\n\t\tfor( int ii = 0; ii < nEventCount; ii++ )\r\n\t\t{\r\n\t\t\tEvent e;\r\n\t\t\ttresult result = data.inputEvents->getEvent(ii, e);\r\n\t\t\tif( result != kResultOk )continue;\r\n\r\n\t\t\tif( e.type == Event::kNoteOnEvent )\r\n\t\t\t{\r\n\t\t\t\tint16 note_no = e.noteOff.pitch;\r\n\t\t\t\tauto target_note = std::find_if(\r\n\t\t\t\t\t_notes.begin(),\r\n\t\t\t\t\t_notes.end(), \r\n\t\t\t\t\t[note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;});\r\n\r\n\t\t\t\tif( target_note != _notes.end() )\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ ノートOFF\r\n\t\t\t\t\ttarget_note->trigger(e.noteOn);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ 利用可能なノートを検索する\r\n\t\t\t\t\tauto available_note = std::find_if(\r\n\t\t\t\t\t\t_notes.begin(),\r\n\t\t\t\t\t\t_notes.end(), \r\n\t\t\t\t\t\t[](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;}); \r\n\r\n\t\t\t\t\tif( available_note != _notes.end() )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ ノートON\r\n\t\t\t\t\t\tavailable_note->trigger( e.noteOn );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if( e.type == Event::kNoteOffEvent )\r\n\t\t\t{\r\n\t\t\t\t\/\/int32 note_id = e.noteOff.noteId;\r\n\t\t\t\t\/\/auto target_note = std::find_if(\r\n\t\t\t\t\/\/\t_notes.begin(),\r\n\t\t\t\t\/\/\t_notes.end(), \r\n\t\t\t\t\/\/\t[note_id](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_id;});\r\n\t\t\t\tint16 note_no = e.noteOff.pitch;\r\n\t\t\t\tauto target_note = std::find_if(\r\n\t\t\t\t\t_notes.begin(),\r\n\t\t\t\t\t_notes.end(), \r\n\t\t\t\t\t[note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;});\r\n\r\n\t\t\t\tif( target_note != _notes.end() )\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ ノートOFF\r\n\t\t\t\t\ttarget_note->release();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if( e.type == Event::kDataEvent )\r\n\t\t\t{\r\n\t\t\t\tunsigned char status = e.data.bytes[0] & 0xf0;\t\/\/ ignoring channel\r\n\r\n\r\n\t\t\t\tif( status == 0xE0 )\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned char data1 = e.data.bytes[1] & 0x7f;\r\n\t\t\t\t\tunsigned char data2 = e.data.bytes[2] & 0x7f;\r\n\r\n\t\t\t\t\tdouble pitch_bend = (( data1 + data2*128 ) - 8192 ) \/ 8192.0;\r\n\r\n\t\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tnote->setPitchBend( pitch_bend );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tbool bAllSilent= std::all_of(\r\n\t\t_notes.begin(),\r\n\t\t_notes.end(),\r\n\t\t[](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;});\r\n\r\n\tif( bAllSilent )\r\n\t{\r\n\t\treturn kResultOk;\r\n\t}\r\n\r\n\t_filter.updateFilter();\r\n\r\n\t\/*--------*\/\r\n\t\/*音声処理*\/\r\n\t\/*--------*\/\r\n\tif (data.numInputs == 0 && data.numOutputs == 1 )\r\n\t{\r\n\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t{\r\n\t\t\t\/\/ ピッチを更新\r\n\t\t\tnote->updateFrequency();\r\n\t\t}\r\n\r\n\t\tif( data.outputs[0].numChannels == 2 )\r\n\t\t{\r\n\t\t\t\/\/float** in = data.inputs[0].channelBuffers32;\r\n\t\t\tfloat** out = data.outputs[0].channelBuffers32;\r\n\r\n\t\t\tconst int32 sampleFrames = data.numSamples;\r\n\t\t\tfor( int ii = 0; ii < sampleFrames; ii++ )\r\n\t\t\t{\r\n\t\t\t\tdouble value = 0.0;\r\n\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t{\t\r\n\t\t\t\t\tif( note->adsr == bandlimited_sawtooth_oscillator_note::Silent )continue;\r\n\r\n\t\t\t\t\t\/\/ ノート毎の音を足し合わせる\r\n\t\t\t\t\tvalue += note->saw * note->envelope * note->velocity();\r\n\t\t\r\n\t\t\t\t\t\/\/ オシレーター更新\r\n\t\t\t\t\tblit.updateOcsillater( *note );\r\n\r\n\t\t\t\t\t\/\/ エンベロープ更新\r\n\t\t\t\t\tblit.updateEnvelope( *note );\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/\r\n\t\t\t\t\/\/ フィルタを掛けたければ掛ける\r\n\t\t\t\t\/\/\r\n\t\t\t\tdouble filterd_value = _filter.process(value);\r\n\r\n\t\t\t\t\/\/ 出力バッファに設定する\r\n\t\t\t\tdouble pan = 0.0;\r\n\t\t\t\tout[0][ii] = static_cast( filterd_value * (1.0 - pan) * 0.5 );\r\n\t\t\t\tout[1][ii] = static_cast( filterd_value * (1.0 + pan) * 0.5 );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn kResultOk;\r\n}\r\n\r\n}}\r\nコメント訂正#include \"BLITSaw_vst3.h\"\r\n#include \"BLITSaw_vst3_guids.h\"\r\n#include \"pluginterfaces\/base\/ibstream.h\"\r\n#include \"pluginterfaces\/vst\/ivstparameterchanges.h\"\r\n#include \"pluginterfaces\/vst\/ivstevents.h\"\r\n#include \r\n\r\nnamespace Steinberg { namespace Vst {\r\n\r\n\/\/-------------------------------------------------------------------------\r\n\/\/ BLITSaw_vst3 Implementation\r\n\/\/-------------------------------------------------------------------------\r\nBLITSaw_vst3::BLITSaw_vst3()\r\n{\r\n\tsetControllerClass(AGainControllerUID);\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\nFUnknown* BLITSaw_vst3::createInstance(void* context)\r\n{\r\n\treturn (IAudioProcessor*)new BLITSaw_vst3();\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\ntresult PLUGIN_API BLITSaw_vst3::initialize(FUnknown* context)\r\n{\r\n\t\/*親クラス初期化処理*\/\r\n\ttresult result = AudioEffect::initialize(context);\r\n\tif(result != kResultOk)\r\n\t{\r\n\t\treturn result;\r\n\t}\r\n\r\n\t\/*バスの設定*\/\r\n\taddAudioOutput(STR16(\"Stereo Out\"), SpeakerArr::kStereo);\r\n\taddEventInput (STR16 (\"Event Input\"), 1);\r\n\r\n\treturn kResultOk;\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\ntresult PLUGIN_API BLITSaw_vst3::setBusArrangements(\r\n\tSpeakerArrangement* inputs,\r\n\tint32 numIns,\r\n\tSpeakerArrangement* outputs,\r\n\tint32 numOuts\r\n){\r\n\tif (numIns == 0 && numOuts == 1 && outputs[0] == SpeakerArr::kStereo)\r\n\t{\r\n\t\treturn AudioEffect::setBusArrangements (inputs, numIns, outputs, numOuts);\r\n\t}\r\n\treturn kResultFalse;\r\n}\r\n\r\ntresult PLUGIN_API BLITSaw_vst3::setProcessing (TBool state)\r\n{\r\n\t\/\/ state 起動1 終了0\r\n\tif( state == 1 )\r\n\t{\r\n\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t{\r\n\t\t\tnote->setSampleRate( processSetup.sampleRate );\r\n\t\t}\r\n\r\n\t\t_filter.setSampleRate( processSetup.sampleRate );\r\n\t}\r\n\r\n\treturn kResultOk;\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------\r\ntresult PLUGIN_API BLITSaw_vst3::process(ProcessData& data)\r\n{\r\n\t\/\/ update parameters\r\n\tif( data.inputParameterChanges )\r\n\t{\r\n\t\tint32 numParamsChanged = data.inputParameterChanges->getParameterCount();\r\n\t\tfor( int32 ii = 0; ii < numParamsChanged; ii++ )\r\n\t\t{\r\n\t\t\tIParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(ii);\r\n\t\t\tif( paramQueue )\r\n\t\t\t{\r\n\t\t\t\tint32 offsetSamples;\r\n\t\t\t\tdouble value;\r\n\t\t\t\t\/\/ 末尾の値を取得\r\n\t\t\t\tif(paramQueue->getPoint(paramQueue->getPointCount() - 1, offsetSamples, value) == kResultTrue)\r\n\t\t\t\t{\r\n\t\t\t\t\tParamID id = paramQueue->getParameterId();\r\n\t\t\t\t\tif( id == feedback )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ -> [0.99, 1.0]\r\n\t\t\t\t\t\tdouble feedback = 0.99 + 0.01 * value; \r\n\t\t\t\t\t\tblit.setFeedback(feedback);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == coarse )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble coarse_pitch = static_cast( 48 * value + 0.5 ) - 24;\r\n\r\n\t\t\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnote->setCorasePitch( coarse_pitch );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == fine )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble finepitch = static_cast( 200 * value + 0.5 ) - 100;\r\n\t\t\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tnote->setFinePitch( finepitch );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == attack )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble attack_time = value * 0.2; \/\/ [0, 0.2]\r\n\t\t\t\t\t\tblit.setAttackTime( attack_time, processSetup.sampleRate );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == release )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble release_time = value * 0.2; \/\/ [0, 0.2]\r\n\t\t\t\t\t\tblit.setReleaseTime( release_time, processSetup.sampleRate );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == cutoff )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble cutoff_freq = 200.0 * pow(20.0, (double)value); \/\/ [200, 4000]\r\n\t\t\t\t\t\t_filter.setCutoff( cutoff_freq );\r\n\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == resonance )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble q = 0.70710678118654757274 * (1.0 - value) + 20.0*value;\r\n\t\t\t\t\t\t_filter.setResonance( q );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == high )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t_filter.setHigh( value );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == band )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t_filter.setBand( value );\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if( id == low )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t_filter.setLow( value );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t\/\/ process events\r\n\tif( data.inputEvents )\r\n\t{\r\n\t\tint nEventCount = data.inputEvents->getEventCount();\r\n\r\n\t\tfor( int ii = 0; ii < nEventCount; ii++ )\r\n\t\t{\r\n\t\t\tEvent e;\r\n\t\t\ttresult result = data.inputEvents->getEvent(ii, e);\r\n\t\t\tif( result != kResultOk )continue;\r\n\r\n\t\t\tif( e.type == Event::kNoteOnEvent )\r\n\t\t\t{\r\n\t\t\t\tint16 note_no = e.noteOff.pitch;\r\n\t\t\t\tauto target_note = std::find_if(\r\n\t\t\t\t\t_notes.begin(),\r\n\t\t\t\t\t_notes.end(), \r\n\t\t\t\t\t[note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;});\r\n\r\n\t\t\t\tif( target_note != _notes.end() )\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ 再度ノートON\r\n\t\t\t\t\ttarget_note->trigger(e.noteOn);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ 利用可能なノートを検索する\r\n\t\t\t\t\tauto available_note = std::find_if(\r\n\t\t\t\t\t\t_notes.begin(),\r\n\t\t\t\t\t\t_notes.end(), \r\n\t\t\t\t\t\t[](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;}); \r\n\r\n\t\t\t\t\tif( available_note != _notes.end() )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ ノートON\r\n\t\t\t\t\t\tavailable_note->trigger( e.noteOn );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if( e.type == Event::kNoteOffEvent )\r\n\t\t\t{\r\n\t\t\t\t\/\/int32 note_id = e.noteOff.noteId;\r\n\t\t\t\t\/\/auto target_note = std::find_if(\r\n\t\t\t\t\/\/\t_notes.begin(),\r\n\t\t\t\t\/\/\t_notes.end(), \r\n\t\t\t\t\/\/\t[note_id](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_id;});\r\n\t\t\t\tint16 note_no = e.noteOff.pitch;\r\n\t\t\t\tauto target_note = std::find_if(\r\n\t\t\t\t\t_notes.begin(),\r\n\t\t\t\t\t_notes.end(), \r\n\t\t\t\t\t[note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;});\r\n\r\n\t\t\t\tif( target_note != _notes.end() )\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ ノートOFF\r\n\t\t\t\t\ttarget_note->release();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if( e.type == Event::kDataEvent )\r\n\t\t\t{\r\n\t\t\t\tunsigned char status = e.data.bytes[0] & 0xf0;\t\/\/ ignoring channel\r\n\r\n\r\n\t\t\t\tif( status == 0xE0 )\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned char data1 = e.data.bytes[1] & 0x7f;\r\n\t\t\t\t\tunsigned char data2 = e.data.bytes[2] & 0x7f;\r\n\r\n\t\t\t\t\tdouble pitch_bend = (( data1 + data2*128 ) - 8192 ) \/ 8192.0;\r\n\r\n\t\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tnote->setPitchBend( pitch_bend );\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tbool bAllSilent= std::all_of(\r\n\t\t_notes.begin(),\r\n\t\t_notes.end(),\r\n\t\t[](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;});\r\n\r\n\tif( bAllSilent )\r\n\t{\r\n\t\treturn kResultOk;\r\n\t}\r\n\r\n\t_filter.updateFilter();\r\n\r\n\t\/*--------*\/\r\n\t\/*音声処理*\/\r\n\t\/*--------*\/\r\n\tif (data.numInputs == 0 && data.numOutputs == 1 )\r\n\t{\r\n\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t{\r\n\t\t\t\/\/ ピッチを更新\r\n\t\t\tnote->updateFrequency();\r\n\t\t}\r\n\r\n\t\tif( data.outputs[0].numChannels == 2 )\r\n\t\t{\r\n\t\t\tfloat** out = data.outputs[0].channelBuffers32;\r\n\r\n\t\t\tconst int32 sampleFrames = data.numSamples;\r\n\t\t\tfor( int ii = 0; ii < sampleFrames; ii++ )\r\n\t\t\t{\r\n\t\t\t\tdouble value = 0.0;\r\n\t\t\t\tfor(auto note = _notes.begin(); note != _notes.end(); ++note)\r\n\t\t\t\t{\t\r\n\t\t\t\t\tif( note->adsr == bandlimited_sawtooth_oscillator_note::Silent )continue;\r\n\r\n\t\t\t\t\t\/\/ ノート毎の音を足し合わせる\r\n\t\t\t\t\tvalue += note->saw * note->envelope * note->velocity();\r\n\t\t\r\n\t\t\t\t\t\/\/ オシレーター更新\r\n\t\t\t\t\tblit.updateOcsillater( *note );\r\n\r\n\t\t\t\t\t\/\/ エンベロープ更新\r\n\t\t\t\t\tblit.updateEnvelope( *note );\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\/\/\r\n\t\t\t\t\/\/ フィルタを掛けたければ掛ける\r\n\t\t\t\t\/\/\r\n\t\t\t\tdouble filterd_value = _filter.process(value);\r\n\r\n\t\t\t\t\/\/ 出力バッファに設定する\r\n\t\t\t\tdouble pan = 0.0;\r\n\t\t\t\tout[0][ii] = static_cast( filterd_value * (1.0 - pan) * 0.5 );\r\n\t\t\t\tout[1][ii] = static_cast( filterd_value * (1.0 + pan) * 0.5 );\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn kResultOk;\r\n}\r\n\r\n}}\r\n<|endoftext|>"} {"text":"\/*\n* Simple ASN.1 String Types\n* (C) 1999-2007,2020 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace {\n\n\/*\n* Choose an encoding for the string\n*\/\nASN1_Type choose_encoding(const std::string& str)\n {\n auto all_printable = CT::Mask::set();\n\n for(size_t i = 0; i != str.size(); ++i)\n {\n const uint8_t c = static_cast(str[i]);\n\n auto is_alpha_lower = CT::Mask::is_within_range(c, 'a', 'z');\n auto is_alpha_upper = CT::Mask::is_within_range(c, 'A', 'Z');\n auto is_decimal = CT::Mask::is_within_range(c, '0', '9');\n\n auto is_print_punc = CT::Mask::is_any_of(c, {\n ' ', '(', ')', '+', ',', '=', ',', '-', '.', '\/',\n ':', '=', '?'});\n\n auto is_printable = is_alpha_lower | is_alpha_upper | is_decimal | is_print_punc;\n\n all_printable &= is_printable;\n }\n\n if(all_printable.is_set())\n return ASN1_Type::PrintableString;\n else\n return ASN1_Type::Utf8String;\n }\n\nbool is_utf8_subset_string_type(ASN1_Type tag)\n {\n return (tag == ASN1_Type::NumericString ||\n tag == ASN1_Type::PrintableString ||\n tag == ASN1_Type::VisibleString ||\n tag == ASN1_Type::Ia5String ||\n tag == ASN1_Type::Utf8String);\n }\n\nbool is_asn1_string_type(ASN1_Type tag)\n {\n return (is_utf8_subset_string_type(tag) ||\n tag == ASN1_Type::TeletexString ||\n tag == ASN1_Type::BmpString ||\n tag == ASN1_Type::UniversalString);\n }\n\n}\n\n\/\/static\nbool ASN1_String::is_string_type(ASN1_Type tag)\n {\n return is_asn1_string_type(tag);\n }\n\nASN1_String::ASN1_String(const std::string& str, ASN1_Type t) : m_utf8_str(str), m_tag(t)\n {\n if(!is_utf8_subset_string_type(m_tag))\n {\n throw Invalid_Argument(\"ASN1_String only supports encoding to UTF-8 or a UTF-8 subset\");\n }\n }\n\nASN1_String::ASN1_String(const std::string& str) :\n ASN1_String(str, choose_encoding(str))\n {}\n\n\/*\n* DER encode an ASN1_String\n*\/\nvoid ASN1_String::encode_into(DER_Encoder& encoder) const\n {\n if(m_data.empty())\n {\n BOTAN_ASSERT_NOMSG(is_utf8_subset_string_type(tagging()));\n encoder.add_object(tagging(), ASN1_Class::Universal, m_utf8_str);\n }\n else\n {\n \/\/ If this string was decoded, reserialize using original encoding\n encoder.add_object(tagging(), ASN1_Class::Universal, m_data.data(), m_data.size());\n }\n }\n\n\/*\n* Decode a BER encoded ASN1_String\n*\/\nvoid ASN1_String::decode_from(BER_Decoder& source)\n {\n BER_Object obj = source.get_next_object();\n\n if(!is_asn1_string_type(obj.type()))\n {\n throw Decoding_Error(\"ASN1_String: Unknown string type \" +\n std::to_string(static_cast(obj.type())));\n }\n\n m_tag = obj.type();\n m_data.assign(obj.bits(), obj.bits() + obj.length());\n\n if(m_tag == ASN1_Type::BmpString)\n {\n m_utf8_str = ucs2_to_utf8(m_data.data(), m_data.size());\n }\n else if(m_tag == ASN1_Type::UniversalString)\n {\n m_utf8_str = ucs4_to_utf8(m_data.data(), m_data.size());\n }\n else if(m_tag == ASN1_Type::TeletexString)\n {\n \/*\n TeletexString is nominally ITU T.61 not ISO-8859-1 but it seems\n the majority of implementations actually used that charset here.\n *\/\n m_utf8_str = latin1_to_utf8(m_data.data(), m_data.size());\n }\n else\n {\n \/\/ All other supported string types are UTF-8 or some subset thereof\n m_utf8_str = ASN1::to_string(obj);\n }\n }\n\n}\nRemove duplicated chars from allowed chars in ASN1_Type::PrintableString\/*\n* Simple ASN.1 String Types\n* (C) 1999-2007,2020 Jack Lloyd\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace {\n\n\/*\n* Choose an encoding for the string\n*\/\nASN1_Type choose_encoding(const std::string& str)\n {\n auto all_printable = CT::Mask::set();\n\n for(size_t i = 0; i != str.size(); ++i)\n {\n const uint8_t c = static_cast(str[i]);\n\n auto is_alpha_lower = CT::Mask::is_within_range(c, 'a', 'z');\n auto is_alpha_upper = CT::Mask::is_within_range(c, 'A', 'Z');\n auto is_decimal = CT::Mask::is_within_range(c, '0', '9');\n\n auto is_print_punc = CT::Mask::is_any_of(c, {\n ' ', '(', ')', '+', ',', '-', '.', '\/',\n ':', '=', '?'});\n\n auto is_printable = is_alpha_lower | is_alpha_upper | is_decimal | is_print_punc;\n\n all_printable &= is_printable;\n }\n\n if(all_printable.is_set())\n return ASN1_Type::PrintableString;\n else\n return ASN1_Type::Utf8String;\n }\n\nbool is_utf8_subset_string_type(ASN1_Type tag)\n {\n return (tag == ASN1_Type::NumericString ||\n tag == ASN1_Type::PrintableString ||\n tag == ASN1_Type::VisibleString ||\n tag == ASN1_Type::Ia5String ||\n tag == ASN1_Type::Utf8String);\n }\n\nbool is_asn1_string_type(ASN1_Type tag)\n {\n return (is_utf8_subset_string_type(tag) ||\n tag == ASN1_Type::TeletexString ||\n tag == ASN1_Type::BmpString ||\n tag == ASN1_Type::UniversalString);\n }\n\n}\n\n\/\/static\nbool ASN1_String::is_string_type(ASN1_Type tag)\n {\n return is_asn1_string_type(tag);\n }\n\nASN1_String::ASN1_String(const std::string& str, ASN1_Type t) : m_utf8_str(str), m_tag(t)\n {\n if(!is_utf8_subset_string_type(m_tag))\n {\n throw Invalid_Argument(\"ASN1_String only supports encoding to UTF-8 or a UTF-8 subset\");\n }\n }\n\nASN1_String::ASN1_String(const std::string& str) :\n ASN1_String(str, choose_encoding(str))\n {}\n\n\/*\n* DER encode an ASN1_String\n*\/\nvoid ASN1_String::encode_into(DER_Encoder& encoder) const\n {\n if(m_data.empty())\n {\n BOTAN_ASSERT_NOMSG(is_utf8_subset_string_type(tagging()));\n encoder.add_object(tagging(), ASN1_Class::Universal, m_utf8_str);\n }\n else\n {\n \/\/ If this string was decoded, reserialize using original encoding\n encoder.add_object(tagging(), ASN1_Class::Universal, m_data.data(), m_data.size());\n }\n }\n\n\/*\n* Decode a BER encoded ASN1_String\n*\/\nvoid ASN1_String::decode_from(BER_Decoder& source)\n {\n BER_Object obj = source.get_next_object();\n\n if(!is_asn1_string_type(obj.type()))\n {\n throw Decoding_Error(\"ASN1_String: Unknown string type \" +\n std::to_string(static_cast(obj.type())));\n }\n\n m_tag = obj.type();\n m_data.assign(obj.bits(), obj.bits() + obj.length());\n\n if(m_tag == ASN1_Type::BmpString)\n {\n m_utf8_str = ucs2_to_utf8(m_data.data(), m_data.size());\n }\n else if(m_tag == ASN1_Type::UniversalString)\n {\n m_utf8_str = ucs4_to_utf8(m_data.data(), m_data.size());\n }\n else if(m_tag == ASN1_Type::TeletexString)\n {\n \/*\n TeletexString is nominally ITU T.61 not ISO-8859-1 but it seems\n the majority of implementations actually used that charset here.\n *\/\n m_utf8_str = latin1_to_utf8(m_data.data(), m_data.size());\n }\n else\n {\n \/\/ All other supported string types are UTF-8 or some subset thereof\n m_utf8_str = ASN1::to_string(obj);\n }\n }\n\n}\n<|endoftext|>"} {"text":"useless aStr string<|endoftext|>"} {"text":"\/\/*******************************************************************\r\n\/\/glfont2.cpp -- glFont Version 2.0 implementation\r\n\/\/Copyright (c) 1998-2002 Brad Fish\r\n\/\/See glfont.html for terms of use\r\n\/\/May 14, 2002\r\n\/\/*******************************************************************\r\n\r\n\/\/STL headers\r\n#include \r\n#include \r\n#include \r\n#include \r\nusing namespace std;\r\n\r\n\/\/OpenGL headers\r\n#ifdef _WINDOWS\r\n#include \r\n#endif\r\n#include \r\n\r\n\/\/glFont header\r\n#include \"glfont2.h\"\r\nusing namespace glfont;\r\n\r\n\/\/*******************************************************************\r\n\/\/GLFont Class Implementation\r\n\/\/*******************************************************************\r\nGLFont::GLFont ()\r\n{\r\n\t\/\/Initialize header to safe state\r\n\theader.tex = -1;\r\n\theader.tex_width = 0;\r\n\theader.tex_height = 0;\r\n\theader.start_char = 0;\r\n\theader.end_char = 0;\r\n\theader.chars = NULL;\r\n}\r\n\/\/*******************************************************************\r\nGLFont::~GLFont ()\r\n{\r\n\t\/\/Destroy the font\r\n\tDestroy();\r\n}\r\n\/\/*******************************************************************\r\nbool GLFont::Create (const char *file_name, int tex)\r\n{\r\n\tifstream input;\r\n\tint num_chars, num_tex_bytes;\r\n\tchar *tex_bytes;\r\n\r\n\t\/\/Destroy the old font if there was one, just to be safe\r\n\tDestroy();\r\n\r\n\t\/\/Open input file\r\n\tinput.open(file_name, ios::in | ios::binary);\r\n\tif (!input)\r\n\t\treturn false;\r\n\r\n\t\/\/Read the header from file\r\n\tinput.read((char *)&header, sizeof(header));\r\n\theader.tex = tex;\r\n\r\n\t\/\/Allocate space for character array\r\n\tnum_chars = header.end_char - header.start_char + 1;\r\n\tif ((header.chars = new GLFontChar[num_chars]) == NULL)\r\n\t\treturn false;\r\n\r\n\t\/\/Read character array\r\n\tfor(int i=0; i < num_chars; i++)\r\n\t\tinput.read((char *)&header.chars[i], sizeof(GLFontChar) - (sizeof(void*) - 4));\r\n\r\n\t\/\/Read texture pixel data\r\n\tnum_tex_bytes = header.tex_width * header.tex_height * 2;\r\n\ttex_bytes = new char[num_tex_bytes];\r\n\tinput.read(tex_bytes, num_tex_bytes);\r\n\r\n\t\/\/Create OpenGL texture\r\n\tglBindTexture(GL_TEXTURE_2D, tex); \r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width,\r\n\t\theader.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE,\r\n\t\t(void *)tex_bytes);\r\n\r\n\t\/\/Free texture pixels memory\r\n\tdelete[] tex_bytes;\r\n\r\n\t\/\/Close input file\r\n\tinput.close();\r\n\r\n\t\/\/Return successfully\r\n\r\n\tcout << \"Start: \" << header.start_char << \", End: \" << header.end_char << \", Chars: \" << header.chars << endl;\r\n\tcout << \"Height: \" << header.tex_height << \", Width: \" << header.tex_width << endl;\r\n\t\/\/Read character array\r\n\tfor(int i=header.start_char; i < header.end_char; i++)\r\n\t{\r\n\t\tGLFontChar c = header.chars[i - header.start_char];\r\n\t\tcout << \"Char: \" << i << \", dx: \" << c.dx << \", dy: \" << c.dy << endl;\r\n\t\tcout << \"ty1: \" << c.ty1 << \", ty2: \" << c.ty2 << \", tx1: \" << c.tx1 << \", tx2: \" << c.tx2 << endl;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\/\/*******************************************************************\r\nbool GLFont::Create (const std::string &file_name, int tex)\r\n{\r\n\treturn Create(file_name.c_str(), tex);\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::Destroy (void)\r\n{\r\n\t\/\/Delete the character array if necessary\r\n\tif (header.chars)\r\n\t{\r\n\t\tdelete[] header.chars;\r\n\t\theader.chars = NULL;\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::GetTexSize (std::pair *size)\r\n{\r\n\t\/\/Retrieve texture size\r\n\tsize->first = header.tex_width;\r\n\tsize->second = header.tex_height;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetTexWidth (void)\r\n{\r\n\t\/\/Return texture width\r\n\treturn header.tex_width;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetTexHeight (void)\r\n{\r\n\t\/\/Return texture height\r\n\treturn header.tex_height;\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::GetCharInterval (std::pair *interval)\r\n{\r\n\t\/\/Retrieve character interval\r\n\tinterval->first = header.start_char;\r\n\tinterval->second = header.end_char;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetStartChar (void)\r\n{\r\n\t\/\/Return start character\r\n\treturn header.start_char;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetEndChar (void)\r\n{\r\n\t\/\/Return end character\r\n\treturn header.end_char;\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::GetCharSize (int c, std::pair *size)\r\n{\r\n\t\/\/Make sure character is in range\r\n\tif (c < header.start_char || c > header.end_char)\r\n\t{\r\n\t\t\/\/Not a valid character, so it obviously has no size\r\n\t\tsize->first = 0;\r\n\t\tsize->second = 0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tGLFontChar *glfont_char;\r\n\r\n\t\t\/\/Retrieve character size\r\n\t\tglfont_char = &header.chars[c - header.start_char];\r\n\t\tsize->first = (int)(glfont_char->dx * header.tex_width);\r\n\t\tsize->second = (int)(glfont_char->dy *\r\n\t\t\theader.tex_height);\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetCharWidth (int c)\r\n{\r\n\t\/\/Make sure in range\r\n\tif (c < header.start_char || c > header.end_char)\r\n\t\treturn 0;\r\n\telse\r\n\t{\r\n\t\tGLFontChar *glfont_char;\r\n\t\t\r\n\t\t\/\/Retrieve character width\r\n\t\tglfont_char = &header.chars[c - header.start_char];\r\n\t\treturn (int)(glfont_char->dx * header.tex_width);\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetCharHeight (int c)\r\n{\r\n\t\/\/Make sure in range\r\n\tif (c < header.start_char || c > header.end_char)\r\n\t\treturn 0;\r\n\telse\r\n\t{\r\n\t\tGLFontChar *glfont_char;\r\n\r\n\t\t\/\/Retrieve character height\r\n\t\tglfont_char = &header.chars[c - header.start_char];\r\n\t\treturn (int)(glfont_char->dy * header.tex_height);\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::Begin (void)\r\n{\r\n\t\/\/Bind to font texture\r\n\tglBindTexture(GL_TEXTURE_2D, header.tex);\r\n}\r\n\/\/*******************************************************************\r\n\r\n\/\/End of file\r\n\r\nfix for 64-bit. i mean it really\/\/*******************************************************************\r\n\/\/glfont2.cpp -- glFont Version 2.0 implementation\r\n\/\/Copyright (c) 1998-2002 Brad Fish\r\n\/\/See glfont.html for terms of use\r\n\/\/May 14, 2002\r\n\/\/*******************************************************************\r\n\r\n\/\/STL headers\r\n#include \r\n#include \r\n#include \r\n#include \r\nusing namespace std;\r\n\r\n\/\/OpenGL headers\r\n#ifdef _WINDOWS\r\n#include \r\n#endif\r\n#include \r\n\r\n\/\/glFont header\r\n#include \"glfont2.h\"\r\nusing namespace glfont;\r\n\r\n\/\/*******************************************************************\r\n\/\/GLFont Class Implementation\r\n\/\/*******************************************************************\r\nGLFont::GLFont ()\r\n{\r\n\t\/\/Initialize header to safe state\r\n\theader.tex = -1;\r\n\theader.tex_width = 0;\r\n\theader.tex_height = 0;\r\n\theader.start_char = 0;\r\n\theader.end_char = 0;\r\n\theader.chars = NULL;\r\n}\r\n\/\/*******************************************************************\r\nGLFont::~GLFont ()\r\n{\r\n\t\/\/Destroy the font\r\n\tDestroy();\r\n}\r\n\/\/*******************************************************************\r\nbool GLFont::Create (const char *file_name, int tex)\r\n{\r\n\tifstream input;\r\n\tint num_chars, num_tex_bytes;\r\n\tchar *tex_bytes;\r\n\r\n\t\/\/Destroy the old font if there was one, just to be safe\r\n\tDestroy();\r\n\r\n\t\/\/Open input file\r\n\tinput.open(file_name, ios::in | ios::binary);\r\n\tif (!input)\r\n\t\treturn false;\r\n\r\n\t\/\/Read the header from file\r\n\tinput.read((char *)&header, sizeof(header) - (sizeof(void*) - 4));\r\n\theader.tex = tex;\r\n\r\n\t\/\/Allocate space for character array\r\n\tnum_chars = header.end_char - header.start_char + 1;\r\n\tif ((header.chars = new GLFontChar[num_chars]) == NULL)\r\n\t\treturn false;\r\n\r\n\t\/\/Read character array\r\n\tfor(int i=0; i < num_chars; i++)\r\n\t\tinput.read((char *)&header.chars[i], sizeof(GLFontChar));\r\n\r\n\t\/\/Read texture pixel data\r\n\tnum_tex_bytes = header.tex_width * header.tex_height * 2;\r\n\ttex_bytes = new char[num_tex_bytes];\r\n\tinput.read(tex_bytes, num_tex_bytes);\r\n\r\n\t\/\/Create OpenGL texture\r\n\tglBindTexture(GL_TEXTURE_2D, tex); \r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width,\r\n\t\theader.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE,\r\n\t\t(void *)tex_bytes);\r\n\r\n\t\/\/Free texture pixels memory\r\n\tdelete[] tex_bytes;\r\n\r\n\t\/\/Close input file\r\n\tinput.close();\r\n\r\n\t\/\/Return successfully\r\n\r\n\tcout << \"Start: \" << header.start_char << \", End: \" << header.end_char << \", Chars: \" << header.chars << endl;\r\n\tcout << \"Height: \" << header.tex_height << \", Width: \" << header.tex_width << endl;\r\n\t\/\/Read character array\r\n\tfor(int i=header.start_char; i < header.end_char; i++)\r\n\t{\r\n\t\tGLFontChar c = header.chars[i - header.start_char];\r\n\t\tcout << \"Char: \" << i << \", dx: \" << c.dx << \", dy: \" << c.dy << endl;\r\n\t\tcout << \"ty1: \" << c.ty1 << \", ty2: \" << c.ty2 << \", tx1: \" << c.tx1 << \", tx2: \" << c.tx2 << endl;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\/\/*******************************************************************\r\nbool GLFont::Create (const std::string &file_name, int tex)\r\n{\r\n\treturn Create(file_name.c_str(), tex);\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::Destroy (void)\r\n{\r\n\t\/\/Delete the character array if necessary\r\n\tif (header.chars)\r\n\t{\r\n\t\tdelete[] header.chars;\r\n\t\theader.chars = NULL;\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::GetTexSize (std::pair *size)\r\n{\r\n\t\/\/Retrieve texture size\r\n\tsize->first = header.tex_width;\r\n\tsize->second = header.tex_height;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetTexWidth (void)\r\n{\r\n\t\/\/Return texture width\r\n\treturn header.tex_width;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetTexHeight (void)\r\n{\r\n\t\/\/Return texture height\r\n\treturn header.tex_height;\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::GetCharInterval (std::pair *interval)\r\n{\r\n\t\/\/Retrieve character interval\r\n\tinterval->first = header.start_char;\r\n\tinterval->second = header.end_char;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetStartChar (void)\r\n{\r\n\t\/\/Return start character\r\n\treturn header.start_char;\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetEndChar (void)\r\n{\r\n\t\/\/Return end character\r\n\treturn header.end_char;\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::GetCharSize (int c, std::pair *size)\r\n{\r\n\t\/\/Make sure character is in range\r\n\tif (c < header.start_char || c > header.end_char)\r\n\t{\r\n\t\t\/\/Not a valid character, so it obviously has no size\r\n\t\tsize->first = 0;\r\n\t\tsize->second = 0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tGLFontChar *glfont_char;\r\n\r\n\t\t\/\/Retrieve character size\r\n\t\tglfont_char = &header.chars[c - header.start_char];\r\n\t\tsize->first = (int)(glfont_char->dx * header.tex_width);\r\n\t\tsize->second = (int)(glfont_char->dy *\r\n\t\t\theader.tex_height);\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetCharWidth (int c)\r\n{\r\n\t\/\/Make sure in range\r\n\tif (c < header.start_char || c > header.end_char)\r\n\t\treturn 0;\r\n\telse\r\n\t{\r\n\t\tGLFontChar *glfont_char;\r\n\t\t\r\n\t\t\/\/Retrieve character width\r\n\t\tglfont_char = &header.chars[c - header.start_char];\r\n\t\treturn (int)(glfont_char->dx * header.tex_width);\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nint GLFont::GetCharHeight (int c)\r\n{\r\n\t\/\/Make sure in range\r\n\tif (c < header.start_char || c > header.end_char)\r\n\t\treturn 0;\r\n\telse\r\n\t{\r\n\t\tGLFontChar *glfont_char;\r\n\r\n\t\t\/\/Retrieve character height\r\n\t\tglfont_char = &header.chars[c - header.start_char];\r\n\t\treturn (int)(glfont_char->dy * header.tex_height);\r\n\t}\r\n}\r\n\/\/*******************************************************************\r\nvoid GLFont::Begin (void)\r\n{\r\n\t\/\/Bind to font texture\r\n\tglBindTexture(GL_TEXTURE_2D, header.tex);\r\n}\r\n\/\/*******************************************************************\r\n\r\n\/\/End of file\r\n\r\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2014 - 2015 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 \"copasi\/utilities\/CBaseUnit.h\"\n#include \"copasi\/utilities\/CCopasiMessage.h\"\n#include \"copasi\/UI\/qtUtilities.h\"\n\n\/\/ static\nconst char * CBaseUnit::Name[] =\n{\n \"dimensionless\",\n \"meter\",\n \"gram\",\n \"second\",\n \"Ampere\",\n \"Kelvin\",\n \"item\",\n \"Candela\",\n NULL\n};\n\n\/\/ static (because CBaseUnit is not meant to be constructed)\nconst std::string CBaseUnit::getSymbol(Kind kind)\n{\n switch (kind)\n {\n case dimensionless:\n return \"\";\n\n case meter:\n return \"m\";\n\n case gram:\n return \"g\";\n\n case second:\n return \"s\";\n\n case ampere:\n return \"A\";\n\n case kelvin:\n return \"K\";\n\n case candela:\n return \"cd\";\n\n case item:\n return \"#\";\n\n default:\n return \"\";\n }\n}\n\n\/\/ static (because CBaseUnit is not meant to be constructed)\nconst CBaseUnit::Kind CBaseUnit::fromSymbol(const std::string & symbol)\n{\n if (symbol == \"m\") return meter;\n\n if (symbol == \"g\") return gram;\n\n if (symbol == \"s\") return second;\n\n if (symbol == \"A\") return ampere;\n\n if (symbol == \"K\") return kelvin;\n\n if (symbol == \"cd\") return candela;\n\n if (symbol == \"#\") return item;\n\n if (symbol == \"\") return dimensionless;\n\n fatalError();\n\n return dimensionless;\n}\n\n\/\/ static (because CBaseUnit is not meant to be constructed)\nconst CBaseUnit::Scale CBaseUnit::scaleFromPrefix(const std::string & prefix)\n{\n if (prefix == \"a\") return atto;\n\n if (prefix == \"f\") return femto;\n\n if (prefix == \"p\") return pico;\n\n if (prefix == \"u\" || prefix == \"\\xc2\\xb5\") return micro;\n\n if (prefix == \"m\") return milli;\n\n if (prefix == \"c\") return centi;\n\n if (prefix == \"d\") return deci;\n\n if (prefix == \"h\") return hecto;\n\n if (prefix == \"k\") return kilo;\n\n if (prefix == \"M\") return mega;\n\n if (prefix == \"G\") return giga;\n\n if (prefix == \"T\") return tera;\n\n if (prefix == \"P\") return peta;\n\n return zero;\n}\n- cbaseuntit should not include qt, as we currently don't have a qt dependency for libcopasise\/copasise\/\/ Copyright (C) 2014 - 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 \"copasi\/utilities\/CBaseUnit.h\"\n#include \"copasi\/utilities\/CCopasiMessage.h\"\n\n\/\/ static\nconst char * CBaseUnit::Name[] =\n{\n \"dimensionless\",\n \"meter\",\n \"gram\",\n \"second\",\n \"Ampere\",\n \"Kelvin\",\n \"item\",\n \"Candela\",\n NULL\n};\n\n\/\/ static (because CBaseUnit is not meant to be constructed)\nconst std::string CBaseUnit::getSymbol(Kind kind)\n{\n switch (kind)\n {\n case dimensionless:\n return \"\";\n\n case meter:\n return \"m\";\n\n case gram:\n return \"g\";\n\n case second:\n return \"s\";\n\n case ampere:\n return \"A\";\n\n case kelvin:\n return \"K\";\n\n case candela:\n return \"cd\";\n\n case item:\n return \"#\";\n\n default:\n return \"\";\n }\n}\n\n\/\/ static (because CBaseUnit is not meant to be constructed)\nconst CBaseUnit::Kind CBaseUnit::fromSymbol(const std::string & symbol)\n{\n if (symbol == \"m\") return meter;\n\n if (symbol == \"g\") return gram;\n\n if (symbol == \"s\") return second;\n\n if (symbol == \"A\") return ampere;\n\n if (symbol == \"K\") return kelvin;\n\n if (symbol == \"cd\") return candela;\n\n if (symbol == \"#\") return item;\n\n if (symbol == \"\") return dimensionless;\n\n fatalError();\n\n return dimensionless;\n}\n\n\/\/ static (because CBaseUnit is not meant to be constructed)\nconst CBaseUnit::Scale CBaseUnit::scaleFromPrefix(const std::string & prefix)\n{\n if (prefix == \"a\") return atto;\n\n if (prefix == \"f\") return femto;\n\n if (prefix == \"p\") return pico;\n\n if (prefix == \"u\" || prefix == \"\\xc2\\xb5\") return micro;\n\n if (prefix == \"m\") return milli;\n\n if (prefix == \"c\") return centi;\n\n if (prefix == \"d\") return deci;\n\n if (prefix == \"h\") return hecto;\n\n if (prefix == \"k\") return kilo;\n\n if (prefix == \"M\") return mega;\n\n if (prefix == \"G\") return giga;\n\n if (prefix == \"T\") return tera;\n\n if (prefix == \"P\") return peta;\n\n return zero;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2009-2011 The VOTCA Development Team (http:\/\/www.votca.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\n#include \n#include \n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\nStatement::~Statement()\n{\n\tsqlite3_finalize(_stmt);\n}\n\ntemplate<>\nvoid Statement::Bind(int col, const int &value)\n{\n\tsqlite3_bind_int(_stmt, col, value);\n}\n\ntemplate<>\nvoid Statement::Bind(int col, const double &value)\n{\n\tsqlite3_bind_double(_stmt, col, value);\n}\n\ntemplate<>\nint Statement::Column(int col)\n{\n\treturn sqlite3_column_int(_stmt, col);\n}\n\ntemplate<>\ndouble Statement::Column(int col)\n{\n\treturn sqlite3_column_double(_stmt, col);\n}\n\ntemplate<>\nstring Statement::Column(int col)\n{\n\treturn string((const char*)sqlite3_column_text(_stmt, col));\n}\n\ntemplate<>\nvoid Statement::Bind(int col, const string &value)\n{\n sqlite3_bind_text(_stmt, col, value.c_str(), -1, NULL);;\n}\n\nint Statement::Step()\n{\n\treturn sqlite3_step(_stmt);\n}\n\nvoid Statement::Reset()\n{\n\tsqlite3_reset(_stmt);\n}\n\n}}\n\nerror handling in statement\/*\n * Copyright 2009-2011 The VOTCA Development Team (http:\/\/www.votca.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\n#include \n#include \n#include \n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\nStatement::~Statement()\n{\n\tsqlite3_finalize(_stmt);\n}\n\ntemplate<>\nvoid Statement::Bind(int col, const int &value)\n{\n\tif(sqlite3_bind_int(_stmt, col, value) != SQLITE_OK)\n throw std::runtime_error(\"sqlite_bind failed\");\n}\n\ntemplate<>\nvoid Statement::Bind(int col, const double &value)\n{\n\tif(sqlite3_bind_double(_stmt, col, value) != SQLITE_OK)\n throw std::runtime_error(\"sqlite_bind failed\");\n}\n\ntemplate<>\nint Statement::Column(int col)\n{\n\treturn sqlite3_column_int(_stmt, col);\n}\n\ntemplate<>\ndouble Statement::Column(int col)\n{\n\treturn sqlite3_column_double(_stmt, col);\n}\n\ntemplate<>\nstring Statement::Column(int col)\n{\n\treturn string((const char*)sqlite3_column_text(_stmt, col));\n}\n\ntemplate<>\nvoid Statement::Bind(int col, const string &value)\n{\n if(sqlite3_bind_text(_stmt, col, value.c_str(), -1, NULL) != SQLITE_OK)\n throw std::runtime_error(\"sqlite_bind failed\");\n}\n\nint Statement::Step()\n{\n\treturn sqlite3_step(_stmt);\n}\n\nvoid Statement::Reset()\n{\n\tsqlite3_reset(_stmt);\n}\n\n}}\n\n<|endoftext|>"} {"text":"Propagate first_and_last option into nonlinear iterative solvers.<|endoftext|>"} {"text":"Fix nvcc sign warning<|endoftext|>"} {"text":"#define PGDLLIMPORT \"C\"\n\n#include \n\n#include \"postgres.h\"\n#include \"funcapi.h\"\n\n#include \"access\/extprotocol.h\"\n#include \"catalog\/pg_proc.h\"\n#include \"utils\/array.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/memutils.h\"\n#include \"fmgr.h\"\n\n#include \"S3ExtWrapper.h\"\n#include \"S3Common.h\"\n#include \"S3Log.h\"\n#include \"utils.h\"\n\n#include \"gps3ext.h\"\n#include \"gps3conf.h\"\n\n#include \n#include \n\n\/* Do the module magic dance *\/\n\nPG_MODULE_MAGIC;\nPG_FUNCTION_INFO_V1(s3_export);\nPG_FUNCTION_INFO_V1(s3_import);\nPG_FUNCTION_INFO_V1(s3_validate_urls);\n\nextern \"C\" {\nDatum s3_export(PG_FUNCTION_ARGS);\nDatum s3_import(PG_FUNCTION_ARGS);\nDatum s3_validate_urls(PG_FUNCTION_ARGS);\n}\n\n#define MUTEX_TYPE pthread_mutex_t\n#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)\n#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))\n#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))\n#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))\n#define THREAD_ID pthread_self()\n\n\/* This array will store all of the mutexes available to OpenSSL. *\/\nstatic MUTEX_TYPE *mutex_buf = NULL;\n\nstatic void locking_function(int mode, int n, const char *file, int line) {\n if (mode & CRYPTO_LOCK)\n MUTEX_LOCK(mutex_buf[n]);\n else\n MUTEX_UNLOCK(mutex_buf[n]);\n}\n\nstatic unsigned long id_function(void) { return ((unsigned long)THREAD_ID); }\n\nint thread_setup(void) {\n int i;\n\n mutex_buf =\n (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));\n if (!mutex_buf) return 0;\n for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);\n CRYPTO_set_id_callback(id_function);\n CRYPTO_set_locking_callback(locking_function);\n return 1;\n}\n\nint thread_cleanup(void) {\n int i;\n\n if (!mutex_buf) return 0;\n CRYPTO_set_id_callback(NULL);\n CRYPTO_set_locking_callback(NULL);\n for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]);\n pfree(mutex_buf);\n mutex_buf = NULL;\n return 1;\n}\n\n\/*\n * Import data into GPDB.\n *\/\nDatum s3_import(PG_FUNCTION_ARGS) {\n S3ExtBase *myData;\n char *data;\n int data_len;\n size_t nread = 0;\n\n \/* Must be called via the external table format manager *\/\n if (!CALLED_AS_EXTPROTOCOL(fcinfo))\n elog(ERROR,\n \"extprotocol_import: not called by external protocol manager\");\n\n \/* Get our internal description of the protocol *\/\n myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo);\n\n if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) {\n if (myData) {\n thread_cleanup();\n if (!myData->Destroy()) {\n ereport(ERROR, (0, errmsg(\"Cleanup S3 extention failed\")));\n }\n delete myData;\n }\n PG_RETURN_INT32(0);\n }\n\n if (myData == NULL) {\n \/* first call. do any desired init *\/\n curl_global_init(CURL_GLOBAL_ALL);\n thread_setup();\n const char *p_name = \"s3\";\n char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo);\n char *url = truncate_options(url_with_options);\n\n char *config_path = get_opt_s3(url_with_options, \"config\");\n if (!config_path) {\n \/\/ no config path in url, use default value\n \/\/ data_folder\/gpseg0\/s3\/s3.conf\n config_path = pstrdup(\"s3\/s3.conf\");\n }\n\n bool result = InitConfig(config_path, \"\");\n if (!result) {\n ereport(ERROR,\n (0, errmsg(\"Can't find config file %s\", config_path)));\n pfree(config_path);\n } else {\n ClearConfig();\n pfree(config_path);\n }\n\n InitLog();\n\n if (s3ext_accessid == \"\") {\n ereport(ERROR, (0, errmsg(\"ERROR: access id is empty\")));\n }\n\n if (s3ext_secret == \"\") {\n ereport(ERROR, (0, errmsg(\"ERROR: secret is empty\")));\n }\n\n if ((s3ext_segnum == -1) || (s3ext_segid == -1)) {\n ereport(ERROR, (0, errmsg(\"ERROR: segment id is invalid\")));\n }\n\n myData = CreateExtWrapper(url);\n\n if (!myData ||\n !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) {\n if (myData) delete myData;\n ereport(ERROR, (0, errmsg(\"Failed to init S3 extension, segid = \"\n \"%d, segnum = %d, please check your \"\n \"configurations and net connection\",\n s3ext_segid, s3ext_segnum)));\n }\n \/*\n if(strcasecmp(parsed_url->protocol, p_name) != 0) {\n elog(ERROR, \"internal error: s3prot called with a different\n protocol\n (%s)\",\n parsed_url->protocol);\n }\n *\/\n\n EXTPROTOCOL_SET_USER_CTX(fcinfo, myData);\n\n free(url);\n }\n\n \/* =======================================================================\n * DO THE IMPORT\n * =======================================================================\n *\/\n\n data = EXTPROTOCOL_GET_DATABUF(fcinfo);\n data_len = EXTPROTOCOL_GET_DATALEN(fcinfo);\n uint64_t readlen = 0;\n if (data_len > 0) {\n readlen = data_len;\n if (!myData->TransferData(data, readlen))\n ereport(ERROR, (0, errmsg(\"s3_import: could not read data\")));\n nread = (size_t)readlen;\n \/\/ S3DEBUG(\"read %d data from S3\", nread);\n }\n\n PG_RETURN_INT32((int)nread);\n}\n\n\/*\n * Export data out of GPDB.\n *\/\nDatum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); }\n\nDatum s3_validate_urls(PG_FUNCTION_ARGS) {\n int nurls;\n int i;\n ValidatorDirection direction;\n PG_RETURN_VOID();\n}\ndon't use use pg alloc functions here, conflict with get_opt_s3() in unit test env#define PGDLLIMPORT \"C\"\n\n#include \n\n#include \"postgres.h\"\n#include \"funcapi.h\"\n\n#include \"access\/extprotocol.h\"\n#include \"catalog\/pg_proc.h\"\n#include \"utils\/array.h\"\n#include \"utils\/builtins.h\"\n#include \"utils\/memutils.h\"\n#include \"fmgr.h\"\n\n#include \"S3ExtWrapper.h\"\n#include \"S3Common.h\"\n#include \"S3Log.h\"\n#include \"utils.h\"\n\n#include \"gps3ext.h\"\n#include \"gps3conf.h\"\n\n#include \n#include \n\n\/* Do the module magic dance *\/\n\nPG_MODULE_MAGIC;\nPG_FUNCTION_INFO_V1(s3_export);\nPG_FUNCTION_INFO_V1(s3_import);\nPG_FUNCTION_INFO_V1(s3_validate_urls);\n\nextern \"C\" {\nDatum s3_export(PG_FUNCTION_ARGS);\nDatum s3_import(PG_FUNCTION_ARGS);\nDatum s3_validate_urls(PG_FUNCTION_ARGS);\n}\n\n#define MUTEX_TYPE pthread_mutex_t\n#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)\n#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))\n#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))\n#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))\n#define THREAD_ID pthread_self()\n\n\/* This array will store all of the mutexes available to OpenSSL. *\/\nstatic MUTEX_TYPE *mutex_buf = NULL;\n\nstatic void locking_function(int mode, int n, const char *file, int line) {\n if (mode & CRYPTO_LOCK)\n MUTEX_LOCK(mutex_buf[n]);\n else\n MUTEX_UNLOCK(mutex_buf[n]);\n}\n\nstatic unsigned long id_function(void) { return ((unsigned long)THREAD_ID); }\n\nint thread_setup(void) {\n int i;\n\n mutex_buf =\n (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));\n if (!mutex_buf) return 0;\n for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]);\n CRYPTO_set_id_callback(id_function);\n CRYPTO_set_locking_callback(locking_function);\n return 1;\n}\n\nint thread_cleanup(void) {\n int i;\n\n if (!mutex_buf) return 0;\n CRYPTO_set_id_callback(NULL);\n CRYPTO_set_locking_callback(NULL);\n for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]);\n pfree(mutex_buf);\n mutex_buf = NULL;\n return 1;\n}\n\n\/*\n * Import data into GPDB.\n *\/\nDatum s3_import(PG_FUNCTION_ARGS) {\n S3ExtBase *myData;\n char *data;\n int data_len;\n size_t nread = 0;\n\n \/* Must be called via the external table format manager *\/\n if (!CALLED_AS_EXTPROTOCOL(fcinfo))\n elog(ERROR,\n \"extprotocol_import: not called by external protocol manager\");\n\n \/* Get our internal description of the protocol *\/\n myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo);\n\n if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) {\n if (myData) {\n thread_cleanup();\n if (!myData->Destroy()) {\n ereport(ERROR, (0, errmsg(\"Cleanup S3 extention failed\")));\n }\n delete myData;\n }\n PG_RETURN_INT32(0);\n }\n\n if (myData == NULL) {\n \/* first call. do any desired init *\/\n curl_global_init(CURL_GLOBAL_ALL);\n thread_setup();\n const char *p_name = \"s3\";\n char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo);\n char *url = truncate_options(url_with_options);\n\n char *config_path = get_opt_s3(url_with_options, \"config\");\n if (!config_path) {\n \/\/ no config path in url, use default value\n \/\/ data_folder\/gpseg0\/s3\/s3.conf\n config_path = strdup(\"s3\/s3.conf\");\n }\n\n bool result = InitConfig(config_path, \"\");\n if (!result) {\n free(config_path);\n ereport(ERROR, (0, errmsg(\"Can't find config file, please check\")));\n } else {\n ClearConfig();\n free(config_path);\n }\n\n InitLog();\n\n if (s3ext_accessid == \"\") {\n ereport(ERROR, (0, errmsg(\"ERROR: access id is empty\")));\n }\n\n if (s3ext_secret == \"\") {\n ereport(ERROR, (0, errmsg(\"ERROR: secret is empty\")));\n }\n\n if ((s3ext_segnum == -1) || (s3ext_segid == -1)) {\n ereport(ERROR, (0, errmsg(\"ERROR: segment id is invalid\")));\n }\n\n myData = CreateExtWrapper(url);\n\n if (!myData ||\n !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) {\n if (myData) delete myData;\n ereport(ERROR, (0, errmsg(\"Failed to init S3 extension, segid = \"\n \"%d, segnum = %d, please check your \"\n \"configurations and net connection\",\n s3ext_segid, s3ext_segnum)));\n }\n \/*\n if(strcasecmp(parsed_url->protocol, p_name) != 0) {\n elog(ERROR, \"internal error: s3prot called with a different\n protocol\n (%s)\",\n parsed_url->protocol);\n }\n *\/\n\n EXTPROTOCOL_SET_USER_CTX(fcinfo, myData);\n\n free(url);\n }\n\n \/* =======================================================================\n * DO THE IMPORT\n * =======================================================================\n *\/\n\n data = EXTPROTOCOL_GET_DATABUF(fcinfo);\n data_len = EXTPROTOCOL_GET_DATALEN(fcinfo);\n uint64_t readlen = 0;\n if (data_len > 0) {\n readlen = data_len;\n if (!myData->TransferData(data, readlen))\n ereport(ERROR, (0, errmsg(\"s3_import: could not read data\")));\n nread = (size_t)readlen;\n \/\/ S3DEBUG(\"read %d data from S3\", nread);\n }\n\n PG_RETURN_INT32((int)nread);\n}\n\n\/*\n * Export data out of GPDB.\n *\/\nDatum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); }\n\nDatum s3_validate_urls(PG_FUNCTION_ARGS) {\n int nurls;\n int i;\n ValidatorDirection direction;\n PG_RETURN_VOID();\n}\n<|endoftext|>"} {"text":"#include \"renderState.h\"\n\n#include \"platform.h\"\n#include \"vertexLayout.h\"\n#include \"gl\/hardware.h\"\n\nnamespace Tangram {\n\n \/\/ Incremented when the GL context is invalidated\nstatic int s_validGeneration;\nstatic int s_textureUnit;\n\nnamespace RenderState {\n\n Blending blending;\n DepthTest depthTest;\n StencilTest stencilTest;\n Culling culling;\n DepthWrite depthWrite;\n BlendingFunc blendingFunc;\n StencilWrite stencilWrite;\n StencilFunc stencilFunc;\n StencilOp stencilOp;\n ColorWrite colorWrite;\n FrontFace frontFace;\n CullFace cullFace;\n\n VertexBuffer vertexBuffer;\n IndexBuffer indexBuffer;\n\n ShaderProgram shaderProgram;\n\n TextureUnit textureUnit;\n Texture texture;\n\n ClearColor clearColor;\n\n GLuint getTextureUnit(GLuint _unit) {\n return GL_TEXTURE0 + _unit;\n }\n\n void bindVertexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _id)); }\n void bindIndexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id)); }\n void activeTextureUnit(GLuint _unit) { GL_CHECK(glActiveTexture(getTextureUnit(_unit))); }\n void bindTexture(GLenum _target, GLuint _textureId) { GL_CHECK(glBindTexture(_target, _textureId)); }\n\n void configure() {\n s_textureUnit = -1;\n s_validGeneration++;\n VertexLayout::clearCache();\n\n blending.init(GL_FALSE);\n blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n culling.init(GL_TRUE);\n cullFace.init(GL_BACK);\n frontFace.init(GL_CCW);\n depthTest.init(GL_TRUE);\n depthWrite.init(GL_TRUE);\n\n GL_CHECK(glDisable(GL_STENCIL_TEST));\n GL_CHECK(glDepthFunc(GL_LESS));\n GL_CHECK(glClearDepthf(1.0));\n GL_CHECK(glDepthRangef(0.0, 1.0));\n\n static size_t max = std::numeric_limits::max();\n\n clearColor.init(0.0, 0.0, 0.0, 0.0);\n shaderProgram.init(max, false);\n vertexBuffer.init(max, false);\n indexBuffer.init(max, false);\n texture.init(GL_TEXTURE_2D, max, false);\n texture.init(GL_TEXTURE_CUBE_MAP, max, false);\n textureUnit.init(max, false);\n }\n\n bool isValidGeneration(int _generation) {\n return _generation == s_validGeneration;\n }\n\n int generation() {\n return s_validGeneration;\n }\n\n int nextAvailableTextureUnit() {\n if (s_textureUnit + 1 > Hardware::maxCombinedTextureUnits) {\n LOGE(\"Too many combined texture units are being used\");\n LOGE(\"GPU supports %d combined texture units\", Hardware::maxCombinedTextureUnits);\n }\n\n return ++s_textureUnit;\n }\n\n void releaseTextureUnit() {\n s_textureUnit--;\n }\n\n int currentTextureUnit() {\n return s_textureUnit;\n }\n\n void resetTextureUnit() {\n s_textureUnit = -1;\n }\n}\n\n}\nInvalidate render state tracking of current texture binding (#784)#include \"renderState.h\"\n\n#include \"platform.h\"\n#include \"vertexLayout.h\"\n#include \"gl\/hardware.h\"\n\nnamespace Tangram {\n\n \/\/ Incremented when the GL context is invalidated\nstatic int s_validGeneration;\nstatic int s_textureUnit;\n\nnamespace RenderState {\n\n Blending blending;\n DepthTest depthTest;\n StencilTest stencilTest;\n Culling culling;\n DepthWrite depthWrite;\n BlendingFunc blendingFunc;\n StencilWrite stencilWrite;\n StencilFunc stencilFunc;\n StencilOp stencilOp;\n ColorWrite colorWrite;\n FrontFace frontFace;\n CullFace cullFace;\n\n VertexBuffer vertexBuffer;\n IndexBuffer indexBuffer;\n\n ShaderProgram shaderProgram;\n\n TextureUnit textureUnit;\n Texture texture;\n\n ClearColor clearColor;\n\n GLuint getTextureUnit(GLuint _unit) {\n return GL_TEXTURE0 + _unit;\n }\n\n static size_t max = std::numeric_limits::max();\n\n void bindVertexBuffer(GLuint _id) {\n GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _id));\n }\n\n void bindIndexBuffer(GLuint _id) {\n GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id));\n }\n\n void activeTextureUnit(GLuint _unit) {\n \/\/ current texture unit is changing, invalidate current texture binding:\n texture.init(GL_TEXTURE_2D, max, false);\n GL_CHECK(glActiveTexture(getTextureUnit(_unit)));\n }\n\n void bindTexture(GLenum _target, GLuint _textureId) {\n GL_CHECK(glBindTexture(_target, _textureId));\n }\n\n void configure() {\n s_textureUnit = -1;\n s_validGeneration++;\n VertexLayout::clearCache();\n\n blending.init(GL_FALSE);\n blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n culling.init(GL_TRUE);\n cullFace.init(GL_BACK);\n frontFace.init(GL_CCW);\n depthTest.init(GL_TRUE);\n depthWrite.init(GL_TRUE);\n\n GL_CHECK(glDisable(GL_STENCIL_TEST));\n GL_CHECK(glDepthFunc(GL_LESS));\n GL_CHECK(glClearDepthf(1.0));\n GL_CHECK(glDepthRangef(0.0, 1.0));\n\n\n clearColor.init(0.0, 0.0, 0.0, 0.0);\n shaderProgram.init(max, false);\n vertexBuffer.init(max, false);\n indexBuffer.init(max, false);\n texture.init(GL_TEXTURE_2D, max, false);\n texture.init(GL_TEXTURE_CUBE_MAP, max, false);\n textureUnit.init(max, false);\n }\n\n bool isValidGeneration(int _generation) {\n return _generation == s_validGeneration;\n }\n\n int generation() {\n return s_validGeneration;\n }\n\n int nextAvailableTextureUnit() {\n if (s_textureUnit + 1 > Hardware::maxCombinedTextureUnits) {\n LOGE(\"Too many combined texture units are being used\");\n LOGE(\"GPU supports %d combined texture units\", Hardware::maxCombinedTextureUnits);\n }\n\n return ++s_textureUnit;\n }\n\n void releaseTextureUnit() {\n s_textureUnit--;\n }\n\n int currentTextureUnit() {\n return s_textureUnit;\n }\n\n void resetTextureUnit() {\n s_textureUnit = -1;\n }\n}\n\n}\n<|endoftext|>"} {"text":"#include \"pbfParser.h\"\n\n#include \"tile\/tile.h\"\n#include \"platform.h\"\n\nnamespace Tangram {\n\nvoid PbfParser::extractGeometry(ParserContext& _ctx, protobuf::message& _geomIn) {\n\n pbfGeomCmd cmd = pbfGeomCmd::moveTo;\n uint32_t cmdRepeat = 0;\n\n double invTileExtent = (1.0\/(double)_ctx.tileExtent);\n\n int64_t x = 0;\n int64_t y = 0;\n\n size_t numCoordinates = 0;\n\n while(_geomIn.getData() < _geomIn.getEnd()) {\n\n if(cmdRepeat == 0) { \/\/ get new command, lengh and parameters..\n uint32_t cmdData = static_cast(_geomIn.varint());\n cmd = static_cast(cmdData & 0x7); \/\/first 3 bits of the cmdData\n cmdRepeat = cmdData >> 3; \/\/last 5 bits\n }\n\n if(cmd == pbfGeomCmd::moveTo || cmd == pbfGeomCmd::lineTo) { \/\/ get parameters\/points\n \/\/ if cmd is move then move to a new line\/set of points and save this line\n if(cmd == pbfGeomCmd::moveTo) {\n if(_ctx.coordinates.size() > 0) {\n _ctx.numCoordinates.push_back(numCoordinates);\n }\n numCoordinates = 0;\n }\n\n x += _geomIn.svarint();\n y += _geomIn.svarint();\n\n \/\/ bring the points in -1 to 1 space\n Point p;\n p.x = invTileExtent * (double)(2 * x - _ctx.tileExtent);\n p.y = invTileExtent * (double)(_ctx.tileExtent - 2 * y);\n\n _ctx.coordinates.push_back(p);\n numCoordinates++;\n\n } else if(cmd == pbfGeomCmd::closePath) {\n \/\/ end of a polygon, push first point in this line as last and push line to poly\n _ctx.coordinates.push_back(_ctx.coordinates[_ctx.coordinates.size() - numCoordinates]);\n _ctx.numCoordinates.push_back(numCoordinates + 1);\n numCoordinates = 0;\n }\n\n cmdRepeat--;\n }\n\n \/\/ Enter the last line\n if (numCoordinates > 0) {\n _ctx.numCoordinates.push_back(numCoordinates);\n }\n}\n\nvoid PbfParser::extractFeature(ParserContext& _ctx, protobuf::message& _featureIn, Feature& _out) {\n\n \/\/Iterate through this feature\n protobuf::message geometry; \/\/ By default data_ and end_ are nullptr\n\n _ctx.properties.clear();\n _ctx.coordinates.clear();\n _ctx.numCoordinates.clear();\n\n while(_featureIn.next()) {\n switch(_featureIn.tag) {\n \/\/ Feature ID\n case 1:\n \/\/ ignored for now, also not used in json parsing\n _featureIn.skip();\n break;\n \/\/ Feature tags (properties)\n case 2:\n {\n \/\/ extract tags message\n protobuf::message tagsMsg = _featureIn.getMessage();\n\n while(tagsMsg) {\n std::size_t tagKey = tagsMsg.varint();\n\n if(_ctx.keys.size() <= tagKey) {\n logMsg(\"ERROR: accessing out of bound key\\n\");\n return;\n }\n\n if(!tagsMsg) {\n logMsg(\"ERROR: uneven number of feature tag ids\\n\");\n return;\n }\n\n std::size_t valueKey = tagsMsg.varint();\n\n if( _ctx.values.size() <= valueKey ) {\n logMsg(\"ERROR: accessing out of bound values\\n\");\n return;\n }\n\n _ctx.properties.emplace_back(_ctx.keys[tagKey], _ctx.values[valueKey]);\n }\n break;\n }\n \/\/ Feature Type\n case 3:\n _out.geometryType = (GeometryType)_featureIn.varint();\n break;\n \/\/ Actual geometry data\n case 4:\n geometry = _featureIn.getMessage();\n extractGeometry(_ctx, geometry);\n break;\n \/\/ None.. skip\n default:\n _featureIn.skip();\n break;\n }\n }\n _out.props = std::move(_ctx.properties);\n\n\n switch(_out.geometryType) {\n case GeometryType::points:\n _out.points.insert(_out.points.begin(),\n _ctx.coordinates.begin(),\n _ctx.coordinates.end());\n break;\n\n case GeometryType::lines:\n case GeometryType::polygons:\n {\n std::vector lines;\n int offset = 0;\n lines.reserve(_ctx.numCoordinates.size());\n\n for (int length : _ctx.numCoordinates) {\n if (length == 0) {\n continue;\n }\n\n lines.emplace_back();\n auto& line = lines.back();\n line.reserve(length);\n\n line.insert(line.begin(),\n _ctx.coordinates.begin() + offset,\n _ctx.coordinates.begin() + offset + length);\n\n offset += length;\n }\n if (_out.geometryType == GeometryType::lines) {\n _out.lines = std::move(lines);\n } else {\n _out.polygons.push_back(std::move(lines));\n }\n break;\n }\n case GeometryType::unknown:\n break;\n default:\n break;\n }\n\n}\n\nvoid PbfParser::extractLayer(ParserContext& _ctx, protobuf::message& _layerIn, Layer& _out) {\n\n _ctx.keys.clear();\n _ctx.values.clear();\n _ctx.featureMsgs.clear();\n\n \/\/iterate layer to populate featureMsgs, keys and values\n while(_layerIn.next()) {\n switch(_layerIn.tag) {\n case 2: \/\/ features\n {\n _ctx.featureMsgs.push_back(_layerIn.getMessage());\n break;\n }\n\n case 3: \/\/ key string\n {\n _ctx.keys.push_back(_layerIn.string());\n break;\n }\n\n case 4: \/\/ values\n {\n protobuf::message valueItr = _layerIn.getMessage();\n\n while (valueItr.next()) {\n switch (valueItr.tag) {\n case 1: \/\/ string value\n _ctx.values.push_back(valueItr.string());\n break;\n case 2: \/\/ float value\n _ctx.values.push_back(valueItr.float32());\n break;\n case 3: \/\/ double value\n _ctx.values.push_back(valueItr.float64());\n break;\n case 4: \/\/ int value\n _ctx.values.push_back(valueItr.int64());\n break;\n case 5: \/\/ uint value\n _ctx.values.push_back(valueItr.varint());\n break;\n case 6: \/\/ sint value\n _ctx.values.push_back(valueItr.int64());\n break;\n case 7: \/\/ bool value\n _ctx.values.push_back(valueItr.boolean());\n break;\n default:\n _ctx.values.push_back(none_type{});\n valueItr.skip();\n break;\n }\n }\n break;\n }\n\n case 5: \/\/extent\n _ctx.tileExtent = static_cast(_layerIn.int64());\n break;\n\n default: \/\/ skip\n _layerIn.skip();\n break;\n }\n }\n\n _out.features.reserve(_ctx.featureMsgs.size());\n for(auto& featureMsg : _ctx.featureMsgs) {\n _out.features.emplace_back();\n extractFeature(_ctx, featureMsg, _out.features.back());\n }\n}\n\n}\nmove value string in pbf parser#include \"pbfParser.h\"\n\n#include \"tile\/tile.h\"\n#include \"platform.h\"\n\nnamespace Tangram {\n\nvoid PbfParser::extractGeometry(ParserContext& _ctx, protobuf::message& _geomIn) {\n\n pbfGeomCmd cmd = pbfGeomCmd::moveTo;\n uint32_t cmdRepeat = 0;\n\n double invTileExtent = (1.0\/(double)_ctx.tileExtent);\n\n int64_t x = 0;\n int64_t y = 0;\n\n size_t numCoordinates = 0;\n\n while(_geomIn.getData() < _geomIn.getEnd()) {\n\n if(cmdRepeat == 0) { \/\/ get new command, lengh and parameters..\n uint32_t cmdData = static_cast(_geomIn.varint());\n cmd = static_cast(cmdData & 0x7); \/\/first 3 bits of the cmdData\n cmdRepeat = cmdData >> 3; \/\/last 5 bits\n }\n\n if(cmd == pbfGeomCmd::moveTo || cmd == pbfGeomCmd::lineTo) { \/\/ get parameters\/points\n \/\/ if cmd is move then move to a new line\/set of points and save this line\n if(cmd == pbfGeomCmd::moveTo) {\n if(_ctx.coordinates.size() > 0) {\n _ctx.numCoordinates.push_back(numCoordinates);\n }\n numCoordinates = 0;\n }\n\n x += _geomIn.svarint();\n y += _geomIn.svarint();\n\n \/\/ bring the points in -1 to 1 space\n Point p;\n p.x = invTileExtent * (double)(2 * x - _ctx.tileExtent);\n p.y = invTileExtent * (double)(_ctx.tileExtent - 2 * y);\n\n _ctx.coordinates.push_back(p);\n numCoordinates++;\n\n } else if(cmd == pbfGeomCmd::closePath) {\n \/\/ end of a polygon, push first point in this line as last and push line to poly\n _ctx.coordinates.push_back(_ctx.coordinates[_ctx.coordinates.size() - numCoordinates]);\n _ctx.numCoordinates.push_back(numCoordinates + 1);\n numCoordinates = 0;\n }\n\n cmdRepeat--;\n }\n\n \/\/ Enter the last line\n if (numCoordinates > 0) {\n _ctx.numCoordinates.push_back(numCoordinates);\n }\n}\n\nvoid PbfParser::extractFeature(ParserContext& _ctx, protobuf::message& _featureIn, Feature& _out) {\n\n \/\/Iterate through this feature\n protobuf::message geometry; \/\/ By default data_ and end_ are nullptr\n\n _ctx.properties.clear();\n _ctx.coordinates.clear();\n _ctx.numCoordinates.clear();\n\n while(_featureIn.next()) {\n switch(_featureIn.tag) {\n \/\/ Feature ID\n case 1:\n \/\/ ignored for now, also not used in json parsing\n _featureIn.skip();\n break;\n \/\/ Feature tags (properties)\n case 2:\n {\n \/\/ extract tags message\n protobuf::message tagsMsg = _featureIn.getMessage();\n\n while(tagsMsg) {\n std::size_t tagKey = tagsMsg.varint();\n\n if(_ctx.keys.size() <= tagKey) {\n logMsg(\"ERROR: accessing out of bound key\\n\");\n return;\n }\n\n if(!tagsMsg) {\n logMsg(\"ERROR: uneven number of feature tag ids\\n\");\n return;\n }\n\n std::size_t valueKey = tagsMsg.varint();\n\n if( _ctx.values.size() <= valueKey ) {\n logMsg(\"ERROR: accessing out of bound values\\n\");\n return;\n }\n\n _ctx.properties.emplace_back(_ctx.keys[tagKey], _ctx.values[valueKey]);\n }\n break;\n }\n \/\/ Feature Type\n case 3:\n _out.geometryType = (GeometryType)_featureIn.varint();\n break;\n \/\/ Actual geometry data\n case 4:\n geometry = _featureIn.getMessage();\n extractGeometry(_ctx, geometry);\n break;\n \/\/ None.. skip\n default:\n _featureIn.skip();\n break;\n }\n }\n _out.props = std::move(_ctx.properties);\n\n\n switch(_out.geometryType) {\n case GeometryType::points:\n _out.points.insert(_out.points.begin(),\n _ctx.coordinates.begin(),\n _ctx.coordinates.end());\n break;\n\n case GeometryType::lines:\n case GeometryType::polygons:\n {\n std::vector lines;\n int offset = 0;\n lines.reserve(_ctx.numCoordinates.size());\n\n for (int length : _ctx.numCoordinates) {\n if (length == 0) {\n continue;\n }\n\n lines.emplace_back();\n auto& line = lines.back();\n line.reserve(length);\n\n line.insert(line.begin(),\n _ctx.coordinates.begin() + offset,\n _ctx.coordinates.begin() + offset + length);\n\n offset += length;\n }\n if (_out.geometryType == GeometryType::lines) {\n _out.lines = std::move(lines);\n } else {\n _out.polygons.push_back(std::move(lines));\n }\n break;\n }\n case GeometryType::unknown:\n break;\n default:\n break;\n }\n\n}\n\nvoid PbfParser::extractLayer(ParserContext& _ctx, protobuf::message& _layerIn, Layer& _out) {\n\n _ctx.keys.clear();\n _ctx.values.clear();\n _ctx.featureMsgs.clear();\n\n \/\/iterate layer to populate featureMsgs, keys and values\n while(_layerIn.next()) {\n switch(_layerIn.tag) {\n case 2: \/\/ features\n {\n _ctx.featureMsgs.push_back(_layerIn.getMessage());\n break;\n }\n\n case 3: \/\/ key string\n {\n _ctx.keys.push_back(_layerIn.string());\n break;\n }\n\n case 4: \/\/ values\n {\n protobuf::message valueItr = _layerIn.getMessage();\n\n while (valueItr.next()) {\n switch (valueItr.tag) {\n case 1: \/\/ string value\n _ctx.values.push_back(std::move(valueItr.string()));\n break;\n case 2: \/\/ float value\n _ctx.values.push_back(valueItr.float32());\n break;\n case 3: \/\/ double value\n _ctx.values.push_back(valueItr.float64());\n break;\n case 4: \/\/ int value\n _ctx.values.push_back(valueItr.int64());\n break;\n case 5: \/\/ uint value\n _ctx.values.push_back(valueItr.varint());\n break;\n case 6: \/\/ sint value\n _ctx.values.push_back(valueItr.int64());\n break;\n case 7: \/\/ bool value\n _ctx.values.push_back(valueItr.boolean());\n break;\n default:\n _ctx.values.push_back(none_type{});\n valueItr.skip();\n break;\n }\n }\n break;\n }\n\n case 5: \/\/extent\n _ctx.tileExtent = static_cast(_layerIn.int64());\n break;\n\n default: \/\/ skip\n _layerIn.skip();\n break;\n }\n }\n\n _out.features.reserve(_ctx.featureMsgs.size());\n for(auto& featureMsg : _ctx.featureMsgs) {\n _out.features.emplace_back();\n extractFeature(_ctx, featureMsg, _out.features.back());\n }\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This file implements the ViewGLContext and PbufferGLContext classes.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"app\/x11_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"app\/gfx\/gl\/gl_context.h\"\n#include \"app\/gfx\/gl\/gl_context_osmesa.h\"\n\nnamespace gfx {\n\ntypedef GLXContext GLContextHandle;\ntypedef GLXPbuffer PbufferHandle;\n\n\/\/ This class is a wrapper around a GL context that renders directly to a\n\/\/ window.\nclass ViewGLContext : public GLContext {\n public:\n explicit ViewGLContext(gfx::PluginWindowHandle window)\n : window_(window),\n context_(NULL) {\n DCHECK(window);\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(bool multisampled);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n gfx::PluginWindowHandle window_;\n GLContextHandle context_;\n\n DISALLOW_COPY_AND_ASSIGN(ViewGLContext);\n};\n\n\/\/ This class is a wrapper around a GL context used for offscreen rendering.\n\/\/ It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful\n\/\/ rendering.\nclass PbufferGLContext : public GLContext {\n public:\n explicit PbufferGLContext()\n : context_(NULL),\n pbuffer_(0) {\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(void* shared_handle);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n GLContextHandle context_;\n PbufferHandle pbuffer_;\n\n DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);\n};\n\n\/\/ Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower...\nclass PixmapGLContext : public GLContext {\n public:\n explicit PixmapGLContext()\n : context_(NULL),\n pixmap_(0),\n glx_pixmap_(0) {\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(void* shared_handle);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n GLContextHandle context_;\n Pixmap pixmap_;\n GLXPixmap glx_pixmap_;\n\n DISALLOW_COPY_AND_ASSIGN(PixmapGLContext);\n};\n\n\/\/ scoped_ptr functor for XFree(). Use as follows:\n\/\/ scoped_ptr_malloc foo(...);\n\/\/ where \"XVisualInfo\" is any X type that is freed with XFree.\nclass ScopedPtrXFree {\n public:\n void operator()(void* x) const {\n ::XFree(x);\n }\n};\n\n\/\/ Some versions of NVIDIA's GL libGL.so include a broken version of\n\/\/ dlopen\/dlsym, and so linking it into chrome breaks it. So we dynamically\n\/\/ load it, and use glew to dynamically resolve symbols.\n\/\/ See http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=16800\n\nstatic bool InitializeOneOff() {\n static bool initialized = false;\n if (initialized)\n return true;\n\n osmewInit();\n if (!OSMesaCreateContext) {\n void* handle = dlopen(\"libGL.so.1\", RTLD_LAZY | RTLD_GLOBAL);\n if (!handle) {\n LOG(ERROR) << \"Could not find libGL.so.1\";\n return false;\n }\n\n \/\/ Initializes context-independent parts of GLEW\n if (glxewInit() != GLEW_OK) {\n LOG(ERROR) << \"glxewInit failed\";\n return false;\n }\n \/\/ glxewContextInit really only needs a display connection to\n \/\/ complete, and we don't want to have to create an OpenGL context\n \/\/ just to get access to GLX 1.3 entry points to create pbuffers.\n \/\/ We therefore added a glxewContextInitWithDisplay entry point.\n Display* display = x11_util::GetXDisplay();\n if (glxewContextInitWithDisplay(display) != GLEW_OK) {\n LOG(ERROR) << \"glxewContextInit failed\";\n return false;\n }\n }\n\n initialized = true;\n return true;\n}\n\nbool ViewGLContext::Initialize(bool multisampled) {\n if (multisampled) {\n DLOG(WARNING) << \"Multisampling not implemented.\";\n }\n\n Display* display = x11_util::GetXDisplay();\n XWindowAttributes attributes;\n XGetWindowAttributes(display, window_, &attributes);\n XVisualInfo visual_info_template;\n visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);\n int visual_info_count = 0;\n scoped_ptr_malloc visual_info_list(\n XGetVisualInfo(display, VisualIDMask,\n &visual_info_template,\n &visual_info_count));\n DCHECK(visual_info_list.get());\n DCHECK_GT(visual_info_count, 0);\n context_ = NULL;\n for (int i = 0; i < visual_info_count; ++i) {\n context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);\n if (context_)\n break;\n }\n if (!context_) {\n DLOG(ERROR) << \"Couldn't create GL context.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid ViewGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n}\n\nbool ViewGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, window_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = 0;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool ViewGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == window_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool ViewGLContext::IsOffscreen() {\n return false;\n}\n\nvoid ViewGLContext::SwapBuffers() {\n Display* display = x11_util::GetXDisplay();\n glXSwapBuffers(display, window_);\n}\n\ngfx::Size ViewGLContext::GetSize() {\n XWindowAttributes attributes;\n Display* display = x11_util::GetXDisplay();\n XGetWindowAttributes(display, window_, &attributes);\n return gfx::Size(attributes.width, attributes.height);\n}\n\nvoid* ViewGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,\n bool multisampled) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n \/\/ TODO(apatrick): Support OSMesa rendering to a window on Linux.\n NOTREACHED() << \"OSMesa rendering to a window is not yet implemented.\";\n return NULL;\n } else {\n scoped_ptr context(new ViewGLContext(window));\n\n if (!context->Initialize(multisampled))\n return NULL;\n\n return context.release();\n }\n}\n\nbool PbufferGLContext::Initialize(void* shared_handle) {\n if (!glXChooseFBConfig ||\n !glXCreateNewContext ||\n !glXCreatePbuffer ||\n !glXDestroyPbuffer) {\n DLOG(ERROR) << \"Pbuffer support not available.\";\n return false;\n }\n\n static const int config_attributes[] = {\n GLX_DRAWABLE_TYPE,\n GLX_PBUFFER_BIT,\n GLX_RENDER_TYPE,\n GLX_RGBA_BIT,\n GLX_DOUBLEBUFFER,\n 0,\n 0\n };\n\n Display* display = x11_util::GetXDisplay();\n\n int nelements = 0;\n \/\/ TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.\n scoped_ptr_malloc config(\n glXChooseFBConfig(display, 0, config_attributes, &nelements));\n if (!config.get()) {\n DLOG(ERROR) << \"glXChooseFBConfig failed.\";\n return false;\n }\n if (!nelements) {\n DLOG(ERROR) << \"glXChooseFBConfig returned 0 elements.\";\n return false;\n }\n context_ = glXCreateNewContext(display,\n config.get()[0],\n GLX_RGBA_TYPE,\n static_cast(shared_handle),\n True);\n if (!context_) {\n DLOG(ERROR) << \"glXCreateNewContext failed.\";\n return false;\n }\n static const int pbuffer_attributes[] = {\n GLX_PBUFFER_WIDTH,\n 1,\n GLX_PBUFFER_HEIGHT,\n 1,\n 0\n };\n pbuffer_ = glXCreatePbuffer(display,\n config.get()[0], pbuffer_attributes);\n if (!pbuffer_) {\n Destroy();\n DLOG(ERROR) << \"glXCreatePbuffer failed.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid PbufferGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n\n if (pbuffer_) {\n glXDestroyPbuffer(display, pbuffer_);\n pbuffer_ = 0;\n }\n}\n\nbool PbufferGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, pbuffer_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool PbufferGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == pbuffer_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool PbufferGLContext::IsOffscreen() {\n return true;\n}\n\nvoid PbufferGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a pbuffer.\";\n}\n\ngfx::Size PbufferGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this pbuffer.\";\n return gfx::Size(1, 1);\n}\n\nvoid* PbufferGLContext::GetHandle() {\n return context_;\n}\n\nbool PixmapGLContext::Initialize(void* shared_handle) {\n DLOG(INFO) << \"GL context: using pixmaps.\";\n if (!glXChooseVisual ||\n !glXCreateGLXPixmap ||\n !glXDestroyGLXPixmap) {\n DLOG(ERROR) << \"Pixmap support not available.\";\n return false;\n }\n\n static int attributes[] = {\n GLX_RGBA,\n 0\n };\n\n Display* display = x11_util::GetXDisplay();\n int screen = DefaultScreen(display);\n\n scoped_ptr_malloc visual_info(\n glXChooseVisual(display, screen, attributes));\n\n if (!visual_info.get()) {\n DLOG(ERROR) << \"glXChooseVisual failed.\";\n return false;\n }\n context_ = glXCreateContext(display, visual_info.get(),\n static_cast(shared_handle),\n True);\n if (!context_) {\n DLOG(ERROR) << \"glXCreateContext failed.\";\n return false;\n }\n\n pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1,\n visual_info->depth);\n if (!pixmap_) {\n DLOG(ERROR) << \"XCreatePixmap failed.\";\n return false;\n }\n\n glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_);\n if (!glx_pixmap_) {\n DLOG(ERROR) << \"XCreatePixmap failed.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid PixmapGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n\n if (glx_pixmap_) {\n glXDestroyGLXPixmap(display, glx_pixmap_);\n glx_pixmap_ = 0;\n }\n\n if (pixmap_) {\n XFreePixmap(display, pixmap_);\n pixmap_ = 0;\n }\n}\n\nbool PixmapGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, glx_pixmap_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool PixmapGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == glx_pixmap_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool PixmapGLContext::IsOffscreen() {\n return true;\n}\n\nvoid PixmapGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a pixmap.\";\n}\n\ngfx::Size PixmapGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this pixmap.\";\n return gfx::Size(1, 1);\n}\n\nvoid* PixmapGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n scoped_ptr context(new OSMesaGLContext);\n\n if (!context->Initialize(shared_handle))\n return NULL;\n\n return context.release();\n } else {\n scoped_ptr context(new PbufferGLContext);\n if (context->Initialize(shared_handle))\n return context.release();\n\n scoped_ptr context_pixmap(new PixmapGLContext);\n if (context_pixmap->Initialize(shared_handle))\n return context_pixmap.release();\n\n return NULL;\n }\n}\n\n} \/\/ namespace gfx\nChanged DLOG to LOG in gl_context_linux.cc to get informative error messages even in release builds when WebGL initialization fails.\/\/ 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\/\/ This file implements the ViewGLContext and PbufferGLContext classes.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"app\/x11_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"app\/gfx\/gl\/gl_context.h\"\n#include \"app\/gfx\/gl\/gl_context_osmesa.h\"\n\nnamespace gfx {\n\ntypedef GLXContext GLContextHandle;\ntypedef GLXPbuffer PbufferHandle;\n\n\/\/ This class is a wrapper around a GL context that renders directly to a\n\/\/ window.\nclass ViewGLContext : public GLContext {\n public:\n explicit ViewGLContext(gfx::PluginWindowHandle window)\n : window_(window),\n context_(NULL) {\n DCHECK(window);\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(bool multisampled);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n gfx::PluginWindowHandle window_;\n GLContextHandle context_;\n\n DISALLOW_COPY_AND_ASSIGN(ViewGLContext);\n};\n\n\/\/ This class is a wrapper around a GL context used for offscreen rendering.\n\/\/ It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful\n\/\/ rendering.\nclass PbufferGLContext : public GLContext {\n public:\n explicit PbufferGLContext()\n : context_(NULL),\n pbuffer_(0) {\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(void* shared_handle);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n GLContextHandle context_;\n PbufferHandle pbuffer_;\n\n DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);\n};\n\n\/\/ Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower...\nclass PixmapGLContext : public GLContext {\n public:\n explicit PixmapGLContext()\n : context_(NULL),\n pixmap_(0),\n glx_pixmap_(0) {\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(void* shared_handle);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n GLContextHandle context_;\n Pixmap pixmap_;\n GLXPixmap glx_pixmap_;\n\n DISALLOW_COPY_AND_ASSIGN(PixmapGLContext);\n};\n\n\/\/ scoped_ptr functor for XFree(). Use as follows:\n\/\/ scoped_ptr_malloc foo(...);\n\/\/ where \"XVisualInfo\" is any X type that is freed with XFree.\nclass ScopedPtrXFree {\n public:\n void operator()(void* x) const {\n ::XFree(x);\n }\n};\n\n\/\/ Some versions of NVIDIA's GL libGL.so include a broken version of\n\/\/ dlopen\/dlsym, and so linking it into chrome breaks it. So we dynamically\n\/\/ load it, and use glew to dynamically resolve symbols.\n\/\/ See http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=16800\n\nstatic bool InitializeOneOff() {\n static bool initialized = false;\n if (initialized)\n return true;\n\n osmewInit();\n if (!OSMesaCreateContext) {\n void* handle = dlopen(\"libGL.so.1\", RTLD_LAZY | RTLD_GLOBAL);\n if (!handle) {\n LOG(ERROR) << \"Could not find libGL.so.1\";\n return false;\n }\n\n \/\/ Initializes context-independent parts of GLEW\n if (glxewInit() != GLEW_OK) {\n LOG(ERROR) << \"glxewInit failed\";\n return false;\n }\n \/\/ glxewContextInit really only needs a display connection to\n \/\/ complete, and we don't want to have to create an OpenGL context\n \/\/ just to get access to GLX 1.3 entry points to create pbuffers.\n \/\/ We therefore added a glxewContextInitWithDisplay entry point.\n Display* display = x11_util::GetXDisplay();\n if (glxewContextInitWithDisplay(display) != GLEW_OK) {\n LOG(ERROR) << \"glxewContextInit failed\";\n return false;\n }\n }\n\n initialized = true;\n return true;\n}\n\nbool ViewGLContext::Initialize(bool multisampled) {\n if (multisampled) {\n LOG(WARNING) << \"Multisampling not implemented.\";\n }\n\n Display* display = x11_util::GetXDisplay();\n XWindowAttributes attributes;\n XGetWindowAttributes(display, window_, &attributes);\n XVisualInfo visual_info_template;\n visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);\n int visual_info_count = 0;\n scoped_ptr_malloc visual_info_list(\n XGetVisualInfo(display, VisualIDMask,\n &visual_info_template,\n &visual_info_count));\n DCHECK(visual_info_list.get());\n DCHECK_GT(visual_info_count, 0);\n context_ = NULL;\n for (int i = 0; i < visual_info_count; ++i) {\n context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);\n if (context_)\n break;\n }\n if (!context_) {\n LOG(ERROR) << \"Couldn't create GL context.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n LOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid ViewGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n}\n\nbool ViewGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, window_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = 0;\n LOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool ViewGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == window_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool ViewGLContext::IsOffscreen() {\n return false;\n}\n\nvoid ViewGLContext::SwapBuffers() {\n Display* display = x11_util::GetXDisplay();\n glXSwapBuffers(display, window_);\n}\n\ngfx::Size ViewGLContext::GetSize() {\n XWindowAttributes attributes;\n Display* display = x11_util::GetXDisplay();\n XGetWindowAttributes(display, window_, &attributes);\n return gfx::Size(attributes.width, attributes.height);\n}\n\nvoid* ViewGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,\n bool multisampled) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n \/\/ TODO(apatrick): Support OSMesa rendering to a window on Linux.\n NOTREACHED() << \"OSMesa rendering to a window is not yet implemented.\";\n return NULL;\n } else {\n scoped_ptr context(new ViewGLContext(window));\n\n if (!context->Initialize(multisampled))\n return NULL;\n\n return context.release();\n }\n}\n\nbool PbufferGLContext::Initialize(void* shared_handle) {\n if (!glXChooseFBConfig ||\n !glXCreateNewContext ||\n !glXCreatePbuffer ||\n !glXDestroyPbuffer) {\n LOG(ERROR) << \"Pbuffer support not available.\";\n return false;\n }\n\n static const int config_attributes[] = {\n GLX_DRAWABLE_TYPE,\n GLX_PBUFFER_BIT,\n GLX_RENDER_TYPE,\n GLX_RGBA_BIT,\n GLX_DOUBLEBUFFER,\n 0,\n 0\n };\n\n Display* display = x11_util::GetXDisplay();\n\n int nelements = 0;\n \/\/ TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.\n scoped_ptr_malloc config(\n glXChooseFBConfig(display, 0, config_attributes, &nelements));\n if (!config.get()) {\n LOG(ERROR) << \"glXChooseFBConfig failed.\";\n return false;\n }\n if (!nelements) {\n LOG(ERROR) << \"glXChooseFBConfig returned 0 elements.\";\n return false;\n }\n context_ = glXCreateNewContext(display,\n config.get()[0],\n GLX_RGBA_TYPE,\n static_cast(shared_handle),\n True);\n if (!context_) {\n LOG(ERROR) << \"glXCreateNewContext failed.\";\n return false;\n }\n static const int pbuffer_attributes[] = {\n GLX_PBUFFER_WIDTH,\n 1,\n GLX_PBUFFER_HEIGHT,\n 1,\n 0\n };\n pbuffer_ = glXCreatePbuffer(display,\n config.get()[0], pbuffer_attributes);\n if (!pbuffer_) {\n Destroy();\n LOG(ERROR) << \"glXCreatePbuffer failed.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n LOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid PbufferGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n\n if (pbuffer_) {\n glXDestroyPbuffer(display, pbuffer_);\n pbuffer_ = 0;\n }\n}\n\nbool PbufferGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, pbuffer_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n LOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool PbufferGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == pbuffer_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool PbufferGLContext::IsOffscreen() {\n return true;\n}\n\nvoid PbufferGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a pbuffer.\";\n}\n\ngfx::Size PbufferGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this pbuffer.\";\n return gfx::Size(1, 1);\n}\n\nvoid* PbufferGLContext::GetHandle() {\n return context_;\n}\n\nbool PixmapGLContext::Initialize(void* shared_handle) {\n LOG(INFO) << \"GL context: using pixmaps.\";\n if (!glXChooseVisual ||\n !glXCreateGLXPixmap ||\n !glXDestroyGLXPixmap) {\n LOG(ERROR) << \"Pixmap support not available.\";\n return false;\n }\n\n static int attributes[] = {\n GLX_RGBA,\n 0\n };\n\n Display* display = x11_util::GetXDisplay();\n int screen = DefaultScreen(display);\n\n scoped_ptr_malloc visual_info(\n glXChooseVisual(display, screen, attributes));\n\n if (!visual_info.get()) {\n LOG(ERROR) << \"glXChooseVisual failed.\";\n return false;\n }\n context_ = glXCreateContext(display, visual_info.get(),\n static_cast(shared_handle),\n True);\n if (!context_) {\n LOG(ERROR) << \"glXCreateContext failed.\";\n return false;\n }\n\n pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1,\n visual_info->depth);\n if (!pixmap_) {\n LOG(ERROR) << \"XCreatePixmap failed.\";\n return false;\n }\n\n glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_);\n if (!glx_pixmap_) {\n LOG(ERROR) << \"XCreatePixmap failed.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n LOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid PixmapGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n\n if (glx_pixmap_) {\n glXDestroyGLXPixmap(display, glx_pixmap_);\n glx_pixmap_ = 0;\n }\n\n if (pixmap_) {\n XFreePixmap(display, pixmap_);\n pixmap_ = 0;\n }\n}\n\nbool PixmapGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, glx_pixmap_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n LOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool PixmapGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == glx_pixmap_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool PixmapGLContext::IsOffscreen() {\n return true;\n}\n\nvoid PixmapGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a pixmap.\";\n}\n\ngfx::Size PixmapGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this pixmap.\";\n return gfx::Size(1, 1);\n}\n\nvoid* PixmapGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n scoped_ptr context(new OSMesaGLContext);\n\n if (!context->Initialize(shared_handle))\n return NULL;\n\n return context.release();\n } else {\n scoped_ptr context(new PbufferGLContext);\n if (context->Initialize(shared_handle))\n return context.release();\n\n scoped_ptr context_pixmap(new PixmapGLContext);\n if (context_pixmap->Initialize(shared_handle))\n return context_pixmap.release();\n\n return NULL;\n }\n}\n\n} \/\/ namespace gfx\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<update hdu2084#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\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<"} {"text":"#include \"Runtime\/CResFactory.hpp\"\n\n#include \"Runtime\/CSimplePool.hpp\"\n#include \"Runtime\/CStopwatch.hpp\"\n\nnamespace urde {\nstatic logvisor::Module Log(\"CResFactory\");\n\nvoid CResFactory::AddToLoadList(SLoadingData&& data) {\n const SObjectTag tag = data.x0_tag;\n m_loadMap.insert_or_assign(tag, m_loadList.insert(m_loadList.end(), std::move(data)));\n}\n\nCFactoryFnReturn CResFactory::BuildSync(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) {\n CFactoryFnReturn ret;\n if (x5c_factoryMgr.CanMakeMemory(tag)) {\n std::unique_ptr data;\n int size = 0;\n x4_loader.LoadMemResourceSync(tag, data, &size);\n if (size)\n ret = x5c_factoryMgr.MakeObjectFromMemory(tag, std::move(data), size, x4_loader.GetResourceCompression(tag), xfer,\n selfRef);\n else\n ret = std::make_unique(nullptr);\n } else {\n if (auto rp = x4_loader.LoadNewResourceSync(tag, nullptr))\n ret = x5c_factoryMgr.MakeObject(tag, *rp, xfer, selfRef);\n else\n ret = std::make_unique(nullptr);\n }\n Log.report(logvisor::Warning, FMT_STRING(\"sync-built {}\"), tag);\n return ret;\n}\n\nbool CResFactory::PumpResource(SLoadingData& data) {\n if (data.x8_dvdReq && data.x8_dvdReq->IsComplete()) {\n data.x8_dvdReq.reset();\n *data.xc_targetPtr =\n x5c_factoryMgr.MakeObjectFromMemory(data.x0_tag, std::move(data.x10_loadBuffer), data.x14_resSize,\n data.m_compressed, data.x18_cvXfer, data.m_selfRef);\n Log.report(logvisor::Info, FMT_STRING(\"async-built {}\"), data.x0_tag);\n return true;\n }\n return false;\n}\n\nstd::unique_ptr CResFactory::Build(const SObjectTag& tag, const CVParamTransfer& xfer,\n CObjectReference* selfRef) {\n auto search = m_loadMap.find(tag);\n if (search != m_loadMap.end()) {\n while (!PumpResource(*search->second) || !search->second->xc_targetPtr) {}\n std::unique_ptr ret = std::move(*search->second->xc_targetPtr);\n m_loadList.erase(search->second);\n m_loadMap.erase(search);\n return ret;\n }\n return BuildSync(tag, xfer, selfRef);\n}\n\nvoid CResFactory::BuildAsync(const SObjectTag& tag, const CVParamTransfer& xfer, std::unique_ptr* target,\n CObjectReference* selfRef) {\n auto search = m_loadMap.find(tag);\n if (search == m_loadMap.end()) {\n SLoadingData data(tag, target, xfer, x4_loader.GetResourceCompression(tag), selfRef);\n data.x14_resSize = x4_loader.ResourceSize(tag);\n if (data.x14_resSize) {\n data.x10_loadBuffer = std::unique_ptr(new u8[data.x14_resSize]);\n data.x8_dvdReq = x4_loader.LoadResourceAsync(tag, data.x10_loadBuffer.get());\n AddToLoadList(std::move(data));\n } else {\n *target = std::make_unique(nullptr);\n }\n }\n}\n\nvoid CResFactory::AsyncIdle() {\n if (m_loadList.empty())\n return;\n auto startTime = std::chrono::steady_clock::now();\n while (std::chrono::duration_cast(std::chrono::steady_clock::now() - startTime).count() <\n 2) {\n auto& task = m_loadList.front();\n if (PumpResource(task)) {\n m_loadMap.erase(task.x0_tag);\n m_loadList.pop_front();\n if (m_loadList.empty())\n return;\n }\n }\n}\n\nvoid CResFactory::CancelBuild(const SObjectTag& tag) {\n auto search = m_loadMap.find(tag);\n if (search != m_loadMap.end()) {\n if (search->second->x8_dvdReq)\n search->second->x8_dvdReq->PostCancelRequest();\n m_loadList.erase(search->second);\n m_loadMap.erase(search);\n }\n}\n\nvoid CResFactory::LoadPersistentResources(CSimplePool& sp) {\n const auto& paks = x4_loader.GetPaks();\n for (auto it = paks.begin(); it != paks.end(); ++it) {\n if (!(*it)->IsWorldPak()) {\n for (const CAssetId& id : (*it)->GetDepList()) {\n SObjectTag tag(GetResourceTypeById(id), id);\n m_nonWorldTokens.push_back(sp.GetObj(tag));\n m_nonWorldTokens.back().Lock();\n }\n }\n }\n}\n\n} \/\/ namespace urde\nChange CResFactory::AsyncIdle timeout to 5ms#include \"Runtime\/CResFactory.hpp\"\n\n#include \"Runtime\/CSimplePool.hpp\"\n#include \"Runtime\/CStopwatch.hpp\"\n\nnamespace urde {\nstatic logvisor::Module Log(\"CResFactory\");\n\nvoid CResFactory::AddToLoadList(SLoadingData&& data) {\n const SObjectTag tag = data.x0_tag;\n m_loadMap.insert_or_assign(tag, m_loadList.insert(m_loadList.end(), std::move(data)));\n}\n\nCFactoryFnReturn CResFactory::BuildSync(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) {\n CFactoryFnReturn ret;\n if (x5c_factoryMgr.CanMakeMemory(tag)) {\n std::unique_ptr data;\n int size = 0;\n x4_loader.LoadMemResourceSync(tag, data, &size);\n if (size)\n ret = x5c_factoryMgr.MakeObjectFromMemory(tag, std::move(data), size, x4_loader.GetResourceCompression(tag), xfer,\n selfRef);\n else\n ret = std::make_unique(nullptr);\n } else {\n if (auto rp = x4_loader.LoadNewResourceSync(tag, nullptr))\n ret = x5c_factoryMgr.MakeObject(tag, *rp, xfer, selfRef);\n else\n ret = std::make_unique(nullptr);\n }\n Log.report(logvisor::Warning, FMT_STRING(\"sync-built {}\"), tag);\n return ret;\n}\n\nbool CResFactory::PumpResource(SLoadingData& data) {\n if (data.x8_dvdReq && data.x8_dvdReq->IsComplete()) {\n data.x8_dvdReq.reset();\n *data.xc_targetPtr =\n x5c_factoryMgr.MakeObjectFromMemory(data.x0_tag, std::move(data.x10_loadBuffer), data.x14_resSize,\n data.m_compressed, data.x18_cvXfer, data.m_selfRef);\n Log.report(logvisor::Info, FMT_STRING(\"async-built {}\"), data.x0_tag);\n return true;\n }\n return false;\n}\n\nstd::unique_ptr CResFactory::Build(const SObjectTag& tag, const CVParamTransfer& xfer,\n CObjectReference* selfRef) {\n auto search = m_loadMap.find(tag);\n if (search != m_loadMap.end()) {\n while (!PumpResource(*search->second) || !search->second->xc_targetPtr) {}\n std::unique_ptr ret = std::move(*search->second->xc_targetPtr);\n m_loadList.erase(search->second);\n m_loadMap.erase(search);\n return ret;\n }\n return BuildSync(tag, xfer, selfRef);\n}\n\nvoid CResFactory::BuildAsync(const SObjectTag& tag, const CVParamTransfer& xfer, std::unique_ptr* target,\n CObjectReference* selfRef) {\n auto search = m_loadMap.find(tag);\n if (search == m_loadMap.end()) {\n SLoadingData data(tag, target, xfer, x4_loader.GetResourceCompression(tag), selfRef);\n data.x14_resSize = x4_loader.ResourceSize(tag);\n if (data.x14_resSize) {\n data.x10_loadBuffer = std::unique_ptr(new u8[data.x14_resSize]);\n data.x8_dvdReq = x4_loader.LoadResourceAsync(tag, data.x10_loadBuffer.get());\n AddToLoadList(std::move(data));\n } else {\n *target = std::make_unique(nullptr);\n }\n }\n}\n\nvoid CResFactory::AsyncIdle() {\n if (m_loadList.empty())\n return;\n auto startTime = std::chrono::steady_clock::now();\n while (std::chrono::duration_cast(std::chrono::steady_clock::now() - startTime).count() <\n 5) {\n auto& task = m_loadList.front();\n if (PumpResource(task)) {\n m_loadMap.erase(task.x0_tag);\n m_loadList.pop_front();\n if (m_loadList.empty())\n return;\n }\n }\n}\n\nvoid CResFactory::CancelBuild(const SObjectTag& tag) {\n auto search = m_loadMap.find(tag);\n if (search != m_loadMap.end()) {\n if (search->second->x8_dvdReq)\n search->second->x8_dvdReq->PostCancelRequest();\n m_loadList.erase(search->second);\n m_loadMap.erase(search);\n }\n}\n\nvoid CResFactory::LoadPersistentResources(CSimplePool& sp) {\n const auto& paks = x4_loader.GetPaks();\n for (auto it = paks.begin(); it != paks.end(); ++it) {\n if (!(*it)->IsWorldPak()) {\n for (const CAssetId& id : (*it)->GetDepList()) {\n SObjectTag tag(GetResourceTypeById(id), id);\n m_nonWorldTokens.push_back(sp.GetObj(tag));\n m_nonWorldTokens.back().Lock();\n }\n }\n }\n}\n\n} \/\/ namespace urde\n<|endoftext|>"} {"text":"sw: RingContainer::merge(): assert that the Rings aren't already linked<|endoftext|>"} {"text":"\/* Copyright 2017 QReal Research Group\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 \"pioneerStateMachineGenerator.h\"\n\n#include \n#include \n\nusing namespace pioneer::lua;\nusing namespace generatorBase;\nusing namespace generatorBase::semantics;\n\nPioneerStateMachineGenerator::PioneerStateMachineGenerator(\n\t\tconst qrRepo::RepoApi &repo\n\t\t, qReal::ErrorReporterInterface &errorReporter\n\t\t, generatorBase::GeneratorCustomizer &customizer\n\t\t, generatorBase::PrimaryControlFlowValidator &validator\n\t\t, const qReal::Id &diagramId\n\t\t, QObject *parent\n\t\t, bool isThisDiagramMain)\n\t: GotoControlFlowGenerator(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)\n{\n\tmAsynchronousNodes << \"GeoTakeoff\" << \"GeoLanding\" << \"GoToPoint\";\n}\n\nvoid PioneerStateMachineGenerator::registerNodeHook(std::function hook)\n{\n\tmNodeHooks.append(hook);\n}\n\nvoid PioneerStateMachineGenerator::performGeneration()\n{\n\tmSemanticTreeManager.reset(new SemanticTreeManager(*mSemanticTree, mErrorReporter, mErrorsOccured));\n\tGotoControlFlowGenerator::performGeneration();\n}\n\nvoid PioneerStateMachineGenerator::visitRegular(const qReal::Id &id, const QList &links)\n{\n\t\/\/ Base class method checks for subprogram calls, which is irrelevant for now, but does not hurt and hopefully\n\t\/\/ will be needed later.\n\tControlFlowGeneratorBase::visitRegular(id, links);\n\n\tSimpleNode * const thisNode = static_cast(mSemanticTree->findNodeFor(id));\n\tSemanticNode *nextNode = nullptr;\n\tconst qReal::Id target = links[0].target;\n\n\tif (mAsynchronousNodes.contains(id.element())) {\n\t\tif (mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ thisNode is asyncronous node that transfers control to already visited node.\n\t\t\t\/\/ Generated code for thisNode will initiate asynchronous action and all we need to do is to generate\n\t\t\t\/\/ transition to a state which will execute target block when this block finishes its asynchronous\n\t\t\t\/\/ operation.\n\t\t\tnextNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\n\t\t\tif (!mLabeledNodes.contains(target)) {\n\t\t\t\t\/\/\n\t\t\t\t\/\/ Target node, despite being already visited, does not have a label, it means that it is a part of a\n\t\t\t\t\/\/ synchronous fragment. We copy that fragment from this node to the first asyncronous node and\n\t\t\t\t\/\/ label a start of the copied fragment. At the end of the fragment we will generate said asynchronous\n\t\t\t\t\/\/ node, which will initiate asynchronous operation, and then transition to its next state, which will\n\t\t\t\t\/\/ continue execution when operation is done.\n\t\t\t\t\/\/\n\t\t\t\t\/\/ It will confuse \"findNodeFor(id)\" (there will be many semantic nodes for a block with given id), but\n\t\t\t\t\/\/ we actually do not care which copy will be used later, since they are the same.\n\t\t\t\t\/\/\n\t\t\t\tnextNode = copySynchronousFragment(nextNode, target, true);\n\t\t\t}\n\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(nextNode, endNode);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ thisNode is asynchronous node that transfers control to a node that has not been visited yet. Generating\n\t\t\t\/\/ transition into a state associated with that node and then a new handler for target node itself.\n\t\t\tnextNode = mSemanticTreeManager->produceLabeledNode(target);\n\t\t\tif (!nextNode) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tmLabeledNodes << nextNode->id();\n\t\t\t}\n\n\t\t\tSemanticNode * const gotoNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, gotoNode);\n\n\t\t\t\/\/ Labeled node can not be a part of a zone (i.e. \"then\" or \"else\" branch), it shall be generated in top\n\t\t\t\/\/ level zone.\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(gotoNode, endNode);\n\t\t\t\tmSemanticTreeManager->addAfter(endNode, nextNode);\n\t\t\t} else {\n\t\t\t\t\/\/ Getting parent node (i.e. If statement to the branch of which our node belongs).\n\t\t\t\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\t\t\t\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\t\t\t\taParent = mSemanticTreeManager->parent(aParent);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Skipping \"end\" that finishes handler with If.\n\t\t\t\tSemanticNode * const endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\t\t\t\taParent\n\t\t\t\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\t\t\t\tif (!endOfHandler) {\n\t\t\t\t\tmErrorReporter.addError(tr(\"Can not find end of an If statement, generation internal error or \"\n\t\t\t\t\t\t\t\"too complex algorithmic construction.\"));\n\t\t\t\t\tmErrorsOccured = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Adding our labeled node denoting new handler after the end of a handler with If node.\n\t\t\t\tmSemanticTreeManager->addAfter(endOfHandler, nextNode);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (!mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ It is not an asynchronous node, generating as-is.\n\t\t\tnextNode = mSemanticTree->produceNodeFor(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\t\t} else {\n\t\t\t\/\/ Synchronous node leading to already visited node. Need some copypasting of synchronous fragments,\n\t\t\t\/\/ or else we will stall the program waiting for an event that was never initiated.\n\t\t\tcopySynchronousFragment(thisNode, target, false);\n\t\t}\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitConditional(const qReal::Id &id, const QList &links)\n{\n\tQ_UNUSED(links)\n\n\tconst QPair branches(ifBranchesFor(id));\n\tconst LinkInfo thenLink = branches.first;\n\tconst LinkInfo elseLink = branches.second;\n\n\tIfNode * const thisNode = static_cast(mSemanticTree->findNodeFor(id));\n\n\tmSemanticTreeManager->addToZone(thisNode->thenZone(), thenLink.target);\n\tmSemanticTreeManager->addToZone(thisNode->elseZone(), elseLink.target);\n\n\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endNode);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitFinal(const qReal::Id &id, const QList &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visitFinal(id, links);\n\n\t\/\/ Here we are going to add finishing end-of-handler node in case it is missing (for example, diagrams like\n\t\/\/ \"Initial Node\" -> \"Final Node\" will not generate it automatically).\n\t\/\/ It is a kind of hack because asynchronous handler shall be a first-class entity and a zone node.\n\n\tSimpleNode * const thisNode = static_cast(mSemanticTree->findNodeFor(id));\n\n\t\/\/ Getting root node.\n\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\taParent = mSemanticTreeManager->parent(aParent);\n\t}\n\n\t\/\/ Searching for end-of-handler node.\n\tSemanticNode * endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\taParent\n\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\tif (!endOfHandler) {\n\t\t\/\/ If not found, create and add one.\n\t\tendOfHandler = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endOfHandler);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visit(const qReal::Id &nodeId, QList &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visit(nodeId, links);\n\tfor (const auto &hook : mNodeHooks) {\n\t\thook(nodeId);\n\t}\n}\n\nSemanticNode *PioneerStateMachineGenerator::copySynchronousFragment(\n\t\tSemanticNode *after\n\t\t, const qReal::Id &from\n\t\t, bool withLabel)\n{\n\tNonZoneNode *oldTarget = dynamic_cast(mSemanticTree->findNodeFor(from));\n\tif (!oldTarget) {\n\t\t\/\/\/ @todo: actually, why not?\n\t\tmErrorReporter.addError(tr(\"Can not close a loop on algorithmic block.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tNonZoneNode *fragmentStartNode = withLabel\n\t\t\t? mSemanticTreeManager->produceLabeledNode(from)\n\t\t\t: dynamic_cast(mSemanticTree->produceNodeFor(from));\n\n\tif (!fragmentStartNode) {\n\t\treturn nullptr;\n\t} else {\n\t\tmLabeledNodes << fragmentStartNode->id();\n\t}\n\n\tif (!dynamic_cast(after)) {\n\t\tmErrorReporter.addError(tr(\"Generation internal error, non-zone node is a start of a fragment.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\t\/\/ End-of-handler shall go before every labeled node, since label here is actually a start of a new handler.\n\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\tmSemanticTreeManager->addAfter(after, endNode);\n\n\tmSemanticTreeManager->addAfter(endNode, fragmentStartNode);\n\n\tif (isAsynchronous(fragmentStartNode)) {\n\t\t\/\/ Synchronous fragment is trivial and its first node is asynchronous. Generating transition from it and we're\n\t\t\/\/ done here.\n\t\t\/\/\n\t\t\/\/ Using oldTarget because fragmentStartNode was just added and does not have siblings, but it is a copy\n\t\t\/\/ of oldTarget.\n\t\tconst auto rightSibling = mSemanticTreeManager->findRightSibling(oldTarget);\n\t\tif (rightSibling) {\n\t\t\tauto gotoNode = produceGotoNode(rightSibling->id());\n\t\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\t\treturn gotoNode;\n\t\t} else {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous fragment start node generation \" \\\n\t\t\t\t\t\"failed.\"));\n\t\t\tmErrorsOccured = true;\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\tauto siblings = mSemanticTreeManager->copyRightSiblingsUntil(\n\t\t\toldTarget\n\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\tif (siblings.isEmpty()) {\n\t\tmErrorReporter.addError(tr(\"Loop can not be closed on a block that is last in its structural construct.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tif (isAsynchronous(siblings.last())) {\n\t\t\/\/ Synchronous fragment finished with asynchronous node\n\t\tfragmentStartNode->appendSiblings(siblings);\n\n\t\t\/\/ Now we shall look for the end of original fragment: find asynchronous node on which a fragment shall be\n\t\t\/\/ ending and get its target node. Assuming that they are already visited (here we assuming that it is a loop,\n\t\t\/\/ may not be the case when logical branching blocks will be introduced).\n\t\tauto asynchronousNode = mSemanticTreeManager->findSibling(\n\t\t\t\toldTarget\n\t\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\t\tconst auto asynchronousNodeTarget = mSemanticTreeManager->findRightSibling(asynchronousNode);\n\t\tif (!asynchronousNodeTarget) {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous node does not have target node.\"));\n\t\t\tmErrorsOccured = true;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tauto gotoNode = produceGotoNode(asynchronousNodeTarget->id());\n\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\treturn gotoNode;\n\t} else {\n\t\tmErrorReporter.addError(tr(\"Purely synchronous loops or If branches are not supported yet.\"));\n\t\tmErrorsOccured = true;\n\t}\n\n\treturn nullptr;\n}\n\nbool PioneerStateMachineGenerator::isAsynchronous(const SemanticNode * const node) const\n{\n\treturn mAsynchronousNodes.contains(node->id().element());\n}\n\nSemanticNode *PioneerStateMachineGenerator::produceEndOfHandlerNode()\n{\n\tqReal::Id syntheticId = qReal::Id::createElementId(\"synthetic\", \"synthetic\", \"EndOfHandler\");\n\tSimpleNode * const result = mSemanticTree->produceSimple(syntheticId);\n\t\/\/ No need for special handling, from the point of view of a generator it is just some simple node.\n\tresult->bindToSyntheticConstruction(SimpleNode::noSytheticBinding);\n\treturn result;\n}\nIf branches converging on final node are generating now\/* Copyright 2017 QReal Research Group\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 \"pioneerStateMachineGenerator.h\"\n\n#include \n#include \n\nusing namespace pioneer::lua;\nusing namespace generatorBase;\nusing namespace generatorBase::semantics;\n\nPioneerStateMachineGenerator::PioneerStateMachineGenerator(\n\t\tconst qrRepo::RepoApi &repo\n\t\t, qReal::ErrorReporterInterface &errorReporter\n\t\t, generatorBase::GeneratorCustomizer &customizer\n\t\t, generatorBase::PrimaryControlFlowValidator &validator\n\t\t, const qReal::Id &diagramId\n\t\t, QObject *parent\n\t\t, bool isThisDiagramMain)\n\t: GotoControlFlowGenerator(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)\n{\n\tmAsynchronousNodes << \"GeoTakeoff\" << \"GeoLanding\" << \"GoToPoint\";\n}\n\nvoid PioneerStateMachineGenerator::registerNodeHook(std::function hook)\n{\n\tmNodeHooks.append(hook);\n}\n\nvoid PioneerStateMachineGenerator::performGeneration()\n{\n\tmSemanticTreeManager.reset(new SemanticTreeManager(*mSemanticTree, mErrorReporter, mErrorsOccured));\n\tGotoControlFlowGenerator::performGeneration();\n}\n\nvoid PioneerStateMachineGenerator::visitRegular(const qReal::Id &id, const QList &links)\n{\n\t\/\/ Base class method checks for subprogram calls, which is irrelevant for now, but does not hurt and hopefully\n\t\/\/ will be needed later.\n\tControlFlowGeneratorBase::visitRegular(id, links);\n\n\tSimpleNode * const thisNode = static_cast(mSemanticTree->findNodeFor(id));\n\tSemanticNode *nextNode = nullptr;\n\tconst qReal::Id target = links[0].target;\n\n\tif (mAsynchronousNodes.contains(id.element())) {\n\t\tif (mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ thisNode is asyncronous node that transfers control to already visited node.\n\t\t\t\/\/ Generated code for thisNode will initiate asynchronous action and all we need to do is to generate\n\t\t\t\/\/ transition to a state which will execute target block when this block finishes its asynchronous\n\t\t\t\/\/ operation.\n\t\t\tnextNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\n\t\t\tif (!mLabeledNodes.contains(target)) {\n\t\t\t\t\/\/\n\t\t\t\t\/\/ Target node, despite being already visited, does not have a label, it means that it is a part of a\n\t\t\t\t\/\/ synchronous fragment. We copy that fragment from this node to the first asyncronous node and\n\t\t\t\t\/\/ label a start of the copied fragment. At the end of the fragment we will generate said asynchronous\n\t\t\t\t\/\/ node, which will initiate asynchronous operation, and then transition to its next state, which will\n\t\t\t\t\/\/ continue execution when operation is done.\n\t\t\t\t\/\/\n\t\t\t\t\/\/ It will confuse \"findNodeFor(id)\" (there will be many semantic nodes for a block with given id), but\n\t\t\t\t\/\/ we actually do not care which copy will be used later, since they are the same.\n\t\t\t\t\/\/\n\t\t\t\tnextNode = copySynchronousFragment(nextNode, target, true);\n\t\t\t}\n\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(nextNode, endNode);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ thisNode is asynchronous node that transfers control to a node that has not been visited yet. Generating\n\t\t\t\/\/ transition into a state associated with that node and then a new handler for target node itself.\n\t\t\tnextNode = mSemanticTreeManager->produceLabeledNode(target);\n\t\t\tif (!nextNode) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tmLabeledNodes << nextNode->id();\n\t\t\t}\n\n\t\t\tSemanticNode * const gotoNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, gotoNode);\n\n\t\t\t\/\/ Labeled node can not be a part of a zone (i.e. \"then\" or \"else\" branch), it shall be generated in top\n\t\t\t\/\/ level zone.\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(gotoNode, endNode);\n\t\t\t\tmSemanticTreeManager->addAfter(endNode, nextNode);\n\t\t\t} else {\n\t\t\t\t\/\/ Getting parent node (i.e. If statement to the branch of which our node belongs).\n\t\t\t\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\t\t\t\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\t\t\t\taParent = mSemanticTreeManager->parent(aParent);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Skipping \"end\" that finishes handler with If.\n\t\t\t\tSemanticNode * const endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\t\t\t\taParent\n\t\t\t\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\t\t\t\tif (!endOfHandler) {\n\t\t\t\t\tmErrorReporter.addError(tr(\"Can not find end of an If statement, generation internal error or \"\n\t\t\t\t\t\t\t\"too complex algorithmic construction.\"));\n\t\t\t\t\tmErrorsOccured = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Adding our labeled node denoting new handler after the end of a handler with If node.\n\t\t\t\tmSemanticTreeManager->addAfter(endOfHandler, nextNode);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (!mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ It is not an asynchronous node, generating as-is.\n\t\t\tnextNode = mSemanticTree->produceNodeFor(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\t\t} else {\n\t\t\t\/\/ Synchronous node leading to already visited node. Need some copypasting of synchronous fragments,\n\t\t\t\/\/ or else we will stall the program waiting for an event that was never initiated.\n\t\t\tcopySynchronousFragment(thisNode, target, false);\n\t\t}\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitConditional(const qReal::Id &id, const QList &links)\n{\n\tQ_UNUSED(links)\n\n\tconst QPair branches(ifBranchesFor(id));\n\tconst LinkInfo thenLink = branches.first;\n\tconst LinkInfo elseLink = branches.second;\n\n\tIfNode * const thisNode = static_cast(mSemanticTree->findNodeFor(id));\n\n\tmSemanticTreeManager->addToZone(thisNode->thenZone(), thenLink.target);\n\tmSemanticTreeManager->addToZone(thisNode->elseZone(), elseLink.target);\n\n\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endNode);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitFinal(const qReal::Id &id, const QList &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visitFinal(id, links);\n\n\t\/\/ Here we are going to add finishing end-of-handler node in case it is missing (for example, diagrams like\n\t\/\/ \"Initial Node\" -> \"Final Node\" will not generate it automatically).\n\t\/\/ It is a kind of hack because asynchronous handler shall be a first-class entity and a zone node.\n\n\tSimpleNode * const thisNode = static_cast(mSemanticTree->findNodeFor(id));\n\n\t\/\/ Getting root node.\n\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\taParent = mSemanticTreeManager->parent(aParent);\n\t}\n\n\t\/\/ Searching for end-of-handler node.\n\tSemanticNode * endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\taParent\n\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\tif (!endOfHandler) {\n\t\t\/\/ If not found, create and add one.\n\t\tendOfHandler = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endOfHandler);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visit(const qReal::Id &nodeId, QList &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visit(nodeId, links);\n\tfor (const auto &hook : mNodeHooks) {\n\t\thook(nodeId);\n\t}\n}\n\nSemanticNode *PioneerStateMachineGenerator::copySynchronousFragment(\n\t\tSemanticNode *after\n\t\t, const qReal::Id &from\n\t\t, bool withLabel)\n{\n\tNonZoneNode *oldTarget = dynamic_cast(mSemanticTree->findNodeFor(from));\n\tif (!oldTarget) {\n\t\t\/\/\/ @todo: actually, why not?\n\t\tmErrorReporter.addError(tr(\"Can not close a loop on algorithmic block.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tNonZoneNode *fragmentStartNode = withLabel\n\t\t\t? mSemanticTreeManager->produceLabeledNode(from)\n\t\t\t: dynamic_cast(mSemanticTree->produceNodeFor(from));\n\n\tif (!fragmentStartNode) {\n\t\treturn nullptr;\n\t} else {\n\t\tmLabeledNodes << fragmentStartNode->id();\n\t}\n\n\tif (!dynamic_cast(after)) {\n\t\tmErrorReporter.addError(tr(\"Generation internal error, non-zone node is a start of a fragment.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tif (withLabel) {\n\t\t\/\/ End-of-handler shall go before every labeled node, since label here is actually a start of a new handler.\n\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(after, endNode);\n\t\tmSemanticTreeManager->addAfter(endNode, fragmentStartNode);\n\t} else {\n\t\tmSemanticTreeManager->addAfter(after, fragmentStartNode);\n\t}\n\n\tif (isAsynchronous(fragmentStartNode)) {\n\t\t\/\/ Synchronous fragment is trivial and its first node is asynchronous. Generating transition from it and we're\n\t\t\/\/ done here.\n\t\t\/\/\n\t\t\/\/ Using oldTarget because fragmentStartNode was just added and does not have siblings, but it is a copy\n\t\t\/\/ of oldTarget.\n\t\tconst auto rightSibling = mSemanticTreeManager->findRightSibling(oldTarget);\n\t\tif (rightSibling) {\n\t\t\tauto gotoNode = produceGotoNode(rightSibling->id());\n\t\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\t\treturn gotoNode;\n\t\t} else {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous fragment start node generation \" \\\n\t\t\t\t\t\"failed.\"));\n\t\t\tmErrorsOccured = true;\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\tauto siblings = mSemanticTreeManager->copyRightSiblingsUntil(\n\t\t\toldTarget\n\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\tif (siblings.isEmpty()) {\n\t\t\/\/ Fragment is trivial and non-asynchronous --- so it must be FinalNode. Fine, no need to copy it.\n\t\tif (fragmentStartNode->id().element() != \"FinalNode\") {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, program ends abruptly.\"));\n\t\t\tmErrorsOccured = true;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\treturn fragmentStartNode;\n\t}\n\n\tif (isAsynchronous(siblings.last())) {\n\t\t\/\/ Synchronous fragment finished with asynchronous node\n\t\tfragmentStartNode->appendSiblings(siblings);\n\n\t\t\/\/ Now we shall look for the end of original fragment: find asynchronous node on which a fragment shall be\n\t\t\/\/ ending and get its target node. Assuming that they are already visited (here we assuming that it is a loop,\n\t\t\/\/ may not be the case when logical branching blocks will be introduced).\n\t\tauto asynchronousNode = mSemanticTreeManager->findSibling(\n\t\t\t\toldTarget\n\t\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\t\tconst auto asynchronousNodeTarget = mSemanticTreeManager->findRightSibling(asynchronousNode);\n\t\tif (!asynchronousNodeTarget) {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous node does not have target node.\"));\n\t\t\tmErrorsOccured = true;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tauto gotoNode = produceGotoNode(asynchronousNodeTarget->id());\n\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\treturn gotoNode;\n\t} else {\n\t\tmErrorReporter.addError(tr(\"Purely synchronous loops or If branches are not supported yet.\"));\n\t\tmErrorsOccured = true;\n\t}\n\n\treturn nullptr;\n}\n\nbool PioneerStateMachineGenerator::isAsynchronous(const SemanticNode * const node) const\n{\n\treturn mAsynchronousNodes.contains(node->id().element());\n}\n\nSemanticNode *PioneerStateMachineGenerator::produceEndOfHandlerNode()\n{\n\tqReal::Id syntheticId = qReal::Id::createElementId(\"synthetic\", \"synthetic\", \"EndOfHandler\");\n\tSimpleNode * const result = mSemanticTree->produceSimple(syntheticId);\n\t\/\/ No need for special handling, from the point of view of a generator it is just some simple node.\n\tresult->bindToSyntheticConstruction(SimpleNode::noSytheticBinding);\n\treturn result;\n}\n<|endoftext|>"} {"text":"\/** \n * @file hud_fox.cpp\n * @brief Purpose: Contains methods to game class' management.\n * \n * MIT License\n * Copyright (c) 2017 MindScape\n *\n * https:\/\/github.com\/TecProg2017-2\/mindscape\/blob\/master\/LICENSE.md\n *\/\n#include \"..\/include\/hud_fox.hpp\"\n#include \"..\/engine\/include\/log.hpp\"\n\nusing namespace mindscape;\n\n\/**\n * @brief Class Contructor. \n * \n * Sets Hud Fox's firsts informations (attributes' values).\n * (Hud Fox: Fox's health bar). \n *\n * @param name Hud Fox's name(name of the object).\n * @param position Hud Fox's coordinates in the game's map.\n * @param priority Hud Fox's priority in game's execution. \n * @return void.\n *\/\nHudFox::HudFox(\n std::string name,\n std::pair position,\n int priority)\n :engine::GameObject(\n name,\n position,\n priority,\n {\n \/\/No engine Keyboard Event needed.\n }\n ) {\n initialize_animations();\n initialize_audio_effects();\n};\n\n\/**\n * @brief Initiates Hud Fox's sound effect. \n * \n * Sets sound effect of heart.\n * @return void.\n *\/\nvoid HudFox::initialize_audio_effects() {\n \n DEBUG(\"Started\");\n \n \/* Initiates sound effect *\/\n engine::Audio * take_this_hp = nullptr;\n take_this_hp = new engine::Audio(\n \"heart\", \"..\/assets\/audios\/effects_songs\/mindscape_heart.wav\", \n engine::Audio::CHUNK);\n \n \/* Set duration of the sound effect and add component in game *\/\n take_this_hp->set_duration(1);\n add_component(take_this_hp);\n\n DEBUG(\"Ended\");\n}\n\n\/**\n * @brief Notifies Hud Fox of Fox's state. \n * \n * Verifies Fox's state and sets stars' animation depending of the quantity of\n * stars collected.\n *\n * @param game_object Object for observe game's situation, \n * in this case, the Fox.\n * @return void.\n *\/\nvoid HudFox::notify(engine::Observable* game_object) {\n \n Fox* fox = nullptr;\n fox = dynamic_cast(game_object);\n\n if(fox) {\n \/* If the fox exists *\/ \n bool give_hp = false; \/*< Boolean. Boolean that defines if \n hp is being given or not *\/\n give_hp = fox->get_animation_hud_fading();\n \n engine::Animation* actual = NULL;\n actual = get_actual_animation();\n \n if(actual == animations[\"three_star_fading\"]) {\n \/* If stars are fading *\/ \n if(actual->is_finished) { \n \/* If stars already faded *\/\n give_hp = false;\n fox->set_star_count(0);\n set_actual_animation(animations[\"zero_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else {\n \/* If the animation is not stars fading *\/ \n int count = 0; \/*< Integer. Number of stars *\/\n count = fox->get_star_count();\n \n if(count == 0) {\n \/* If there are no stars *\/\n if(!(get_actual_animation() == animations[\"zero_star\"])) {\n set_actual_animation(animations[\"zero_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 1) {\n \/* If there is one star *\/ \n if(!(get_actual_animation() == animations[\"one_star\"])){\n set_actual_animation(animations[\"one_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 2) {\n \/* If there are two stars *\/ \n if(!(get_actual_animation() == animations[\"two_star\"])) {\n set_actual_animation(animations[\"two_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 3 && !give_hp) {\n \/* If there are three stars and is not giving hp *\/\n if(!(get_actual_animation() == animations[\"three_star\"])) {\n set_actual_animation(animations[\"three_star\"]);\n } \n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 3 && give_hp) {\n \/* If there are three stars and is giving hp *\/\n fox->set_animation_hud_fading(false);\n set_actual_animation(animations[\"three_star_fading\"]);\n play_song(\"heart\");\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n }\n\n else {\n \/* Do nothing *\/\n WARN(\"HudFox: Fox IS NULL\");\n }\n\n}\n\n\/**\n * @brief Initiates Hud Fox's animation. \n * \n * Initiates all Hud Fox's sprites(images).\n *\n * @return void.\n *\/\nvoid HudFox::initialize_animations() {\n\n DEBUG(\"Started\");\n \n engine::Animation* fox_zero_star = nullptr;\n fox_zero_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_0.png\",\n 1,1,0.9, \"RIGHT\"\n );\n add_animation(\"zero_star\", fox_zero_star);\n \n engine::Animation* fox_one_star = nullptr;\n fox_one_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_1.png\",\n 1,1,0.9, \"RIGHT\"\n );\n add_animation(\"one_star\", fox_one_star);\n \n engine::Animation* fox_two_star = nullptr;\n fox_two_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_2.png\",\n 1,1,0.9, \"RIGHT\"\n );\n add_animation(\"two_star\", fox_two_star);\n \n engine::Animation* fox_three_star = nullptr;\n fox_three_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_3.png\",\n 1,1,0.9, \"RIGHT\"\n );\n add_animation(\"three_star\", fox_three_star);\n \n engine::Animation* fox_three_star_fading = nullptr;\n fox_three_star_fading = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_3_animation.png\",\n 1,4,1.0, \"RIGHT\"\n );\n fox_three_star_fading->in_loop = false;\n add_animation(\"three_star_fading\", fox_three_star_fading);\n \n fox_zero_star->activate();\n set_actual_animation(fox_zero_star);\n\n DEBUG(\"Ended\");\n}\n\n\/**\n * @brief Creates Hud Fox's animation. \n * \n * Creates all Hud Fox's animation based on Hud Fox's sprites.\n *\n * @param image_path Path of the Hud Fox's sprite. \n * @param sprite_lines Line of the Hud Fox's sprite. \n * @warning Limitations of sprite_lines and sprite_columns are\n * 1 to the quantity of lines\/columns in the image.\n * @param sprite_columns Column of the Fox's sprite needed.\n * @param duration Duration of the Hud Fox's image to show up.\n * @param direction Direction of the Hud Fox's image.\n * @return engine::Animation* The animation constructed.\n *\/\nengine::Animation* HudFox::create_animation(\n std::string path,\n int sprite_lines,\n int sprite_columns,\n double duration,\n std::string direction) {\n\n DEBUG(\"Started\");\n engine::Game& game = engine::Game::get_instance();\n \n engine::Animation* animation = nullptr;\n animation = new engine::Animation(\n game.get_renderer(),\n path, \n \/\/ is_active \n false, \n std::make_pair(0, 0), \n \/\/ priority\n 1, \n sprite_lines, \n sprite_columns, \n duration, \n \/\/ in_loop\n true, \n direction \n );\n\n animation->set_values(\n std::make_pair(170, 78),\n std::make_pair(170, 78),\n std::make_pair(0, 0)\n );\n\n DEBUG(\"Ended\");\n \n return animation;\n}\n[CONSTANTS] Applies constants in Hud_Fox.cpp\/** \n * @file hud_fox.cpp\n * @brief Purpose: Contains methods to game class' management.\n * \n * MIT License\n * Copyright (c) 2017 MindScape\n *\n * https:\/\/github.com\/TecProg2017-2\/mindscape\/blob\/master\/LICENSE.md\n *\/\n#include \"..\/include\/hud_fox.hpp\"\n#include \"..\/engine\/include\/log.hpp\"\n\nusing namespace mindscape;\n\n\/**\n * @brief Class Contructor. \n * \n * Sets Hud Fox's firsts informations (attributes' values).\n * (Hud Fox: Fox's health bar). \n *\n * @param name Hud Fox's name(name of the object).\n * @param position Hud Fox's coordinates in the game's map.\n * @param priority Hud Fox's priority in game's execution. \n * @return void.\n *\/\nHudFox::HudFox(\n std::string name,\n std::pair position,\n int priority)\n :engine::GameObject(\n name,\n position,\n priority,\n {\n \/\/No engine Keyboard Event needed.\n }\n ) {\n initialize_animations();\n initialize_audio_effects();\n};\n\n\/**\n * @brief Initiates Hud Fox's sound effect. \n * \n * Sets sound effect of heart.\n * @return void.\n *\/\nvoid HudFox::initialize_audio_effects() {\n \n DEBUG(\"Started\");\n \n \/* Initiates sound effect *\/\n engine::Audio * take_this_hp = nullptr;\n take_this_hp = new engine::Audio(\n \"heart\", \"..\/assets\/audios\/effects_songs\/mindscape_heart.wav\", \n engine::Audio::CHUNK);\n \n \/* Set duration of the sound effect and add component in game *\/\n const int sound_duration = 1; \/**< Integer. Duration of the sound effect in seconds*\/\n take_this_hp->set_duration(sound_duration);\n add_component(take_this_hp);\n\n DEBUG(\"Ended\");\n}\n\n\/**\n * @brief Notifies Hud Fox of Fox's state. \n * \n * Verifies Fox's state and sets stars' animation depending of the quantity of\n * stars collected.\n *\n * @param game_object Object for observe game's situation, \n * in this case, the Fox.\n * @return void.\n *\/\nvoid HudFox::notify(engine::Observable* game_object) {\n \n Fox* fox = nullptr;\n fox = dynamic_cast(game_object);\n\n if(fox) {\n \/* If the fox exists *\/ \n bool give_hp = false; \/*< Boolean. Boolean that defines if \n hp is being given or not *\/\n give_hp = fox->get_animation_hud_fading();\n \n engine::Animation* actual = NULL;\n actual = get_actual_animation();\n \n if(actual == animations[\"three_star_fading\"]) {\n \/* If stars are fading *\/ \n if(actual->is_finished) { \n \/* If stars already faded *\/\n give_hp = false;\n const int default_star_count = 0; \/**< Integer.\n Default star count. Range 0-3*\/\n fox->set_star_count(default_star_count);\n set_actual_animation(animations[\"zero_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else {\n \/* If the animation is not stars fading *\/ \n int count = 0; \/*< Integer. Number of stars *\/\n count = fox->get_star_count();\n \n if(count == 0) {\n \/* If there are no stars *\/\n if(!(get_actual_animation() == animations[\"zero_star\"])) {\n set_actual_animation(animations[\"zero_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 1) {\n \/* If there is one star *\/ \n if(!(get_actual_animation() == animations[\"one_star\"])){\n set_actual_animation(animations[\"one_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 2) {\n \/* If there are two stars *\/ \n if(!(get_actual_animation() == animations[\"two_star\"])) {\n set_actual_animation(animations[\"two_star\"]);\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 3 && !give_hp) {\n \/* If there are three stars and is not giving hp *\/\n if(!(get_actual_animation() == animations[\"three_star\"])) {\n set_actual_animation(animations[\"three_star\"]);\n } \n else {\n \/* Do nothing *\/\n }\n }\n\n else if(count == 3 && give_hp) {\n \/* If there are three stars and is giving hp *\/\n fox->set_animation_hud_fading(false);\n set_actual_animation(animations[\"three_star_fading\"]);\n play_song(\"heart\");\n }\n\n else {\n \/* Do nothing *\/\n }\n }\n }\n\n else {\n \/* Do nothing *\/\n WARN(\"HudFox: Fox IS NULL\");\n }\n\n}\n\n\/**\n * @brief Initiates Hud Fox's animation. \n * \n * Initiates all Hud Fox's sprites(images).\n *\n * @return void.\n *\/\nvoid HudFox::initialize_animations() {\n\n DEBUG(\"Started\");\n const int default_sprite_line = 1; \/**< Integer. Default sprite line, RANGE 1 *\/\n const int default_sprite_column = 1; \/**< Integer. Default sprite column, RANGE 1 *\/\n const double default_animation_duration = 0.9; \/**< Double. Default animation \n duration in seconds *\/\n\n\n engine::Animation* fox_zero_star = nullptr;\n fox_zero_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_0.png\",\n default_sprite_line, default_sprite_column, default_animation_duration,\n \"RIGHT\"\n );\n add_animation(\"zero_star\", fox_zero_star);\n \n engine::Animation* fox_one_star = nullptr;\n fox_one_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_1.png\",\n default_sprite_line, default_sprite_column, default_animation_duration,\n \"RIGHT\"\n );\n add_animation(\"one_star\", fox_one_star);\n \n engine::Animation* fox_two_star = nullptr;\n fox_two_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_2.png\",\n default_sprite_line, default_sprite_column, default_animation_duration,\n \"RIGHT\"\n );\n add_animation(\"two_star\", fox_two_star);\n \n engine::Animation* fox_three_star = nullptr;\n fox_three_star = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_3.png\",\n default_sprite_line, default_sprite_column, default_animation_duration,\n \"RIGHT\"\n );\n add_animation(\"three_star\", fox_three_star);\n \n const int sprite_columns_tree_star = 4; \/**< Default sprite column of tree \n star fading *\/\n const double duration_tree_star = 1.0; \/**< Default duration of tree \n star fading in seconds *\/\n\n engine::Animation* fox_three_star_fading = nullptr;\n fox_three_star_fading = create_animation(\n \"..\/assets\/images\/sprites\/hud\/hud_fox_3_animation.png\",\n default_sprite_line, sprite_columns_tree_star, duration_tree_star,\n \"RIGHT\"\n );\n fox_three_star_fading->in_loop = false;\n add_animation(\"three_star_fading\", fox_three_star_fading);\n \n fox_zero_star->activate();\n set_actual_animation(fox_zero_star);\n\n DEBUG(\"Ended\");\n}\n\n\/**\n * @brief Creates Hud Fox's animation. \n * \n * Creates all Hud Fox's animation based on Hud Fox's sprites.\n *\n * @param image_path Path of the Hud Fox's sprite. \n * @param sprite_lines Line of the Hud Fox's sprite. \n * @warning Limitations of sprite_lines and sprite_columns are\n * 1 to the quantity of lines\/columns in the image.\n * @param sprite_columns Column of the Fox's sprite needed.\n * @param duration Duration of the Hud Fox's image to show up.\n * @param direction Direction of the Hud Fox's image.\n * @return engine::Animation* The animation constructed.\n *\/\nengine::Animation* HudFox::create_animation(\n std::string path,\n int sprite_lines,\n int sprite_columns,\n double duration,\n std::string direction) {\n\n DEBUG(\"Started\");\n engine::Game& game = engine::Game::get_instance();\n \n \/* Constants for default animation creation *\/\n const bool default_is_active = false;\n const std::pair default_displacement = std::make_pair(0, 0);\n const int default_priority = 1;\n const bool default_in_loop = true;\n \n engine::Animation* animation = nullptr;\n animation = new engine::Animation(\n game.get_renderer(),\n path, \n default_is_active, \n default_displacement, \n default_priority, \n sprite_lines, \n sprite_columns, \n duration, \n default_in_loop, \n direction \n );\n\n\n \/* Defaults dimensions and coordinates of hud fox in pixels *\/\n const std::pair default_dimensions_hud_fox = \n std::make_pair(170, 78);\n const std::pair coordinates_on_texture_hud_fox = \n std::make_pair(0, 0);\n\n animation->set_values(\n default_dimensions_hud_fox,\n default_dimensions_hud_fox ,\n coordinates_on_texture_hud_fox\n );\n\n DEBUG(\"Ended\");\n \n return animation;\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/utils\/stopreg\/p9_stop_data_struct.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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\/\/\/\n\/\/\/ @file p9_stop_data_struct.H\n\/\/\/ @brief describes data structures internal to STOP API.\n\/\/\/\n\/\/ *HWP HW Owner : Greg Still \n\/\/ *HWP FW Owner : Prem Shanker Jha \n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : HB:HYP\n#ifndef __STOP_DATA_STRUCT_\n#define __STOP_DATA_STRUCT_\n\n#include \"p9_hcd_memmap_base.H\"\n\n#ifdef __SKIBOOT__\n #include \n#endif\n\n#ifdef __FAPI_2_\n #include \n#endif\n\n#ifdef PPC_HYP\n\n #define STATIC\n\n#else\n\n #define STATIC static\n\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\nnamespace stopImageSection\n{\n#endif\n\nenum\n{\n MAX_SPR_RESTORE_INST = 0x08,\n SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) \/ sizeof(uint32_t)),\n};\n\ntypedef struct\n{\n uint32_t scomEntryHeader;\n uint32_t scomEntryAddress;\n uint64_t scomEntryData;\n} ScomEntry_t;\n\n\/**\n * @brief models a CPU register restoration area in STOP section of homer image.\n *\/\ntypedef struct\n{\n uint8_t threadArea[CORE_RESTORE_THREAD_AREA_SIZE];\n uint8_t coreArea[CORE_RESTORE_CORE_AREA_SIZE];\n} SprRestoreArea_t;\n\n\/**\n * @brief models homer image of a chip.\n * @note sections not relevant for CPU register restoration have been\n * abstracted using field 'reserve'.\n *\/\ntypedef struct\n{\n uint8_t occ_host_sgpe_area[ TWO_MB ]; \/\/ CPU restore area starts at an offset of 2MB from chip HOMER\n uint8_t interrruptHandler[SELF_RESTORE_INT_SIZE];\n uint8_t threadLauncher[THREAD_LAUNCHER_SIZE];\n SprRestoreArea_t coreThreadRestore[MAX_CORES_PER_CHIP][MAX_THREADS_PER_CORE];\n uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL];\n} HomerSection_t;\n\n\/**\n * @brief models cache subsection in STOP section of a given homer image.\n * @note given the start of cache subsection associated with a given core,\n * the structure below represents what a cache subsection would look\n * like. Based on known start address, quick traversing can be done\n * within the cache subsection.\n *\/\ntypedef struct\n{\n ScomEntry_t nonCacheArea[MAX_EQ_SCOM_ENTRIES];\n ScomEntry_t l2CacheArea[MAX_L2_SCOM_ENTRIES];\n ScomEntry_t l3CacheArea[MAX_L3_SCOM_ENTRIES];\n} StopCacheSection_t;\n\n\/**\n * @brief summarizes attributes associated with a SPR register.\n *\/\ntypedef struct\n{\n uint32_t sprId;\n bool isThreadScope;\n} StopSprReg_t;\n\nenum\n{\n SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ),\n SCOM_ENTRY_START = 0xDEADDEAD,\n};\n\n#ifdef __FAPI_2_\n #define MY_ERR( _fmt_, _args_...) FAPI_ERR(_fmt_, ##_args_)\n #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)\n#else\n #define MY_ERR( _fmt_, _args_...)\n #define MY_INF(_fmt_, _args_...)\n#endif\n\n#define CORE_ID_SCOM_START(io_image,\\\n i_chipletId) \\\n((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\\\n ((i_chipletId - CORE_CHIPLET_ID_MIN) * \\\n CORE_SCOM_RESTORE_SIZE_PER_CORE)));\n\n#define CACHE_SECTN_START(io_image,\\\n i_chipletId) \\\n((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\\\n ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \\\n QUAD_SCOM_RESTORE_SIZE_PER_QUAD)));\n\n#define CACHE_SCOM_ADDR(io_image,\\\n i_chipletId,\\\n i_maxScomEntry)\\\n((ScomEntry_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\\\n ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \\\n ((i_maxScomEntry + 1) * 16 ))));\n#ifdef __cplusplus\n} \/\/ extern \"C\"\n\n} \/\/namespace stopImageSection ends\n#endif \/\/__cplusplus\n\n#endif\nUV Support : Augmented STOP API and self restore for enabling ultravisor.\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/utils\/stopreg\/p9_stop_data_struct.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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\/\/\/\n\/\/\/ @file p9_stop_data_struct.H\n\/\/\/ @brief describes data structures internal to STOP API.\n\/\/\/\n\/\/ *HWP HW Owner : Greg Still \n\/\/ *HWP FW Owner : Prem Shanker Jha \n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : HB:HYP\n#ifndef __STOP_DATA_STRUCT_\n#define __STOP_DATA_STRUCT_\n\n#include \"p9_hcd_memmap_base.H\"\n\n#ifdef __SKIBOOT__\n #include \n#endif\n\n#ifdef __FAPI_2_\n #include \n#endif\n\n#ifdef PPC_HYP\n\n #define STATIC\n\n#else\n\n #define STATIC static\n\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\nnamespace stopImageSection\n{\n#endif\n\nenum\n{\n MAX_SPR_RESTORE_INST = 0x08,\n SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) \/ sizeof(uint32_t)),\n MAX_THREAD_LEVEL_SPRS = 11,\n MAX_CORE_LEVEL_SPRS = 6,\n MAX_SPR_BIT_POS = 31,\n SPR_BIT_POS_8 = 8,\n SPR_BIT_POS_19 = 19,\n SPR_BIT_POS_25 = 25,\n SPR_BIT_POS_27 = 27,\n};\n\nenum SprEntryUpdateMode\n{\n INIT_SPR_REGION = 0x01,\n UPDATE_SPR_ENTRY = 0x02,\n};\n\ntypedef struct\n{\n uint32_t scomEntryHeader;\n uint32_t scomEntryAddress;\n uint64_t scomEntryData;\n} ScomEntry_t;\n\n\/**\n * @brief models a CPU register restoration area in STOP section of homer image.\n *\/\ntypedef struct\n{\n uint8_t iv_threadRestoreArea[MAX_THREADS_PER_CORE][CORE_RESTORE_THREAD_AREA_SIZE];\n uint8_t iv_threadSaveArea[MAX_THREADS_PER_CORE][SELF_SAVE_THREAD_AREA_SIZE];\n uint8_t iv_coreRestoreArea[CORE_RESTORE_CORE_AREA_SIZE];\n uint8_t iv_coreSaveArea[CORE_SAVE_CORE_AREA_SIZE];\n} SprRestoreArea_t;\n\n\/**\n * @brief models homer image of a chip.\n * @note sections not relevant for CPU register restoration have been\n * abstracted using field 'reserve'.\n *\/\ntypedef struct\n{\n uint8_t iv_occ_host_sgpe_area[ TWO_MB ]; \/\/ CPU restore area starts at an offset of 2MB from chip HOMER\n uint8_t iv_interrruptHandler[SELF_RESTORE_INT_SIZE];\n uint8_t iv_threadLauncher[THREAD_LAUNCHER_SIZE];\n SprRestoreArea_t iv_coreThreadRestore[MAX_CORES_PER_CHIP];\n uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL];\n} HomerSection_t;\n\n\/**\n * @brief models cache subsection in STOP section of a given homer image.\n * @note given the start of cache subsection associated with a given core,\n * the structure below represents what a cache subsection would look\n * like. Based on known start address, quick traversing can be done\n * within the cache subsection.\n *\/\ntypedef struct\n{\n ScomEntry_t nonCacheArea[MAX_EQ_SCOM_ENTRIES];\n ScomEntry_t l2CacheArea[MAX_L2_SCOM_ENTRIES];\n ScomEntry_t l3CacheArea[MAX_L3_SCOM_ENTRIES];\n} StopCacheSection_t;\n\n\/**\n * @brief summarizes attributes associated with a SPR register.\n *\/\ntypedef struct\n{\n uint32_t iv_sprId;\n bool iv_isThreadScope;\n uint32_t iv_saveMaskPos;\n\n} StopSprReg_t;\n\nenum\n{\n SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ),\n SCOM_ENTRY_START = 0xDEADDEAD,\n BAD_SAVE_MASK = 0x007FF000,\n MAX_SPR_INDEX = 31,\n TEST_BIT_PATTERN = 0x80000000,\n};\n\n#ifdef __FAPI_2_\n #define MY_ERR( _fmt_, _args_...) FAPI_ERR(_fmt_, ##_args_)\n #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)\n#else\n #define MY_ERR( _fmt_, _args_...)\n #define MY_INF(_fmt_, _args_...)\n#endif\n\n#define CORE_ID_SCOM_START(io_image,\\\n i_chipletId) \\\n((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\\\n ((i_chipletId - CORE_CHIPLET_ID_MIN) * \\\n CORE_SCOM_RESTORE_SIZE_PER_CORE)));\n\n#define CACHE_SECTN_START(io_image,\\\n i_chipletId) \\\n((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\\\n ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \\\n QUAD_SCOM_RESTORE_SIZE_PER_QUAD)));\n\n#define CACHE_SCOM_ADDR(io_image,\\\n i_chipletId,\\\n i_maxScomEntry)\\\n((ScomEntry_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\\\n ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \\\n ((i_maxScomEntry + 1) * 16 ))));\n#ifdef __cplusplus\n} \/\/ extern \"C\"\n\n} \/\/namespace stopImageSection ends\n#endif \/\/__cplusplus\n\n#endif\n<|endoftext|>"} {"text":"#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"jml\/arch\/atomic_ops.h\"\n#include \"jml\/arch\/exception.h\"\n#include \"jml\/arch\/futex.h\"\n#include \"jml\/arch\/timers.h\"\n#include \"jml\/utils\/exc_assert.h\"\n#include \"jml\/utils\/string_functions.h\"\n#include \"soa\/service\/message_loop.h\"\n#include \"soa\/service\/runner.h\"\n#include \"soa\/service\/sink.h\"\n#include \"soa\/types\/date.h\"\n\n#include \n\n#include \"runner_test.h\"\n\n#include \"signals.h\"\n\nusing namespace std;\nusing namespace Datacratic;\n\n\/\/ #define BOOST_CHECK_EQUAL(x,y) { ExcCheckEqual((x), (y), \"\"); }\n\nstruct _Init {\n _Init() {\n signal(SIGPIPE, SIG_IGN);\n }\n} myInit;\n\n\n#if 1\n\/* ensures that the basic callback system works *\/\nBOOST_AUTO_TEST_CASE( test_runner_callbacks )\n{\n BlockedSignals blockedSigs2(SIGCHLD);\n\n MessageLoop loop;\n\n RunnerTestHelperCommands commands;\n commands.sendOutput(true, \"hello stdout\");\n commands.sendOutput(true, \"hello stdout2\");\n commands.sendOutput(false, \"hello stderr\");\n commands.sendExit(0);\n\n string receivedStdOut, expectedStdOut;\n string receivedStdErr, expectedStdErr;\n\n expectedStdOut = (\"helper: ready\\nhello stdout\\nhello stdout2\\n\"\n \"helper: exit with code 0\\n\");\n expectedStdErr = \"hello stderr\\n\";\n\n int done = false;\n auto onTerminate = [&] (const Runner::RunResult & result) {\n done = true;\n ML::futex_wake(done);\n };\n\n auto onStdOut = [&] (string && message) {\n \/\/ cerr << \"received message on stdout: \/\" + message + \"\/\" << endl;\n receivedStdOut += message;\n };\n auto stdOutSink = make_shared(onStdOut);\n\n auto onStdErr = [&] (string && message) {\n \/\/ cerr << \"received message on stderr: \/\" + message + \"\/\" << endl;\n receivedStdErr += message;\n };\n auto stdErrSink = make_shared(onStdErr);\n\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n onTerminate, stdOutSink, stdErrSink);\n for (const string & command: commands) {\n while (!stdInSink.write(string(command))) {\n ML::sleep(0.1);\n }\n }\n stdInSink.requestClose();\n\n while (!done) {\n ML::futex_wait(done, false);\n }\n\n BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut),\n ML::hexify_string(expectedStdOut));\n BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdErr),\n ML::hexify_string(expectedStdErr));\n\n loop.shutdown();\n}\n#endif\n\n#if 1\n\/* ensures that the returned status is properly set after termination *\/\nBOOST_AUTO_TEST_CASE( test_runner_normal_exit )\n{\n BlockedSignals blockedSigs(SIGCHLD);\n\n auto nullSink = make_shared();\n\n \/* normal termination, with code *\/\n {\n MessageLoop loop;\n\n RunnerTestHelperCommands commands;\n commands.sendExit(123);\n\n Runner::RunResult result;\n auto onTerminate = [&] (const Runner::RunResult & newResult) {\n result = newResult;\n };\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n onTerminate, nullSink, nullSink);\n for (const string & command: commands) {\n stdInSink.write(string(command));\n }\n stdInSink.requestClose();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 123);\n\n loop.shutdown();\n }\n\n \/* aborted termination, with signum *\/\n {\n MessageLoop loop;\n\n RunnerTestHelperCommands commands;\n commands.sendAbort();\n\n Runner::RunResult result;\n auto onTerminate = [&] (const Runner::RunResult & newResult) {\n result = newResult;\n };\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n onTerminate, nullSink, nullSink);\n for (const string & command: commands) {\n stdInSink.write(string(command));\n }\n stdInSink.requestClose();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, true);\n BOOST_CHECK_EQUAL(result.returnCode, SIGABRT);\n\n loop.shutdown();\n }\n}\n#endif\n\n#if 1\n\/* test the behaviour of the Runner class when attempting to launch a missing\n * executable, mostly mimicking bash *\/\nBOOST_AUTO_TEST_CASE( test_runner_missing_exe )\n{\n Runner::RunResult result;\n auto onTerminate = [&] (const Runner::RunResult & newResult) {\n result = newResult;\n };\n\n \/* running a program that does not exist *\/\n {\n MessageLoop loop;\n Runner runner;\n\n loop.start();\n loop.addSource(\"runner1\", runner);\n\n runner.run({\"\/this\/command\/is\/missing\"}, onTerminate);\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 127);\n\n loop.removeSource(&runner);\n loop.shutdown();\n }\n\n \/* running a non-executable but existing file *\/\n {\n MessageLoop loop;\n Runner runner;\n\n loop.start();\n loop.addSource(\"runner2\", runner);\n\n runner.run({\"\/dev\/null\"}, onTerminate);\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 126);\n\n loop.removeSource(&runner);\n loop.shutdown();\n }\n\n \/* running a non-executable but existing non-file *\/\n {\n MessageLoop loop;\n Runner runner;\n\n loop.start();\n loop.addSource(\"runner3\", runner);\n\n runner.run({\"\/dev\"}, onTerminate);\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 126);\n\n loop.removeSource(&runner);\n loop.shutdown();\n }\n\n}\n#endif\n\n#if 1\n\/* test the \"execute\" function *\/\nBOOST_AUTO_TEST_CASE( test_runner_execute )\n{\n string received;\n auto onStdOut = [&] (string && message) {\n received = move(message);\n };\n auto stdOutSink = make_shared(onStdOut, nullptr);\n\n auto result = execute({\"\/bin\/cat\", \"-\"},\n stdOutSink, nullptr, \"hello callbacks\");\n BOOST_CHECK_EQUAL(received, \"hello callbacks\");\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 0);\n}\n#endif\n\n#if 1\n\/* perform multiple runs with the same Runner and ensures task-specific\n * components are properly segregated *\/\nBOOST_AUTO_TEST_CASE( test_runner_cleanup )\n{\n MessageLoop loop;\n\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto nullSink = make_shared();\n\n auto performLoop = [&] (const string & loopData) {\n RunnerTestHelperCommands commands;\n commands.sendOutput(true, loopData);\n commands.sendExit(0);\n\n string expectedStdOut(\"helper: ready\\n\" + loopData\n + \"\\nhelper: exit with code 0\\n\");\n string receivedStdOut;\n auto onStdOut = [&] (string && message) {\n \/\/ cerr << \"received message on stdout: \/\" + message + \"\/\" << endl;\n receivedStdOut += message;\n };\n auto stdOutSink = make_shared(onStdOut);\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n nullptr, stdOutSink, nullSink);\n for (const string & command: commands) {\n stdInSink.write(string(command));\n }\n stdInSink.requestClose();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut),\n ML::hexify_string(expectedStdOut));\n };\n\n for (int i = 0; i < 5; i++) {\n performLoop(to_string(i));\n }\n\n loop.shutdown();\n}\n#endif\n\n#if 1\n\/* Ensures that the output is received as soon as it is emitted, and not by\n * chunks. This is done by expecting different types of strings: a simple one\n * with a few chars, another one with two carriage returns and a third one\n * with 1024 chars. The test works by ensuring that all strings are received\n * one by one, with a relatively precise and constant delay of 1 second\n * between them. *\/\nstatic void\ntest_runner_no_output_delay_helper(bool stdout)\n{\n double delays[3];\n int sizes[3];\n int pos(stdout ? -1 : 0);\n shared_ptr stdOutSink(nullptr);\n shared_ptr stdErrSink(nullptr);\n\n Date start = Date::now();\n Date last = start;\n\n auto onCapture = [&] (string && message) {\n Date now = Date::now();\n if (pos > -1 && pos < 3) {\n \/* skip \"helper: ready\" message *\/\n delays[pos] = now.secondsSinceEpoch() - last.secondsSinceEpoch();\n sizes[pos] = message.size();\n }\n pos++;\n last = now;\n };\n if (stdout) {\n stdOutSink.reset(new CallbackInputSink(onCapture));\n }\n else {\n stdErrSink.reset(new CallbackInputSink(onCapture));\n }\n\n RunnerTestHelperCommands commands;\n commands.sendSleep(10);\n commands.sendOutput(stdout, \"first\");\n commands.sendSleep(10);\n commands.sendOutput(stdout, \"second\\nsecond\");\n commands.sendSleep(10);\n\n string third;\n for (int i = 0; i < 128; i++) {\n third += \"abcdefgh\";\n }\n commands.sendOutput(stdout, third);\n commands.sendSleep(10);\n commands.sendExit(0);\n\n MessageLoop loop;\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n nullptr, stdOutSink, stdErrSink);\n for (const string & command: commands) {\n while (!stdInSink.write(string(command))) {\n ML::sleep(0.1);\n }\n }\n stdInSink.requestClose();\n Date end = Date::now();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(sizes[0], 6);\n BOOST_CHECK(delays[0] >= 0.9);\n BOOST_CHECK_EQUAL(sizes[1], 14);\n BOOST_CHECK(delays[1] >= 0.9);\n BOOST_CHECK_EQUAL(sizes[2], 1025);\n BOOST_CHECK(delays[2] >= 0.9);\n\n for (int i = 0; i < 3; i++) {\n ::fprintf(stderr, \"%d: size: %d; delay: %f\\n\", i, sizes[i], delays[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stdout )\n{\n test_runner_no_output_delay_helper(true);\n}\n\nBOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stderr )\n{\n test_runner_no_output_delay_helper(false);\n}\n#endif\n\nRevert \"runner_test: worked around timing issues causing test to hang when using the same MessageLoop\"#define BOOST_TEST_MAIN\n#define BOOST_TEST_DYN_LINK\n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"jml\/arch\/atomic_ops.h\"\n#include \"jml\/arch\/exception.h\"\n#include \"jml\/arch\/futex.h\"\n#include \"jml\/arch\/timers.h\"\n#include \"jml\/utils\/exc_assert.h\"\n#include \"jml\/utils\/string_functions.h\"\n#include \"soa\/service\/message_loop.h\"\n#include \"soa\/service\/runner.h\"\n#include \"soa\/service\/sink.h\"\n#include \"soa\/types\/date.h\"\n\n#include \n\n#include \"runner_test.h\"\n\n#include \"signals.h\"\n\nusing namespace std;\nusing namespace Datacratic;\n\n\/\/ #define BOOST_CHECK_EQUAL(x,y) { ExcCheckEqual((x), (y), \"\"); }\n\nstruct _Init {\n _Init() {\n signal(SIGPIPE, SIG_IGN);\n }\n} myInit;\n\n\n#if 1\n\/* ensures that the basic callback system works *\/\nBOOST_AUTO_TEST_CASE( test_runner_callbacks )\n{\n BlockedSignals blockedSigs2(SIGCHLD);\n\n MessageLoop loop;\n\n RunnerTestHelperCommands commands;\n commands.sendOutput(true, \"hello stdout\");\n commands.sendOutput(true, \"hello stdout2\");\n commands.sendOutput(false, \"hello stderr\");\n commands.sendExit(0);\n\n string receivedStdOut, expectedStdOut;\n string receivedStdErr, expectedStdErr;\n\n expectedStdOut = (\"helper: ready\\nhello stdout\\nhello stdout2\\n\"\n \"helper: exit with code 0\\n\");\n expectedStdErr = \"hello stderr\\n\";\n\n int done = false;\n auto onTerminate = [&] (const Runner::RunResult & result) {\n done = true;\n ML::futex_wake(done);\n };\n\n auto onStdOut = [&] (string && message) {\n \/\/ cerr << \"received message on stdout: \/\" + message + \"\/\" << endl;\n receivedStdOut += message;\n };\n auto stdOutSink = make_shared(onStdOut);\n\n auto onStdErr = [&] (string && message) {\n \/\/ cerr << \"received message on stderr: \/\" + message + \"\/\" << endl;\n receivedStdErr += message;\n };\n auto stdErrSink = make_shared(onStdErr);\n\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n onTerminate, stdOutSink, stdErrSink);\n for (const string & command: commands) {\n while (!stdInSink.write(string(command))) {\n ML::sleep(0.1);\n }\n }\n stdInSink.requestClose();\n\n while (!done) {\n ML::futex_wait(done, false);\n }\n\n BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut),\n ML::hexify_string(expectedStdOut));\n BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdErr),\n ML::hexify_string(expectedStdErr));\n\n loop.shutdown();\n}\n#endif\n\n#if 1\n\/* ensures that the returned status is properly set after termination *\/\nBOOST_AUTO_TEST_CASE( test_runner_normal_exit )\n{\n BlockedSignals blockedSigs(SIGCHLD);\n\n auto nullSink = make_shared();\n\n \/* normal termination, with code *\/\n {\n MessageLoop loop;\n\n RunnerTestHelperCommands commands;\n commands.sendExit(123);\n\n Runner::RunResult result;\n auto onTerminate = [&] (const Runner::RunResult & newResult) {\n result = newResult;\n };\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n onTerminate, nullSink, nullSink);\n for (const string & command: commands) {\n stdInSink.write(string(command));\n }\n stdInSink.requestClose();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 123);\n\n loop.shutdown();\n }\n\n \/* aborted termination, with signum *\/\n {\n MessageLoop loop;\n\n RunnerTestHelperCommands commands;\n commands.sendAbort();\n\n Runner::RunResult result;\n auto onTerminate = [&] (const Runner::RunResult & newResult) {\n result = newResult;\n };\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n onTerminate, nullSink, nullSink);\n for (const string & command: commands) {\n stdInSink.write(string(command));\n }\n stdInSink.requestClose();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, true);\n BOOST_CHECK_EQUAL(result.returnCode, SIGABRT);\n\n loop.shutdown();\n }\n}\n#endif\n\n#if 1\n\/* test the behaviour of the Runner class when attempting to launch a missing\n * executable, mostly mimicking bash *\/\nBOOST_AUTO_TEST_CASE( test_runner_missing_exe )\n{\n MessageLoop loop;\n\n loop.start();\n\n Runner::RunResult result;\n auto onTerminate = [&] (const Runner::RunResult & newResult) {\n result = newResult;\n };\n\n \/* running a program that does not exist *\/\n {\n Runner runner;\n loop.addSource(\"runner1\", runner);\n\n runner.run({\"\/this\/command\/is\/missing\"}, onTerminate);\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 127);\n\n loop.removeSource(&runner);\n }\n\n \/* running a non-executable but existing file *\/\n {\n Runner runner;\n loop.addSource(\"runner2\", runner);\n\n runner.run({\"\/dev\/null\"}, onTerminate);\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 126);\n\n loop.removeSource(&runner);\n }\n\n \/* running a non-executable but existing non-file *\/\n {\n Runner runner;\n loop.addSource(\"runner2\", runner);\n\n runner.run({\"\/dev\"}, onTerminate);\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 126);\n\n loop.removeSource(&runner);\n }\n\n loop.shutdown();\n}\n#endif\n\n#if 1\n\/* test the \"execute\" function *\/\nBOOST_AUTO_TEST_CASE( test_runner_execute )\n{\n string received;\n auto onStdOut = [&] (string && message) {\n received = move(message);\n };\n auto stdOutSink = make_shared(onStdOut, nullptr);\n\n auto result = execute({\"\/bin\/cat\", \"-\"},\n stdOutSink, nullptr, \"hello callbacks\");\n BOOST_CHECK_EQUAL(received, \"hello callbacks\");\n BOOST_CHECK_EQUAL(result.signaled, false);\n BOOST_CHECK_EQUAL(result.returnCode, 0);\n}\n#endif\n\n#if 1\n\/* perform multiple runs with the same Runner and ensures task-specific\n * components are properly segregated *\/\nBOOST_AUTO_TEST_CASE( test_runner_cleanup )\n{\n MessageLoop loop;\n\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto nullSink = make_shared();\n\n auto performLoop = [&] (const string & loopData) {\n RunnerTestHelperCommands commands;\n commands.sendOutput(true, loopData);\n commands.sendExit(0);\n\n string expectedStdOut(\"helper: ready\\n\" + loopData\n + \"\\nhelper: exit with code 0\\n\");\n string receivedStdOut;\n auto onStdOut = [&] (string && message) {\n \/\/ cerr << \"received message on stdout: \/\" + message + \"\/\" << endl;\n receivedStdOut += message;\n };\n auto stdOutSink = make_shared(onStdOut);\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n nullptr, stdOutSink, nullSink);\n for (const string & command: commands) {\n stdInSink.write(string(command));\n }\n stdInSink.requestClose();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut),\n ML::hexify_string(expectedStdOut));\n };\n\n for (int i = 0; i < 5; i++) {\n performLoop(to_string(i));\n }\n\n loop.shutdown();\n}\n#endif\n\n#if 1\n\/* Ensures that the output is received as soon as it is emitted, and not by\n * chunks. This is done by expecting different types of strings: a simple one\n * with a few chars, another one with two carriage returns and a third one\n * with 1024 chars. The test works by ensuring that all strings are received\n * one by one, with a relatively precise and constant delay of 1 second\n * between them. *\/\nstatic void\ntest_runner_no_output_delay_helper(bool stdout)\n{\n double delays[3];\n int sizes[3];\n int pos(stdout ? -1 : 0);\n shared_ptr stdOutSink(nullptr);\n shared_ptr stdErrSink(nullptr);\n\n Date start = Date::now();\n Date last = start;\n\n auto onCapture = [&] (string && message) {\n Date now = Date::now();\n if (pos > -1 && pos < 3) {\n \/* skip \"helper: ready\" message *\/\n delays[pos] = now.secondsSinceEpoch() - last.secondsSinceEpoch();\n sizes[pos] = message.size();\n }\n pos++;\n last = now;\n };\n if (stdout) {\n stdOutSink.reset(new CallbackInputSink(onCapture));\n }\n else {\n stdErrSink.reset(new CallbackInputSink(onCapture));\n }\n\n RunnerTestHelperCommands commands;\n commands.sendSleep(10);\n commands.sendOutput(stdout, \"first\");\n commands.sendSleep(10);\n commands.sendOutput(stdout, \"second\\nsecond\");\n commands.sendSleep(10);\n\n string third;\n for (int i = 0; i < 128; i++) {\n third += \"abcdefgh\";\n }\n commands.sendOutput(stdout, third);\n commands.sendSleep(10);\n commands.sendExit(0);\n\n MessageLoop loop;\n Runner runner;\n loop.addSource(\"runner\", runner);\n loop.start();\n\n auto & stdInSink = runner.getStdInSink();\n runner.run({\"build\/x86_64\/bin\/runner_test_helper\"},\n nullptr, stdOutSink, stdErrSink);\n for (const string & command: commands) {\n while (!stdInSink.write(string(command))) {\n ML::sleep(0.1);\n }\n }\n stdInSink.requestClose();\n Date end = Date::now();\n runner.waitTermination();\n\n BOOST_CHECK_EQUAL(sizes[0], 6);\n BOOST_CHECK(delays[0] >= 0.9);\n BOOST_CHECK_EQUAL(sizes[1], 14);\n BOOST_CHECK(delays[1] >= 0.9);\n BOOST_CHECK_EQUAL(sizes[2], 1025);\n BOOST_CHECK(delays[2] >= 0.9);\n\n for (int i = 0; i < 3; i++) {\n ::fprintf(stderr, \"%d: size: %d; delay: %f\\n\", i, sizes[i], delays[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stdout )\n{\n test_runner_no_output_delay_helper(true);\n}\n\nBOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stderr )\n{\n test_runner_no_output_delay_helper(false);\n}\n#endif\n\n<|endoftext|>"} {"text":"\/***********************************************************************\nMoses - factored phrase-based language decoder\nCopyright (C) 2006 University of Edinburgh\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library 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 GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n***********************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \"LanguageModelRandLM.h\"\n#include \"FactorCollection.h\"\n#include \"Phrase.h\"\n#include \"InputFileStream.h\"\n#include \"StaticData.h\"\n\nnamespace Moses\n{\nusing namespace std;\n\nbool LanguageModelRandLM::Load(const std::string &filePath, FactorType factorType, \n\t\t\t size_t nGramOrder) {\n cerr << \"Loading LanguageModelRandLM...\" << endl;\n FactorCollection &factorCollection = FactorCollection::Instance();\n m_filePath = filePath;\n m_factorType = factorType;\n m_nGramOrder = nGramOrder;\n int cache_MB = 50; \/\/ increase cache size\n m_lm = randlm::RandLM::initRandLM(filePath, nGramOrder, cache_MB);\n assert(m_lm != NULL);\n \/\/ get special word ids\n m_oov_id = m_lm->getWordID(m_lm->getOOV());\n CreateFactors(factorCollection);\n return true;\n}\n\nvoid LanguageModelRandLM::CreateFactors(FactorCollection &factorCollection) { \/\/ add factors which have randlm id\n \/\/ code copied & paste from SRI LM class. should do template function\n \/\/ first get all bf vocab in map\n std::map randlm_ids_map; \/\/ map from factor id -> randlm id\n size_t maxFactorId = 0; \/\/ to create lookup vector later on\n for(std::map::const_iterator vIter = m_lm->vocabStart();\n vIter != m_lm->vocabEnd(); vIter++){\n \/\/ get word from randlm vocab and associate with (new) factor id\n size_t factorId=factorCollection.AddFactor(Output,m_factorType,vIter->first)->GetId();\n randlm_ids_map[factorId] = vIter->second;\n maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;\n }\n \/\/ add factors for BOS and EOS and store bf word ids\n size_t factorId;\n m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, m_lm->getBOS());\n factorId = m_sentenceStart->GetId();\n maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;\n m_sentenceStartArray[m_factorType] = m_sentenceStart;\n\n m_sentenceEnd\t= factorCollection.AddFactor(Output, m_factorType, m_lm->getEOS());\n factorId = m_sentenceEnd->GetId();\n maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;\n m_sentenceEndArray[m_factorType] = m_sentenceEnd;\n\n \/\/ add to lookup vector in object\n m_randlm_ids_vec.resize(maxFactorId+1);\n \/\/ fill with OOV code\n fill(m_randlm_ids_vec.begin(), m_randlm_ids_vec.end(), m_oov_id);\n\n for (map::const_iterator iter = randlm_ids_map.begin();\n iter != randlm_ids_map.end() ; ++iter)\n m_randlm_ids_vec[iter->first] = iter->second;\n\n}\n\nrandlm::WordID LanguageModelRandLM::GetLmID( const std::string &str ) const {\n return m_lm->getWordID(str);\n}\n\nfloat LanguageModelRandLM::GetValue(const vector &contextFactor,\n\t\t\t\t State* finalState) const {\n FactorType factorType = GetFactorType();\n \/\/ set up context\n randlm::WordID ngram[MAX_NGRAM_SIZE];\n int count = contextFactor.size();\n for (int i = 0 ; i < count ; i++) {\n ngram[i] = GetLmID((*contextFactor[i])[factorType]);\n \/\/std::cerr << m_lm->getWord(ngram[i]) << \" \";\n }\n int found = 0;\n float logprob = FloorScore(TransformLMScore(m_lm->getProb(&ngram[0], count, &found, finalState)));\n \/\/if (finalState)\n \/\/ std::cerr << \" = \" << logprob << \"(\" << *finalState << \", \" <<\")\"<< std::endl;\n \/\/else\n \/\/ std::cerr << \" = \" << logprob << std::endl;\n return logprob;\n}\n\n}\n\n\nChanged white space to test effect on svn blame.\/***********************************************************************\nMoses - factored phrase-based language decoder\nCopyright (C) 2006 University of Edinburgh\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library 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 GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n***********************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \"LanguageModelRandLM.h\"\n#include \"FactorCollection.h\"\n#include \"Phrase.h\"\n#include \"InputFileStream.h\"\n#include \"StaticData.h\"\n\nnamespace Moses\n{\nusing namespace std;\n\nbool LanguageModelRandLM::Load(const std::string &filePath, FactorType factorType, \n size_t nGramOrder) {\n cerr << \"Loading LanguageModelRandLM...\" << endl;\n FactorCollection &factorCollection = FactorCollection::Instance();\n m_filePath = filePath;\n m_factorType = factorType;\n m_nGramOrder = nGramOrder;\n int cache_MB = 50; \/\/ increase cache size\n m_lm = randlm::RandLM::initRandLM(filePath, nGramOrder, cache_MB);\n assert(m_lm != NULL);\n \/\/ get special word ids\n m_oov_id = m_lm->getWordID(m_lm->getOOV());\n CreateFactors(factorCollection);\n return true;\n}\n\nvoid LanguageModelRandLM::CreateFactors(FactorCollection &factorCollection) { \/\/ add factors which have randlm id\n \/\/ code copied & paste from SRI LM class. should do template function\n \/\/ first get all bf vocab in map\n std::map randlm_ids_map; \/\/ map from factor id -> randlm id\n size_t maxFactorId = 0; \/\/ to create lookup vector later on\n for(std::map::const_iterator vIter = m_lm->vocabStart();\n vIter != m_lm->vocabEnd(); vIter++){\n \/\/ get word from randlm vocab and associate with (new) factor id\n size_t factorId=factorCollection.AddFactor(Output,m_factorType,vIter->first)->GetId();\n randlm_ids_map[factorId] = vIter->second;\n maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;\n }\n \/\/ add factors for BOS and EOS and store bf word ids\n size_t factorId;\n m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, m_lm->getBOS());\n factorId = m_sentenceStart->GetId();\n maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;\n m_sentenceStartArray[m_factorType] = m_sentenceStart;\n\n m_sentenceEnd\t= factorCollection.AddFactor(Output, m_factorType, m_lm->getEOS());\n factorId = m_sentenceEnd->GetId();\n maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId;\n m_sentenceEndArray[m_factorType] = m_sentenceEnd;\n\n \/\/ add to lookup vector in object\n m_randlm_ids_vec.resize(maxFactorId+1);\n \/\/ fill with OOV code\n fill(m_randlm_ids_vec.begin(), m_randlm_ids_vec.end(), m_oov_id);\n\n for (map::const_iterator iter = randlm_ids_map.begin();\n iter != randlm_ids_map.end() ; ++iter)\n m_randlm_ids_vec[iter->first] = iter->second;\n\n}\n\nrandlm::WordID LanguageModelRandLM::GetLmID( const std::string &str ) const {\n return m_lm->getWordID(str);\n}\n\nfloat LanguageModelRandLM::GetValue(const vector &contextFactor,\n\t\t\t\t State* finalState) const {\n FactorType factorType = GetFactorType();\n \/\/ set up context\n randlm::WordID ngram[MAX_NGRAM_SIZE];\n int count = contextFactor.size();\n for (int i = 0 ; i < count ; i++) {\n ngram[i] = GetLmID((*contextFactor[i])[factorType]);\n \/\/std::cerr << m_lm->getWord(ngram[i]) << \" \";\n }\n int found = 0;\n float logprob = FloorScore(TransformLMScore(m_lm->getProb(&ngram[0], count, &found, finalState)));\n \/\/if (finalState)\n \/\/ std::cerr << \" = \" << logprob << \"(\" << *finalState << \", \" <<\")\"<< std::endl;\n \/\/else\n \/\/ std::cerr << \" = \" << logprob << std::endl;\n return logprob;\n}\n\n}\n\n\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2013-2018 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n#include \n#include \n\n#include \"incomes.hpp\"\n#include \"accounts.hpp\"\n#include \"budget_exception.hpp\"\n#include \"args.hpp\"\n#include \"data.hpp\"\n#include \"guid.hpp\"\n#include \"config.hpp\"\n#include \"utils.hpp\"\n#include \"console.hpp\"\n#include \"earnings.hpp\"\n#include \"expenses.hpp\"\n#include \"writer.hpp\"\n\nusing namespace budget;\n\nnamespace {\n\nstatic data_handler incomes { \"incomes\", \"incomes.data\" };\n\n} \/\/end of anonymous namespace\n\nstd::map budget::income::get_params(){\n std::map params;\n\n params[\"input_id\"] = budget::to_string(id);\n params[\"input_guid\"] = guid;\n params[\"input_amount\"] = budget::to_string(amount);\n params[\"input_since\"] = budget::to_string(since);\n params[\"input_until\"] = budget::to_string(until);\n\n return params;\n}\n\nvoid budget::incomes_module::load(){\n load_incomes();\n}\n\nvoid budget::incomes_module::unload(){\n save_incomes();\n}\n\nvoid budget::incomes_module::handle(const std::vector& args){\n console_writer w(std::cout);\n\n if(args.size() == 1){\n show_incomes(w);\n } else {\n auto& subcommand = args[1];\n\n if (subcommand == \"show\") {\n show_incomes(w);\n } else if (subcommand == \"set\") {\n budget::money amount;\n edit_money(amount, \"Amount\", not_negative_checker());\n\n auto & new_income = budget::new_income(amount, true);\n std::cout << \"Income \" << new_income.id << \" has been created\" << std::endl;\n } else {\n throw budget_exception(\"Invalid subcommand \\\"\" + subcommand + \"\\\"\");\n }\n }\n}\n\nvoid budget::show_incomes(budget::writer& w) {\n if (!incomes.size()) {\n w << title_begin << \"No income \" << add_button(\"incomes\") << title_end;\n return;\n }\n\n w << title_begin << \"Incomes \" << add_button(\"incomes\") << title_end;\n\n std::vector columns = {\"ID\", \"Amount\", \"Since\", \"Until\", \"Edit\"};\n std::vector> contents;\n\n for(auto& income : incomes.data){\n contents.push_back({to_string(income.id), to_string(income.amount), to_string(income.since), to_string(income.until), \"::edit::incomes::\" + to_string(income.id)});\n }\n\n w.display_table(columns, contents);\n}\n\nvoid budget::load_incomes(){\n incomes.load();\n}\n\nvoid budget::save_incomes(){\n incomes.save();\n}\n\nstd::ostream& budget::operator<<(std::ostream& stream, const income& income){\n return stream << income.id << ':' << income.guid << ':' << income.amount << ':' << to_string(income.since) << ':' << to_string(income.until);\n}\n\nvoid budget::operator>>(const std::vector& parts, income& income){\n bool random = config_contains(\"random\");\n\n income.id = to_number(parts[0]);\n income.guid = parts[1];\n income.since = from_string(parts[3]);\n income.until = from_string(parts[4]);\n\n if(random){\n income.amount = budget::random_money(1000, 10000);\n } else {\n income.amount = parse_money(parts[2]);\n }\n}\n\nstd::vector& budget::all_incomes(){\n return incomes.data;\n}\n\nvoid budget::set_incomes_changed(){\n incomes.set_changed();\n}\n\nvoid budget::set_incomes_next_id(size_t next_id){\n incomes.next_id = next_id;\n}\n\nbool budget::income_exists(size_t id){\n return incomes.exists(id);\n}\n\nvoid budget::income_delete(size_t id) {\n if (!incomes.exists(id)) {\n throw budget_exception(\"There are no income with id \");\n }\n\n incomes.remove(id);\n}\n\nincome& budget::income_get(size_t id) {\n if (!incomes.exists(id)) {\n throw budget_exception(\"There are no income with id \");\n }\n\n return incomes[id];\n}\n\nvoid budget::add_income(budget::income&& income){\n incomes.add(std::forward(income));\n}\n\nbudget::money budget::get_base_income(){\n auto today = budget::local_day();\n return get_base_income(today);\n}\n\nbudget::money budget::get_base_income(budget::date d){\n \/\/ First, we try to get the base income from the incomes module\n\n for (auto & income : incomes) {\n if (income.since <= d && income.until >= d) {\n return income.amount;\n }\n }\n\n \/\/ Otherwise, we use the accounts\n\n budget::money income;\n\n for (auto& account : all_accounts(d.year(), d.month())) {\n income += account.amount;\n }\n\n return income;\n}\n\nbudget::income & budget::new_income(budget::money amount, bool print){\n budget::date d = budget::local_day();\n\n budget::date since(d.year(), d.month(), 1);\n budget::date until = budget::date(2099,12,31);\n\n budget::income new_income;\n new_income.guid = generate_guid();\n new_income.since = since;\n new_income.until = until;\n new_income.amount = amount;\n\n if (incomes.size()) {\n \/\/ Try to edit the income from the same month\n for (auto & income : incomes) {\n if (income.since == since && income.until == until) {\n income.amount = new_income.amount;\n\n if (incomes.edit(income)) {\n if (print) {\n std::cout << \"Income \" << income.id << \" has been modified\" << std::endl;\n }\n }\n\n return income;\n }\n }\n\n \/\/ Edit the previous income\n\n budget::date date = incomes.data.front().since;\n size_t id = incomes.data.front().id;\n\n for (auto & income : incomes) {\n if (income.since > date) {\n date = income.since;\n id = income.id;\n }\n }\n\n auto & previous_income = incomes[id];\n\n previous_income.until = since - budget::days(1);\n\n if (incomes.edit(previous_income)) {\n if (print) {\n std::cout << \"Income \" << id << \" has been modified\" << std::endl;\n }\n }\n\n return previous_income;\n }\n\n auto id = incomes.add(std::move(new_income));\n return incomes[id];\n}\nDisplay current income\/\/=======================================================================\n\/\/ Copyright (c) 2013-2018 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n#include \n#include \n#include \n\n#include \"incomes.hpp\"\n#include \"accounts.hpp\"\n#include \"budget_exception.hpp\"\n#include \"args.hpp\"\n#include \"data.hpp\"\n#include \"guid.hpp\"\n#include \"config.hpp\"\n#include \"utils.hpp\"\n#include \"console.hpp\"\n#include \"earnings.hpp\"\n#include \"expenses.hpp\"\n#include \"writer.hpp\"\n\nusing namespace budget;\n\nnamespace {\n\nstatic data_handler incomes { \"incomes\", \"incomes.data\" };\n\n} \/\/end of anonymous namespace\n\nstd::map budget::income::get_params(){\n std::map params;\n\n params[\"input_id\"] = budget::to_string(id);\n params[\"input_guid\"] = guid;\n params[\"input_amount\"] = budget::to_string(amount);\n params[\"input_since\"] = budget::to_string(since);\n params[\"input_until\"] = budget::to_string(until);\n\n return params;\n}\n\nvoid budget::incomes_module::load(){\n load_incomes();\n}\n\nvoid budget::incomes_module::unload(){\n save_incomes();\n}\n\nvoid budget::incomes_module::handle(const std::vector& args){\n console_writer w(std::cout);\n\n if(args.size() == 1){\n show_incomes(w);\n } else {\n auto& subcommand = args[1];\n\n if (subcommand == \"show\") {\n show_incomes(w);\n } else if (subcommand == \"set\") {\n budget::money amount;\n edit_money(amount, \"Amount\", not_negative_checker());\n\n auto & new_income = budget::new_income(amount, true);\n std::cout << \"Income \" << new_income.id << \" has been created\" << std::endl;\n } else {\n throw budget_exception(\"Invalid subcommand \\\"\" + subcommand + \"\\\"\");\n }\n }\n}\n\nvoid budget::show_incomes(budget::writer& w) {\n if (!incomes.size()) {\n w << title_begin << \"No income \" << add_button(\"incomes\") << title_end;\n return;\n }\n\n w << title_begin << \"Incomes \" << add_button(\"incomes\") << title_end;\n\n w << p_begin << \"Current income: \" << get_base_income() << \" \" << get_default_currency() << p_end;\n\n std::vector columns = {\"ID\", \"Amount\", \"Since\", \"Until\", \"Edit\"};\n std::vector> contents;\n\n for(auto& income : incomes.data){\n contents.push_back({to_string(income.id), to_string(income.amount), to_string(income.since), to_string(income.until), \"::edit::incomes::\" + to_string(income.id)});\n }\n\n w.display_table(columns, contents);\n}\n\nvoid budget::load_incomes(){\n incomes.load();\n}\n\nvoid budget::save_incomes(){\n incomes.save();\n}\n\nstd::ostream& budget::operator<<(std::ostream& stream, const income& income){\n return stream << income.id << ':' << income.guid << ':' << income.amount << ':' << to_string(income.since) << ':' << to_string(income.until);\n}\n\nvoid budget::operator>>(const std::vector& parts, income& income){\n bool random = config_contains(\"random\");\n\n income.id = to_number(parts[0]);\n income.guid = parts[1];\n income.since = from_string(parts[3]);\n income.until = from_string(parts[4]);\n\n if(random){\n income.amount = budget::random_money(1000, 10000);\n } else {\n income.amount = parse_money(parts[2]);\n }\n}\n\nstd::vector& budget::all_incomes(){\n return incomes.data;\n}\n\nvoid budget::set_incomes_changed(){\n incomes.set_changed();\n}\n\nvoid budget::set_incomes_next_id(size_t next_id){\n incomes.next_id = next_id;\n}\n\nbool budget::income_exists(size_t id){\n return incomes.exists(id);\n}\n\nvoid budget::income_delete(size_t id) {\n if (!incomes.exists(id)) {\n throw budget_exception(\"There are no income with id \");\n }\n\n incomes.remove(id);\n}\n\nincome& budget::income_get(size_t id) {\n if (!incomes.exists(id)) {\n throw budget_exception(\"There are no income with id \");\n }\n\n return incomes[id];\n}\n\nvoid budget::add_income(budget::income&& income){\n incomes.add(std::forward(income));\n}\n\nbudget::money budget::get_base_income(){\n auto today = budget::local_day();\n return get_base_income(today);\n}\n\nbudget::money budget::get_base_income(budget::date d){\n \/\/ First, we try to get the base income from the incomes module\n\n for (auto & income : incomes) {\n if (income.since <= d && income.until >= d) {\n return income.amount;\n }\n }\n\n \/\/ Otherwise, we use the accounts\n\n budget::money income;\n\n for (auto& account : all_accounts(d.year(), d.month())) {\n income += account.amount;\n }\n\n return income;\n}\n\nbudget::income & budget::new_income(budget::money amount, bool print){\n budget::date d = budget::local_day();\n\n budget::date since(d.year(), d.month(), 1);\n budget::date until = budget::date(2099,12,31);\n\n budget::income new_income;\n new_income.guid = generate_guid();\n new_income.since = since;\n new_income.until = until;\n new_income.amount = amount;\n\n if (incomes.size()) {\n \/\/ Try to edit the income from the same month\n for (auto & income : incomes) {\n if (income.since == since && income.until == until) {\n income.amount = new_income.amount;\n\n if (incomes.edit(income)) {\n if (print) {\n std::cout << \"Income \" << income.id << \" has been modified\" << std::endl;\n }\n }\n\n return income;\n }\n }\n\n \/\/ Edit the previous income\n\n budget::date date = incomes.data.front().since;\n size_t id = incomes.data.front().id;\n\n for (auto & income : incomes) {\n if (income.since > date) {\n date = income.since;\n id = income.id;\n }\n }\n\n auto & previous_income = incomes[id];\n\n previous_income.until = since - budget::days(1);\n\n if (incomes.edit(previous_income)) {\n if (print) {\n std::cout << \"Income \" << id << \" has been modified\" << std::endl;\n }\n }\n\n return previous_income;\n }\n\n auto id = incomes.add(std::move(new_income));\n return incomes[id];\n}\n<|endoftext|>"} {"text":"\/\/ =============================================================================\n\/\/ This file is part of:\n\/\/ Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM)\n\/\/\n\/\/ Copyright (c) 2015-2016, Trustees of Indiana University,\n\/\/ All rights reserved.\n\/\/\n\/\/ DASHMM 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\/\/ DASHMM 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 DASHMM. If not, see .\n\/\/\n\/\/ This software was created at the Indiana University Center for Research in\n\/\/ Extreme Scale Technologies (CREST).\n\/\/ =============================================================================\n\n\n\/\/\/ \\file\n\/\/\/ \\brief Implemention of DASHMM initialization and finalization\n\n\n#include \n#include \n\n#include \"dashmm\/types.h\"\n\n\nnamespace dashmm {\n\n\nReturnCode init(int *argc, char ***argv) {\n if (HPX_SUCCESS != hpx_init(argc, argv)) {\n return kRuntimeError;\n }\n\n if (libhpx_inst_tracer_active()) {\n libhpx_inst_phase_end();\n }\n\n return kSuccess;\n}\n\n\nReturnCode finalize() {\n hpx_finalize();\n\n return kSuccess;\n}\n\n\n} \/\/ namespace dashmm\nProtect against poor coding in HPX-5 instrumentation. init() now checks for DASHMM_INSTRUMENTATION before interacting with the instrumentation stuff at all.\/\/ =============================================================================\n\/\/ This file is part of:\n\/\/ Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM)\n\/\/\n\/\/ Copyright (c) 2015-2016, Trustees of Indiana University,\n\/\/ All rights reserved.\n\/\/\n\/\/ DASHMM 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\/\/ DASHMM 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 DASHMM. If not, see .\n\/\/\n\/\/ This software was created at the Indiana University Center for Research in\n\/\/ Extreme Scale Technologies (CREST).\n\/\/ =============================================================================\n\n\n\/\/\/ \\file\n\/\/\/ \\brief Implemention of DASHMM initialization and finalization\n\n\n#include \n#include \n\n#include \"dashmm\/types.h\"\n\n\nnamespace dashmm {\n\n\nReturnCode init(int *argc, char ***argv) {\n if (HPX_SUCCESS != hpx_init(argc, argv)) {\n return kRuntimeError;\n }\n\n#ifdef DASHMM_INSTRUMENTATION\n if (libhpx_inst_tracer_active()) {\n libhpx_inst_phase_end();\n }\n#endif\n\n return kSuccess;\n}\n\n\nReturnCode finalize() {\n hpx_finalize();\n\n return kSuccess;\n}\n\n\n} \/\/ namespace dashmm\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 \"ash\/system\/power\/tray_power.h\"\n\n#include \"ash\/shell.h\"\n#include \"ash\/system\/date\/date_view.h\"\n#include \"ash\/system\/power\/power_supply_status.h\"\n#include \"ash\/system\/tray\/system_tray_delegate.h\"\n#include \"ash\/system\/tray\/tray_constants.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"grit\/ash_strings.h\"\n#include \"grit\/ui_resources.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"third_party\/skia\/include\/core\/SkRect.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/views\/controls\/button\/button.h\"\n#include \"ui\/views\/controls\/button\/text_button.h\"\n#include \"ui\/views\/controls\/image_view.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/layout\/box_layout.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"unicode\/fieldpos.h\"\n#include \"unicode\/fmtable.h\"\n\nnamespace ash {\nnamespace internal {\n\nnamespace {\n\/\/ Width and height of battery images.\nconst int kBatteryImageHeight = 25;\nconst int kBatteryImageWidth = 25;\n\/\/ Number of different power states.\nconst int kNumPowerImages = 15;\n}\n\nnamespace tray {\n\n\/\/ This view is used only for the tray.\nclass PowerTrayView : public views::ImageView {\n public:\n PowerTrayView() {\n UpdateImage();\n }\n\n virtual ~PowerTrayView() {\n }\n\n void UpdatePowerStatus(const PowerSupplyStatus& status) {\n supply_status_ = status;\n \/\/ Sanitize.\n if (supply_status_.battery_is_full)\n supply_status_.battery_percentage = 100.0;\n\n UpdateImage();\n SetVisible(status.battery_is_present);\n }\n\n private:\n void UpdateImage() {\n SkBitmap image;\n gfx::Image all = ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_AURA_UBER_TRAY_POWER_SMALL);\n\n int image_index = 0;\n if (supply_status_.battery_percentage >= 100) {\n image_index = kNumPowerImages - 1;\n } else if (!supply_status_.battery_is_present) {\n image_index = kNumPowerImages;\n } else {\n image_index = static_cast (\n supply_status_.battery_percentage \/ 100.0 *\n (kNumPowerImages - 1));\n image_index =\n std::max(std::min(image_index, kNumPowerImages - 2), 0);\n }\n\n \/\/ TODO(mbolohan): Remove the 2px offset when the assets are centered. See\n \/\/ crbug.com\/119832.\n SkIRect region = SkIRect::MakeXYWH(\n (supply_status_.line_power_on ? kBatteryImageWidth : 0) + 2,\n image_index * kBatteryImageHeight,\n kBatteryImageWidth - 2, kBatteryImageHeight);\n all.ToSkBitmap()->extractSubset(&image, region);\n\n SetImage(image);\n }\n\n PowerSupplyStatus supply_status_;\n\n DISALLOW_COPY_AND_ASSIGN(PowerTrayView);\n};\n\n\/\/ This view is used only for the popup.\nclass PowerPopupView : public views::Label {\n public:\n PowerPopupView() {\n SetHorizontalAlignment(ALIGN_RIGHT);\n UpdateText();\n }\n\n virtual ~PowerPopupView() {\n }\n\n void UpdatePowerStatus(const PowerSupplyStatus& status) {\n supply_status_ = status;\n \/\/ Sanitize.\n if (supply_status_.battery_is_full)\n supply_status_.battery_percentage = 100.0;\n\n UpdateText();\n }\n\n private:\n void UpdateText() {\n base::TimeDelta time = base::TimeDelta::FromSeconds(\n supply_status_.line_power_on ?\n supply_status_.battery_seconds_to_full :\n supply_status_.battery_seconds_to_empty);\n int hour = time.InHours();\n int min = (time - base::TimeDelta::FromHours(hour)).InMinutes();\n ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();\n if (hour && min) {\n SetText(l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_BATTERY_STATUS,\n base::IntToString16(\n static_cast(supply_status_.battery_percentage)),\n base::IntToString16(hour),\n base::IntToString16(min)));\n } else {\n if (supply_status_.line_power_on) {\n SetText(bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_BATTERY_FULL));\n } else {\n \/\/ Completely discharged? ... ha?\n SetText(string16());\n }\n }\n }\n\n PowerSupplyStatus supply_status_;\n\n DISALLOW_COPY_AND_ASSIGN(PowerPopupView);\n};\n\n} \/\/ namespace tray\n\nTrayPower::TrayPower()\n : power_(NULL),\n power_tray_(NULL) {\n}\n\nTrayPower::~TrayPower() {\n}\n\nviews::View* TrayPower::CreateTrayView(user::LoginStatus status) {\n \/\/ There may not be enough information when this is created about whether\n \/\/ there is a battery or not. So always create this, and adjust visibility as\n \/\/ necessary.\n PowerSupplyStatus power_status =\n ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus();\n power_tray_.reset(new tray::PowerTrayView());\n power_tray_->UpdatePowerStatus(power_status);\n return power_tray_.get();\n}\n\nviews::View* TrayPower::CreateDefaultView(user::LoginStatus status) {\n date_.reset(new tray::DateView(tray::DateView::DATE));\n if (status != user::LOGGED_IN_NONE && status != user::LOGGED_IN_LOCKED)\n date_->set_actionable(true);\n\n views::View* container = new views::View;\n views::BoxLayout* layout = new views::BoxLayout(views::BoxLayout::kHorizontal,\n kTrayPopupPaddingHorizontal, 10, 0);\n layout->set_spread_blank_space(true);\n container->SetLayoutManager(layout);\n container->set_background(views::Background::CreateSolidBackground(\n SkColorSetRGB(245, 245, 245)));\n container->AddChildView(date_.get());\n\n PowerSupplyStatus power_status =\n ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus();\n if (power_status.battery_is_present) {\n power_.reset(new tray::PowerPopupView());\n power_->UpdatePowerStatus(power_status);\n container->AddChildView(power_.get());\n }\n return container;\n}\n\nviews::View* TrayPower::CreateDetailedView(user::LoginStatus status) {\n return NULL;\n}\n\nvoid TrayPower::DestroyTrayView() {\n power_tray_.reset();\n}\n\nvoid TrayPower::DestroyDefaultView() {\n date_.reset();\n power_.reset();\n}\n\nvoid TrayPower::DestroyDetailedView() {\n}\n\nvoid TrayPower::OnPowerStatusChanged(const PowerSupplyStatus& status) {\n if (power_tray_.get())\n power_tray_->UpdatePowerStatus(status);\n if (power_.get())\n power_->UpdatePowerStatus(status);\n}\n\n} \/\/ namespace internal\n} \/\/ namespace ash\nash: Fix the awesome logic for showing battery status.\/\/ 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 \"ash\/system\/power\/tray_power.h\"\n\n#include \"ash\/shell.h\"\n#include \"ash\/system\/date\/date_view.h\"\n#include \"ash\/system\/power\/power_supply_status.h\"\n#include \"ash\/system\/tray\/system_tray_delegate.h\"\n#include \"ash\/system\/tray\/tray_constants.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"grit\/ash_strings.h\"\n#include \"grit\/ui_resources.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"third_party\/skia\/include\/core\/SkRect.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/views\/controls\/button\/button.h\"\n#include \"ui\/views\/controls\/button\/text_button.h\"\n#include \"ui\/views\/controls\/image_view.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/layout\/box_layout.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"unicode\/fieldpos.h\"\n#include \"unicode\/fmtable.h\"\n\nnamespace ash {\nnamespace internal {\n\nnamespace {\n\/\/ Width and height of battery images.\nconst int kBatteryImageHeight = 25;\nconst int kBatteryImageWidth = 25;\n\/\/ Number of different power states.\nconst int kNumPowerImages = 15;\n}\n\nnamespace tray {\n\n\/\/ This view is used only for the tray.\nclass PowerTrayView : public views::ImageView {\n public:\n PowerTrayView() {\n UpdateImage();\n }\n\n virtual ~PowerTrayView() {\n }\n\n void UpdatePowerStatus(const PowerSupplyStatus& status) {\n supply_status_ = status;\n \/\/ Sanitize.\n if (supply_status_.battery_is_full)\n supply_status_.battery_percentage = 100.0;\n\n UpdateImage();\n SetVisible(status.battery_is_present);\n }\n\n private:\n void UpdateImage() {\n SkBitmap image;\n gfx::Image all = ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_AURA_UBER_TRAY_POWER_SMALL);\n\n int image_index = 0;\n if (supply_status_.battery_percentage >= 100) {\n image_index = kNumPowerImages - 1;\n } else if (!supply_status_.battery_is_present) {\n image_index = kNumPowerImages;\n } else {\n image_index = static_cast (\n supply_status_.battery_percentage \/ 100.0 *\n (kNumPowerImages - 1));\n image_index =\n std::max(std::min(image_index, kNumPowerImages - 2), 0);\n }\n\n \/\/ TODO(mbolohan): Remove the 2px offset when the assets are centered. See\n \/\/ crbug.com\/119832.\n SkIRect region = SkIRect::MakeXYWH(\n (supply_status_.line_power_on ? kBatteryImageWidth : 0) + 2,\n image_index * kBatteryImageHeight,\n kBatteryImageWidth - 2, kBatteryImageHeight);\n all.ToSkBitmap()->extractSubset(&image, region);\n\n SetImage(image);\n }\n\n PowerSupplyStatus supply_status_;\n\n DISALLOW_COPY_AND_ASSIGN(PowerTrayView);\n};\n\n\/\/ This view is used only for the popup.\nclass PowerPopupView : public views::Label {\n public:\n PowerPopupView() {\n SetHorizontalAlignment(ALIGN_RIGHT);\n UpdateText();\n }\n\n virtual ~PowerPopupView() {\n }\n\n void UpdatePowerStatus(const PowerSupplyStatus& status) {\n supply_status_ = status;\n \/\/ Sanitize.\n if (supply_status_.battery_is_full)\n supply_status_.battery_percentage = 100.0;\n\n UpdateText();\n }\n\n private:\n void UpdateText() {\n base::TimeDelta time = base::TimeDelta::FromSeconds(\n supply_status_.line_power_on ?\n supply_status_.battery_seconds_to_full :\n supply_status_.battery_seconds_to_empty);\n int hour = time.InHours();\n int min = (time - base::TimeDelta::FromHours(hour)).InMinutes();\n ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance();\n if (hour || min) {\n SetText(l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_BATTERY_STATUS,\n base::IntToString16(\n static_cast(supply_status_.battery_percentage)),\n base::IntToString16(hour),\n base::IntToString16(min)));\n } else {\n if (supply_status_.line_power_on) {\n SetText(bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_BATTERY_FULL));\n } else {\n \/\/ Completely discharged? ... ha?\n SetText(string16());\n }\n }\n }\n\n PowerSupplyStatus supply_status_;\n\n DISALLOW_COPY_AND_ASSIGN(PowerPopupView);\n};\n\n} \/\/ namespace tray\n\nTrayPower::TrayPower()\n : power_(NULL),\n power_tray_(NULL) {\n}\n\nTrayPower::~TrayPower() {\n}\n\nviews::View* TrayPower::CreateTrayView(user::LoginStatus status) {\n \/\/ There may not be enough information when this is created about whether\n \/\/ there is a battery or not. So always create this, and adjust visibility as\n \/\/ necessary.\n PowerSupplyStatus power_status =\n ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus();\n power_tray_.reset(new tray::PowerTrayView());\n power_tray_->UpdatePowerStatus(power_status);\n return power_tray_.get();\n}\n\nviews::View* TrayPower::CreateDefaultView(user::LoginStatus status) {\n date_.reset(new tray::DateView(tray::DateView::DATE));\n if (status != user::LOGGED_IN_NONE && status != user::LOGGED_IN_LOCKED)\n date_->set_actionable(true);\n\n views::View* container = new views::View;\n views::BoxLayout* layout = new views::BoxLayout(views::BoxLayout::kHorizontal,\n kTrayPopupPaddingHorizontal, 10, 0);\n layout->set_spread_blank_space(true);\n container->SetLayoutManager(layout);\n container->set_background(views::Background::CreateSolidBackground(\n SkColorSetRGB(245, 245, 245)));\n container->AddChildView(date_.get());\n\n PowerSupplyStatus power_status =\n ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus();\n if (power_status.battery_is_present) {\n power_.reset(new tray::PowerPopupView());\n power_->UpdatePowerStatus(power_status);\n container->AddChildView(power_.get());\n }\n return container;\n}\n\nviews::View* TrayPower::CreateDetailedView(user::LoginStatus status) {\n return NULL;\n}\n\nvoid TrayPower::DestroyTrayView() {\n power_tray_.reset();\n}\n\nvoid TrayPower::DestroyDefaultView() {\n date_.reset();\n power_.reset();\n}\n\nvoid TrayPower::DestroyDetailedView() {\n}\n\nvoid TrayPower::OnPowerStatusChanged(const PowerSupplyStatus& status) {\n if (power_tray_.get())\n power_tray_->UpdatePowerStatus(status);\n if (power_.get())\n power_->UpdatePowerStatus(status);\n}\n\n} \/\/ namespace internal\n} \/\/ namespace ash\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmhtml.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 16:23:09 $\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_sfx2.hxx\"\n\n#include \n#include \n\n#ifndef _HTMLTOKN_H\n#include \n#endif\n#ifndef SVTOOLS_ASYNCLINK_HXX\n#include \n#endif\n\n#ifndef GCC\n#endif\n\n#include \"docinf.hxx\"\n\n#define _SVSTDARR_USHORTS\n#define _SVSTDARR_ULONGS\n#include \n\n#include \"sfx.hrc\"\n\n#include \"frmhtml.hxx\"\n#include \"docfile.hxx\"\n#include \"viewfrm.hxx\"\n#include \"evntconf.hxx\"\n#include \"request.hxx\"\n#include \"fcontnr.hxx\"\n#include \"sfxtypes.hxx\"\n\n#define SFX_HTMLFRMSIZE_REL 0x0001\n#define SFX_HTMLFRMSIZE_PERCENT 0x0002\n\nstatic sal_Char __READONLY_DATA sHTML_SC_yes[] = \"YES\";\nstatic sal_Char __READONLY_DATA sHTML_SC_no[] = \"NO\";\nstatic sal_Char __READONLY_DATA sHTML_SC_auto[] = \"AUTO\";\n\n#define HTML_O_READONLY \"READONLY\"\n#define HTML_O_EDIT \"EDIT\"\n\nstatic HTMLOptionEnum __READONLY_DATA aScollingTable[] =\n{\n { sHTML_SC_yes, ScrollingYes },\n { sHTML_SC_no, ScrollingNo },\n { sHTML_SC_auto, ScrollingAuto },\n { 0, 0 }\n};\n\nvoid SfxFrameHTMLParser::ParseFrameOptions( SfxFrameDescriptor *pFrame, const HTMLOptions *pOptions, const String& rBaseURL )\n{\n \/\/ die Optionen holen und setzen\n Size aMargin( pFrame->GetMargin() );\n\n \/\/ MIB 15.7.97: Netscape scheint marginwidth auf 0 zu setzen, sobald\n \/\/ marginheight gesetzt wird und umgekehrt. Machen wir jetzt wegen\n \/\/ bug #41665# auch so.\n \/\/ Netscape l\"a\\st aber ein direktes Setzen auf 0 nicht zu, IE4.0 schon.\n \/\/ Den Bug machen wir nicht mit!\n BOOL bMarginWidth = FALSE, bMarginHeight = FALSE;\n\n USHORT nArrLen = pOptions->Count();\n for ( USHORT i=0; iGetToken() )\n {\n case HTML_O_BORDERCOLOR:\n {\n Color aColor;\n pOption->GetColor( aColor );\n pFrame->SetWallpaper( Wallpaper( aColor ) );\n break;\n }\n case HTML_O_SRC:\n pFrame->SetURL(\n String(\n INetURLObject::GetAbsURL(\n rBaseURL, pOption->GetString())) );\n break;\n case HTML_O_NAME:\n pFrame->SetName( pOption->GetString() );\n break;\n case HTML_O_MARGINWIDTH:\n aMargin.Width() = pOption->GetNumber();\n\n\/\/ if( aMargin.Width() < 1 )\n\/\/ aMargin.Width() = 1;\n if( !bMarginHeight )\n aMargin.Height() = 0;\n bMarginWidth = TRUE;\n break;\n case HTML_O_MARGINHEIGHT:\n aMargin.Height() = pOption->GetNumber();\n\n\/\/ if( aMargin.Height() < 1 )\n\/\/ aMargin.Height() = 1;\n if( !bMarginWidth )\n aMargin.Width() = 0;\n bMarginHeight = TRUE;\n break;\n case HTML_O_SCROLLING:\n pFrame->SetScrollingMode(\n (ScrollingMode)pOption->GetEnum( aScollingTable,\n ScrollingAuto ) );\n break;\n case HTML_O_FRAMEBORDER:\n {\n String aStr = pOption->GetString();\n BOOL bBorder = TRUE;\n if ( aStr.EqualsIgnoreCaseAscii(\"NO\") ||\n aStr.EqualsIgnoreCaseAscii(\"0\") )\n bBorder = FALSE;\n pFrame->SetFrameBorder( bBorder );\n break;\n }\n case HTML_O_NORESIZE:\n pFrame->SetResizable( FALSE );\n break;\n default:\n if ( pOption->GetTokenString().EqualsIgnoreCaseAscii(\n HTML_O_READONLY ) )\n {\n String aStr = pOption->GetString();\n BOOL bReadonly = TRUE;\n if ( aStr.EqualsIgnoreCaseAscii(\"FALSE\") )\n bReadonly = FALSE;\n pFrame->SetReadOnly( bReadonly );\n }\n else if ( pOption->GetTokenString().EqualsIgnoreCaseAscii(\n HTML_O_EDIT ) )\n {\n String aStr = pOption->GetString();\n BOOL bEdit = TRUE;\n if ( aStr.EqualsIgnoreCaseAscii(\"FALSE\") )\n bEdit = FALSE;\n pFrame->SetEditable( bEdit );\n }\n\n break;\n }\n }\n\n pFrame->SetMargin( aMargin );\n}\nINTEGRATION: CWS vgbugs07 (1.11.218); FILE MERGED 2007\/06\/04 13:34:43 vg 1.11.218.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmhtml.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 23:03:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#include \n#include \n\n#ifndef _HTMLTOKN_H\n#include \n#endif\n#ifndef SVTOOLS_ASYNCLINK_HXX\n#include \n#endif\n\n#ifndef GCC\n#endif\n\n#include \n\n#define _SVSTDARR_USHORTS\n#define _SVSTDARR_ULONGS\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sfxtypes.hxx\"\n\n#define SFX_HTMLFRMSIZE_REL 0x0001\n#define SFX_HTMLFRMSIZE_PERCENT 0x0002\n\nstatic sal_Char __READONLY_DATA sHTML_SC_yes[] = \"YES\";\nstatic sal_Char __READONLY_DATA sHTML_SC_no[] = \"NO\";\nstatic sal_Char __READONLY_DATA sHTML_SC_auto[] = \"AUTO\";\n\n#define HTML_O_READONLY \"READONLY\"\n#define HTML_O_EDIT \"EDIT\"\n\nstatic HTMLOptionEnum __READONLY_DATA aScollingTable[] =\n{\n { sHTML_SC_yes, ScrollingYes },\n { sHTML_SC_no, ScrollingNo },\n { sHTML_SC_auto, ScrollingAuto },\n { 0, 0 }\n};\n\nvoid SfxFrameHTMLParser::ParseFrameOptions( SfxFrameDescriptor *pFrame, const HTMLOptions *pOptions, const String& rBaseURL )\n{\n \/\/ die Optionen holen und setzen\n Size aMargin( pFrame->GetMargin() );\n\n \/\/ MIB 15.7.97: Netscape scheint marginwidth auf 0 zu setzen, sobald\n \/\/ marginheight gesetzt wird und umgekehrt. Machen wir jetzt wegen\n \/\/ bug #41665# auch so.\n \/\/ Netscape l\"a\\st aber ein direktes Setzen auf 0 nicht zu, IE4.0 schon.\n \/\/ Den Bug machen wir nicht mit!\n BOOL bMarginWidth = FALSE, bMarginHeight = FALSE;\n\n USHORT nArrLen = pOptions->Count();\n for ( USHORT i=0; iGetToken() )\n {\n case HTML_O_BORDERCOLOR:\n {\n Color aColor;\n pOption->GetColor( aColor );\n pFrame->SetWallpaper( Wallpaper( aColor ) );\n break;\n }\n case HTML_O_SRC:\n pFrame->SetURL(\n String(\n INetURLObject::GetAbsURL(\n rBaseURL, pOption->GetString())) );\n break;\n case HTML_O_NAME:\n pFrame->SetName( pOption->GetString() );\n break;\n case HTML_O_MARGINWIDTH:\n aMargin.Width() = pOption->GetNumber();\n\n\/\/ if( aMargin.Width() < 1 )\n\/\/ aMargin.Width() = 1;\n if( !bMarginHeight )\n aMargin.Height() = 0;\n bMarginWidth = TRUE;\n break;\n case HTML_O_MARGINHEIGHT:\n aMargin.Height() = pOption->GetNumber();\n\n\/\/ if( aMargin.Height() < 1 )\n\/\/ aMargin.Height() = 1;\n if( !bMarginWidth )\n aMargin.Width() = 0;\n bMarginHeight = TRUE;\n break;\n case HTML_O_SCROLLING:\n pFrame->SetScrollingMode(\n (ScrollingMode)pOption->GetEnum( aScollingTable,\n ScrollingAuto ) );\n break;\n case HTML_O_FRAMEBORDER:\n {\n String aStr = pOption->GetString();\n BOOL bBorder = TRUE;\n if ( aStr.EqualsIgnoreCaseAscii(\"NO\") ||\n aStr.EqualsIgnoreCaseAscii(\"0\") )\n bBorder = FALSE;\n pFrame->SetFrameBorder( bBorder );\n break;\n }\n case HTML_O_NORESIZE:\n pFrame->SetResizable( FALSE );\n break;\n default:\n if ( pOption->GetTokenString().EqualsIgnoreCaseAscii(\n HTML_O_READONLY ) )\n {\n String aStr = pOption->GetString();\n BOOL bReadonly = TRUE;\n if ( aStr.EqualsIgnoreCaseAscii(\"FALSE\") )\n bReadonly = FALSE;\n pFrame->SetReadOnly( bReadonly );\n }\n else if ( pOption->GetTokenString().EqualsIgnoreCaseAscii(\n HTML_O_EDIT ) )\n {\n String aStr = pOption->GetString();\n BOOL bEdit = TRUE;\n if ( aStr.EqualsIgnoreCaseAscii(\"FALSE\") )\n bEdit = FALSE;\n pFrame->SetEditable( bEdit );\n }\n\n break;\n }\n }\n\n pFrame->SetMargin( aMargin );\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2010 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\/\/ $Id$\n\n#include \"sqlite_datasource.hpp\"\n#include \"sqlite_featureset.hpp\"\n\n\/\/ mapnik\n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\n\nusing mapnik::datasource;\nusing mapnik::parameters;\n\nDATASOURCE_PLUGIN(sqlite_datasource)\n\nusing mapnik::box2d;\nusing mapnik::coord2d;\nusing mapnik::query;\nusing mapnik::featureset_ptr;\nusing mapnik::layer_descriptor;\nusing mapnik::attribute_descriptor;\nusing mapnik::datasource_exception;\n\n\nsqlite_datasource::sqlite_datasource(parameters const& params, bool bind)\n : datasource(params),\n extent_(),\n extent_initialized_(false),\n type_(datasource::Vector),\n table_(*params_.get(\"table\",\"\")),\n fields_(*params_.get(\"fields\",\"*\")),\n metadata_(*params_.get(\"metadata\",\"\")),\n geometry_table_(*params_.get(\"geometry_table\",\"\")),\n geometry_field_(*params_.get(\"geometry_field\",\"the_geom\")),\n \/\/ http:\/\/www.sqlite.org\/lang_createtable.html#rowid\n key_field_(*params_.get(\"key_field\",\"rowid\")),\n row_offset_(*params_.get(\"row_offset\",0)),\n row_limit_(*params_.get(\"row_limit\",0)),\n desc_(*params_.get(\"type\"), *params_.get(\"encoding\",\"utf-8\")),\n format_(mapnik::wkbGeneric)\n{\n boost::optional file = params_.get(\"file\");\n if (!file) throw datasource_exception(\"Sqlite Plugin: missing parameter\");\n\n if (table_.empty()) throw mapnik::datasource_exception(\"Sqlite Plugin: missing parameter\");\n\n boost::optional wkb = params_.get(\"wkb_format\");\n if (wkb)\n {\n if (*wkb == \"spatialite\")\n format_ = mapnik::wkbSpatiaLite; \n }\n\n multiple_geometries_ = *params_.get(\"multiple_geometries\",false);\n use_spatial_index_ = *params_.get(\"use_spatial_index\",true);\n\n boost::optional ext = params_.get(\"extent\");\n if (ext) extent_initialized_ = extent_.from_string(*ext);\n\n boost::optional base = params_.get(\"base\");\n if (base)\n dataset_name_ = *base + \"\/\" + *file;\n else\n dataset_name_ = *file;\n\n if (bind)\n {\n this->bind();\n }\n}\n\nvoid sqlite_datasource::bind() const\n{\n if (is_bound_) return;\n \n if (!boost::filesystem::exists(dataset_name_))\n throw datasource_exception(\"Sqlite Plugin: \" + dataset_name_ + \" does not exist\");\n \n dataset_ = new sqlite_connection (dataset_name_);\n\n if(geometry_table_.empty())\n {\n geometry_table_ = mapnik::table_from_sql(table_);\n }\n \n\n if (use_spatial_index_)\n {\n std::ostringstream s;\n s << \"SELECT COUNT (*) FROM sqlite_master\";\n s << \" WHERE LOWER(name) = LOWER('idx_\" << geometry_table_ << \"_\" << geometry_field_ << \"')\";\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n use_spatial_index_ = rs->column_integer (0) == 1;\n }\n\n if (!use_spatial_index_)\n std::clog << \"Sqlite Plugin: spatial index not found for table '\"\n << geometry_table_ << \"'\" << std::endl;\n }\n\n if (metadata_ != \"\" && !extent_initialized_)\n {\n std::ostringstream s;\n s << \"SELECT xmin, ymin, xmax, ymax FROM \" << metadata_;\n s << \" WHERE LOWER(f_table_name) = LOWER('\" << geometry_table_ << \"')\";\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n double xmin = rs->column_double (0);\n double ymin = rs->column_double (1);\n double xmax = rs->column_double (2);\n double ymax = rs->column_double (3);\n\n extent_.init (xmin,ymin,xmax,ymax);\n extent_initialized_ = true;\n }\n }\n \n if (!extent_initialized_ && use_spatial_index_)\n {\n std::ostringstream s;\n s << \"SELECT MIN(xmin), MIN(ymin), MAX(xmax), MAX(ymax) FROM \" \n << \"idx_\" << geometry_table_ << \"_\" << geometry_field_;\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n double xmin = rs->column_double (0);\n double ymin = rs->column_double (1);\n double xmax = rs->column_double (2);\n double ymax = rs->column_double (3);\n\n extent_.init (xmin,ymin,xmax,ymax);\n extent_initialized_ = true;\n } \n }\n \n {\n\n \/\/ should we deduce column names and types using PRAGMA?\n bool use_pragma_table_info = true;\n \n if (table_ != geometry_table_)\n {\n \/\/ if 'table_' is a subquery then we try to deduce names\n \/\/ and types from the first row returned from that query\n use_pragma_table_info = false;\n }\n\n if (!use_pragma_table_info)\n {\n std::ostringstream s;\n s << \"SELECT \" << fields_ << \" FROM (\" << table_ << \") LIMIT 1\";\n \n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n for (int i = 0; i < rs->column_count (); ++i)\n {\n const int type_oid = rs->column_type (i);\n const char* fld_name = rs->column_name (i);\n switch (type_oid)\n {\n case SQLITE_INTEGER:\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));\n break;\n \n case SQLITE_FLOAT:\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n break;\n \n case SQLITE_TEXT:\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n \n case SQLITE_NULL:\n \/\/ sqlite reports based on value, not actual column type unless\n \/\/ PRAGMA table_info is used so here we assume the column is a string\n \/\/ which is a lesser evil than altogether dropping the column\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n \n case SQLITE_BLOB:\n break;\n \n default:\n #ifdef MAPNIK_DEBUG\n std::clog << \"Sqlite Plugin: unknown type_oid=\" << type_oid << std::endl;\n #endif\n break;\n }\n }\n }\n else\n {\n \/\/ if we do not have at least a row and\n \/\/ we cannot determine the right columns types and names \n \/\/ as all column_type are SQLITE_NULL\n \/\/ so we fallback to using PRAGMA table_info\n use_pragma_table_info = true;\n }\n }\n\n \/\/ TODO - ensure that the supplied key_field is a valid \"integer primary key\"\n desc_.add_descriptor(attribute_descriptor(\"rowid\",mapnik::Integer));\n \n if (use_pragma_table_info)\n {\n std::ostringstream s;\n s << \"PRAGMA table_info(\" << geometry_table_ << \")\";\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n while (rs->is_valid () && rs->step_next())\n {\n const char* fld_name = rs->column_text(1);\n std::string fld_type(rs->column_text(2));\n boost::algorithm::to_lower(fld_type);\n\n \/\/ see 2.1 \"Column Affinity\" at http:\/\/www.sqlite.org\/datatype3.html\n \n if (boost::algorithm::contains(fld_type,\"int\"))\n {\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));\n }\n else if (boost::algorithm::contains(fld_type,\"text\") ||\n boost::algorithm::contains(fld_type,\"char\") ||\n boost::algorithm::contains(fld_type,\"clob\"))\n {\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n }\n else if (boost::algorithm::contains(fld_type,\"real\") ||\n boost::algorithm::contains(fld_type,\"float\") ||\n boost::algorithm::contains(fld_type,\"double\"))\n {\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n }\n \/\/else if (boost::algorithm::contains(fld_type,\"blob\")\n \/\/ desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n#ifdef MAPNIK_DEBUG\n else\n {\n \/\/ \"Column Affinity\" says default to \"Numeric\" but for now we pass..\n \/\/desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n std::clog << \"Sqlite Plugin: unknown type_oid=\" << fld_type << std::endl;\n }\n#endif\n }\n }\n }\n \n is_bound_ = true;\n}\n\nsqlite_datasource::~sqlite_datasource()\n{\n if (is_bound_) \n {\n delete dataset_;\n }\n}\n\nstd::string sqlite_datasource::name()\n{\n return \"sqlite\";\n}\n\nint sqlite_datasource::type() const\n{\n return type_;\n}\n\nbox2d sqlite_datasource::envelope() const\n{\n if (!is_bound_) bind();\n return extent_;\n}\n\nlayer_descriptor sqlite_datasource::get_descriptor() const\n{\n if (!is_bound_) bind();\n return desc_;\n}\n\nfeatureset_ptr sqlite_datasource::features(query const& q) const\n{\n if (!is_bound_) bind();\n if (dataset_)\n {\n mapnik::box2d const& e = q.get_bbox();\n\n std::ostringstream s;\n \n s << \"SELECT \" << geometry_field_ << \",\" << key_field_;\n std::set const& props = q.property_names();\n std::set::const_iterator pos = props.begin();\n std::set::const_iterator end = props.end();\n while (pos != end)\n {\n s << \",\\\"\" << *pos << \"\\\"\";\n ++pos;\n } \n \n s << \" FROM \"; \n \n std::string query (table_); \n \n if (use_spatial_index_)\n {\n std::ostringstream spatial_sql;\n spatial_sql << std::setprecision(16);\n spatial_sql << \" WHERE \" << key_field_ << \" IN (SELECT pkid FROM idx_\" << geometry_table_ << \"_\" << geometry_field_;\n spatial_sql << \" WHERE xmax>=\" << e.minx() << \" AND xmin<=\" << e.maxx() ;\n spatial_sql << \" AND ymax>=\" << e.miny() << \" AND ymin<=\" << e.maxy() << \")\";\n if (boost::algorithm::ifind_first(query, \"WHERE\"))\n {\n boost::algorithm::ireplace_first(query, \"WHERE\", spatial_sql.str() + \" AND \");\n }\n else if (boost::algorithm::ifind_first(query, geometry_table_)) \n {\n boost::algorithm::ireplace_first(query, table_, table_ + \" \" + spatial_sql.str());\n }\n }\n \n s << query ;\n \n if (row_limit_ > 0) {\n s << \" LIMIT \" << row_limit_;\n }\n\n if (row_offset_ > 0) {\n s << \" OFFSET \" << row_offset_;\n }\n\n#ifdef MAPNIK_DEBUG\n std::clog << \"Sqlite Plugin: \" << s.str() << std::endl;\n#endif\n\n boost::shared_ptr rs (dataset_->execute_query (s.str()));\n\n return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_));\n }\n\n return featureset_ptr();\n}\n\nfeatureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const\n{\n if (!is_bound_) bind();\n\n return featureset_ptr();\n}\n\nsqlite plugin: add features_at_point() impl\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2010 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\/\/ $Id$\n\n#include \"sqlite_datasource.hpp\"\n#include \"sqlite_featureset.hpp\"\n\n\/\/ mapnik\n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\n\nusing mapnik::datasource;\nusing mapnik::parameters;\n\nDATASOURCE_PLUGIN(sqlite_datasource)\n\nusing mapnik::box2d;\nusing mapnik::coord2d;\nusing mapnik::query;\nusing mapnik::featureset_ptr;\nusing mapnik::layer_descriptor;\nusing mapnik::attribute_descriptor;\nusing mapnik::datasource_exception;\n\n\nsqlite_datasource::sqlite_datasource(parameters const& params, bool bind)\n : datasource(params),\n extent_(),\n extent_initialized_(false),\n type_(datasource::Vector),\n table_(*params_.get(\"table\",\"\")),\n fields_(*params_.get(\"fields\",\"*\")),\n metadata_(*params_.get(\"metadata\",\"\")),\n geometry_table_(*params_.get(\"geometry_table\",\"\")),\n geometry_field_(*params_.get(\"geometry_field\",\"the_geom\")),\n \/\/ http:\/\/www.sqlite.org\/lang_createtable.html#rowid\n key_field_(*params_.get(\"key_field\",\"rowid\")),\n row_offset_(*params_.get(\"row_offset\",0)),\n row_limit_(*params_.get(\"row_limit\",0)),\n desc_(*params_.get(\"type\"), *params_.get(\"encoding\",\"utf-8\")),\n format_(mapnik::wkbGeneric)\n{\n boost::optional file = params_.get(\"file\");\n if (!file) throw datasource_exception(\"Sqlite Plugin: missing parameter\");\n\n if (table_.empty()) throw mapnik::datasource_exception(\"Sqlite Plugin: missing
parameter\");\n\n boost::optional wkb = params_.get(\"wkb_format\");\n if (wkb)\n {\n if (*wkb == \"spatialite\")\n format_ = mapnik::wkbSpatiaLite; \n }\n\n multiple_geometries_ = *params_.get(\"multiple_geometries\",false);\n use_spatial_index_ = *params_.get(\"use_spatial_index\",true);\n\n boost::optional ext = params_.get(\"extent\");\n if (ext) extent_initialized_ = extent_.from_string(*ext);\n\n boost::optional base = params_.get(\"base\");\n if (base)\n dataset_name_ = *base + \"\/\" + *file;\n else\n dataset_name_ = *file;\n\n if (bind)\n {\n this->bind();\n }\n}\n\nvoid sqlite_datasource::bind() const\n{\n if (is_bound_) return;\n \n if (!boost::filesystem::exists(dataset_name_))\n throw datasource_exception(\"Sqlite Plugin: \" + dataset_name_ + \" does not exist\");\n \n dataset_ = new sqlite_connection (dataset_name_);\n\n if(geometry_table_.empty())\n {\n geometry_table_ = mapnik::table_from_sql(table_);\n }\n \n\n if (use_spatial_index_)\n {\n std::ostringstream s;\n s << \"SELECT COUNT (*) FROM sqlite_master\";\n s << \" WHERE LOWER(name) = LOWER('idx_\" << geometry_table_ << \"_\" << geometry_field_ << \"')\";\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n use_spatial_index_ = rs->column_integer (0) == 1;\n }\n\n if (!use_spatial_index_)\n std::clog << \"Sqlite Plugin: spatial index not found for table '\"\n << geometry_table_ << \"'\" << std::endl;\n }\n\n if (metadata_ != \"\" && !extent_initialized_)\n {\n std::ostringstream s;\n s << \"SELECT xmin, ymin, xmax, ymax FROM \" << metadata_;\n s << \" WHERE LOWER(f_table_name) = LOWER('\" << geometry_table_ << \"')\";\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n double xmin = rs->column_double (0);\n double ymin = rs->column_double (1);\n double xmax = rs->column_double (2);\n double ymax = rs->column_double (3);\n\n extent_.init (xmin,ymin,xmax,ymax);\n extent_initialized_ = true;\n }\n }\n \n if (!extent_initialized_ && use_spatial_index_)\n {\n std::ostringstream s;\n s << \"SELECT MIN(xmin), MIN(ymin), MAX(xmax), MAX(ymax) FROM \" \n << \"idx_\" << geometry_table_ << \"_\" << geometry_field_;\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n double xmin = rs->column_double (0);\n double ymin = rs->column_double (1);\n double xmax = rs->column_double (2);\n double ymax = rs->column_double (3);\n\n extent_.init (xmin,ymin,xmax,ymax);\n extent_initialized_ = true;\n } \n }\n \n {\n\n \/\/ should we deduce column names and types using PRAGMA?\n bool use_pragma_table_info = true;\n \n if (table_ != geometry_table_)\n {\n \/\/ if 'table_' is a subquery then we try to deduce names\n \/\/ and types from the first row returned from that query\n use_pragma_table_info = false;\n }\n\n if (!use_pragma_table_info)\n {\n std::ostringstream s;\n s << \"SELECT \" << fields_ << \" FROM (\" << table_ << \") LIMIT 1\";\n \n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n if (rs->is_valid () && rs->step_next())\n {\n for (int i = 0; i < rs->column_count (); ++i)\n {\n const int type_oid = rs->column_type (i);\n const char* fld_name = rs->column_name (i);\n switch (type_oid)\n {\n case SQLITE_INTEGER:\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));\n break;\n \n case SQLITE_FLOAT:\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n break;\n \n case SQLITE_TEXT:\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n \n case SQLITE_NULL:\n \/\/ sqlite reports based on value, not actual column type unless\n \/\/ PRAGMA table_info is used so here we assume the column is a string\n \/\/ which is a lesser evil than altogether dropping the column\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n \n case SQLITE_BLOB:\n break;\n \n default:\n #ifdef MAPNIK_DEBUG\n std::clog << \"Sqlite Plugin: unknown type_oid=\" << type_oid << std::endl;\n #endif\n break;\n }\n }\n }\n else\n {\n \/\/ if we do not have at least a row and\n \/\/ we cannot determine the right columns types and names \n \/\/ as all column_type are SQLITE_NULL\n \/\/ so we fallback to using PRAGMA table_info\n use_pragma_table_info = true;\n }\n }\n\n \/\/ TODO - ensure that the supplied key_field is a valid \"integer primary key\"\n desc_.add_descriptor(attribute_descriptor(\"rowid\",mapnik::Integer));\n \n if (use_pragma_table_info)\n {\n std::ostringstream s;\n s << \"PRAGMA table_info(\" << geometry_table_ << \")\";\n boost::scoped_ptr rs (dataset_->execute_query (s.str()));\n while (rs->is_valid () && rs->step_next())\n {\n const char* fld_name = rs->column_text(1);\n std::string fld_type(rs->column_text(2));\n boost::algorithm::to_lower(fld_type);\n\n \/\/ see 2.1 \"Column Affinity\" at http:\/\/www.sqlite.org\/datatype3.html\n \n if (boost::algorithm::contains(fld_type,\"int\"))\n {\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer));\n }\n else if (boost::algorithm::contains(fld_type,\"text\") ||\n boost::algorithm::contains(fld_type,\"char\") ||\n boost::algorithm::contains(fld_type,\"clob\"))\n {\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n }\n else if (boost::algorithm::contains(fld_type,\"real\") ||\n boost::algorithm::contains(fld_type,\"float\") ||\n boost::algorithm::contains(fld_type,\"double\"))\n {\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n }\n \/\/else if (boost::algorithm::contains(fld_type,\"blob\")\n \/\/ desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n#ifdef MAPNIK_DEBUG\n else\n {\n \/\/ \"Column Affinity\" says default to \"Numeric\" but for now we pass..\n \/\/desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double));\n std::clog << \"Sqlite Plugin: unknown type_oid=\" << fld_type << std::endl;\n }\n#endif\n }\n }\n }\n \n is_bound_ = true;\n}\n\nsqlite_datasource::~sqlite_datasource()\n{\n if (is_bound_) \n {\n delete dataset_;\n }\n}\n\nstd::string sqlite_datasource::name()\n{\n return \"sqlite\";\n}\n\nint sqlite_datasource::type() const\n{\n return type_;\n}\n\nbox2d sqlite_datasource::envelope() const\n{\n if (!is_bound_) bind();\n return extent_;\n}\n\nlayer_descriptor sqlite_datasource::get_descriptor() const\n{\n if (!is_bound_) bind();\n return desc_;\n}\n\nfeatureset_ptr sqlite_datasource::features(query const& q) const\n{\n if (!is_bound_) bind();\n if (dataset_)\n {\n mapnik::box2d const& e = q.get_bbox();\n\n std::ostringstream s;\n \n s << \"SELECT \" << geometry_field_ << \",\" << key_field_;\n std::set const& props = q.property_names();\n std::set::const_iterator pos = props.begin();\n std::set::const_iterator end = props.end();\n while (pos != end)\n {\n s << \",\\\"\" << *pos << \"\\\"\";\n ++pos;\n } \n \n s << \" FROM \"; \n \n std::string query (table_); \n \n if (use_spatial_index_)\n {\n std::ostringstream spatial_sql;\n spatial_sql << std::setprecision(16);\n spatial_sql << \" WHERE \" << key_field_ << \" IN (SELECT pkid FROM idx_\" << geometry_table_ << \"_\" << geometry_field_;\n spatial_sql << \" WHERE xmax>=\" << e.minx() << \" AND xmin<=\" << e.maxx() ;\n spatial_sql << \" AND ymax>=\" << e.miny() << \" AND ymin<=\" << e.maxy() << \")\";\n if (boost::algorithm::ifind_first(query, \"WHERE\"))\n {\n boost::algorithm::ireplace_first(query, \"WHERE\", spatial_sql.str() + \" AND \");\n }\n else if (boost::algorithm::ifind_first(query, geometry_table_)) \n {\n boost::algorithm::ireplace_first(query, table_, table_ + \" \" + spatial_sql.str());\n }\n }\n \n s << query ;\n \n if (row_limit_ > 0) {\n s << \" LIMIT \" << row_limit_;\n }\n\n if (row_offset_ > 0) {\n s << \" OFFSET \" << row_offset_;\n }\n\n#ifdef MAPNIK_DEBUG\n std::clog << \"Sqlite Plugin: \" << s.str() << std::endl;\n#endif\n\n boost::shared_ptr rs (dataset_->execute_query (s.str()));\n\n return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_));\n }\n\n return featureset_ptr();\n}\n\nfeatureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const\n{\n if (!is_bound_) bind();\n\n if (dataset_)\n {\n \/\/ TODO - need tolerance\n mapnik::box2d const e(pt.x,pt.y,pt.x,pt.y);\n\n std::ostringstream s;\n\n \n s << \"SELECT \" << geometry_field_ << \",\" << key_field_;\n std::vector::const_iterator itr = desc_.get_descriptors().begin();\n std::vector::const_iterator end = desc_.get_descriptors().end();\n while (itr != end)\n {\n std::string fld_name = itr->get_name();\n if (fld_name != key_field_)\n s << \",\\\"\" << itr->get_name() << \"\\\"\";\n ++itr;\n }\n \n s << \" FROM \"; \n \n std::string query (table_); \n \n if (use_spatial_index_)\n {\n std::ostringstream spatial_sql;\n spatial_sql << std::setprecision(16);\n spatial_sql << \" WHERE \" << key_field_ << \" IN (SELECT pkid FROM idx_\" << geometry_table_ << \"_\" << geometry_field_;\n spatial_sql << \" WHERE xmax>=\" << e.minx() << \" AND xmin<=\" << e.maxx() ;\n spatial_sql << \" AND ymax>=\" << e.miny() << \" AND ymin<=\" << e.maxy() << \")\";\n if (boost::algorithm::ifind_first(query, \"WHERE\"))\n {\n boost::algorithm::ireplace_first(query, \"WHERE\", spatial_sql.str() + \" AND \");\n }\n else if (boost::algorithm::ifind_first(query, geometry_table_)) \n {\n boost::algorithm::ireplace_first(query, table_, table_ + \" \" + spatial_sql.str());\n }\n }\n \n s << query ;\n \n if (row_limit_ > 0) {\n s << \" LIMIT \" << row_limit_;\n }\n\n if (row_offset_ > 0) {\n s << \" OFFSET \" << row_offset_;\n }\n\n#ifdef MAPNIK_DEBUG\n std::clog << \"Sqlite Plugin: \" << s.str() << std::endl;\n#endif\n\n boost::shared_ptr rs (dataset_->execute_query (s.str()));\n\n return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_));\n }\n \n return featureset_ptr();\n}\n\n<|endoftext|>"} {"text":"\/\/----------------------------------*-C++-*----------------------------------\/\/\n\/*!\n * \\file xs\/test\/tstXS.cc\n * \\author Thomas M. Evans\n * \\date Fri Jan 31 12:54:58 2014\n * \\brief XS container test.\n * \\note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \"gtest\/utils_gtest.hh\"\n\n#include \"..\/XS.hh\"\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Test fixture\n\/\/---------------------------------------------------------------------------\/\/\n\n\/\/ NOTE: the test class name must not contain underscores.\nclass XS_Test : public testing::Test\n{\n protected:\n typedef profugus::XS XS;\n typedef XS::Vector Vector;\n typedef XS::Matrix Matrix;\n typedef XS::OneDArray OneDArray;\n typedef XS::TwoDArray TwoDArray;\n typedef XS::Vec_Int Vec_Int;\n\n protected:\n \/\/ Initialization that are performed for each test\n void SetUp()\n {\n Ng = 4;\n\n \/\/ build data\n m1_sig.resize(Ng);\n\n m5_sig.resize(Ng);\n sigf.resize(Ng);\n nusigf.resize(Ng);\n chi.resize(Ng);\n\n m1_sig[0] = 2.0;\n m1_sig[1] = 3.0;\n m1_sig[2] = 4.0;\n m1_sig[3] = 5.0;\n\n m5_sig[0] = 20.0;\n m5_sig[1] = 30.0;\n m5_sig[2] = 40.0;\n m5_sig[3] = 50.0;\n\n sigf[0] = 11.0;\n sigf[1] = 12.0;\n sigf[2] = 13.0;\n sigf[3] = 14.0;\n\n double nu = 2.4;\n for (int n = 0; n < 4; ++n)\n {\n nusigf[n] = sigf[n] * nu;\n }\n\n chi[0] = 0.6;\n chi[1] = 0.3;\n chi[2] = 0.1;\n\n xs.set(1, Ng);\n }\n\n protected:\n\n int Ng;\n\n OneDArray m1_sig;\n OneDArray m5_sig, sigf, nusigf, chi;\n\n XS xs;\n\n};\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ TESTS\n\/\/---------------------------------------------------------------------------\/\/\n\nTEST_F(XS_Test, totals_assignment)\n{\n EXPECT_EQ(1, xs.pn_order());\n EXPECT_EQ(4, xs.num_groups());\n EXPECT_EQ(0, xs.num_mat());\n\n xs.add(1, XS::TOTAL, m1_sig);\n\n xs.add(5, XS::TOTAL, m5_sig);\n xs.add(5, XS::SIG_F, sigf);\n xs.add(5, XS::NU_SIG_F, nusigf);\n xs.add(5, XS::CHI, chi);\n\n EXPECT_EQ(0, xs.num_mat());\n\n xs.complete();\n\n EXPECT_EQ(2, xs.num_mat());\n EXPECT_EQ(1, xs.pn_order());\n EXPECT_EQ(4, xs.num_groups());\n\n EXPECT_TRUE(xs.has(1));\n EXPECT_TRUE(xs.has(5));\n\n Vec_Int mids;\n xs.get_matids(mids);\n EXPECT_EQ(2, mids.size());\n EXPECT_EQ(1, mids[0]);\n EXPECT_EQ(5, mids[1]);\n\n \/\/ material 1\n {\n const Vector &sigt = xs.vector(1, XS::TOTAL);\n EXPECT_EQ(4, sigt.length());\n\n EXPECT_EQ(2.0, sigt(0));\n EXPECT_EQ(3.0, sigt(1));\n EXPECT_EQ(4.0, sigt(2));\n EXPECT_EQ(5.0, sigt(3));\n\n for (int t = 1; t < XS::END_XS_TYPES; ++t)\n {\n const Vector &sig = xs.vector(1, t);\n EXPECT_EQ(4, sig.length());\n for (int g = 0; g < 4; ++g)\n {\n EXPECT_EQ(0.0, sig(g));\n }\n }\n }\n\n \/\/ material 5\n {\n const Vector &sigt = xs.vector(5, XS::TOTAL);\n EXPECT_EQ(4, sigt.length());\n\n EXPECT_EQ(20.0, sigt(0));\n EXPECT_EQ(30.0, sigt(1));\n EXPECT_EQ(40.0, sigt(2));\n EXPECT_EQ(50.0, sigt(3));\n\n const Vector &sigf = xs.vector(5, XS::SIG_F);\n EXPECT_EQ(4, sigf.length());\n\n EXPECT_EQ(11.0, sigf(0));\n EXPECT_EQ(12.0, sigf(1));\n EXPECT_EQ(13.0, sigf(2));\n EXPECT_EQ(14.0, sigf(3));\n\n const Vector &nusigf = xs.vector(5, XS::NU_SIG_F);\n EXPECT_EQ(4, nusigf.length());\n\n EXPECT_EQ(2.4*11.0, nusigf(0));\n EXPECT_EQ(2.4*12.0, nusigf(1));\n EXPECT_EQ(2.4*13.0, nusigf(2));\n EXPECT_EQ(2.4*14.0, nusigf(3));\n\n const Vector &chi = xs.vector(5, XS::CHI);\n EXPECT_EQ(4, chi.length());\n\n EXPECT_EQ(0.6, chi(0));\n EXPECT_EQ(0.3, chi(1));\n EXPECT_EQ(0.1, chi(2));\n EXPECT_EQ(0.0, chi(3));\n }\n\n for (int m = 0; m < 2; ++m)\n {\n int matid = mids[m];\n for (int n = 0; n < 1; ++n)\n {\n const Matrix &sigs = xs.matrix(matid, n);\n EXPECT_EQ(4, sigs.numRows());\n EXPECT_EQ(4, sigs.numCols());\n for (int g = 0; g < 4; ++g)\n {\n for (int gp = 0; gp < 4; ++gp)\n {\n EXPECT_EQ(0.0, sigs(g, gp));\n }\n }\n }\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end of tstXS.cc\n\/\/---------------------------------------------------------------------------\/\/\nFinished XS assignment.\/\/----------------------------------*-C++-*----------------------------------\/\/\n\/*!\n * \\file xs\/test\/tstXS.cc\n * \\author Thomas M. Evans\n * \\date Fri Jan 31 12:54:58 2014\n * \\brief XS container test.\n * \\note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \"gtest\/utils_gtest.hh\"\n\n#include \"..\/XS.hh\"\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Test fixture\n\/\/---------------------------------------------------------------------------\/\/\n\n\/\/ NOTE: the test class name must not contain underscores.\nclass XS_Test : public testing::Test\n{\n protected:\n typedef profugus::XS XS;\n typedef XS::Vector Vector;\n typedef XS::Matrix Matrix;\n typedef XS::OneDArray OneDArray;\n typedef XS::TwoDArray TwoDArray;\n typedef XS::Vec_Int Vec_Int;\n\n protected:\n \/\/ Initialization that are performed for each test\n void SetUp()\n {\n Ng = 4;\n\n \/\/ build data\n m1_sig.resize(Ng);\n\n m5_sig.resize(Ng);\n sigf.resize(Ng);\n nusigf.resize(Ng);\n chi.resize(Ng);\n\n m1_sigs0.resizeRows(Ng);\n m1_sigs0.resizeCols(Ng);\n\n m1_sigs1.resizeRows(Ng);\n m1_sigs1.resizeCols(Ng);\n\n m5_sigs0.resizeRows(Ng);\n m5_sigs0.resizeCols(Ng);\n\n m5_sigs1.resizeRows(Ng);\n m5_sigs1.resizeCols(Ng);\n\n m1_sig[0] = 2.0;\n m1_sig[1] = 3.0;\n m1_sig[2] = 4.0;\n m1_sig[3] = 5.0;\n\n m5_sig[0] = 20.0;\n m5_sig[1] = 30.0;\n m5_sig[2] = 40.0;\n m5_sig[3] = 50.0;\n\n sigf[0] = 11.0;\n sigf[1] = 12.0;\n sigf[2] = 13.0;\n sigf[3] = 14.0;\n\n double nu = 2.4;\n for (int n = 0; n < 4; ++n)\n {\n nusigf[n] = sigf[n] * nu;\n }\n\n chi[0] = 0.6;\n chi[1] = 0.3;\n chi[2] = 0.1;\n\n \/\/ scattering m1\n double m1s0[][4] = {{1.1, 0.0, 0.0, 0.0},\n {0.4, 1.4, 0.0, 0.0},\n {0.2, 0.9, 3.2, 0.2},\n {0.1, 0.2, 0.4, 4.8}};\n double m1s1[][4] = {{0.11, 0.00, 0.00, 0.00},\n {0.04, 0.14, 0.00, 0.00},\n {0.02, 0.09, 0.32, 0.02},\n {0.01, 0.02, 0.04, 0.48}};\n\n \/\/ scattering m5\n double m5s0[][4] = {{2.1, 0.0, 0.0, 0.0},\n {1.4, 2.4, 0.0, 0.0},\n {1.2, 1.9, 5.2, 1.2},\n {1.1, 1.2, 2.4, 9.8}};\n double m5s1[][4] = {{0.21, 0.00, 0.00, 0.00},\n {0.14, 0.24, 0.00, 0.00},\n {0.12, 0.19, 0.52, 0.12},\n {0.11, 0.12, 0.24, 0.98}};\n\n for (int g = 0; g < 4; ++g)\n {\n for (int gp = 0; gp < 4; ++gp)\n {\n m1_sigs0(g, gp) = m1s0[g][gp];\n m1_sigs1(g, gp) = m1s1[g][gp];\n m5_sigs0(g, gp) = m5s0[g][gp];\n m5_sigs1(g, gp) = m5s1[g][gp];\n }\n }\n\n xs.set(1, Ng);\n }\n\n protected:\n\n int Ng;\n\n OneDArray m1_sig;\n OneDArray m5_sig, sigf, nusigf, chi;\n\n TwoDArray m1_sigs0, m1_sigs1, m5_sigs0, m5_sigs1;\n\n XS xs;\n\n};\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ TESTS\n\/\/---------------------------------------------------------------------------\/\/\n\nTEST_F(XS_Test, totals_assignment)\n{\n EXPECT_EQ(1, xs.pn_order());\n EXPECT_EQ(4, xs.num_groups());\n EXPECT_EQ(0, xs.num_mat());\n\n xs.add(1, XS::TOTAL, m1_sig);\n\n xs.add(5, XS::TOTAL, m5_sig);\n xs.add(5, XS::SIG_F, sigf);\n xs.add(5, XS::NU_SIG_F, nusigf);\n xs.add(5, XS::CHI, chi);\n\n EXPECT_EQ(0, xs.num_mat());\n\n xs.complete();\n\n EXPECT_EQ(2, xs.num_mat());\n EXPECT_EQ(1, xs.pn_order());\n EXPECT_EQ(4, xs.num_groups());\n\n EXPECT_TRUE(xs.has(1));\n EXPECT_TRUE(xs.has(5));\n\n Vec_Int mids;\n xs.get_matids(mids);\n EXPECT_EQ(2, mids.size());\n EXPECT_EQ(1, mids[0]);\n EXPECT_EQ(5, mids[1]);\n\n \/\/ material 1\n {\n const Vector &sigt = xs.vector(1, XS::TOTAL);\n EXPECT_EQ(4, sigt.length());\n\n EXPECT_EQ(2.0, sigt(0));\n EXPECT_EQ(3.0, sigt(1));\n EXPECT_EQ(4.0, sigt(2));\n EXPECT_EQ(5.0, sigt(3));\n\n for (int t = 1; t < XS::END_XS_TYPES; ++t)\n {\n const Vector &sig = xs.vector(1, t);\n EXPECT_EQ(4, sig.length());\n for (int g = 0; g < 4; ++g)\n {\n EXPECT_EQ(0.0, sig(g));\n }\n }\n }\n\n \/\/ material 5\n {\n const Vector &sigt = xs.vector(5, XS::TOTAL);\n EXPECT_EQ(4, sigt.length());\n\n EXPECT_EQ(20.0, sigt(0));\n EXPECT_EQ(30.0, sigt(1));\n EXPECT_EQ(40.0, sigt(2));\n EXPECT_EQ(50.0, sigt(3));\n\n const Vector &sigf = xs.vector(5, XS::SIG_F);\n EXPECT_EQ(4, sigf.length());\n\n EXPECT_EQ(11.0, sigf(0));\n EXPECT_EQ(12.0, sigf(1));\n EXPECT_EQ(13.0, sigf(2));\n EXPECT_EQ(14.0, sigf(3));\n\n const Vector &nusigf = xs.vector(5, XS::NU_SIG_F);\n EXPECT_EQ(4, nusigf.length());\n\n EXPECT_EQ(2.4*11.0, nusigf(0));\n EXPECT_EQ(2.4*12.0, nusigf(1));\n EXPECT_EQ(2.4*13.0, nusigf(2));\n EXPECT_EQ(2.4*14.0, nusigf(3));\n\n const Vector &chi = xs.vector(5, XS::CHI);\n EXPECT_EQ(4, chi.length());\n\n EXPECT_EQ(0.6, chi(0));\n EXPECT_EQ(0.3, chi(1));\n EXPECT_EQ(0.1, chi(2));\n EXPECT_EQ(0.0, chi(3));\n }\n\n for (int m = 0; m < 2; ++m)\n {\n int matid = mids[m];\n for (int n = 0; n < 1; ++n)\n {\n const Matrix &sigs = xs.matrix(matid, n);\n EXPECT_EQ(4, sigs.numRows());\n EXPECT_EQ(4, sigs.numCols());\n for (int g = 0; g < 4; ++g)\n {\n for (int gp = 0; gp < 4; ++gp)\n {\n EXPECT_EQ(0.0, sigs(g, gp));\n }\n }\n }\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\nTEST_F(XS_Test, scat_assignment)\n{\n xs.add(1, XS::TOTAL, m1_sig);\n xs.add(1, 0, m1_sigs0);\n xs.add(1, 1, m1_sigs1);\n xs.add(5, XS::TOTAL, m5_sig);\n xs.add(5, 0, m5_sigs0);\n xs.add(5, 1, m5_sigs1);\n\n xs.complete();\n\n EXPECT_EQ(2, xs.num_mat());\n EXPECT_EQ(1, xs.pn_order());\n EXPECT_EQ(4, xs.num_groups());\n\n \/\/ material 1\n {\n const Vector &sigt = xs.vector(1, XS::TOTAL);\n EXPECT_EQ(4, sigt.length());\n\n EXPECT_EQ(2.0, sigt(0));\n EXPECT_EQ(3.0, sigt(1));\n EXPECT_EQ(4.0, sigt(2));\n EXPECT_EQ(5.0, sigt(3));\n\n const Matrix &p0 = xs.matrix(1, 0);\n const Matrix &p1 = xs.matrix(1, 1);\n EXPECT_EQ(4, p0.numRows());\n EXPECT_EQ(4, p0.numCols());\n EXPECT_EQ(4, p1.numRows());\n EXPECT_EQ(4, p1.numCols());\n\n EXPECT_EQ(1.1, p0(0, 0));\n EXPECT_EQ(0.0, p0(0, 1));\n EXPECT_EQ(0.0, p0(0, 2));\n EXPECT_EQ(0.0, p0(0, 3));\n\n EXPECT_EQ(0.4, p0(1, 0));\n EXPECT_EQ(1.4, p0(1, 1));\n EXPECT_EQ(0.0, p0(1, 2));\n EXPECT_EQ(0.0, p0(1, 3));\n\n EXPECT_EQ(0.2, p0(2, 0));\n EXPECT_EQ(0.9, p0(2, 1));\n EXPECT_EQ(3.2, p0(2, 2));\n EXPECT_EQ(0.2, p0(2, 3));\n\n EXPECT_EQ(0.1, p0(3, 0));\n EXPECT_EQ(0.2, p0(3, 1));\n EXPECT_EQ(0.4, p0(3, 2));\n EXPECT_EQ(4.8, p0(3, 3));\n\n for (int g = 0; g < 4; ++g)\n {\n for (int gp = 0; gp < 4; ++gp)\n {\n EXPECT_SOFTEQ(p0(g,gp)*0.1, p1(g,gp), 1.0e-12);\n }\n }\n }\n\n \/\/ material 5\n {\n const Vector &sigt = xs.vector(5, XS::TOTAL);\n EXPECT_EQ(4, sigt.length());\n\n EXPECT_EQ(20.0, sigt(0));\n EXPECT_EQ(30.0, sigt(1));\n EXPECT_EQ(40.0, sigt(2));\n EXPECT_EQ(50.0, sigt(3));\n\n const Matrix &p0 = xs.matrix(5, 0);\n const Matrix &p1 = xs.matrix(5, 1);\n EXPECT_EQ(4, p0.numRows());\n EXPECT_EQ(4, p0.numCols());\n EXPECT_EQ(4, p1.numRows());\n EXPECT_EQ(4, p1.numCols());\n\n EXPECT_EQ(2.1, p0(0, 0));\n EXPECT_EQ(0.0, p0(0, 1));\n EXPECT_EQ(0.0, p0(0, 2));\n EXPECT_EQ(0.0, p0(0, 3));\n\n EXPECT_EQ(1.4, p0(1, 0));\n EXPECT_EQ(2.4, p0(1, 1));\n EXPECT_EQ(0.0, p0(1, 2));\n EXPECT_EQ(0.0, p0(1, 3));\n\n EXPECT_EQ(1.2, p0(2, 0));\n EXPECT_EQ(1.9, p0(2, 1));\n EXPECT_EQ(5.2, p0(2, 2));\n EXPECT_EQ(1.2, p0(2, 3));\n\n EXPECT_EQ(1.1, p0(3, 0));\n EXPECT_EQ(1.2, p0(3, 1));\n EXPECT_EQ(2.4, p0(3, 2));\n EXPECT_EQ(9.8, p0(3, 3));\n\n for (int g = 0; g < 4; ++g)\n {\n for (int gp = 0; gp < 4; ++gp)\n {\n EXPECT_SOFTEQ(p0(g,gp)*0.1, p1(g,gp), 1.0e-12);\n }\n }\n }\n\n Vec_Int mids;\n xs.get_matids(mids);\n\n for (int m = 0; m < 2; ++m)\n {\n for (int t = 1; t < XS::END_XS_TYPES; ++t)\n {\n const Vector &sig = xs.vector(mids[m], t);\n EXPECT_EQ(4, sig.length());\n for (int g = 0; g < 4; ++g)\n {\n EXPECT_EQ(0.0, sig(g));\n }\n }\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end of tstXS.cc\n\/\/---------------------------------------------------------------------------\/\/\n<|endoftext|>"} {"text":"\/***********************************************************************\n\tcreated:\t22\/2\/2004\n\tauthor:\t\tPaul D Turner\n\n\tpurpose:\tImplements the WindowFactoryManager\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2006 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 \"CEGUI\/WindowFactoryManager.h\"\n#include \"CEGUI\/WindowFactory.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tStatic Data Definitions\n*************************************************************************\/\n\/\/ singleton instance pointer\ntemplate<> WindowFactoryManager* Singleton::ms_Singleton\t= 0;\n\/\/ list of owned WindowFactory object pointers\nWindowFactoryManager::OwnedWindowFactoryList WindowFactoryManager::d_ownedFactories;\n\n\/\/----------------------------------------------------------------------------\/\/\nWindowFactoryManager::WindowFactoryManager(void)\n{\n Logger::getSingleton().logEvent(\n \"CEGUI::WindowFactoryManager singleton created\");\n\n \/\/ complete addition of any pre-added WindowFactory objects\n WindowFactoryManager::OwnedWindowFactoryList::iterator i =\n d_ownedFactories.begin();\n\n if (d_ownedFactories.end() != i)\n {\n Logger::getSingleton().logEvent(\n \"---- Adding pre-registered WindowFactory objects ----\");\n\n for (; d_ownedFactories.end() != i; ++i)\n addFactory(*i);\n }\n}\n\n\/*************************************************************************\n\tAdds a WindowFactory object to the registry\n*************************************************************************\/\nvoid WindowFactoryManager::addFactory(WindowFactory* factory)\n{\n\t\/\/ throw exception if passed factory is null.\n\tif (!factory)\n\t{\n\t\tCEGUI_THROW(NullObjectException(\n \"The provided WindowFactory pointer was invalid.\"));\n\t}\n\n\t\/\/ throw exception if type name for factory is already in use\n\tif (d_factoryRegistry.find(factory->getTypeName()) != d_factoryRegistry.end())\n\t{\n\t\tCEGUI_THROW(AlreadyExistsException(\n \"A WindowFactory for type '\" + factory->getTypeName() +\n \"' is already registered.\"));\n\t}\n\n\t\/\/ add the factory to the registry\n\td_factoryRegistry[factory->getTypeName()] = factory;\n\n char addr_buff[32];\n sprintf(addr_buff, \"(%p)\", static_cast(factory));\n\tLogger::getSingleton().logEvent(\"WindowFactory for '\" +\n factory->getTypeName() +\"' windows added. \" + addr_buff);\n}\n\n\n\/*************************************************************************\n\tremoves a WindowFactory from the registry (by name)\n*************************************************************************\/\nvoid WindowFactoryManager::removeFactory(const String& name)\n{\n WindowFactoryRegistry::iterator i = d_factoryRegistry.find(name);\n\n \/\/ exit if no factory exists for this type\n if (i == d_factoryRegistry.end())\n return;\n\n \/\/ see if we own this factory\n OwnedWindowFactoryList::iterator j = std::find(d_ownedFactories.begin(),\n d_ownedFactories.end(),\n (*i).second);\n\n char addr_buff[32];\n sprintf(addr_buff, \"(%p)\", static_cast((*i).second));\n\n\td_factoryRegistry.erase(name);\n\n Logger::getSingleton().logEvent(\"WindowFactory for '\" + name +\n \"' windows removed. \" + addr_buff);\n\n \/\/ delete factory object if we created it\n if (j != d_ownedFactories.end())\n {\n Logger::getSingleton().logEvent(\"Deleted WindowFactory for '\" +\n (*j)->getTypeName() +\n \"' windows.\");\n\n CEGUI_DELETE_AO (*j);\n d_ownedFactories.erase(j);\n }\n}\n\n\n\/*************************************************************************\n\tremoves a WindowFactory from the registry (by pointer)\n*************************************************************************\/\nvoid WindowFactoryManager::removeFactory(WindowFactory* factory)\n{\n\tif (factory)\n\t{\n\t\tremoveFactory(factory->getTypeName());\n\t}\n\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid WindowFactoryManager::removeAllFactories(void)\n{\n while (!d_factoryRegistry.empty())\n removeFactory((*d_factoryRegistry.begin()).second);\n}\n\n\n\/*************************************************************************\n\treturns a pointer to the requested WindowFactory object\n*************************************************************************\/\nWindowFactory* WindowFactoryManager::getFactory(const String& type) const\n{\n \/\/ first, dereference aliased types, as needed.\n String targetType(getDereferencedAliasType(type));\n\n\t\/\/ try for a 'real' type\n\tWindowFactoryRegistry::const_iterator pos = d_factoryRegistry.find(targetType);\n\n\t\/\/ found an actual factory for this type\n\tif (pos != d_factoryRegistry.end())\n\t{\n\t\treturn pos->second;\n\t}\n \/\/ no concrete type, try for a falagard mapped type\n else\n {\n FalagardMapRegistry::const_iterator falagard = d_falagardRegistry.find(targetType);\n\n \/\/ found falagard mapping for this type\n if (falagard != d_falagardRegistry.end())\n {\n \/\/ recursively call getFactory on the target base type\n return getFactory(falagard->second.d_baseType);\n }\n \/\/ type not found anywhere, give up with an exception.\n else\n {\n CEGUI_THROW(UnknownObjectException(\n \"A WindowFactory object, an alias, or mapping for '\" + type +\n \"' Window objects is not registered with the system.\"));\n }\n }\n}\n\n\n\/*************************************************************************\n Returns true if a WindowFactory, an alias, or a falagard mapping for\n a specified window type is present\n*************************************************************************\/\nbool WindowFactoryManager::isFactoryPresent(const String& name) const\n{\n \/\/ first, dereference aliased types, as needed.\n String targetType(getDereferencedAliasType(name));\n\n \/\/ now try for a 'real' type\n if (d_factoryRegistry.find(targetType) != d_factoryRegistry.end())\n {\n return true;\n }\n \/\/ not a concrete type, so return whether it's a Falagard mapped type.\n else\n {\n return (d_falagardRegistry.find(targetType) != d_falagardRegistry.end());\n }\n}\n\n\n\/*************************************************************************\n\tReturn a WindowFactoryManager::WindowFactoryIterator object to\n\titerate over the available WindowFactory types.\n*************************************************************************\/\nWindowFactoryManager::WindowFactoryIterator\tWindowFactoryManager::getIterator(void) const\n{\n\treturn WindowFactoryIterator(d_factoryRegistry.begin(), d_factoryRegistry.end());\n}\n\n\n\/*************************************************************************\n\tReturn a WindowFactoryManager::TypeAliasIterator object to iterate\n\tover the defined aliases for window types.\n*************************************************************************\/\nWindowFactoryManager::TypeAliasIterator WindowFactoryManager::getAliasIterator(void) const\n{\n\treturn TypeAliasIterator(d_aliasRegistry.begin(), d_aliasRegistry.end());\n}\n\n\n\/*************************************************************************\n\tAdd a window type alias mapping\n*************************************************************************\/\nvoid WindowFactoryManager::addWindowTypeAlias(const String& aliasName, const String& targetType)\n{\n\tTypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName);\n\n\tif (pos == d_aliasRegistry.end())\n\t{\n\t\td_aliasRegistry[aliasName].d_targetStack.push_back(targetType);\n\t}\n\t\/\/ alias already exists, add our new entry to the list already there\n\telse\n\t{\n\t\tpos->second.d_targetStack.push_back(targetType);\n\t}\n\n\tLogger::getSingleton().logEvent(\"Window type alias named '\" + aliasName + \"' added for window type '\" + targetType +\"'.\");\n}\n\n\n\/*************************************************************************\n\tRemove a window type alias mapping\n*************************************************************************\/\nvoid WindowFactoryManager::removeWindowTypeAlias(const String& aliasName, const String& targetType)\n{\n\t\/\/ find alias name\n\tTypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName);\n\n\t\/\/ if alias name exists\n\tif (pos != d_aliasRegistry.end())\n\t{\n\t\t\/\/ find the specified target for this alias\n\t\tAliasTargetStack::TargetTypeStack::iterator aliasPos = std::find(pos->second.d_targetStack.begin(), pos->second.d_targetStack.end(), targetType);\n\n\t\t\/\/ if the target exists for this alias\n\t\tif (aliasPos != pos->second.d_targetStack.end())\n\t\t{\n\t\t\t\/\/ erase the target mapping\n\t\t\tpos->second.d_targetStack.erase(aliasPos);\n\n\t\t\tLogger::getSingleton().logEvent(\"Window type alias named '\" + aliasName + \"' removed for window type '\" + targetType +\"'.\");\n\n\t\t\t\/\/ if the list of targets for this alias is now empty\n\t\t\tif (pos->second.d_targetStack.empty())\n\t\t\t{\n\t\t\t\t\/\/ erase the alias name also\n\t\t\t\td_aliasRegistry.erase(aliasName);\n\n\t\t\t\tLogger::getSingleton().logEvent(\"Window type alias named '\" + aliasName + \"' has no more targets and has been removed.\", Informative);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\nvoid WindowFactoryManager::removeAllWindowTypeAliases()\n{\n\td_aliasRegistry.clear();\n}\n\nvoid WindowFactoryManager::addFalagardWindowMapping(const String& newType,\n const String& targetType,\n const String& lookName,\n const String& renderer,\n const String& effectName)\n{\n WindowFactoryManager::FalagardWindowMapping mapping;\n mapping.d_windowType = newType;\n mapping.d_baseType = targetType;\n mapping.d_lookName = lookName;\n mapping.d_rendererType = renderer;\n mapping.d_effectName = effectName;\n\n \/\/ see if the type we're creating already exists\n if (d_falagardRegistry.find(newType) != d_falagardRegistry.end())\n {\n \/\/ type already exists, log the fact that it's going to be replaced.\n Logger::getSingleton().logEvent(\"Falagard mapping for type '\" + newType + \"' already exists - current mapping will be replaced.\");\n }\n\n char addr_buff[32];\n sprintf(addr_buff, \"(%p)\", static_cast(&mapping));\n Logger::getSingleton().logEvent(\"Creating falagard mapping for type '\" +\n newType + \"' using base type '\" + targetType + \"', window renderer '\" +\n renderer + \"' Look'N'Feel '\" + lookName + \"' and RenderEffect '\" +\n effectName + \"'. \" + addr_buff);\n\n d_falagardRegistry[newType] = mapping;\n}\n\nvoid WindowFactoryManager::removeFalagardWindowMapping(const String& type)\n{\n FalagardMapRegistry::iterator iter = d_falagardRegistry.find(type);\n\n if (iter != d_falagardRegistry.end())\n {\n Logger::getSingleton().logEvent(\"Removing falagard mapping for type '\" + type + \"'.\");\n d_falagardRegistry.erase(iter);\n }\n}\n\nvoid WindowFactoryManager::removeAllFalagardWindowMappings()\n{\n\td_falagardRegistry.clear();\n}\n\nWindowFactoryManager::FalagardMappingIterator WindowFactoryManager::getFalagardMappingIterator() const\n{\n return FalagardMappingIterator(d_falagardRegistry.begin(), d_falagardRegistry.end());\n}\n\nbool WindowFactoryManager::isFalagardMappedType(const String& type) const\n{\n return d_falagardRegistry.find(getDereferencedAliasType(type)) != d_falagardRegistry.end();\n}\n\nconst String& WindowFactoryManager::getMappedLookForType(const String& type) const\n{\n FalagardMapRegistry::const_iterator iter =\n d_falagardRegistry.find(getDereferencedAliasType(type));\n\n if (iter != d_falagardRegistry.end())\n {\n return (*iter).second.d_lookName;\n }\n \/\/ type does not exist as a mapped type (or an alias for one)\n else\n {\n CEGUI_THROW(InvalidRequestException(\n \"Window factory type '\" + type +\n \"' is not a falagard mapped type (or an alias for one).\"));\n }\n}\n\nconst String& WindowFactoryManager::getMappedRendererForType(const String& type) const\n{\n FalagardMapRegistry::const_iterator iter =\n d_falagardRegistry.find(getDereferencedAliasType(type));\n\n if (iter != d_falagardRegistry.end())\n {\n return (*iter).second.d_rendererType;\n }\n \/\/ type does not exist as a mapped type (or an alias for one)\n else\n {\n CEGUI_THROW(InvalidRequestException(\n \"Window factory type '\" + type +\n \"' is not a falagard mapped type (or an alias for one).\"));\n }\n}\n\nString WindowFactoryManager::getDereferencedAliasType(const String& type) const\n{\n TypeAliasRegistry::const_iterator alias = d_aliasRegistry.find(type);\n\n \/\/ if this is an aliased type, ensure to fully dereference by recursively\n \/\/ calling ourselves on the active target for the given type.\n if (alias != d_aliasRegistry.end())\n return getDereferencedAliasType(alias->second.getActiveTarget());\n\n \/\/ we're not an alias, so return the input type unchanged\n return type;\n}\n\nconst WindowFactoryManager::FalagardWindowMapping& WindowFactoryManager::getFalagardMappingForType(const String& type) const\n{\n FalagardMapRegistry::const_iterator iter =\n d_falagardRegistry.find(getDereferencedAliasType(type));\n\n if (iter != d_falagardRegistry.end())\n {\n return (*iter).second;\n }\n \/\/ type does not exist as a mapped type (or an alias for one)\n else\n {\n CEGUI_THROW(InvalidRequestException(\n \"Window factory type '\" + type +\n \"' is not a falagard mapped type (or an alias for one).\"));\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*************************************************************************\n\tMethods for AliasTargetStack class\n*************************************************************************\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst String& WindowFactoryManager::AliasTargetStack::getActiveTarget(void) const\n{\n\treturn d_targetStack.back();\n}\n\n\nuint WindowFactoryManager::AliasTargetStack::getStackedTargetCount(void) const\n{\n\treturn (uint)d_targetStack.size();\n}\n\n\n} \/\/ End of CEGUI namespace section\nHint towards SchemeManager when window factory manager can't find a window factory\/***********************************************************************\n\tcreated:\t22\/2\/2004\n\tauthor:\t\tPaul D Turner\n\n\tpurpose:\tImplements the WindowFactoryManager\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2006 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 \"CEGUI\/WindowFactoryManager.h\"\n#include \"CEGUI\/WindowFactory.h\"\n#include \"CEGUI\/Exceptions.h\"\n#include \n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tStatic Data Definitions\n*************************************************************************\/\n\/\/ singleton instance pointer\ntemplate<> WindowFactoryManager* Singleton::ms_Singleton\t= 0;\n\/\/ list of owned WindowFactory object pointers\nWindowFactoryManager::OwnedWindowFactoryList WindowFactoryManager::d_ownedFactories;\n\n\/\/----------------------------------------------------------------------------\/\/\nWindowFactoryManager::WindowFactoryManager(void)\n{\n Logger::getSingleton().logEvent(\n \"CEGUI::WindowFactoryManager singleton created\");\n\n \/\/ complete addition of any pre-added WindowFactory objects\n WindowFactoryManager::OwnedWindowFactoryList::iterator i =\n d_ownedFactories.begin();\n\n if (d_ownedFactories.end() != i)\n {\n Logger::getSingleton().logEvent(\n \"---- Adding pre-registered WindowFactory objects ----\");\n\n for (; d_ownedFactories.end() != i; ++i)\n addFactory(*i);\n }\n}\n\n\/*************************************************************************\n\tAdds a WindowFactory object to the registry\n*************************************************************************\/\nvoid WindowFactoryManager::addFactory(WindowFactory* factory)\n{\n\t\/\/ throw exception if passed factory is null.\n\tif (!factory)\n\t{\n\t\tCEGUI_THROW(NullObjectException(\n \"The provided WindowFactory pointer was invalid.\"));\n\t}\n\n\t\/\/ throw exception if type name for factory is already in use\n\tif (d_factoryRegistry.find(factory->getTypeName()) != d_factoryRegistry.end())\n\t{\n\t\tCEGUI_THROW(AlreadyExistsException(\n \"A WindowFactory for type '\" + factory->getTypeName() +\n \"' is already registered.\"));\n\t}\n\n\t\/\/ add the factory to the registry\n\td_factoryRegistry[factory->getTypeName()] = factory;\n\n char addr_buff[32];\n sprintf(addr_buff, \"(%p)\", static_cast(factory));\n\tLogger::getSingleton().logEvent(\"WindowFactory for '\" +\n factory->getTypeName() +\"' windows added. \" + addr_buff);\n}\n\n\n\/*************************************************************************\n\tremoves a WindowFactory from the registry (by name)\n*************************************************************************\/\nvoid WindowFactoryManager::removeFactory(const String& name)\n{\n WindowFactoryRegistry::iterator i = d_factoryRegistry.find(name);\n\n \/\/ exit if no factory exists for this type\n if (i == d_factoryRegistry.end())\n return;\n\n \/\/ see if we own this factory\n OwnedWindowFactoryList::iterator j = std::find(d_ownedFactories.begin(),\n d_ownedFactories.end(),\n (*i).second);\n\n char addr_buff[32];\n sprintf(addr_buff, \"(%p)\", static_cast((*i).second));\n\n\td_factoryRegistry.erase(name);\n\n Logger::getSingleton().logEvent(\"WindowFactory for '\" + name +\n \"' windows removed. \" + addr_buff);\n\n \/\/ delete factory object if we created it\n if (j != d_ownedFactories.end())\n {\n Logger::getSingleton().logEvent(\"Deleted WindowFactory for '\" +\n (*j)->getTypeName() +\n \"' windows.\");\n\n CEGUI_DELETE_AO (*j);\n d_ownedFactories.erase(j);\n }\n}\n\n\n\/*************************************************************************\n\tremoves a WindowFactory from the registry (by pointer)\n*************************************************************************\/\nvoid WindowFactoryManager::removeFactory(WindowFactory* factory)\n{\n\tif (factory)\n\t{\n\t\tremoveFactory(factory->getTypeName());\n\t}\n\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid WindowFactoryManager::removeAllFactories(void)\n{\n while (!d_factoryRegistry.empty())\n removeFactory((*d_factoryRegistry.begin()).second);\n}\n\n\n\/*************************************************************************\n\treturns a pointer to the requested WindowFactory object\n*************************************************************************\/\nWindowFactory* WindowFactoryManager::getFactory(const String& type) const\n{\n \/\/ first, dereference aliased types, as needed.\n String targetType(getDereferencedAliasType(type));\n\n\t\/\/ try for a 'real' type\n\tWindowFactoryRegistry::const_iterator pos = d_factoryRegistry.find(targetType);\n\n\t\/\/ found an actual factory for this type\n\tif (pos != d_factoryRegistry.end())\n\t{\n\t\treturn pos->second;\n\t}\n \/\/ no concrete type, try for a falagard mapped type\n else\n {\n FalagardMapRegistry::const_iterator falagard = d_falagardRegistry.find(targetType);\n\n \/\/ found falagard mapping for this type\n if (falagard != d_falagardRegistry.end())\n {\n \/\/ recursively call getFactory on the target base type\n return getFactory(falagard->second.d_baseType);\n }\n \/\/ type not found anywhere, give up with an exception.\n else\n {\n CEGUI_THROW(UnknownObjectException(\n \"A WindowFactory object, an alias, or mapping for '\" + type +\n \"' Window objects is not registered with the system.\\n\\n\"\n \"Have you forgotten to load a scheme using \"\n \"CEGUI::SchemeManager::createFromFile(..)?\"));\n }\n }\n}\n\n\n\/*************************************************************************\n Returns true if a WindowFactory, an alias, or a falagard mapping for\n a specified window type is present\n*************************************************************************\/\nbool WindowFactoryManager::isFactoryPresent(const String& name) const\n{\n \/\/ first, dereference aliased types, as needed.\n String targetType(getDereferencedAliasType(name));\n\n \/\/ now try for a 'real' type\n if (d_factoryRegistry.find(targetType) != d_factoryRegistry.end())\n {\n return true;\n }\n \/\/ not a concrete type, so return whether it's a Falagard mapped type.\n else\n {\n return (d_falagardRegistry.find(targetType) != d_falagardRegistry.end());\n }\n}\n\n\n\/*************************************************************************\n\tReturn a WindowFactoryManager::WindowFactoryIterator object to\n\titerate over the available WindowFactory types.\n*************************************************************************\/\nWindowFactoryManager::WindowFactoryIterator\tWindowFactoryManager::getIterator(void) const\n{\n\treturn WindowFactoryIterator(d_factoryRegistry.begin(), d_factoryRegistry.end());\n}\n\n\n\/*************************************************************************\n\tReturn a WindowFactoryManager::TypeAliasIterator object to iterate\n\tover the defined aliases for window types.\n*************************************************************************\/\nWindowFactoryManager::TypeAliasIterator WindowFactoryManager::getAliasIterator(void) const\n{\n\treturn TypeAliasIterator(d_aliasRegistry.begin(), d_aliasRegistry.end());\n}\n\n\n\/*************************************************************************\n\tAdd a window type alias mapping\n*************************************************************************\/\nvoid WindowFactoryManager::addWindowTypeAlias(const String& aliasName, const String& targetType)\n{\n\tTypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName);\n\n\tif (pos == d_aliasRegistry.end())\n\t{\n\t\td_aliasRegistry[aliasName].d_targetStack.push_back(targetType);\n\t}\n\t\/\/ alias already exists, add our new entry to the list already there\n\telse\n\t{\n\t\tpos->second.d_targetStack.push_back(targetType);\n\t}\n\n\tLogger::getSingleton().logEvent(\"Window type alias named '\" + aliasName + \"' added for window type '\" + targetType +\"'.\");\n}\n\n\n\/*************************************************************************\n\tRemove a window type alias mapping\n*************************************************************************\/\nvoid WindowFactoryManager::removeWindowTypeAlias(const String& aliasName, const String& targetType)\n{\n\t\/\/ find alias name\n\tTypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName);\n\n\t\/\/ if alias name exists\n\tif (pos != d_aliasRegistry.end())\n\t{\n\t\t\/\/ find the specified target for this alias\n\t\tAliasTargetStack::TargetTypeStack::iterator aliasPos = std::find(pos->second.d_targetStack.begin(), pos->second.d_targetStack.end(), targetType);\n\n\t\t\/\/ if the target exists for this alias\n\t\tif (aliasPos != pos->second.d_targetStack.end())\n\t\t{\n\t\t\t\/\/ erase the target mapping\n\t\t\tpos->second.d_targetStack.erase(aliasPos);\n\n\t\t\tLogger::getSingleton().logEvent(\"Window type alias named '\" + aliasName + \"' removed for window type '\" + targetType +\"'.\");\n\n\t\t\t\/\/ if the list of targets for this alias is now empty\n\t\t\tif (pos->second.d_targetStack.empty())\n\t\t\t{\n\t\t\t\t\/\/ erase the alias name also\n\t\t\t\td_aliasRegistry.erase(aliasName);\n\n\t\t\t\tLogger::getSingleton().logEvent(\"Window type alias named '\" + aliasName + \"' has no more targets and has been removed.\", Informative);\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\nvoid WindowFactoryManager::removeAllWindowTypeAliases()\n{\n\td_aliasRegistry.clear();\n}\n\nvoid WindowFactoryManager::addFalagardWindowMapping(const String& newType,\n const String& targetType,\n const String& lookName,\n const String& renderer,\n const String& effectName)\n{\n WindowFactoryManager::FalagardWindowMapping mapping;\n mapping.d_windowType = newType;\n mapping.d_baseType = targetType;\n mapping.d_lookName = lookName;\n mapping.d_rendererType = renderer;\n mapping.d_effectName = effectName;\n\n \/\/ see if the type we're creating already exists\n if (d_falagardRegistry.find(newType) != d_falagardRegistry.end())\n {\n \/\/ type already exists, log the fact that it's going to be replaced.\n Logger::getSingleton().logEvent(\"Falagard mapping for type '\" + newType + \"' already exists - current mapping will be replaced.\");\n }\n\n char addr_buff[32];\n sprintf(addr_buff, \"(%p)\", static_cast(&mapping));\n Logger::getSingleton().logEvent(\"Creating falagard mapping for type '\" +\n newType + \"' using base type '\" + targetType + \"', window renderer '\" +\n renderer + \"' Look'N'Feel '\" + lookName + \"' and RenderEffect '\" +\n effectName + \"'. \" + addr_buff);\n\n d_falagardRegistry[newType] = mapping;\n}\n\nvoid WindowFactoryManager::removeFalagardWindowMapping(const String& type)\n{\n FalagardMapRegistry::iterator iter = d_falagardRegistry.find(type);\n\n if (iter != d_falagardRegistry.end())\n {\n Logger::getSingleton().logEvent(\"Removing falagard mapping for type '\" + type + \"'.\");\n d_falagardRegistry.erase(iter);\n }\n}\n\nvoid WindowFactoryManager::removeAllFalagardWindowMappings()\n{\n\td_falagardRegistry.clear();\n}\n\nWindowFactoryManager::FalagardMappingIterator WindowFactoryManager::getFalagardMappingIterator() const\n{\n return FalagardMappingIterator(d_falagardRegistry.begin(), d_falagardRegistry.end());\n}\n\nbool WindowFactoryManager::isFalagardMappedType(const String& type) const\n{\n return d_falagardRegistry.find(getDereferencedAliasType(type)) != d_falagardRegistry.end();\n}\n\nconst String& WindowFactoryManager::getMappedLookForType(const String& type) const\n{\n FalagardMapRegistry::const_iterator iter =\n d_falagardRegistry.find(getDereferencedAliasType(type));\n\n if (iter != d_falagardRegistry.end())\n {\n return (*iter).second.d_lookName;\n }\n \/\/ type does not exist as a mapped type (or an alias for one)\n else\n {\n CEGUI_THROW(InvalidRequestException(\n \"Window factory type '\" + type +\n \"' is not a falagard mapped type (or an alias for one).\"));\n }\n}\n\nconst String& WindowFactoryManager::getMappedRendererForType(const String& type) const\n{\n FalagardMapRegistry::const_iterator iter =\n d_falagardRegistry.find(getDereferencedAliasType(type));\n\n if (iter != d_falagardRegistry.end())\n {\n return (*iter).second.d_rendererType;\n }\n \/\/ type does not exist as a mapped type (or an alias for one)\n else\n {\n CEGUI_THROW(InvalidRequestException(\n \"Window factory type '\" + type +\n \"' is not a falagard mapped type (or an alias for one).\"));\n }\n}\n\nString WindowFactoryManager::getDereferencedAliasType(const String& type) const\n{\n TypeAliasRegistry::const_iterator alias = d_aliasRegistry.find(type);\n\n \/\/ if this is an aliased type, ensure to fully dereference by recursively\n \/\/ calling ourselves on the active target for the given type.\n if (alias != d_aliasRegistry.end())\n return getDereferencedAliasType(alias->second.getActiveTarget());\n\n \/\/ we're not an alias, so return the input type unchanged\n return type;\n}\n\nconst WindowFactoryManager::FalagardWindowMapping& WindowFactoryManager::getFalagardMappingForType(const String& type) const\n{\n FalagardMapRegistry::const_iterator iter =\n d_falagardRegistry.find(getDereferencedAliasType(type));\n\n if (iter != d_falagardRegistry.end())\n {\n return (*iter).second;\n }\n \/\/ type does not exist as a mapped type (or an alias for one)\n else\n {\n CEGUI_THROW(InvalidRequestException(\n \"Window factory type '\" + type +\n \"' is not a falagard mapped type (or an alias for one).\"));\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*************************************************************************\n\tMethods for AliasTargetStack class\n*************************************************************************\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst String& WindowFactoryManager::AliasTargetStack::getActiveTarget(void) const\n{\n\treturn d_targetStack.back();\n}\n\n\nuint WindowFactoryManager::AliasTargetStack::getStackedTargetCount(void) const\n{\n\treturn (uint)d_targetStack.size();\n}\n\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"\/**\n * @file Cosa\/Wireless.hh\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013, 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 * You should have received a copy of the GNU Lesser General\n * Public 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 * This file is part of the Arduino Che Cosa project.\n *\/\n\n#ifndef __COSA_WIRELESS_HH__\n#define __COSA_WIRELESS_HH__\n\n#include \"Cosa\/Power.hh\"\n\n\/**\n * Cosa Common Wireless devise driver interface.\n *\/\nclass Wireless {\npublic:\n class Driver {\n public:\n \/** Network address *\/\n struct addr_t {\n uint8_t device;\t\t\/**< device address (LSB) *\/\n int16_t network;\t\t\/**< network address *\/\n addr_t(int16_t net, uint8_t dev) \n {\n\tnetwork = net;\n\tdevice = dev;\n }\n };\n \n protected:\n \/** Current channel *\/\n uint8_t m_channel;\n \/** Current network and device address *\/\n addr_t m_addr;\n \/** Message available *\/\n volatile bool m_avail;\n \/** Sleep mode on wait *\/\n uint8_t m_mode;\n\n public:\n \/**\n * Construct Wireless Driver with given network and device address.\n * @param[in] network address.\n * @param[in] device address.\n *\/\n Driver(int16_t network, uint8_t device) :\n m_channel(0),\n m_addr(network, device),\n m_avail(false),\n m_mode(SLEEP_MODE_IDLE)\n {}\n\n \/**\n * Set power sleep mode during wait.\n * @param[in] mode of sleep.\n *\/\n void set_sleep(uint8_t mode)\n {\n m_mode = mode;\n }\n\n \/**\n * Set network and device address. Do not use the broadcast\n * address(0). Should be used before calling begin().\n * @param[in] net network address.\n * @param[in] dev device address.\n *\/\n void set_address(int16_t net, uint8_t dev)\n {\n m_addr.network = net;\n m_addr.device = dev;\n }\n\n \/**\n * Set device transmission channel. Should be used before calling\n * begin(). \n * @param[in] channel.\n *\/\n void set_channel(uint8_t channel)\n {\n m_channel = channel;\n }\n\n \/**\n * Start the Wireless device driver. Return true(1) if successful\n * otherwise false(0).\n * @param[in] config configuration vector (default NULL)\n * @return bool\n *\/\n virtual bool begin(const void* config = NULL) = 0;\n\n \/**\n * Shut down the device driver. Return true(1) if successful\n * otherwise false(0).\n * @return bool\n *\/\n virtual bool end()\n {\n return (true);\n }\n \n \/**\n * Set device in power down mode. \n *\/\n virtual void powerdown() {}\n\n \/**\n * Set device in wakeup on radio mode. \n *\/\n virtual void wakeup_on_radio() {}\n\n \/**\n * Return true(1) if a message is available otherwise false(0).\n * @return bool\n *\/\n virtual bool available()\n {\n return (m_avail);\n }\n\n \/**\n * Return true(1) if there is room to send on the device otherwise\n * false(0). \n * @return bool\n *\/\n virtual bool room()\n {\n return (true);\n }\n \n \/**\n * Send message in given buffer, with given number of bytes. Returns\n * number of bytes sent. Returns error code(-1) if number of bytes\n * is greater than PAYLOAD_MAX. Return error code(-2) if fails to\n * set transmit mode. \n * @param[in] dest destination network address.\n * @param[in] buf buffer to transmit.\n * @param[in] len number of bytes in buffer.\n * @return number of bytes send or negative error code.\n *\/\n virtual int send(uint8_t dest, const void* buf, size_t len) = 0;\n\n \/**\n * Boardcast message in given buffer, with given number of bytes. \n * Returns number of bytes sent. Returns error code(-1) if number\n * of bytes is greater than PAYLOAD_MAX. Return error code(-2) if\n * fails to set transmit mode. \n * @param[in] buf buffer to transmit.\n * @param[in] len number of bytes in buffer.\n * @return number of bytes send or negative error code.\n *\/\n int broadcast(const void* buf, size_t len)\n {\n return (send(0x00, buf, len));\n }\n\n \/**\n * Receive message and store into given buffer with given maximum\n * length. The source network address is returned in the parameter src.\n * Returns error code(-2) if no message is available and\/or a\n * timeout occured. Returns error code(-1) if the buffer size if to\n * small for incoming message or if the receiver fifo has overflowed. \n * Otherwise the actual number of received bytes is returned\n * @param[out] src source network address.\n * @param[in] buf buffer to store incoming message.\n * @param[in] len maximum number of bytes to receive.\n * @param[in] ms maximum time out period.\n * @return number of bytes received or negative error code.\n *\/\n virtual int recv(uint8_t& src, void* buf, size_t len, uint32_t ms = 0L) = 0;\n };\n};\n#endif\nFixed spelling error.\/**\n * @file Cosa\/Wireless.hh\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013, 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 * You should have received a copy of the GNU Lesser General\n * Public 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 * This file is part of the Arduino Che Cosa project.\n *\/\n\n#ifndef __COSA_WIRELESS_HH__\n#define __COSA_WIRELESS_HH__\n\n#include \"Cosa\/Power.hh\"\n\n\/**\n * Cosa Common Wireless device driver interface.\n *\/\nclass Wireless {\npublic:\n class Driver {\n public:\n \/** Network address *\/\n struct addr_t {\n uint8_t device;\t\t\/**< device address (LSB) *\/\n int16_t network;\t\t\/**< network address *\/\n addr_t(int16_t net, uint8_t dev) \n {\n\tnetwork = net;\n\tdevice = dev;\n }\n };\n \n protected:\n \/** Current channel *\/\n uint8_t m_channel;\n \/** Current network and device address *\/\n addr_t m_addr;\n \/** Message available *\/\n volatile bool m_avail;\n \/** Sleep mode on wait *\/\n uint8_t m_mode;\n\n public:\n \/**\n * Construct Wireless Driver with given network and device address.\n * @param[in] network address.\n * @param[in] device address.\n *\/\n Driver(int16_t network, uint8_t device) :\n m_channel(0),\n m_addr(network, device),\n m_avail(false),\n m_mode(SLEEP_MODE_IDLE)\n {}\n\n \/**\n * Set power sleep mode during wait.\n * @param[in] mode of sleep.\n *\/\n void set_sleep(uint8_t mode)\n {\n m_mode = mode;\n }\n\n \/**\n * Set network and device address. Do not use the broadcast\n * address(0). Should be used before calling begin().\n * @param[in] net network address.\n * @param[in] dev device address.\n *\/\n void set_address(int16_t net, uint8_t dev)\n {\n m_addr.network = net;\n m_addr.device = dev;\n }\n\n \/**\n * Set device transmission channel. Should be used before calling\n * begin(). \n * @param[in] channel.\n *\/\n void set_channel(uint8_t channel)\n {\n m_channel = channel;\n }\n\n \/**\n * Start the Wireless device driver. Return true(1) if successful\n * otherwise false(0).\n * @param[in] config configuration vector (default NULL)\n * @return bool\n *\/\n virtual bool begin(const void* config = NULL) = 0;\n\n \/**\n * Shut down the device driver. Return true(1) if successful\n * otherwise false(0).\n * @return bool\n *\/\n virtual bool end()\n {\n return (true);\n }\n \n \/**\n * Set device in power down mode. \n *\/\n virtual void powerdown() {}\n\n \/**\n * Set device in wakeup on radio mode. \n *\/\n virtual void wakeup_on_radio() {}\n\n \/**\n * Return true(1) if a message is available otherwise false(0).\n * @return bool\n *\/\n virtual bool available()\n {\n return (m_avail);\n }\n\n \/**\n * Return true(1) if there is room to send on the device otherwise\n * false(0). \n * @return bool\n *\/\n virtual bool room()\n {\n return (true);\n }\n \n \/**\n * Send message in given buffer, with given number of bytes. Returns\n * number of bytes sent. Returns error code(-1) if number of bytes\n * is greater than PAYLOAD_MAX. Return error code(-2) if fails to\n * set transmit mode. \n * @param[in] dest destination network address.\n * @param[in] buf buffer to transmit.\n * @param[in] len number of bytes in buffer.\n * @return number of bytes send or negative error code.\n *\/\n virtual int send(uint8_t dest, const void* buf, size_t len) = 0;\n\n \/**\n * Boardcast message in given buffer, with given number of bytes. \n * Returns number of bytes sent. Returns error code(-1) if number\n * of bytes is greater than PAYLOAD_MAX. Return error code(-2) if\n * fails to set transmit mode. \n * @param[in] buf buffer to transmit.\n * @param[in] len number of bytes in buffer.\n * @return number of bytes send or negative error code.\n *\/\n int broadcast(const void* buf, size_t len)\n {\n return (send(0x00, buf, len));\n }\n\n \/**\n * Receive message and store into given buffer with given maximum\n * length. The source network address is returned in the parameter src.\n * Returns error code(-2) if no message is available and\/or a\n * timeout occured. Returns error code(-1) if the buffer size if to\n * small for incoming message or if the receiver fifo has overflowed. \n * Otherwise the actual number of received bytes is returned\n * @param[out] src source network address.\n * @param[in] buf buffer to store incoming message.\n * @param[in] len maximum number of bytes to receive.\n * @param[in] ms maximum time out period.\n * @return number of bytes received or negative error code.\n *\/\n virtual int recv(uint8_t& src, void* buf, size_t len, uint32_t ms = 0L) = 0;\n };\n};\n#endif\n<|endoftext|>"} {"text":"\/** \\brief Utility to determine Zeder entries that have yet to be imported into zts_harvester.\n * \\author Madeeswaran Kannan (madeeswaran.kannan@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 \"IniFile.h\"\n#include \"JournalConfig.h\"\n#include \"MiscUtil.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n#include \"Zeder.h\"\n\n\nnamespace {\n\n\nvoid LoadToolConfig(const IniFile &config_file, const Zeder::Flavour flavour,\n std::unordered_map * const filter_regexps)\n{\n const auto flavour_section(config_file.getSection(Zeder::FLAVOUR_TO_STRING_MAP.at(flavour)));\n for (const auto &column_name : flavour_section->getEntryNames())\n (*filter_regexps)[column_name] = flavour_section->getString(column_name);\n}\n\n\nvoid DownloadFullDump(const Zeder::Flavour flavour, const std::unordered_map & filter_regexps,\n Zeder::EntryCollection * const downloaded_entries)\n{\n const auto endpoint_url(Zeder::GetFullDumpEndpointPath(flavour));\n std::unique_ptr downloader_params(new Zeder::FullDumpDownloader::Params(endpoint_url,\n {}, filter_regexps));\n\n auto downloader(Zeder::FullDumpDownloader::Factory(Zeder::FullDumpDownloader::Type::FULL_DUMP, std::move(downloader_params)));\n if (not downloader->download(downloaded_entries))\n LOG_ERROR(\"Couldn't download full dump for \" + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour));\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 4)\n ::Usage(\"flavour config_file harvester_config_file\");\n\n const Zeder::Flavour flavour(Zeder::ParseFlavour(argv[1]));\n const IniFile tool_config(argv[2]);\n const IniFile harvester_config(argv[3]);\n const JournalConfig::Reader bundle_reader(harvester_config);\n std::unordered_map column_filter_regexps;\n Zeder::EntryCollection full_dump;\n\n LoadToolConfig(tool_config, flavour, &column_filter_regexps);\n DownloadFullDump(flavour, column_filter_regexps, &full_dump);\n\n std::set imported_ids;\n for (const auto §ion : harvester_config) {\n const auto section_name(section.getSectionName());\n const auto group(bundle_reader.zotero(section_name).value(JournalConfig::Zotero::GROUP, \"\"));\n if (group != Zeder::FLAVOUR_TO_STRING_MAP.at(flavour))\n continue;\n\n imported_ids.insert(StringUtil::ToUnsigned(bundle_reader.zeder(section_name).value(JournalConfig::Zeder::ID)));\n }\n\n std::set full_dump_ids, not_imported_ids;\n std::transform(full_dump.begin(), full_dump.end(), std::inserter(full_dump_ids, full_dump_ids.begin()),\n [](const Zeder::Entry &entry) -> unsigned int { return entry.getId(); });\n std::set_difference(full_dump_ids.begin(), full_dump_ids.end(), imported_ids.begin(),\n imported_ids.end(), std::inserter(not_imported_ids, not_imported_ids.begin()));\n\n LOG_INFO(\"Zeder '\" + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour) + \"' instance: \" + std::to_string(full_dump.size()) + \" entries\");\n LOG_INFO(\"Number of imported entries: \" + std::to_string(imported_ids.size()));\n LOG_INFO(\"Number of yet-to-be-imported entries: \" + std::to_string(not_imported_ids.size()));\n\n std::set buffer;\n\n std::transform(imported_ids.begin(), imported_ids.end(), std::inserter(buffer, buffer.begin()),\n [](unsigned int id) -> std::string { return std::to_string(id); });\n LOG_INFO(\"\\nImported entries: \" + StringUtil::Join(buffer.begin(), buffer.end(), \",\"));\n\n buffer.clear();\n std::transform(not_imported_ids.begin(), not_imported_ids.end(), std::inserter(buffer, buffer.begin()),\n [](unsigned int id) -> std::string { return std::to_string(id); });\n LOG_INFO(\"\\nYet-to-be-imported entries: \" + StringUtil::Join(buffer.begin(), buffer.end(), \",\"));\n\n return EXIT_SUCCESS;\n}\nzeder_count_imported: fix syntax for CentOS compatibility\/** \\brief Utility to determine Zeder entries that have yet to be imported into zts_harvester.\n * \\author Madeeswaran Kannan (madeeswaran.kannan@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 \"IniFile.h\"\n#include \"JournalConfig.h\"\n#include \"MiscUtil.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n#include \"Zeder.h\"\n\n\nnamespace {\n\n\nvoid LoadToolConfig(const IniFile &config_file, const Zeder::Flavour flavour,\n std::unordered_map * const filter_regexps)\n{\n const auto flavour_section(config_file.getSection(Zeder::FLAVOUR_TO_STRING_MAP.at(flavour)));\n for (const auto &column_name : flavour_section->getEntryNames())\n (*filter_regexps)[column_name] = flavour_section->getString(column_name);\n}\n\n\nvoid DownloadFullDump(const Zeder::Flavour flavour, const std::unordered_map & filter_regexps,\n Zeder::EntryCollection * const downloaded_entries)\n{\n const auto endpoint_url(Zeder::GetFullDumpEndpointPath(flavour));\n const std::unordered_set columns_to_download; \/\/ intentionally empty\n std::unique_ptr downloader_params(new Zeder::FullDumpDownloader::Params(endpoint_url,\n columns_to_download, filter_regexps));\n\n auto downloader(Zeder::FullDumpDownloader::Factory(Zeder::FullDumpDownloader::Type::FULL_DUMP, std::move(downloader_params)));\n if (not downloader->download(downloaded_entries))\n LOG_ERROR(\"Couldn't download full dump for \" + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour));\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 4)\n ::Usage(\"flavour config_file harvester_config_file\");\n\n const Zeder::Flavour flavour(Zeder::ParseFlavour(argv[1]));\n const IniFile tool_config(argv[2]);\n const IniFile harvester_config(argv[3]);\n const JournalConfig::Reader bundle_reader(harvester_config);\n std::unordered_map column_filter_regexps;\n Zeder::EntryCollection full_dump;\n\n LoadToolConfig(tool_config, flavour, &column_filter_regexps);\n DownloadFullDump(flavour, column_filter_regexps, &full_dump);\n\n std::set imported_ids;\n for (const auto §ion : harvester_config) {\n const auto section_name(section.getSectionName());\n const auto group(bundle_reader.zotero(section_name).value(JournalConfig::Zotero::GROUP, \"\"));\n if (group != Zeder::FLAVOUR_TO_STRING_MAP.at(flavour))\n continue;\n\n imported_ids.insert(StringUtil::ToUnsigned(bundle_reader.zeder(section_name).value(JournalConfig::Zeder::ID)));\n }\n\n std::set full_dump_ids, not_imported_ids;\n std::transform(full_dump.begin(), full_dump.end(), std::inserter(full_dump_ids, full_dump_ids.begin()),\n [](const Zeder::Entry &entry) -> unsigned int { return entry.getId(); });\n std::set_difference(full_dump_ids.begin(), full_dump_ids.end(), imported_ids.begin(),\n imported_ids.end(), std::inserter(not_imported_ids, not_imported_ids.begin()));\n\n LOG_INFO(\"Zeder '\" + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour) + \"' instance: \" + std::to_string(full_dump.size()) + \" entries\");\n LOG_INFO(\"Number of imported entries: \" + std::to_string(imported_ids.size()));\n LOG_INFO(\"Number of yet-to-be-imported entries: \" + std::to_string(not_imported_ids.size()));\n\n std::set buffer;\n\n std::transform(imported_ids.begin(), imported_ids.end(), std::inserter(buffer, buffer.begin()),\n [](unsigned int id) -> std::string { return std::to_string(id); });\n LOG_INFO(\"\\nImported entries: \" + StringUtil::Join(buffer.begin(), buffer.end(), \",\"));\n\n buffer.clear();\n std::transform(not_imported_ids.begin(), not_imported_ids.end(), std::inserter(buffer, buffer.begin()),\n [](unsigned int id) -> std::string { return std::to_string(id); });\n LOG_INFO(\"\\nYet-to-be-imported entries: \" + StringUtil::Join(buffer.begin(), buffer.end(), \",\"));\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"Map and link in also the filterconfig1 UNO component<|endoftext|>"} {"text":"#ifndef __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__\n#define __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__\n\n#include \n\n#include \"ClaimStrategy.hpp\"\n#include \"AbstractMultithreadedClaimStrategy.hpp\"\n\nnamespace disruptor {\n\nclass MultiThreadedClaimStrategy\n : public AbstractMultithreadedClaimStrategy\n{\n static const int RETRIES = 1000;\n\n std::atomic_long* pendingPublication_;\n std::size_t pendingBufferSize_;\n int pendingMask_;\n\npublic:\n \/**\n * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size.\n *\n * @param bufferSize for the underlying data structure.\n * @param pendingBufferSize number of item that can be pending for serialisation\n *\/\n MultiThreadedClaimStrategy(const int bufferSize, const int pendingBufferSize)\n : AbstractMultithreadedClaimStrategy(bufferSize)\n , pendingPublication_(nullptr)\n , pendingBufferSize_(pendingBufferSize)\n , pendingMask_(pendingBufferSize - 1)\n {\n if (util::bitCount(pendingBufferSize) != 1) {\n throw std::out_of_range(\"pendingBufferSize must be a power of 2, was: \" + pendingBufferSize_);\n }\n\n pendingPublication_ = new std::atomic_long[pendingBufferSize_];\n }\n\n \/**\n * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size.\n *\n * @param bufferSize for the underlying data structure.\n *\/\n MultiThreadedClaimStrategy(const int bufferSize)\n : AbstractMultithreadedClaimStrategy(bufferSize)\n , pendingPublication_(nullptr)\n , pendingBufferSize_(1024)\n , pendingMask_(pendingBufferSize_ - 1)\n {\n pendingPublication_ = new std::atomic_long[pendingBufferSize_];\n }\n\n ~MultiThreadedClaimStrategy() {\n if (nullptr != pendingPublication_) {\n delete [] pendingPublication_;\n }\n }\n\n MultiThreadedClaimStrategy(const MultiThreadedClaimStrategy&) = delete;\n MultiThreadedClaimStrategy& operator=(const MultiThreadedClaimStrategy&) = delete;\n\n void serialisePublishing(const long sequence, Sequence& cursor, const int batchSize) {\n int counter = RETRIES;\n while ((sequence - cursor.get()) > (int)pendingBufferSize_) {\n if (--counter == 0) {\n std::this_thread::yield();\n counter = RETRIES;\n }\n }\n\n long expectedSequence = sequence - batchSize;\n for (long pendingSequence = expectedSequence + 1; pendingSequence < sequence; pendingSequence++) {\n \/* XXX: I *believe* store(..., std::memory_order_relaxed) to be\n the correct alternative to lazySet. Whether that is the\n reality, we shall see. *\/\n pendingPublication_[(int) pendingSequence & pendingMask_].store(pendingSequence, std::memory_order_relaxed);\n }\n pendingPublication_[(int) sequence & pendingMask_].store(sequence);\n\n long cursorSequence = cursor.get();\n if (cursorSequence >= sequence) {\n return;\n }\n\n expectedSequence = std::max(expectedSequence, cursorSequence);\n long nextSequence = expectedSequence + 1;\n while (cursor.compareAndSet(expectedSequence, nextSequence)) {\n expectedSequence = nextSequence;\n nextSequence++;\n if (pendingPublication_[(int) nextSequence & pendingMask_] != nextSequence) {\n break;\n }\n }\n }\n\n};\n\n}\n\n#endif \/* __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ *\/\nCleanup - removed unnecessary header and formatting.#ifndef __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__\n#define __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__\n\n#include \n\n#include \"AbstractMultithreadedClaimStrategy.hpp\"\n\nnamespace disruptor {\n\nclass MultiThreadedClaimStrategy\n : public AbstractMultithreadedClaimStrategy\n{\n static const int RETRIES = 1000;\n\n std::atomic_long* pendingPublication_;\n std::size_t pendingBufferSize_;\n int pendingMask_;\n\npublic:\n \/**\n * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size.\n *\n * @param bufferSize for the underlying data structure.\n * @param pendingBufferSize number of item that can be pending for serialisation\n *\/\n MultiThreadedClaimStrategy(const int bufferSize, const int pendingBufferSize)\n : AbstractMultithreadedClaimStrategy(bufferSize)\n , pendingPublication_(nullptr)\n , pendingBufferSize_(pendingBufferSize)\n , pendingMask_(pendingBufferSize - 1)\n {\n if (util::bitCount(pendingBufferSize) != 1) {\n throw std::out_of_range(\"pendingBufferSize must be a power of 2, was: \" + pendingBufferSize_);\n }\n\n pendingPublication_ = new std::atomic_long[pendingBufferSize_];\n }\n\n \/**\n * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size.\n *\n * @param bufferSize for the underlying data structure.\n *\/\n MultiThreadedClaimStrategy(const int bufferSize)\n : AbstractMultithreadedClaimStrategy(bufferSize)\n , pendingPublication_(nullptr)\n , pendingBufferSize_(1024)\n , pendingMask_(pendingBufferSize_ - 1)\n {\n pendingPublication_ = new std::atomic_long[pendingBufferSize_];\n }\n\n ~MultiThreadedClaimStrategy() {\n if (nullptr != pendingPublication_) {\n delete [] pendingPublication_;\n }\n }\n\n MultiThreadedClaimStrategy(const MultiThreadedClaimStrategy&) = delete;\n MultiThreadedClaimStrategy& operator=(const MultiThreadedClaimStrategy&) = delete;\n\n void serialisePublishing(const long sequence, Sequence& cursor, const int batchSize) {\n int counter = RETRIES;\n while ((sequence - cursor.get()) > (int)pendingBufferSize_) {\n if (--counter == 0) {\n std::this_thread::yield();\n counter = RETRIES;\n }\n }\n\n long expectedSequence = sequence - batchSize;\n for (long pendingSequence = expectedSequence + 1; pendingSequence < sequence; pendingSequence++) {\n \/* XXX: I *believe* store(..., std::memory_order_relaxed) to be\n the correct alternative to lazySet. Whether that is the\n reality, we shall see. *\/\n pendingPublication_[(int) pendingSequence & pendingMask_].store(pendingSequence, std::memory_order_relaxed);\n }\n pendingPublication_[(int) sequence & pendingMask_].store(sequence);\n\n long cursorSequence = cursor.get();\n if (cursorSequence >= sequence) {\n return;\n }\n\n expectedSequence = std::max(expectedSequence, cursorSequence);\n long nextSequence = expectedSequence + 1;\n while (cursor.compareAndSet(expectedSequence, nextSequence)) {\n expectedSequence = nextSequence;\n nextSequence++;\n if (pendingPublication_[(int) nextSequence & pendingMask_] != nextSequence) {\n break;\n }\n }\n }\n\n};\n\n}\n\n#endif \/* __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ *\/\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\/browser_main.h\"\n#include \"chrome\/browser\/browser_main_win.h\"\n\n#include \n#include \n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"app\/win_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/first_run\/first_run.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/views\/uninstall_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/helper.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/shell_util.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/winsock_init.h\"\n#include \"net\/socket\/ssl_client_socket_nss_factory.h\"\n#include \"views\/focus\/accelerator_handler.h\"\n#include \"views\/window\/window.h\"\n\nvoid DidEndMainMessageLoop() {\n OleUninitialize();\n}\n\nvoid RecordBreakpadStatusUMA(MetricsService* metrics) {\n DWORD len = ::GetEnvironmentVariableW(\n ASCIIToWide(env_vars::kNoOOBreakpad).c_str() , NULL, 0);\n metrics->RecordBreakpadRegistration((len == 0));\n metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());\n}\n\nvoid WarnAboutMinimumSystemRequirements() {\n if (base::win::GetVersion() < base::win::VERSION_XP) {\n \/\/ Display a warning message if the user is running chrome on Windows 2000.\n const std::wstring text =\n l10n_util::GetString(IDS_UNSUPPORTED_OS_PRE_WIN_XP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n win_util::MessageBox(NULL, text, caption,\n MB_OK | MB_ICONWARNING | MB_TOPMOST);\n }\n}\n\nint AskForUninstallConfirmation() {\n int ret = ResultCodes::NORMAL_EXIT;\n views::Window::CreateChromeWindow(NULL, gfx::Rect(),\n new UninstallView(ret))->Show();\n views::AcceleratorHandler accelerator_handler;\n MessageLoopForUI::current()->Run(&accelerator_handler);\n return ret;\n}\n\nvoid ShowCloseBrowserFirstMessageBox() {\n const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n}\n\nint DoUninstallTasks(bool chrome_still_running) {\n \/\/ We want to show a warning to user (and exit) if Chrome is already running\n \/\/ *before* we show the uninstall confirmation dialog box. But while the\n \/\/ uninstall confirmation dialog is up, user might start Chrome, so we\n \/\/ check once again after user acknowledges Uninstall dialog.\n if (chrome_still_running) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n int ret = AskForUninstallConfirmation();\n if (Upgrade::IsBrowserAlreadyRunning()) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n\n if (ret != ResultCodes::UNINSTALL_USER_CANCEL) {\n \/\/ The following actions are just best effort.\n VLOG(1) << \"Executing uninstall actions\";\n if (!FirstRun::RemoveSentinel())\n VLOG(1) << \"Failed to delete sentinel file.\";\n \/\/ We want to remove user level shortcuts and we only care about the ones\n \/\/ created by us and not by the installer so |alternate| is false.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n if (!ShellUtil::RemoveChromeDesktopShortcut(dist, ShellUtil::CURRENT_USER,\n false))\n VLOG(1) << \"Failed to delete desktop shortcut.\";\n if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist,\n ShellUtil::CURRENT_USER))\n VLOG(1) << \"Failed to delete quick launch shortcut.\";\n }\n return ret;\n}\n\n\/\/ Prepares the localized strings that are going to be displayed to\n\/\/ the user if the browser process dies. These strings are stored in the\n\/\/ environment block so they are accessible in the early stages of the\n\/\/ chrome executable's lifetime.\nvoid PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {\n \/\/ Clear this var so child processes don't show the dialog by default.\n scoped_ptr env(base::Environment::Create());\n env->UnSetVar(env_vars::kShowRestart);\n\n \/\/ For non-interactive tests we don't restart on crash.\n if (env->HasVar(env_vars::kHeadless))\n return;\n\n \/\/ If the known command-line test options are used we don't create the\n \/\/ environment block which means we don't get the restart dialog.\n if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||\n parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||\n parsed_command_line.HasSwitch(switches::kNoErrorDialogs))\n return;\n\n \/\/ The encoding we use for the info is \"title|context|direction\" where\n \/\/ direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending\n \/\/ on the current locale.\n string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));\n dlg_strings.push_back('|');\n string16 adjusted_string(\n l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));\n base::i18n::AdjustStringForLocaleDirection(&adjusted_string);\n dlg_strings.append(adjusted_string);\n dlg_strings.push_back('|');\n dlg_strings.append(ASCIIToUTF16(\n base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));\n\n env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings));\n}\n\n\/\/ This method handles the --hide-icons and --show-icons command line options\n\/\/ for chrome that get triggered by Windows from registry entries\n\/\/ HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons\n\/\/ functionality so we just ask the users if they want to uninstall Chrome.\nint HandleIconsCommands(const CommandLine &parsed_command_line) {\n if (parsed_command_line.HasSwitch(switches::kHideIcons)) {\n std::wstring cp_applet;\n base::win::Version version = base::win::GetVersion();\n if (version >= base::win::VERSION_VISTA) {\n cp_applet.assign(L\"Programs and Features\"); \/\/ Windows Vista and later.\n } else if (version >= base::win::VERSION_XP) {\n cp_applet.assign(L\"Add\/Remove Programs\"); \/\/ Windows XP.\n } else {\n return ResultCodes::UNSUPPORTED_PARAM; \/\/ Not supported\n }\n\n const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED,\n cp_applet);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;\n if (IDOK == win_util::MessageBox(NULL, msg, caption, flags))\n ShellExecute(NULL, NULL, L\"appwiz.cpl\", NULL, NULL, SW_SHOWNORMAL);\n return ResultCodes::NORMAL_EXIT; \/\/ Exit as we are not launching browser.\n }\n \/\/ We don't hide icons so we shouldn't do anything special to show them\n return ResultCodes::UNSUPPORTED_PARAM;\n}\n\n\/\/ Check if there is any machine level Chrome installed on the current\n\/\/ machine. If yes and the current Chrome process is user level, we do not\n\/\/ allow the user level Chrome to run. So we notify the user and uninstall\n\/\/ user level Chrome.\nbool CheckMachineLevelInstall() {\n \/\/ TODO(tommi): Check if using the default distribution is always the right\n \/\/ thing to do.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n scoped_ptr version(InstallUtil::GetChromeVersion(dist,\n true));\n if (version.get()) {\n FilePath exe_path;\n PathService::Get(base::DIR_EXE, &exe_path);\n std::wstring exe = exe_path.value();\n FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));\n if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {\n const std::wstring text =\n l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n FilePath uninstall_path(InstallUtil::GetChromeUninstallCmd(false, dist));\n CommandLine uninstall_cmd(uninstall_path);\n if (!uninstall_cmd.GetProgram().value().empty()) {\n uninstall_cmd.AppendSwitch(installer_util::switches::kForceUninstall);\n uninstall_cmd.AppendSwitch(\n installer_util::switches::kDoNotRemoveSharedItems);\n base::LaunchApp(uninstall_cmd, false, false, NULL);\n }\n return true;\n }\n }\n return false;\n}\n\n\/\/ BrowserMainPartsWin ---------------------------------------------------------\n\nclass BrowserMainPartsWin : public BrowserMainParts {\n public:\n explicit BrowserMainPartsWin(const MainFunctionParams& parameters)\n : BrowserMainParts(parameters) {}\n\n protected:\n virtual void PreEarlyInitialization() {\n \/\/ Initialize Winsock.\n net::EnsureWinsockInit();\n }\n\n virtual void PreMainMessageLoopStart() {\n OleInitialize(NULL);\n\n \/\/ If we're running tests (ui_task is non-null), then the ResourceBundle\n \/\/ has already been initialized.\n if (!parameters().ui_task) {\n \/\/ Override the configured locale with the user's preferred UI language.\n l10n_util::OverrideLocaleWithUILanguageList();\n }\n }\n\n private:\n virtual void InitializeSSL() {\n \/\/ Use NSS for SSL by default.\n \/\/ Because of a build system issue (http:\/\/crbug.com\/43461), the default\n \/\/ client socket factory uses SChannel (the system SSL library) for SSL by\n \/\/ default on Windows.\n if (!parsed_command_line().HasSwitch(switches::kUseSystemSSL)) {\n net::ClientSocketFactory::SetSSLClientSocketFactory(\n net::SSLClientSocketNSSFactory);\n \/\/ We want to be sure to init NSPR on the main thread.\n base::EnsureNSPRInit();\n }\n }\n};\n\n\/\/ static\nBrowserMainParts* BrowserMainParts::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n return new BrowserMainPartsWin(parameters);\n}\nUse SChannel for 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\/browser_main.h\"\n#include \"chrome\/browser\/browser_main_win.h\"\n\n#include \n#include \n\n#include \n\n#include \"app\/l10n_util.h\"\n#include \"app\/l10n_util_win.h\"\n#include \"app\/win_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/environment.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/nss_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/first_run\/first_run.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/views\/uninstall_view.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/helper.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/shell_util.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/winsock_init.h\"\n#include \"net\/socket\/ssl_client_socket_nss_factory.h\"\n#include \"views\/focus\/accelerator_handler.h\"\n#include \"views\/window\/window.h\"\n\nvoid DidEndMainMessageLoop() {\n OleUninitialize();\n}\n\nvoid RecordBreakpadStatusUMA(MetricsService* metrics) {\n DWORD len = ::GetEnvironmentVariableW(\n ASCIIToWide(env_vars::kNoOOBreakpad).c_str() , NULL, 0);\n metrics->RecordBreakpadRegistration((len == 0));\n metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());\n}\n\nvoid WarnAboutMinimumSystemRequirements() {\n if (base::win::GetVersion() < base::win::VERSION_XP) {\n \/\/ Display a warning message if the user is running chrome on Windows 2000.\n const std::wstring text =\n l10n_util::GetString(IDS_UNSUPPORTED_OS_PRE_WIN_XP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n win_util::MessageBox(NULL, text, caption,\n MB_OK | MB_ICONWARNING | MB_TOPMOST);\n }\n}\n\nint AskForUninstallConfirmation() {\n int ret = ResultCodes::NORMAL_EXIT;\n views::Window::CreateChromeWindow(NULL, gfx::Rect(),\n new UninstallView(ret))->Show();\n views::AcceleratorHandler accelerator_handler;\n MessageLoopForUI::current()->Run(&accelerator_handler);\n return ret;\n}\n\nvoid ShowCloseBrowserFirstMessageBox() {\n const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n}\n\nint DoUninstallTasks(bool chrome_still_running) {\n \/\/ We want to show a warning to user (and exit) if Chrome is already running\n \/\/ *before* we show the uninstall confirmation dialog box. But while the\n \/\/ uninstall confirmation dialog is up, user might start Chrome, so we\n \/\/ check once again after user acknowledges Uninstall dialog.\n if (chrome_still_running) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n int ret = AskForUninstallConfirmation();\n if (Upgrade::IsBrowserAlreadyRunning()) {\n ShowCloseBrowserFirstMessageBox();\n return ResultCodes::UNINSTALL_CHROME_ALIVE;\n }\n\n if (ret != ResultCodes::UNINSTALL_USER_CANCEL) {\n \/\/ The following actions are just best effort.\n VLOG(1) << \"Executing uninstall actions\";\n if (!FirstRun::RemoveSentinel())\n VLOG(1) << \"Failed to delete sentinel file.\";\n \/\/ We want to remove user level shortcuts and we only care about the ones\n \/\/ created by us and not by the installer so |alternate| is false.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n if (!ShellUtil::RemoveChromeDesktopShortcut(dist, ShellUtil::CURRENT_USER,\n false))\n VLOG(1) << \"Failed to delete desktop shortcut.\";\n if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist,\n ShellUtil::CURRENT_USER))\n VLOG(1) << \"Failed to delete quick launch shortcut.\";\n }\n return ret;\n}\n\n\/\/ Prepares the localized strings that are going to be displayed to\n\/\/ the user if the browser process dies. These strings are stored in the\n\/\/ environment block so they are accessible in the early stages of the\n\/\/ chrome executable's lifetime.\nvoid PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {\n \/\/ Clear this var so child processes don't show the dialog by default.\n scoped_ptr env(base::Environment::Create());\n env->UnSetVar(env_vars::kShowRestart);\n\n \/\/ For non-interactive tests we don't restart on crash.\n if (env->HasVar(env_vars::kHeadless))\n return;\n\n \/\/ If the known command-line test options are used we don't create the\n \/\/ environment block which means we don't get the restart dialog.\n if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||\n parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||\n parsed_command_line.HasSwitch(switches::kNoErrorDialogs))\n return;\n\n \/\/ The encoding we use for the info is \"title|context|direction\" where\n \/\/ direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending\n \/\/ on the current locale.\n string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));\n dlg_strings.push_back('|');\n string16 adjusted_string(\n l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));\n base::i18n::AdjustStringForLocaleDirection(&adjusted_string);\n dlg_strings.append(adjusted_string);\n dlg_strings.push_back('|');\n dlg_strings.append(ASCIIToUTF16(\n base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));\n\n env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings));\n}\n\n\/\/ This method handles the --hide-icons and --show-icons command line options\n\/\/ for chrome that get triggered by Windows from registry entries\n\/\/ HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons\n\/\/ functionality so we just ask the users if they want to uninstall Chrome.\nint HandleIconsCommands(const CommandLine &parsed_command_line) {\n if (parsed_command_line.HasSwitch(switches::kHideIcons)) {\n std::wstring cp_applet;\n base::win::Version version = base::win::GetVersion();\n if (version >= base::win::VERSION_VISTA) {\n cp_applet.assign(L\"Programs and Features\"); \/\/ Windows Vista and later.\n } else if (version >= base::win::VERSION_XP) {\n cp_applet.assign(L\"Add\/Remove Programs\"); \/\/ Windows XP.\n } else {\n return ResultCodes::UNSUPPORTED_PARAM; \/\/ Not supported\n }\n\n const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED,\n cp_applet);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;\n if (IDOK == win_util::MessageBox(NULL, msg, caption, flags))\n ShellExecute(NULL, NULL, L\"appwiz.cpl\", NULL, NULL, SW_SHOWNORMAL);\n return ResultCodes::NORMAL_EXIT; \/\/ Exit as we are not launching browser.\n }\n \/\/ We don't hide icons so we shouldn't do anything special to show them\n return ResultCodes::UNSUPPORTED_PARAM;\n}\n\n\/\/ Check if there is any machine level Chrome installed on the current\n\/\/ machine. If yes and the current Chrome process is user level, we do not\n\/\/ allow the user level Chrome to run. So we notify the user and uninstall\n\/\/ user level Chrome.\nbool CheckMachineLevelInstall() {\n \/\/ TODO(tommi): Check if using the default distribution is always the right\n \/\/ thing to do.\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n scoped_ptr version(InstallUtil::GetChromeVersion(dist,\n true));\n if (version.get()) {\n FilePath exe_path;\n PathService::Get(base::DIR_EXE, &exe_path);\n std::wstring exe = exe_path.value();\n FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));\n if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {\n const std::wstring text =\n l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);\n const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);\n const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;\n win_util::MessageBox(NULL, text, caption, flags);\n FilePath uninstall_path(InstallUtil::GetChromeUninstallCmd(false, dist));\n CommandLine uninstall_cmd(uninstall_path);\n if (!uninstall_cmd.GetProgram().value().empty()) {\n uninstall_cmd.AppendSwitch(installer_util::switches::kForceUninstall);\n uninstall_cmd.AppendSwitch(\n installer_util::switches::kDoNotRemoveSharedItems);\n base::LaunchApp(uninstall_cmd, false, false, NULL);\n }\n return true;\n }\n }\n return false;\n}\n\n\/\/ BrowserMainPartsWin ---------------------------------------------------------\n\nclass BrowserMainPartsWin : public BrowserMainParts {\n public:\n explicit BrowserMainPartsWin(const MainFunctionParams& parameters)\n : BrowserMainParts(parameters) {}\n\n protected:\n virtual void PreEarlyInitialization() {\n \/\/ Initialize Winsock.\n net::EnsureWinsockInit();\n }\n\n virtual void PreMainMessageLoopStart() {\n OleInitialize(NULL);\n\n \/\/ If we're running tests (ui_task is non-null), then the ResourceBundle\n \/\/ has already been initialized.\n if (!parameters().ui_task) {\n \/\/ Override the configured locale with the user's preferred UI language.\n l10n_util::OverrideLocaleWithUILanguageList();\n }\n }\n\n private:\n virtual void InitializeSSL() {\n \/\/ Use NSS for SSL by default.\n \/\/ Because of a build system issue (http:\/\/crbug.com\/43461), the default\n \/\/ client socket factory uses SChannel (the system SSL library) for SSL by\n \/\/ default on Windows.\n\n \/\/ Disabling this temporarily to test out if NSS is causing heap corruption.\n#if 0\n if (!parsed_command_line().HasSwitch(switches::kUseSystemSSL)) {\n net::ClientSocketFactory::SetSSLClientSocketFactory(\n net::SSLClientSocketNSSFactory);\n \/\/ We want to be sure to init NSPR on the main thread.\n base::EnsureNSPRInit();\n }\n#endif\n }\n};\n\n\/\/ static\nBrowserMainParts* BrowserMainParts::CreateBrowserMainParts(\n const MainFunctionParams& parameters) {\n return new BrowserMainPartsWin(parameters);\n}\n<|endoftext|>"} {"text":"The table was deleted after the model and the table accesses the model in its destructor, causing a failure in the browser tests.<|endoftext|>"} {"text":"\/*\n * examples\/nullspacebasis.C\n *\n * Copyright (C) 2014 J-G. Dumas\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\/**\\file examples\/nullspacebasis.C\n * @example examples\/nullspacebasis_rank.C\n \\brief NullSpace of sparse matrix over GFq.\n \\brief nullspace is allocated m \\times n.\n \\ingroup examples\n *\/\n\n#include \n#include \"linbox\/field\/Givaro\/givaro-gfq.h\"\n#include \"linbox\/algorithms\/gauss.h\"\n\nusing namespace LinBox;\n\nint main (int argc, char **argv)\n{\n\n\tif ( argc < 2 || argc > 4) {\n\t\tstd::cerr << \"Usage to get a random null space basis over GF(p,k): p [k]\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::ifstream input (argv[1]);\n\tif (!input) { std::cerr << \"Error opening matrix file \" << argv[1] << std::endl; return -1; }\n\n\t\/\/typedef Modular Field;\n\ttypedef GivaroGfq Field;\n\tField F(atoi(argv[2]),argc>3?atoi(argv[3]):1);\n\tSparseMatrix B (F);\n\tB.read (input);\n\tstd::cout << \"B is \" << B.rowdim() << \" by \" << B.coldim() << std::endl;\n\n BlasMatrix NullSpace(F,B.coldim(),B.coldim());\n GaussDomain GD(F);\n \n GD.nullspacebasisin(NullSpace, B);\n \n NullSpace.write( std::cerr << \"X:=\", Tag::FileFormat::Maple ) << ';' << std::endl;\n\n std::cerr << \"NullsSpace dimensions:\" << NullSpace.rowdim() << 'x' << NullSpace.coldim() << std::endl;\n \n return 0;\n \n\n}\nlicence\/*\n * examples\/nullspacebasis.C\n *\n * Copyright (C) 2014 J-G. Dumas\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\/**\\file examples\/nullspacebasis.C\n * @example examples\/nullspacebasis.C\n \\brief NullSpace of sparse matrix over GFq.\n \\brief nullspace is allocated m \\times n.\n \\ingroup examples\n *\/\n\n#include \n#include \"linbox\/field\/Givaro\/givaro-gfq.h\"\n#include \"linbox\/algorithms\/gauss.h\"\n\nusing namespace LinBox;\n\nint main (int argc, char **argv)\n{\n\n\tif ( argc < 2 || argc > 4) {\n\t\tstd::cerr << \"Usage to get a random null space basis over GF(p,k): p [k]\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::ifstream input (argv[1]);\n\tif (!input) { std::cerr << \"Error opening matrix file \" << argv[1] << std::endl; return -1; }\n\n\t\/\/typedef Modular Field;\n\ttypedef GivaroGfq Field;\n\tField F(atoi(argv[2]),argc>3?atoi(argv[3]):1);\n\tSparseMatrix B (F);\n\tB.read (input);\n\tstd::cout << \"B is \" << B.rowdim() << \" by \" << B.coldim() << std::endl;\n\n BlasMatrix NullSpace(F,B.coldim(),B.coldim());\n GaussDomain GD(F);\n \n GD.nullspacebasisin(NullSpace, B);\n \n NullSpace.write( std::cerr << \"X:=\", Tag::FileFormat::Maple ) << ';' << std::endl;\n\n std::cerr << \"NullsSpace dimensions:\" << NullSpace.rowdim() << 'x' << NullSpace.coldim() << std::endl;\n \n return 0;\n \n\n}\n<|endoftext|>"} {"text":"\/\/===-- Symbols.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 \"lldb\/Host\/Symbols.h\"\n#include \"lldb\/Core\/ArchSpec.h\"\n#include \"lldb\/Core\/DataBuffer.h\"\n#include \"lldb\/Core\/DataExtractor.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/ModuleSpec.h\"\n#include \"lldb\/Core\/StreamString.h\"\n#include \"lldb\/Core\/Timer.h\"\n#include \"lldb\/Core\/UUID.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n#include \"lldb\/Target\/Target.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n#if defined (__linux__) || defined (__FreeBSD__)\n\nFileSpec\nSymbols::LocateExecutableObjectFile (const ModuleSpec &module_spec)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nFileSpec\nSymbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec)\n{\n const char *symbol_filename = module_spec.GetSymbolFileSpec().GetFilename().AsCString();\n if (!symbol_filename || !symbol_filename[0])\n return FileSpec();\n\n FileSpecList debug_file_search_paths (Target::GetDefaultDebugFileSearchPaths());\n\n \/\/ Add module directory.\n const ConstString &file_dir = module_spec.GetFileSpec().GetDirectory();\n debug_file_search_paths.AppendIfUnique (FileSpec(file_dir.AsCString(\".\"), true));\n\n \/\/ Add current working directory.\n debug_file_search_paths.AppendIfUnique (FileSpec(\".\", true));\n\n \/\/ Add \/usr\/lib\/debug directory.\n debug_file_search_paths.AppendIfUnique (FileSpec(\"\/usr\/lib\/debug\", true));\n\n std::string uuid_str;\n const UUID &module_uuid = module_spec.GetUUID();\n if (module_uuid.IsValid())\n {\n \/\/ Some debug files are stored in the .build-id directory like this:\n \/\/ \/usr\/lib\/debug\/.build-id\/ff\/e7fe727889ad82bb153de2ad065b2189693315.debug\n uuid_str = module_uuid.GetAsString(\"\");\n uuid_str.insert (2, 1, '\/');\n uuid_str = uuid_str + \".debug\";\n }\n\n \/\/ Get full path to our module. Needed to check debug files like this:\n \/\/ \/usr\/lib\/debug\/usr\/lib\/libboost_date_time.so.1.46.1\n std::string module_filename = module_spec.GetFileSpec().GetPath();\n\n size_t num_directories = debug_file_search_paths.GetSize();\n for (size_t idx = 0; idx < num_directories; ++idx)\n {\n FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex (idx);\n dirspec.ResolvePath();\n if (!dirspec.Exists() || !dirspec.IsDirectory())\n continue;\n\n std::vector files;\n std::string dirname = dirspec.GetPath();\n\n files.push_back (dirname + \"\/\" + symbol_filename);\n files.push_back (dirname + \"\/.debug\/\" + symbol_filename);\n files.push_back (dirname + \"\/.build-id\/\" + uuid_str);\n files.push_back (dirname + module_filename);\n\n const uint32_t num_files = files.size();\n for (size_t idx_file = 0; idx_file < num_files; ++idx_file)\n {\n const std::string &filename = files[idx_file];\n FileSpec file_spec (filename.c_str(), true);\n\n if (file_spec == module_spec.GetFileSpec())\n continue;\n\n if (file_spec.Exists())\n {\n lldb_private::ModuleSpecList specs;\n const size_t num_specs = ObjectFile::GetModuleSpecifications (file_spec, 0, specs);\n assert (num_specs <= 1 && \"Symbol Vendor supports only a single architecture\");\n if (num_specs == 1)\n {\n ModuleSpec mspec;\n if (specs.GetModuleSpecAtIndex (0, mspec))\n {\n if (mspec.GetUUID() == module_uuid)\n return file_spec;\n }\n }\n }\n }\n }\n\n return FileSpec();\n}\n\nFileSpec\nSymbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle,\n const lldb_private::UUID *uuid,\n const ArchSpec *arch)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nbool\nSymbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup)\n{\n \/\/ Fill in the module_spec.GetFileSpec() for the object file and\/or the\n \/\/ module_spec.GetSymbolFileSpec() for the debug symbols file.\n return false;\n}\n\n#elif !defined (__APPLE__)\n\nFileSpec\nSymbols::LocateExecutableObjectFile (const ModuleSpec &module_spec)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nFileSpec\nSymbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nFileSpec\nSymbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle,\n const lldb_private::UUID *uuid,\n const ArchSpec *arch)\n{\n return FileSpec();\n}\n\nbool\nSymbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup)\n{\n \/\/ Fill in the module_spec.GetFileSpec() for the object file and\/or the\n \/\/ module_spec.GetSymbolFileSpec() for the debug symbols file.\n return false;\n}\n\n#endif\nMissed a checking that should have been checked in with 186211.\/\/===-- Symbols.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 \"lldb\/Host\/Symbols.h\"\n#include \"lldb\/Core\/ArchSpec.h\"\n#include \"lldb\/Core\/DataBuffer.h\"\n#include \"lldb\/Core\/DataExtractor.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/ModuleSpec.h\"\n#include \"lldb\/Core\/StreamString.h\"\n#include \"lldb\/Core\/Timer.h\"\n#include \"lldb\/Core\/UUID.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n#include \"lldb\/Target\/Target.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n#if defined (__linux__) || defined (__FreeBSD__)\n\nFileSpec\nSymbols::LocateExecutableObjectFile (const ModuleSpec &module_spec)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nFileSpec\nSymbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec)\n{\n const char *symbol_filename = module_spec.GetSymbolFileSpec().GetFilename().AsCString();\n if (!symbol_filename || !symbol_filename[0])\n return FileSpec();\n\n FileSpecList debug_file_search_paths (Target::GetDefaultDebugFileSearchPaths());\n\n \/\/ Add module directory.\n const ConstString &file_dir = module_spec.GetFileSpec().GetDirectory();\n debug_file_search_paths.AppendIfUnique (FileSpec(file_dir.AsCString(\".\"), true));\n\n \/\/ Add current working directory.\n debug_file_search_paths.AppendIfUnique (FileSpec(\".\", true));\n\n \/\/ Add \/usr\/lib\/debug directory.\n debug_file_search_paths.AppendIfUnique (FileSpec(\"\/usr\/lib\/debug\", true));\n\n std::string uuid_str;\n const UUID &module_uuid = module_spec.GetUUID();\n if (module_uuid.IsValid())\n {\n \/\/ Some debug files are stored in the .build-id directory like this:\n \/\/ \/usr\/lib\/debug\/.build-id\/ff\/e7fe727889ad82bb153de2ad065b2189693315.debug\n uuid_str = module_uuid.GetAsString(\"\");\n uuid_str.insert (2, 1, '\/');\n uuid_str = uuid_str + \".debug\";\n }\n\n \/\/ Get full path to our module. Needed to check debug files like this:\n \/\/ \/usr\/lib\/debug\/usr\/lib\/libboost_date_time.so.1.46.1\n std::string module_filename = module_spec.GetFileSpec().GetPath();\n\n size_t num_directories = debug_file_search_paths.GetSize();\n for (size_t idx = 0; idx < num_directories; ++idx)\n {\n FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex (idx);\n dirspec.ResolvePath();\n if (!dirspec.Exists() || !dirspec.IsDirectory())\n continue;\n\n std::vector files;\n std::string dirname = dirspec.GetPath();\n\n files.push_back (dirname + \"\/\" + symbol_filename);\n files.push_back (dirname + \"\/.debug\/\" + symbol_filename);\n files.push_back (dirname + \"\/.build-id\/\" + uuid_str);\n files.push_back (dirname + module_filename);\n\n const uint32_t num_files = files.size();\n for (size_t idx_file = 0; idx_file < num_files; ++idx_file)\n {\n const std::string &filename = files[idx_file];\n FileSpec file_spec (filename.c_str(), true);\n\n if (file_spec == module_spec.GetFileSpec())\n continue;\n\n if (file_spec.Exists())\n {\n lldb_private::ModuleSpecList specs;\n const size_t num_specs = ObjectFile::GetModuleSpecifications (file_spec, 0, 0, specs);\n assert (num_specs <= 1 && \"Symbol Vendor supports only a single architecture\");\n if (num_specs == 1)\n {\n ModuleSpec mspec;\n if (specs.GetModuleSpecAtIndex (0, mspec))\n {\n if (mspec.GetUUID() == module_uuid)\n return file_spec;\n }\n }\n }\n }\n }\n\n return FileSpec();\n}\n\nFileSpec\nSymbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle,\n const lldb_private::UUID *uuid,\n const ArchSpec *arch)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nbool\nSymbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup)\n{\n \/\/ Fill in the module_spec.GetFileSpec() for the object file and\/or the\n \/\/ module_spec.GetSymbolFileSpec() for the debug symbols file.\n return false;\n}\n\n#elif !defined (__APPLE__)\n\nFileSpec\nSymbols::LocateExecutableObjectFile (const ModuleSpec &module_spec)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nFileSpec\nSymbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec)\n{\n \/\/ FIXME\n return FileSpec();\n}\n\nFileSpec\nSymbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle,\n const lldb_private::UUID *uuid,\n const ArchSpec *arch)\n{\n return FileSpec();\n}\n\nbool\nSymbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup)\n{\n \/\/ Fill in the module_spec.GetFileSpec() for the object file and\/or the\n \/\/ module_spec.GetSymbolFileSpec() for the debug symbols file.\n return false;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ $Id: TCPTransfer_test.C,v 1.12 2002\/01\/09 12:22:17 amoll Exp $\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\n\/\/ include a helper class testing for network availability\n\/\/ (or more precisely: the ability to perform HTTP or FTP transfers)\n\n#include \"networkTest.h\"\n\nSTART_TEST(TCPTransfer, \"$Id: TCPTransfer_test.C,v 1.12 2002\/01\/09 12:22:17 amoll Exp $\")\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTCPTransfer* tcp_ptr;\nCHECK(cstr)\n\ttcp_ptr = new TCPTransfer;\n\tTEST_NOT_EQUAL(tcp_ptr, 0)\n\tTEST_EQUAL(tcp_ptr->getStatusCode(), TCPTransfer::UNINITIALIZED_ERROR)\nRESULT\n\nCHECK(~TCPTransfer_test)\n\tdelete tcp_ptr;\nRESULT\n\nCHECK(set(ofstream& file, const String& address))\n\tABORT_IF(!NetworkTest::test(\"www.mpi-sb.mpg.de\", NetworkTest::HTTP))\n\tTCPTransfer tcp_t;\n\tofstream out;\n\ttcp_t.set(out, \"http:\/\/www.mpi-sb.mpg.de\/BALL\/test\/http_test.txt\");\n\tTEST_EQUAL(tcp_t.getHostAddress(), \"www.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t.getFileAddress(), \"\/BALL\/test\/http_test.txt\")\n\tTEST_EQUAL(tcp_t.getPort(), 80)\n\tTEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR)\n\tTEST_EQUAL(tcp_t.getReceivedBytes(), 0)\n\tTEST_EQUAL(tcp_t.getLogin(), \"\")\n\tTEST_EQUAL(tcp_t.getPassword(), \"\")\n\tTEST_EQUAL(tcp_t.getStream(), &out)\nRESULT\n\nCHECK(http\/no login)\n\tABORT_IF(!NetworkTest::test(\"www.mpi-sb.mpg.de\", NetworkTest::HTTP))\n\tString filename;\n\tFile::createTemporaryFilename(filename);\n\tofstream out(filename.c_str(), std::ios::out);\n\t\n\tTCPTransfer tcp_t(out ,\"http:\/\/www.mpi-sb.mpg.de\/BALL\/test\/http_test.txt\" , false);\n\tTEST_EQUAL(tcp_t.getHostAddress(), \"www.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t.getFileAddress(), \"\/BALL\/test\/http_test.txt\")\n\tTEST_EQUAL(tcp_t.getPort(), 80)\n\tTEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR)\n\tTEST_EQUAL(tcp_t.getReceivedBytes(), 3048)\n\tTEST_EQUAL(tcp_t.getLogin(), \"\")\n\tTEST_EQUAL(tcp_t.getPassword(), \"\")\n\tout.close();\n\t\n\tTEST_FILE(filename.c_str(), \"data\/http_test.txt\", false)\nRESULT\n\nCHECK(http\/login)\n\tABORT_IF(!NetworkTest::test(\"www.mpi-sb.mpg.de\", NetworkTest::HTTP))\n\tString filename;\n\tFile::createTemporaryFilename(filename);\n\tofstream out(filename.c_str(), std::ios::out);\n\tTCPTransfer tcp_t2(out ,\"http:\/\/BALL:test@www.mpi-sb.mpg.de\/BALL\/INTERNAL\/internal.html\", true);\n\tTEST_EQUAL(tcp_t2.getHostAddress(), \"www.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t2.getFileAddress(), \"\/BALL\/INTERNAL\/internal.html\")\n\tTEST_EQUAL(tcp_t2.getPort(), 80)\n\tTEST_EQUAL(tcp_t2.getStatusCode(), TCPTransfer::NO_ERROR)\n\t\/\/?????, waiting for www-server config\n\t\/\/TEST_EQUAL(tcp_t2.getReceivedBytes(), 11908)\n\tTEST_EQUAL(tcp_t2.getLogin(), \"BALL\")\n\tTEST_EQUAL(tcp_t2.getPassword(), \"test\")\n\tout.close();\nRESULT\n\nCHECK(ftp)\n\tABORT_IF(!NetworkTest::test(\"ftp.mpi-sb.mpg.de\", NetworkTest::FTP))\n String filename;\n\tFile::createTemporaryFilename(filename);\n\tofstream out(filename.c_str(), std::ios::out);\n\tTCPTransfer tcp_t(out, \"ftp:\/\/ftp.mpi-sb.mpg.de\/pub\/outgoing\/BALL\/ftp_test.txt\");\n\tTEST_EQUAL(tcp_t.getHostAddress(), \"ftp.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t.getFileAddress(), \"\/pub\/outgoing\/BALL\/ftp_test.txt\")\n\tTEST_EQUAL(tcp_t.getPort(), 21)\n\tTEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR)\n\tTEST_EQUAL(tcp_t.getReceivedBytes(), 2312)\n\tTEST_EQUAL(tcp_t.getLogin(), \"\")\n\tTEST_EQUAL(tcp_t.getPassword(), \"\")\n\tTEST_EQUAL(tcp_t.getStream(), &out)\n\tout.close();\n\n\tTEST_FILE(filename.c_str(), \"data\/ftp_test.txt\", false)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\nfixed: removed superfluous test for network in set test\/\/ $Id: TCPTransfer_test.C,v 1.13 2002\/01\/09 12:27:03 amoll Exp $\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\n\/\/ include a helper class testing for network availability\n\/\/ (or more precisely: the ability to perform HTTP or FTP transfers)\n\n#include \"networkTest.h\"\n\nSTART_TEST(TCPTransfer, \"$Id: TCPTransfer_test.C,v 1.13 2002\/01\/09 12:27:03 amoll Exp $\")\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTCPTransfer* tcp_ptr;\nCHECK(cstr)\n\ttcp_ptr = new TCPTransfer;\n\tTEST_NOT_EQUAL(tcp_ptr, 0)\n\tTEST_EQUAL(tcp_ptr->getStatusCode(), TCPTransfer::UNINITIALIZED_ERROR)\nRESULT\n\nCHECK(~TCPTransfer_test)\n\tdelete tcp_ptr;\nRESULT\n\nCHECK(set(ofstream& file, const String& address))\n\tTCPTransfer tcp_t;\n\tofstream out;\n\ttcp_t.set(out, \"http:\/\/www.mpi-sb.mpg.de\/BALL\/test\/http_test.txt\");\n\tTEST_EQUAL(tcp_t.getHostAddress(), \"www.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t.getFileAddress(), \"\/BALL\/test\/http_test.txt\")\n\tTEST_EQUAL(tcp_t.getPort(), 80)\n\tTEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR)\n\tTEST_EQUAL(tcp_t.getReceivedBytes(), 0)\n\tTEST_EQUAL(tcp_t.getLogin(), \"\")\n\tTEST_EQUAL(tcp_t.getPassword(), \"\")\n\tTEST_EQUAL(tcp_t.getStream(), &out)\nRESULT\n\nCHECK(http\/no login)\n\tABORT_IF(!NetworkTest::test(\"www.mpi-sb.mpg.de\", NetworkTest::HTTP))\n\tString filename;\n\tFile::createTemporaryFilename(filename);\n\tofstream out(filename.c_str(), std::ios::out);\n\t\n\tTCPTransfer tcp_t(out ,\"http:\/\/www.mpi-sb.mpg.de\/BALL\/test\/http_test.txt\" , false);\n\tTEST_EQUAL(tcp_t.getHostAddress(), \"www.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t.getFileAddress(), \"\/BALL\/test\/http_test.txt\")\n\tTEST_EQUAL(tcp_t.getPort(), 80)\n\tTEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR)\n\tTEST_EQUAL(tcp_t.getReceivedBytes(), 3048)\n\tTEST_EQUAL(tcp_t.getLogin(), \"\")\n\tTEST_EQUAL(tcp_t.getPassword(), \"\")\n\tout.close();\n\t\n\tTEST_FILE(filename.c_str(), \"data\/http_test.txt\", false)\nRESULT\n\nCHECK(http\/login)\n\tABORT_IF(!NetworkTest::test(\"www.mpi-sb.mpg.de\", NetworkTest::HTTP))\n\tString filename;\n\tFile::createTemporaryFilename(filename);\n\tofstream out(filename.c_str(), std::ios::out);\n\tTCPTransfer tcp_t2(out ,\"http:\/\/BALL:test@www.mpi-sb.mpg.de\/BALL\/INTERNAL\/internal.html\", true);\n\tTEST_EQUAL(tcp_t2.getHostAddress(), \"www.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t2.getFileAddress(), \"\/BALL\/INTERNAL\/internal.html\")\n\tTEST_EQUAL(tcp_t2.getPort(), 80)\n\tTEST_EQUAL(tcp_t2.getStatusCode(), TCPTransfer::NO_ERROR)\n\t\/\/?????, waiting for www-server config\n\t\/\/TEST_EQUAL(tcp_t2.getReceivedBytes(), 11908)\n\tTEST_EQUAL(tcp_t2.getLogin(), \"BALL\")\n\tTEST_EQUAL(tcp_t2.getPassword(), \"test\")\n\tout.close();\nRESULT\n\nCHECK(ftp)\n\tABORT_IF(!NetworkTest::test(\"ftp.mpi-sb.mpg.de\", NetworkTest::FTP))\n String filename;\n\tFile::createTemporaryFilename(filename);\n\tofstream out(filename.c_str(), std::ios::out);\n\tTCPTransfer tcp_t(out, \"ftp:\/\/ftp.mpi-sb.mpg.de\/pub\/outgoing\/BALL\/ftp_test.txt\");\n\tTEST_EQUAL(tcp_t.getHostAddress(), \"ftp.mpi-sb.mpg.de\")\n\tTEST_EQUAL(tcp_t.getFileAddress(), \"\/pub\/outgoing\/BALL\/ftp_test.txt\")\n\tTEST_EQUAL(tcp_t.getPort(), 21)\n\tTEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR)\n\tTEST_EQUAL(tcp_t.getReceivedBytes(), 2312)\n\tTEST_EQUAL(tcp_t.getLogin(), \"\")\n\tTEST_EQUAL(tcp_t.getPassword(), \"\")\n\tTEST_EQUAL(tcp_t.getStream(), &out)\n\tout.close();\n\n\tTEST_FILE(filename.c_str(), \"data\/ftp_test.txt\", false)\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"} {"text":"\/\/===--------------------- ModuleCache.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 \"ModuleCache.h\"\n\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/ModuleList.h\"\n#include \"lldb\/Core\/ModuleSpec.h\"\n#include \"lldb\/Host\/File.h\"\n#include \"lldb\/Host\/FileSystem.h\"\n#include \"lldb\/Host\/LockFile.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/FileUtilities.h\"\n\n#include \n\n#include \n\nusing namespace lldb;\nusing namespace lldb_private;\n\nnamespace {\n\nconst char* kModulesSubdir = \".cache\";\nconst char* kLockDirName = \".lock\";\nconst char* kTempFileName = \".temp\";\nconst char* kTempSymFileName = \".symtemp\";\nconst char* kSymFileExtension = \".sym\";\n\nclass ModuleLock\n{\nprivate:\n File m_file;\n std::unique_ptr m_lock;\n FileSpec m_file_spec;\n\npublic:\n ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error);\n void Delete ();\n};\n\nFileSpec\nJoinPath (const FileSpec &path1, const char* path2)\n{\n FileSpec result_spec (path1);\n result_spec.AppendPathComponent (path2);\n return result_spec;\n}\n\nError\nMakeDirectory (const FileSpec &dir_path)\n{\n if (dir_path.Exists ())\n {\n if (!dir_path.IsDirectory ())\n return Error (\"Invalid existing path\");\n\n return Error ();\n }\n\n return FileSystem::MakeDirectory(dir_path, eFilePermissionsDirectoryDefault);\n}\n\nFileSpec\nGetModuleDirectory (const FileSpec &root_dir_spec, const UUID &uuid)\n{\n const auto modules_dir_spec = JoinPath (root_dir_spec, kModulesSubdir);\n return JoinPath (modules_dir_spec, uuid.GetAsString ().c_str ());\n}\n\nFileSpec\nGetSymbolFileSpec(const FileSpec& module_file_spec)\n{\n return FileSpec((module_file_spec.GetPath() + kSymFileExtension).c_str(), false);\n}\n\nvoid\nDeleteExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec)\n{\n Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_MODULES));\n UUID module_uuid;\n {\n auto module_sp = std::make_shared(ModuleSpec (sysroot_module_path_spec));\n module_uuid = module_sp->GetUUID ();\n }\n\n if (!module_uuid.IsValid ())\n return;\n\n Error error;\n ModuleLock lock (root_dir_spec, module_uuid, error);\n if (error.Fail ())\n {\n if (log)\n log->Printf (\"Failed to lock module %s: %s\",\n module_uuid.GetAsString ().c_str (),\n error.AsCString ());\n }\n\n auto link_count = FileSystem::GetHardlinkCount (sysroot_module_path_spec);\n if (link_count == -1)\n return;\n\n if (link_count > 2) \/\/ module is referred by other hosts.\n return;\n\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_uuid);\n FileSystem::DeleteDirectory (module_spec_dir, true);\n lock.Delete();\n}\n\nvoid\nDecrementRefExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec)\n{\n \/\/ Remove $platform\/.cache\/$uuid folder if nobody else references it.\n DeleteExistingModule (root_dir_spec, sysroot_module_path_spec);\n\n \/\/ Remove sysroot link.\n FileSystem::Unlink (sysroot_module_path_spec);\n\n FileSpec symfile_spec = GetSymbolFileSpec (sysroot_module_path_spec);\n if (symfile_spec.Exists ()) \/\/ delete module's symbol file if exists.\n FileSystem::Unlink (symfile_spec);\n}\n\nError\nCreateHostSysRootModuleLink (const FileSpec &root_dir_spec, const char *hostname,\n const FileSpec &platform_module_spec,\n const FileSpec &local_module_spec,\n bool delete_existing)\n{\n const auto sysroot_module_path_spec = JoinPath (\n JoinPath (root_dir_spec, hostname), platform_module_spec.GetPath ().c_str ());\n if (sysroot_module_path_spec.Exists())\n {\n if (!delete_existing)\n return Error ();\n\n DecrementRefExistingModule (root_dir_spec, sysroot_module_path_spec);\n }\n\n const auto error = MakeDirectory (FileSpec (sysroot_module_path_spec.GetDirectory ().AsCString (), false));\n if (error.Fail ())\n return error;\n\n return FileSystem::Hardlink(sysroot_module_path_spec, local_module_spec);\n}\n\n} \/\/ namespace\n\nModuleLock::ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error)\n{\n const auto lock_dir_spec = JoinPath (root_dir_spec, kLockDirName);\n error = MakeDirectory (lock_dir_spec);\n if (error.Fail ())\n return;\n\n m_file_spec = JoinPath (lock_dir_spec, uuid.GetAsString ().c_str ());\n m_file.Open (m_file_spec.GetCString (),\n File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionCloseOnExec);\n if (!m_file)\n {\n error.SetErrorToErrno ();\n return;\n }\n\n m_lock.reset (new lldb_private::LockFile (m_file.GetDescriptor ()));\n error = m_lock->WriteLock (0, 1);\n if (error.Fail ())\n error.SetErrorStringWithFormat (\"Failed to lock file: %s\", error.AsCString ());\n}\n\nvoid ModuleLock::Delete ()\n{\n if (!m_file)\n return;\n\n m_file.Close ();\n FileSystem::Unlink (m_file_spec);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nError\nModuleCache::Put (const FileSpec &root_dir_spec,\n const char *hostname,\n const ModuleSpec &module_spec,\n const FileSpec &tmp_file,\n const FileSpec &target_file)\n{\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ());\n const auto module_file_path = JoinPath (module_spec_dir, target_file.GetFilename ().AsCString ());\n\n const auto tmp_file_path = tmp_file.GetPath ();\n const auto err_code = llvm::sys::fs::rename (tmp_file_path.c_str (), module_file_path.GetPath ().c_str ());\n if (err_code)\n return Error (\"Failed to rename file %s to %s: %s\",\n tmp_file_path.c_str (), module_file_path.GetPath ().c_str (), err_code.message ().c_str ());\n\n const auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, target_file, module_file_path, true);\n if (error.Fail ())\n return Error (\"Failed to create link to %s: %s\", module_file_path.GetPath ().c_str (), error.AsCString ());\n return Error ();\n}\n\nError\nModuleCache::Get (const FileSpec &root_dir_spec,\n const char *hostname,\n const ModuleSpec &module_spec,\n ModuleSP &cached_module_sp,\n bool *did_create_ptr)\n{\n const auto find_it = m_loaded_modules.find (module_spec.GetUUID ().GetAsString());\n if (find_it != m_loaded_modules.end ())\n {\n cached_module_sp = (*find_it).second.lock ();\n if (cached_module_sp)\n return Error ();\n m_loaded_modules.erase (find_it);\n }\n\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ());\n const auto module_file_path = JoinPath (module_spec_dir, module_spec.GetFileSpec ().GetFilename ().AsCString ());\n\n if (!module_file_path.Exists ())\n return Error (\"Module %s not found\", module_file_path.GetPath ().c_str ());\n if (module_file_path.GetByteSize () != module_spec.GetObjectSize ())\n return Error (\"Module %s has invalid file size\", module_file_path.GetPath ().c_str ());\n\n \/\/ We may have already cached module but downloaded from an another host - in this case let's create a link to it.\n auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, module_spec.GetFileSpec(), module_file_path, false);\n if (error.Fail ())\n return Error (\"Failed to create link to %s: %s\", module_file_path.GetPath().c_str(), error.AsCString());\n\n auto cached_module_spec (module_spec);\n cached_module_spec.GetUUID ().Clear (); \/\/ Clear UUID since it may contain md5 content hash instead of real UUID.\n cached_module_spec.GetFileSpec () = module_file_path;\n cached_module_spec.GetPlatformFileSpec () = module_spec.GetFileSpec ();\n \n error = ModuleList::GetSharedModule(cached_module_spec,\n cached_module_sp,\n nullptr,\n nullptr,\n did_create_ptr,\n false);\n if (error.Fail())\n return error;\n\n FileSpec symfile_spec = GetSymbolFileSpec(cached_module_sp->GetFileSpec ());\n if (symfile_spec.Exists ())\n cached_module_sp->SetSymbolFileFileSpec (symfile_spec);\n\n m_loaded_modules.insert (std::make_pair (module_spec.GetUUID ().GetAsString (), cached_module_sp));\n\n return Error ();\n}\n\nError\nModuleCache::GetAndPut (const FileSpec &root_dir_spec,\n const char *hostname,\n const ModuleSpec &module_spec,\n const ModuleDownloader &module_downloader,\n const SymfileDownloader &symfile_downloader,\n lldb::ModuleSP &cached_module_sp,\n bool *did_create_ptr)\n{\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ());\n auto error = MakeDirectory (module_spec_dir);\n if (error.Fail ())\n return error;\n\n ModuleLock lock (root_dir_spec, module_spec.GetUUID (), error);\n if (error.Fail ())\n return Error(\"Failed to lock module %s: %s\", module_spec.GetUUID ().GetAsString().c_str(), error.AsCString ());\n\n \/\/ Check local cache for a module.\n error = Get (root_dir_spec, hostname, module_spec, cached_module_sp, did_create_ptr);\n if (error.Success ())\n return error;\n\n const auto tmp_download_file_spec = JoinPath (module_spec_dir, kTempFileName);\n error = module_downloader (module_spec, tmp_download_file_spec);\n llvm::FileRemover tmp_file_remover (tmp_download_file_spec.GetPath ().c_str ());\n if (error.Fail ())\n return Error(\"Failed to download module: %s\", error.AsCString ());\n\n \/\/ Put downloaded file into local module cache.\n error = Put (root_dir_spec, hostname, module_spec, tmp_download_file_spec, module_spec.GetFileSpec ());\n if (error.Fail ())\n return Error (\"Failed to put module into cache: %s\", error.AsCString ());\n\n tmp_file_remover.releaseFile ();\n error = Get (root_dir_spec, hostname, module_spec, cached_module_sp, did_create_ptr);\n if (error.Fail ())\n return error;\n\n \/\/ Fetching a symbol file for the module\n const auto tmp_download_sym_file_spec = JoinPath (module_spec_dir, kTempSymFileName);\n error = symfile_downloader (cached_module_sp, tmp_download_sym_file_spec);\n llvm::FileRemover tmp_symfile_remover (tmp_download_sym_file_spec.GetPath ().c_str ());\n if (error.Fail ())\n \/\/ Failed to download a symfile but fetching the module was successful. The module might\n \/\/ contain the neccessary symbols and the debugging is also possible without a symfile.\n return Error ();\n\n error = Put (root_dir_spec, hostname, module_spec, tmp_download_sym_file_spec, GetSymbolFileSpec(module_spec.GetFileSpec ()));\n if (error.Fail ())\n return Error (\"Failed to put symbol file into cache: %s\", error.AsCString ());\n \n tmp_symfile_remover.releaseFile();\n\n FileSpec symfile_spec = GetSymbolFileSpec (cached_module_sp->GetFileSpec ());\n cached_module_sp->SetSymbolFileFileSpec (symfile_spec);\n return Error ();\n}\nReplace file system forbidden symbols in the hostname which passed to the ModuleCache.\/\/===--------------------- ModuleCache.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 \"ModuleCache.h\"\n\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/ModuleList.h\"\n#include \"lldb\/Core\/ModuleSpec.h\"\n#include \"lldb\/Host\/File.h\"\n#include \"lldb\/Host\/FileSystem.h\"\n#include \"lldb\/Host\/LockFile.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/FileUtilities.h\"\n\n#include \n\n#include \n\nusing namespace lldb;\nusing namespace lldb_private;\n\nnamespace {\n\nconst char* kModulesSubdir = \".cache\";\nconst char* kLockDirName = \".lock\";\nconst char* kTempFileName = \".temp\";\nconst char* kTempSymFileName = \".symtemp\";\nconst char* kSymFileExtension = \".sym\";\nconst char* kFSIllegalChars = \"\\\\\/:*?\\\"<>|\";\n\nstd::string\nGetEscapedHostname(const char* hostname)\n{\n std::string result(hostname);\n size_t size = result.size();\n for (size_t i = 0; i < size; ++i)\n {\n if ((result[i] >=1 && result[i] <= 31) ||\n strchr(kFSIllegalChars, result[i]) != nullptr)\n result[i] = '_';\n }\n return result;\n}\n\nclass ModuleLock\n{\nprivate:\n File m_file;\n std::unique_ptr m_lock;\n FileSpec m_file_spec;\n\npublic:\n ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error);\n void Delete ();\n};\n\nFileSpec\nJoinPath (const FileSpec &path1, const char* path2)\n{\n FileSpec result_spec (path1);\n result_spec.AppendPathComponent (path2);\n return result_spec;\n}\n\nError\nMakeDirectory (const FileSpec &dir_path)\n{\n if (dir_path.Exists ())\n {\n if (!dir_path.IsDirectory ())\n return Error (\"Invalid existing path\");\n\n return Error ();\n }\n\n return FileSystem::MakeDirectory(dir_path, eFilePermissionsDirectoryDefault);\n}\n\nFileSpec\nGetModuleDirectory (const FileSpec &root_dir_spec, const UUID &uuid)\n{\n const auto modules_dir_spec = JoinPath (root_dir_spec, kModulesSubdir);\n return JoinPath (modules_dir_spec, uuid.GetAsString ().c_str ());\n}\n\nFileSpec\nGetSymbolFileSpec(const FileSpec& module_file_spec)\n{\n return FileSpec((module_file_spec.GetPath() + kSymFileExtension).c_str(), false);\n}\n\nvoid\nDeleteExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec)\n{\n Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_MODULES));\n UUID module_uuid;\n {\n auto module_sp = std::make_shared(ModuleSpec (sysroot_module_path_spec));\n module_uuid = module_sp->GetUUID ();\n }\n\n if (!module_uuid.IsValid ())\n return;\n\n Error error;\n ModuleLock lock (root_dir_spec, module_uuid, error);\n if (error.Fail ())\n {\n if (log)\n log->Printf (\"Failed to lock module %s: %s\",\n module_uuid.GetAsString ().c_str (),\n error.AsCString ());\n }\n\n auto link_count = FileSystem::GetHardlinkCount (sysroot_module_path_spec);\n if (link_count == -1)\n return;\n\n if (link_count > 2) \/\/ module is referred by other hosts.\n return;\n\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_uuid);\n FileSystem::DeleteDirectory (module_spec_dir, true);\n lock.Delete();\n}\n\nvoid\nDecrementRefExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec)\n{\n \/\/ Remove $platform\/.cache\/$uuid folder if nobody else references it.\n DeleteExistingModule (root_dir_spec, sysroot_module_path_spec);\n\n \/\/ Remove sysroot link.\n FileSystem::Unlink (sysroot_module_path_spec);\n\n FileSpec symfile_spec = GetSymbolFileSpec (sysroot_module_path_spec);\n if (symfile_spec.Exists ()) \/\/ delete module's symbol file if exists.\n FileSystem::Unlink (symfile_spec);\n}\n\nError\nCreateHostSysRootModuleLink (const FileSpec &root_dir_spec, const char *hostname,\n const FileSpec &platform_module_spec,\n const FileSpec &local_module_spec,\n bool delete_existing)\n{\n const auto sysroot_module_path_spec = JoinPath (\n JoinPath (root_dir_spec, hostname), platform_module_spec.GetPath ().c_str ());\n if (sysroot_module_path_spec.Exists())\n {\n if (!delete_existing)\n return Error ();\n\n DecrementRefExistingModule (root_dir_spec, sysroot_module_path_spec);\n }\n\n const auto error = MakeDirectory (FileSpec (sysroot_module_path_spec.GetDirectory ().AsCString (), false));\n if (error.Fail ())\n return error;\n\n return FileSystem::Hardlink(sysroot_module_path_spec, local_module_spec);\n}\n\n} \/\/ namespace\n\nModuleLock::ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error)\n{\n const auto lock_dir_spec = JoinPath (root_dir_spec, kLockDirName);\n error = MakeDirectory (lock_dir_spec);\n if (error.Fail ())\n return;\n\n m_file_spec = JoinPath (lock_dir_spec, uuid.GetAsString ().c_str ());\n m_file.Open (m_file_spec.GetCString (),\n File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionCloseOnExec);\n if (!m_file)\n {\n error.SetErrorToErrno ();\n return;\n }\n\n m_lock.reset (new lldb_private::LockFile (m_file.GetDescriptor ()));\n error = m_lock->WriteLock (0, 1);\n if (error.Fail ())\n error.SetErrorStringWithFormat (\"Failed to lock file: %s\", error.AsCString ());\n}\n\nvoid ModuleLock::Delete ()\n{\n if (!m_file)\n return;\n\n m_file.Close ();\n FileSystem::Unlink (m_file_spec);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nError\nModuleCache::Put (const FileSpec &root_dir_spec,\n const char *hostname,\n const ModuleSpec &module_spec,\n const FileSpec &tmp_file,\n const FileSpec &target_file)\n{\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ());\n const auto module_file_path = JoinPath (module_spec_dir, target_file.GetFilename ().AsCString ());\n\n const auto tmp_file_path = tmp_file.GetPath ();\n const auto err_code = llvm::sys::fs::rename (tmp_file_path.c_str (), module_file_path.GetPath ().c_str ());\n if (err_code)\n return Error (\"Failed to rename file %s to %s: %s\",\n tmp_file_path.c_str (), module_file_path.GetPath ().c_str (), err_code.message ().c_str ());\n\n const auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, target_file, module_file_path, true);\n if (error.Fail ())\n return Error (\"Failed to create link to %s: %s\", module_file_path.GetPath ().c_str (), error.AsCString ());\n return Error ();\n}\n\nError\nModuleCache::Get (const FileSpec &root_dir_spec,\n const char *hostname,\n const ModuleSpec &module_spec,\n ModuleSP &cached_module_sp,\n bool *did_create_ptr)\n{\n const auto find_it = m_loaded_modules.find (module_spec.GetUUID ().GetAsString());\n if (find_it != m_loaded_modules.end ())\n {\n cached_module_sp = (*find_it).second.lock ();\n if (cached_module_sp)\n return Error ();\n m_loaded_modules.erase (find_it);\n }\n\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ());\n const auto module_file_path = JoinPath (module_spec_dir, module_spec.GetFileSpec ().GetFilename ().AsCString ());\n\n if (!module_file_path.Exists ())\n return Error (\"Module %s not found\", module_file_path.GetPath ().c_str ());\n if (module_file_path.GetByteSize () != module_spec.GetObjectSize ())\n return Error (\"Module %s has invalid file size\", module_file_path.GetPath ().c_str ());\n\n \/\/ We may have already cached module but downloaded from an another host - in this case let's create a link to it.\n auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, module_spec.GetFileSpec(), module_file_path, false);\n if (error.Fail ())\n return Error (\"Failed to create link to %s: %s\", module_file_path.GetPath().c_str(), error.AsCString());\n\n auto cached_module_spec (module_spec);\n cached_module_spec.GetUUID ().Clear (); \/\/ Clear UUID since it may contain md5 content hash instead of real UUID.\n cached_module_spec.GetFileSpec () = module_file_path;\n cached_module_spec.GetPlatformFileSpec () = module_spec.GetFileSpec ();\n \n error = ModuleList::GetSharedModule(cached_module_spec,\n cached_module_sp,\n nullptr,\n nullptr,\n did_create_ptr,\n false);\n if (error.Fail())\n return error;\n\n FileSpec symfile_spec = GetSymbolFileSpec(cached_module_sp->GetFileSpec ());\n if (symfile_spec.Exists ())\n cached_module_sp->SetSymbolFileFileSpec (symfile_spec);\n\n m_loaded_modules.insert (std::make_pair (module_spec.GetUUID ().GetAsString (), cached_module_sp));\n\n return Error ();\n}\n\nError\nModuleCache::GetAndPut (const FileSpec &root_dir_spec,\n const char *hostname,\n const ModuleSpec &module_spec,\n const ModuleDownloader &module_downloader,\n const SymfileDownloader &symfile_downloader,\n lldb::ModuleSP &cached_module_sp,\n bool *did_create_ptr)\n{\n const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ());\n auto error = MakeDirectory (module_spec_dir);\n if (error.Fail ())\n return error;\n\n ModuleLock lock (root_dir_spec, module_spec.GetUUID (), error);\n if (error.Fail ())\n return Error(\"Failed to lock module %s: %s\", module_spec.GetUUID ().GetAsString().c_str(), error.AsCString ());\n\n const auto escaped_hostname(GetEscapedHostname(hostname));\n \/\/ Check local cache for a module.\n error = Get (root_dir_spec, escaped_hostname.c_str(), module_spec, cached_module_sp, did_create_ptr);\n if (error.Success ())\n return error;\n\n const auto tmp_download_file_spec = JoinPath (module_spec_dir, kTempFileName);\n error = module_downloader (module_spec, tmp_download_file_spec);\n llvm::FileRemover tmp_file_remover (tmp_download_file_spec.GetPath ().c_str ());\n if (error.Fail ())\n return Error(\"Failed to download module: %s\", error.AsCString ());\n\n \/\/ Put downloaded file into local module cache.\n error = Put (root_dir_spec, escaped_hostname.c_str(), module_spec, tmp_download_file_spec, module_spec.GetFileSpec ());\n if (error.Fail ())\n return Error (\"Failed to put module into cache: %s\", error.AsCString ());\n\n tmp_file_remover.releaseFile ();\n error = Get (root_dir_spec, escaped_hostname.c_str(), module_spec, cached_module_sp, did_create_ptr);\n if (error.Fail ())\n return error;\n\n \/\/ Fetching a symbol file for the module\n const auto tmp_download_sym_file_spec = JoinPath (module_spec_dir, kTempSymFileName);\n error = symfile_downloader (cached_module_sp, tmp_download_sym_file_spec);\n llvm::FileRemover tmp_symfile_remover (tmp_download_sym_file_spec.GetPath ().c_str ());\n if (error.Fail ())\n \/\/ Failed to download a symfile but fetching the module was successful. The module might\n \/\/ contain the neccessary symbols and the debugging is also possible without a symfile.\n return Error ();\n\n error = Put (root_dir_spec, escaped_hostname.c_str(), module_spec, tmp_download_sym_file_spec, GetSymbolFileSpec(module_spec.GetFileSpec ()));\n if (error.Fail ())\n return Error (\"Failed to put symbol file into cache: %s\", error.AsCString ());\n \n tmp_symfile_remover.releaseFile();\n\n FileSpec symfile_spec = GetSymbolFileSpec (cached_module_sp->GetFileSpec ());\n cached_module_sp->SetSymbolFileFileSpec (symfile_spec);\n return Error ();\n}\n<|endoftext|>"} {"text":"#ifndef VRTYPE_HPP\n#define VRTYPE_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace dicom\n{\n\nnamespace data\n{\n\nnamespace vrtype\n{\n\nbool rule_n(std::size_t multiplier, std::size_t current, std::size_t new_elements)\n{\n return (current + new_elements) % multiplier == 0;\n}\n\nbool rule_less(std::size_t size, std::size_t current, std::size_t new_elements)\n{\n return current + new_elements <= size;\n}\n\nbool rule_more(std::size_t size, std::size_t current, std::size_t new_elements)\n{\n return current + new_elements >= size;\n}\n\nbool rule_equals(std::size_t size, std::size_t current, std::size_t new_elements)\n{\n return current + new_elements == size;\n}\n\n\n\ntemplate \nclass vrtype\n{\n private:\n std::vector value_sequence;\n std::string multiplicity;\n\n std::vector> multiplicity_rules;\n\n \/**\n * @brief validate_multiplicity verifies that the respective attribute's\n * multiplicity definitions are satisfied.\n * @param num_new_elements number of new elements to be added\n * @pre multiplicity rule must be satisfied for the current number of\n * elements.\n * @return\n *\/\n bool validate_multiplicity(std::size_t num_new_elements) const\n {\n return std::all_of(multiplicity_rules.begin()\n , multiplicity_rules.end()\n , [=](std::function rule)\n { return rule(value_sequence.size(), num_new_elements); } );\n }\n\n \/**\n * @brief populate_mult_rules parses the multiplicity definiton and adds\n * all necessary rules.\n *\/\n void populate_mult_rules()\n {\n auto it = std::remove_if(multiplicity.begin(), multiplicity.end(), ::isspace);\n multiplicity.erase(it, multiplicity.end());\n\n std::vector components;\n boost::split(components, multiplicity, boost::is_any_of(\"-\"));\n\n if (components.size() > 1) {\n if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) {\n std::size_t lower = std::stoull(components[0]);\n if (std::all_of(components[1].begin(), components[1].end(), ::isdigit)) {\n std::size_t upper = std::stoull(components[1]);\n multiplicity_rules.push_back(std::bind1st(rule_more, lower));\n multiplicity_rules.push_back(std::bind1st(rule_less, upper));\n } else if (components[1].find('n') != std::string::npos) {\n std::string multiplier {components[1].begin(), components[1].find_last_of('n')};\n multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier)));\n multiplicity_rules.push_back(std::bind1st(rule_more, lower));\n }\n }\n } else {\n if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) {\n std::size_t value = std::stoull(components[0]);\n multiplicity_rules.push_back(std::bind1st(rule_equals, value));\n } else if (components[0].find('n') != std::string::npos) {\n std::string multiplier {components[0].begin(), components[0].find_last_of('n')};\n multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier)));\n multiplicity_rules.push_back(std::bind1st(rule_more, 1));\n }\n }\n }\n\n\n protected:\n vrtype(std::string multiplicity):\n multiplicity {multiplicity}\n {\n populate_mult_rules();\n }\n\n vrtype(std::string multiplicity, std::initializer_list values):\n vrtype(multiplicity)\n {\n add(values);\n }\n\n\n public:\n virtual ~vrtype() = 0;\n\n \/**\n * @brief is_sequence checks if the attribute can hold more than one value.\n * @return\n *\/\n bool is_sequence() const\n {\n return !multiplicity == \"0\" &&\n !multiplicity == \"1\";\n }\n\n \/**\n * @brief add adds all specified values to the attribute, if doing so\n * does not break multiplicity conditions.\n * @param values list of values to be added.\n *\/\n void add(std::initializer_list values)\n {\n if (!is_sequence()) {\n throw new std::runtime_error(\"can't add to a non-sequence!\");\n }\n if (!validate_multiplicity(values.size())) {\n throw new std::runtime_error(\"addition of \" + values.size() + \" elements would violate the multiplicity rule: \" + multiplicity);\n }\n std::copy(values.begin(), values.end(), std::back_inserter(value_sequence));\n value_sequence.push_back(element);\n }\n};\n\ntemplate \nvrtype::~vrtype()\n{\n}\n\n}\n\n}\n\n}\n\n#endif \/\/ VRTYPE_HPP\nadded abstract (de)serialization methods#ifndef VRTYPE_HPP\n#define VRTYPE_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace dicom\n{\n\nnamespace data\n{\n\nnamespace vrtype\n{\n\nbool rule_n(std::size_t multiplier, std::size_t current, std::size_t new_elements)\n{\n return (current + new_elements) % multiplier == 0;\n}\n\nbool rule_less(std::size_t size, std::size_t current, std::size_t new_elements)\n{\n return current + new_elements <= size;\n}\n\nbool rule_more(std::size_t size, std::size_t current, std::size_t new_elements)\n{\n return current + new_elements >= size;\n}\n\nbool rule_equals(std::size_t size, std::size_t current, std::size_t new_elements)\n{\n return current + new_elements == size;\n}\n\n\n\/**\n * The vrtype class represents the value field of an attribute. It holds the\n * value(s) of type T and asserts the consistency of the appropriate value\n * multiplicity with the value count.\n * @tparam T type of the underlying data\n *\/\ntemplate \nclass vrtype\n{\n private:\n std::vector value_sequence;\n const std::string multiplicity;\n\n std::vector> multiplicity_rules;\n\n \/**\n * @brief validate_multiplicity verifies that the respective attribute's\n * multiplicity definitions are satisfied.\n * @param num_new_elements number of new elements to be added\n * @pre multiplicity rule must be satisfied for the current number of\n * elements.\n * @return\n *\/\n bool validate_multiplicity(std::size_t num_new_elements) const\n {\n return std::all_of(multiplicity_rules.begin()\n , multiplicity_rules.end()\n , [=](std::function rule)\n { return rule(value_sequence.size(), num_new_elements); } );\n }\n\n \/**\n * @brief populate_mult_rules parses the multiplicity definiton and adds\n * all necessary rules.\n *\/\n void populate_mult_rules()\n {\n auto it = std::remove_if(multiplicity.begin(), multiplicity.end(), ::isspace);\n multiplicity.erase(it, multiplicity.end());\n\n std::vector components;\n boost::split(components, multiplicity, boost::is_any_of(\"-\"));\n\n if (components.size() > 1) {\n if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) {\n std::size_t lower = std::stoull(components[0]);\n if (std::all_of(components[1].begin(), components[1].end(), ::isdigit)) {\n std::size_t upper = std::stoull(components[1]);\n multiplicity_rules.push_back(std::bind1st(rule_more, lower));\n multiplicity_rules.push_back(std::bind1st(rule_less, upper));\n } else if (components[1].find('n') != std::string::npos) {\n std::string multiplier {components[1].begin(), components[1].find_last_of('n')};\n multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier)));\n multiplicity_rules.push_back(std::bind1st(rule_more, lower));\n }\n }\n } else {\n if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) {\n std::size_t value = std::stoull(components[0]);\n multiplicity_rules.push_back(std::bind1st(rule_equals, value));\n } else if (components[0].find('n') != std::string::npos) {\n std::string multiplier {components[0].begin(), components[0].find_last_of('n')};\n multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier)));\n multiplicity_rules.push_back(std::bind1st(rule_more, 1));\n }\n }\n }\n\n\n protected:\n vrtype(std::string multiplicity):\n multiplicity {multiplicity}\n {\n populate_mult_rules();\n }\n\n vrtype(std::string multiplicity, std::initializer_list values):\n vrtype(multiplicity)\n {\n add(values);\n }\n\n \/**\n * @brief serialize serializes the current instance into a byte stream\n * @return serialized data\n *\/\n virtual std::vector serialize() = 0;\n\n \/**\n * @brief deserialize deserializes the raw byte data into a structured\n * representation.\n * @param data serialized data\n * @return reference to the instance which contains the data\n *\/\n virtual vrtype& deserialize(std::vector data) = 0;\n\n\n public:\n virtual ~vrtype() = 0;\n\n \/**\n * @brief is_sequence checks if the attribute can hold more than one value.\n * @return\n *\/\n bool is_sequence() const\n {\n return !multiplicity == \"0\" &&\n !multiplicity == \"1\";\n }\n\n \/**\n * @brief add adds all specified values to the attribute, if doing so\n * does not break multiplicity conditions.\n * @param values list of values to be added.\n *\/\n void add(std::initializer_list values)\n {\n if (!is_sequence()) {\n throw new std::runtime_error(\"can't add to a non-sequence!\");\n }\n if (!validate_multiplicity(values.size())) {\n throw new std::runtime_error(\"addition of \" + values.size() + \" elements would violate the multiplicity rule: \" + multiplicity);\n }\n std::copy(values.begin(), values.end(), std::back_inserter(value_sequence));\n value_sequence.push_back(element);\n }\n};\n\ntemplate \nvrtype::~vrtype()\n{\n}\n\n}\n\n}\n\n}\n\n#endif \/\/ VRTYPE_HPP\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ ValueSymbol.cpp\n\/\/ Base class for all value symbols\n\/\/\n\/\/ File is under the MIT license; see LICENSE for details\n\/\/------------------------------------------------------------------------------\n#include \"slang\/symbols\/ValueSymbol.h\"\n\n#include \"slang\/binding\/AssignmentExpressions.h\"\n#include \"slang\/binding\/Expression.h\"\n#include \"slang\/binding\/MiscExpressions.h\"\n#include \"slang\/binding\/SelectExpressions.h\"\n#include \"slang\/compilation\/Compilation.h\"\n#include \"slang\/diagnostics\/ExpressionsDiags.h\"\n#include \"slang\/symbols\/Scope.h\"\n#include \"slang\/symbols\/VariableSymbols.h\"\n#include \"slang\/syntax\/AllSyntax.h\"\n#include \"slang\/types\/NetType.h\"\n\nnamespace slang {\n\nValueSymbol::ValueSymbol(SymbolKind kind, string_view name, SourceLocation location,\n bitmask flags) :\n Symbol(kind, name, location),\n declaredType(*this, flags) {\n}\n\nvoid ValueSymbol::setFromDeclarator(const DeclaratorSyntax& decl) {\n declaredType.setFromDeclarator(decl);\n setSyntax(decl);\n}\n\nbool ValueSymbol::isKind(SymbolKind kind) {\n switch (kind) {\n case SymbolKind::Net:\n case SymbolKind::EnumValue:\n case SymbolKind::Parameter:\n case SymbolKind::PrimitivePort:\n case SymbolKind::ModportPort:\n case SymbolKind::Specparam:\n return true;\n default:\n return VariableSymbol::isKind(kind);\n }\n}\n\nValueSymbol::Driver::Driver(DriverKind kind, const Expression& longestStaticPrefix) :\n longestStaticPrefix(&longestStaticPrefix), kind(kind) {\n}\n\nstatic const Expression* nextPrefix(const Expression& expr) {\n switch (expr.kind) {\n case ExpressionKind::NamedValue:\n case ExpressionKind::HierarchicalValue:\n return nullptr;\n case ExpressionKind::ElementSelect:\n return &expr.as().value();\n case ExpressionKind::RangeSelect:\n return &expr.as().value();\n case ExpressionKind::MemberAccess:\n return &expr.as().value();\n default:\n THROW_UNREACHABLE;\n }\n}\n\nstatic bool prefixOverlaps(EvalContext& ctx, const Expression& left, const Expression& right) {\n \/\/ A named value here should always point to the same symbol,\n \/\/ so we only need to check if they have the same expression kind.\n if (ValueExpressionBase::isKind(left.kind) && ValueExpressionBase::isKind(right.kind))\n return true;\n\n auto getRange = [&ctx](const Expression& expr) -> optional {\n ConstantValue unused;\n if (expr.kind == ExpressionKind::ElementSelect)\n return expr.as().evalIndex(ctx, nullptr, unused);\n if (expr.kind == ExpressionKind::RangeSelect)\n return expr.as().evalRange(ctx, nullptr);\n if (expr.kind == ExpressionKind::MemberAccess)\n return expr.as().getSelectRange();\n return std::nullopt;\n };\n\n auto lrange = getRange(left);\n auto rrange = getRange(right);\n if (!lrange || !rrange)\n return false;\n\n return lrange->overlaps(*rrange);\n}\n\nbool ValueSymbol::Driver::overlaps(Compilation& compilation, const Driver& other) const {\n auto buildPath = [](const Expression* expr, SmallVector& path) {\n do {\n if (expr->kind == ExpressionKind::Conversion) {\n expr = &expr->as().operand();\n }\n else {\n path.append({ expr });\n expr = nextPrefix(*expr);\n }\n } while (expr);\n };\n\n SmallVectorSized ourPath;\n buildPath(longestStaticPrefix, ourPath);\n\n SmallVectorSized otherPath;\n buildPath(other.longestStaticPrefix, otherPath);\n\n EvalContext ctx(compilation);\n for (size_t i = ourPath.size(), j = otherPath.size(); i > 0 && j > 0; i--, j--) {\n auto ourElem = ourPath[i - 1];\n auto otherElem = otherPath[j - 1];\n if (!prefixOverlaps(ctx, *ourElem, *otherElem))\n return false;\n }\n\n return true;\n}\n\nvoid ValueSymbol::addDriver(DriverKind driverKind, const Expression& longestStaticPrefix) const {\n auto scope = getParentScope();\n ASSERT(scope);\n\n auto& comp = scope->getCompilation();\n auto driver = comp.emplace(driverKind, longestStaticPrefix);\n if (!firstDriver) {\n auto makeRef = [&]() -> const Expression& {\n BindContext bindContext(*scope, LookupLocation::min);\n SourceRange range = { location, location + name.length() };\n return ValueExpressionBase::fromSymbol(bindContext, *this, \/* isHierarchical *\/ false,\n range);\n };\n\n \/\/ The first time we add a driver, check whether there is also an\n \/\/ initializer expression that should count as a driver as well.\n switch (kind) {\n case SymbolKind::Net:\n if (auto init = getInitializer())\n firstDriver = comp.emplace(DriverKind::Continuous, makeRef());\n break;\n case SymbolKind::Variable:\n case SymbolKind::ClassProperty:\n case SymbolKind::Field:\n if (as().lifetime == VariableLifetime::Static) {\n if (auto init = getInitializer())\n firstDriver = comp.emplace(DriverKind::Procedural, makeRef());\n }\n break;\n default:\n break;\n }\n\n if (!firstDriver) {\n firstDriver = driver;\n return;\n }\n }\n\n const bool checkOverlap =\n (VariableSymbol::isKind(kind) &&\n as().lifetime == VariableLifetime::Static) ||\n (kind == SymbolKind::Net && as().netType.netKind == NetType::UWire);\n\n \/\/ Walk the list of drivers to the end and add this one there.\n \/\/ Along the way, check that the driver is valid given the ones that already exist.\n auto curr = firstDriver;\n while (true) {\n \/\/ Variables can't be driven by multiple continuous assignments or\n \/\/ a mix of continuous and procedural assignments.\n if (checkOverlap &&\n (driverKind == DriverKind::Continuous || curr->kind == DriverKind::Continuous) &&\n curr->overlaps(comp, *driver)) {\n\n auto currRange = curr->longestStaticPrefix->sourceRange;\n auto driverRange = driver->longestStaticPrefix->sourceRange;\n auto code =\n kind == SymbolKind::Net ? diag::MultipleUWireDrivers\n : (driverKind == DriverKind::Continuous && curr->kind == DriverKind::Continuous)\n ? diag::MultipleContAssigns\n : diag::MixedVarAssigns;\n\n auto& diag = scope->addDiag(code, driverRange);\n diag << name;\n diag.addNote(diag::NoteAssignedHere, currRange.start()) << currRange;\n return;\n }\n\n if (!curr->next) {\n curr->next = driver;\n return;\n }\n\n curr = curr->next;\n }\n}\n\n} \/\/ namespace slang\nFix warning about unused variable\/\/------------------------------------------------------------------------------\n\/\/ ValueSymbol.cpp\n\/\/ Base class for all value symbols\n\/\/\n\/\/ File is under the MIT license; see LICENSE for details\n\/\/------------------------------------------------------------------------------\n#include \"slang\/symbols\/ValueSymbol.h\"\n\n#include \"slang\/binding\/AssignmentExpressions.h\"\n#include \"slang\/binding\/Expression.h\"\n#include \"slang\/binding\/MiscExpressions.h\"\n#include \"slang\/binding\/SelectExpressions.h\"\n#include \"slang\/compilation\/Compilation.h\"\n#include \"slang\/diagnostics\/ExpressionsDiags.h\"\n#include \"slang\/symbols\/Scope.h\"\n#include \"slang\/symbols\/VariableSymbols.h\"\n#include \"slang\/syntax\/AllSyntax.h\"\n#include \"slang\/types\/NetType.h\"\n\nnamespace slang {\n\nValueSymbol::ValueSymbol(SymbolKind kind, string_view name, SourceLocation location,\n bitmask flags) :\n Symbol(kind, name, location),\n declaredType(*this, flags) {\n}\n\nvoid ValueSymbol::setFromDeclarator(const DeclaratorSyntax& decl) {\n declaredType.setFromDeclarator(decl);\n setSyntax(decl);\n}\n\nbool ValueSymbol::isKind(SymbolKind kind) {\n switch (kind) {\n case SymbolKind::Net:\n case SymbolKind::EnumValue:\n case SymbolKind::Parameter:\n case SymbolKind::PrimitivePort:\n case SymbolKind::ModportPort:\n case SymbolKind::Specparam:\n return true;\n default:\n return VariableSymbol::isKind(kind);\n }\n}\n\nValueSymbol::Driver::Driver(DriverKind kind, const Expression& longestStaticPrefix) :\n longestStaticPrefix(&longestStaticPrefix), kind(kind) {\n}\n\nstatic const Expression* nextPrefix(const Expression& expr) {\n switch (expr.kind) {\n case ExpressionKind::NamedValue:\n case ExpressionKind::HierarchicalValue:\n return nullptr;\n case ExpressionKind::ElementSelect:\n return &expr.as().value();\n case ExpressionKind::RangeSelect:\n return &expr.as().value();\n case ExpressionKind::MemberAccess:\n return &expr.as().value();\n default:\n THROW_UNREACHABLE;\n }\n}\n\nstatic bool prefixOverlaps(EvalContext& ctx, const Expression& left, const Expression& right) {\n \/\/ A named value here should always point to the same symbol,\n \/\/ so we only need to check if they have the same expression kind.\n if (ValueExpressionBase::isKind(left.kind) && ValueExpressionBase::isKind(right.kind))\n return true;\n\n auto getRange = [&ctx](const Expression& expr) -> optional {\n ConstantValue unused;\n if (expr.kind == ExpressionKind::ElementSelect)\n return expr.as().evalIndex(ctx, nullptr, unused);\n if (expr.kind == ExpressionKind::RangeSelect)\n return expr.as().evalRange(ctx, nullptr);\n if (expr.kind == ExpressionKind::MemberAccess)\n return expr.as().getSelectRange();\n return std::nullopt;\n };\n\n auto lrange = getRange(left);\n auto rrange = getRange(right);\n if (!lrange || !rrange)\n return false;\n\n return lrange->overlaps(*rrange);\n}\n\nbool ValueSymbol::Driver::overlaps(Compilation& compilation, const Driver& other) const {\n auto buildPath = [](const Expression* expr, SmallVector& path) {\n do {\n if (expr->kind == ExpressionKind::Conversion) {\n expr = &expr->as().operand();\n }\n else {\n path.append({ expr });\n expr = nextPrefix(*expr);\n }\n } while (expr);\n };\n\n SmallVectorSized ourPath;\n buildPath(longestStaticPrefix, ourPath);\n\n SmallVectorSized otherPath;\n buildPath(other.longestStaticPrefix, otherPath);\n\n EvalContext ctx(compilation);\n for (size_t i = ourPath.size(), j = otherPath.size(); i > 0 && j > 0; i--, j--) {\n auto ourElem = ourPath[i - 1];\n auto otherElem = otherPath[j - 1];\n if (!prefixOverlaps(ctx, *ourElem, *otherElem))\n return false;\n }\n\n return true;\n}\n\nvoid ValueSymbol::addDriver(DriverKind driverKind, const Expression& longestStaticPrefix) const {\n auto scope = getParentScope();\n ASSERT(scope);\n\n auto& comp = scope->getCompilation();\n auto driver = comp.emplace(driverKind, longestStaticPrefix);\n if (!firstDriver) {\n auto makeRef = [&]() -> const Expression& {\n BindContext bindContext(*scope, LookupLocation::min);\n SourceRange range = { location, location + name.length() };\n return ValueExpressionBase::fromSymbol(bindContext, *this, \/* isHierarchical *\/ false,\n range);\n };\n\n \/\/ The first time we add a driver, check whether there is also an\n \/\/ initializer expression that should count as a driver as well.\n switch (kind) {\n case SymbolKind::Net:\n if (getInitializer())\n firstDriver = comp.emplace(DriverKind::Continuous, makeRef());\n break;\n case SymbolKind::Variable:\n case SymbolKind::ClassProperty:\n case SymbolKind::Field:\n if (as().lifetime == VariableLifetime::Static) {\n if (getInitializer())\n firstDriver = comp.emplace(DriverKind::Procedural, makeRef());\n }\n break;\n default:\n break;\n }\n\n if (!firstDriver) {\n firstDriver = driver;\n return;\n }\n }\n\n const bool checkOverlap =\n (VariableSymbol::isKind(kind) &&\n as().lifetime == VariableLifetime::Static) ||\n (kind == SymbolKind::Net && as().netType.netKind == NetType::UWire);\n\n \/\/ Walk the list of drivers to the end and add this one there.\n \/\/ Along the way, check that the driver is valid given the ones that already exist.\n auto curr = firstDriver;\n while (true) {\n \/\/ Variables can't be driven by multiple continuous assignments or\n \/\/ a mix of continuous and procedural assignments.\n if (checkOverlap &&\n (driverKind == DriverKind::Continuous || curr->kind == DriverKind::Continuous) &&\n curr->overlaps(comp, *driver)) {\n\n auto currRange = curr->longestStaticPrefix->sourceRange;\n auto driverRange = driver->longestStaticPrefix->sourceRange;\n auto code =\n kind == SymbolKind::Net ? diag::MultipleUWireDrivers\n : (driverKind == DriverKind::Continuous && curr->kind == DriverKind::Continuous)\n ? diag::MultipleContAssigns\n : diag::MixedVarAssigns;\n\n auto& diag = scope->addDiag(code, driverRange);\n diag << name;\n diag.addNote(diag::NoteAssignedHere, currRange.start()) << currRange;\n return;\n }\n\n if (!curr->next) {\n curr->next = driver;\n return;\n }\n\n curr = curr->next;\n }\n}\n\n} \/\/ namespace slang\n<|endoftext|>"} {"text":"\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2016-2017 Simon Ninon \n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \n#include \n#include \n\n#include \n\nnamespace tacopie {\n\n\/\/!\n\/\/! ctor & dtor\n\/\/!\n\ntcp_server::tcp_server(void)\n: m_io_service(get_default_io_service())\n, m_on_new_connection_callback(nullptr) { __TACOPIE_LOG(debug, \"create tcp_server\"); }\n\ntcp_server::~tcp_server(void) {\n __TACOPIE_LOG(debug, \"destroy tcp_server\");\n stop();\n}\n\n\/\/!\n\/\/! start & stop the tcp server\n\/\/!\n\nvoid\ntcp_server::start(const std::string& host, std::uint32_t port, const on_new_connection_callback_t& callback) {\n if (is_running()) { __TACOPIE_THROW(warn, \"tcp_server is already running\"); }\n\n m_socket.bind(host, port);\n m_socket.listen(__TACOPIE_CONNECTION_QUEUE_SIZE);\n\n m_io_service->track(m_socket);\n m_io_service->set_rd_callback(m_socket, std::bind(&tcp_server::on_read_available, this, std::placeholders::_1));\n m_on_new_connection_callback = callback;\n\n m_is_running = true;\n\n __TACOPIE_LOG(info, \"tcp_server running\");\n}\n\nvoid\ntcp_server::stop(bool wait_for_removal, bool recursive_wait_for_removal) {\n if (!is_running()) { return; }\n\n m_is_running = false;\n\n m_io_service->untrack(m_socket);\n if (wait_for_removal) { m_io_service->wait_for_removal(m_socket); }\n m_socket.close();\n\n std::lock_guard lock(m_clients_mtx);\n for (auto& client : m_clients) {\n client->disconnect(recursive_wait_for_removal && wait_for_removal);\n }\n m_clients.clear();\n\n __TACOPIE_LOG(info, \"tcp_server stopped\");\n}\n\n\/\/!\n\/\/! io service read callback\n\/\/!\n\nvoid\ntcp_server::on_read_available(fd_t) {\n try {\n __TACOPIE_LOG(info, \"tcp_server received new connection\");\n\n auto client = std::make_shared(m_socket.accept());\n\n if (!m_on_new_connection_callback || m_on_new_connection_callback(client)) {\n __TACOPIE_LOG(info, \"tcp_server accepted new connection\");\n\n client->set_on_disconnection_handler(std::bind(&tcp_server::on_client_disconnected, this, client));\n m_clients.push_back(client);\n }\n else {\n __TACOPIE_LOG(info, \"tcp_server dismissed new connection\");\n }\n }\n catch (const tacopie::tacopie_error&) {\n __TACOPIE_LOG(warn, \"accept operation failure\");\n stop();\n }\n}\n\n\/\/!\n\/\/! client disconnected\n\/\/!\n\nvoid\ntcp_server::on_client_disconnected(const std::shared_ptr& client) {\n \/\/! If we are not running the server\n \/\/! Then it means that this function is called by tcp_client::disconnect() at the destruction of all clients\n if (!is_running()) { return; }\n\n __TACOPIE_LOG(debug, \"handle server's client disconnection\");\n\n std::lock_guard lock(m_clients_mtx);\n auto it = std::find(m_clients.begin(), m_clients.end(), client);\n\n if (it != m_clients.end()) { m_clients.erase(it); }\n}\n\n\/\/!\n\/\/! returns whether the server is currently running or not\n\/\/!\n\nbool\ntcp_server::is_running(void) const {\n return m_is_running;\n}\n\n\/\/!\n\/\/! get socket\n\/\/!\n\ntcp_socket&\ntcp_server::get_socket(void) {\n return m_socket;\n}\n\nconst tcp_socket&\ntcp_server::get_socket(void) const {\n return m_socket;\n}\n\n\/\/!\n\/\/! get client sockets\n\/\/!\n\nconst std::list>&\ntcp_server::get_clients(void) const {\n return m_clients;\n}\n\n\/\/!\n\/\/! comparison operator\n\/\/!\nbool\ntcp_server::operator==(const tcp_server& rhs) const {\n return m_socket == rhs.m_socket;\n}\n\nbool\ntcp_server::operator!=(const tcp_server& rhs) const {\n return !operator==(rhs);\n}\n\n} \/\/! tacopie\nchange behavior of on_new_connection_handler. Returning true means connection is handled by tcp_client wrapper and nothing will be done by tcp_server. Returning false means connection is handled by tcp_server, will be stored in an internal list and tcp_client disconection_handler overriden.\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2016-2017 Simon Ninon \n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \n#include \n#include \n\n#include \n\nnamespace tacopie {\n\n\/\/!\n\/\/! ctor & dtor\n\/\/!\n\ntcp_server::tcp_server(void)\n: m_io_service(get_default_io_service())\n, m_on_new_connection_callback(nullptr) { __TACOPIE_LOG(debug, \"create tcp_server\"); }\n\ntcp_server::~tcp_server(void) {\n __TACOPIE_LOG(debug, \"destroy tcp_server\");\n stop();\n}\n\n\/\/!\n\/\/! start & stop the tcp server\n\/\/!\n\nvoid\ntcp_server::start(const std::string& host, std::uint32_t port, const on_new_connection_callback_t& callback) {\n if (is_running()) { __TACOPIE_THROW(warn, \"tcp_server is already running\"); }\n\n m_socket.bind(host, port);\n m_socket.listen(__TACOPIE_CONNECTION_QUEUE_SIZE);\n\n m_io_service->track(m_socket);\n m_io_service->set_rd_callback(m_socket, std::bind(&tcp_server::on_read_available, this, std::placeholders::_1));\n m_on_new_connection_callback = callback;\n\n m_is_running = true;\n\n __TACOPIE_LOG(info, \"tcp_server running\");\n}\n\nvoid\ntcp_server::stop(bool wait_for_removal, bool recursive_wait_for_removal) {\n if (!is_running()) { return; }\n\n m_is_running = false;\n\n m_io_service->untrack(m_socket);\n if (wait_for_removal) { m_io_service->wait_for_removal(m_socket); }\n m_socket.close();\n\n std::lock_guard lock(m_clients_mtx);\n for (auto& client : m_clients) {\n client->disconnect(recursive_wait_for_removal && wait_for_removal);\n }\n m_clients.clear();\n\n __TACOPIE_LOG(info, \"tcp_server stopped\");\n}\n\n\/\/!\n\/\/! io service read callback\n\/\/!\n\nvoid\ntcp_server::on_read_available(fd_t) {\n try {\n __TACOPIE_LOG(info, \"tcp_server received new connection\");\n\n auto client = std::make_shared(m_socket.accept());\n\n if (!m_on_new_connection_callback || !m_on_new_connection_callback(client)) {\n __TACOPIE_LOG(info, \"connection handling delegated to tcp_server\");\n\n client->set_on_disconnection_handler(std::bind(&tcp_server::on_client_disconnected, this, client));\n m_clients.push_back(client);\n }\n else {\n __TACOPIE_LOG(info, \"connection handled by tcp_server wrapper\");\n }\n }\n catch (const tacopie::tacopie_error&) {\n __TACOPIE_LOG(warn, \"accept operation failure\");\n stop();\n }\n}\n\n\/\/!\n\/\/! client disconnected\n\/\/!\n\nvoid\ntcp_server::on_client_disconnected(const std::shared_ptr& client) {\n \/\/! If we are not running the server\n \/\/! Then it means that this function is called by tcp_client::disconnect() at the destruction of all clients\n if (!is_running()) { return; }\n\n __TACOPIE_LOG(debug, \"handle server's client disconnection\");\n\n std::lock_guard lock(m_clients_mtx);\n auto it = std::find(m_clients.begin(), m_clients.end(), client);\n\n if (it != m_clients.end()) { m_clients.erase(it); }\n}\n\n\/\/!\n\/\/! returns whether the server is currently running or not\n\/\/!\n\nbool\ntcp_server::is_running(void) const {\n return m_is_running;\n}\n\n\/\/!\n\/\/! get socket\n\/\/!\n\ntcp_socket&\ntcp_server::get_socket(void) {\n return m_socket;\n}\n\nconst tcp_socket&\ntcp_server::get_socket(void) const {\n return m_socket;\n}\n\n\/\/!\n\/\/! get client sockets\n\/\/!\n\nconst std::list>&\ntcp_server::get_clients(void) const {\n return m_clients;\n}\n\n\/\/!\n\/\/! comparison operator\n\/\/!\nbool\ntcp_server::operator==(const tcp_server& rhs) const {\n return m_socket == rhs.m_socket;\n}\n\nbool\ntcp_server::operator!=(const tcp_server& rhs) const {\n return !operator==(rhs);\n}\n\n} \/\/ namespace tacopie\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016-2017 deepstreamHub 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#define BOOST_TEST_MAIN\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n\n\/\/ Remarks:\n\/\/ - Do not use BOOST_CHECK_EQUAL() to compare const char* variables as\n\/\/ Boost.Test attempts to be smart by calling std::strcmp()\n\/\/ [with Boost 1.53, see boost\/test\/impl\/test_tools.ipp:383, equal_impl()].\n\/\/ In this file, const char* variables do not always reference null-terminated\n\/\/ strings, e.g., when using std::vector::data(). If this happens,\n\/\/ Valgrind may detect invalid reads.\n\n\nnamespace deepstream {\nnamespace parser\n{\n\nBOOST_AUTO_TEST_CASE(empty_string)\n{\n\tdeepstream_parser_state state(\"\", 0);\n\n\tint token = state.handle_token(TOKEN_EOF, \"\\0\", 1);\n\tBOOST_CHECK_EQUAL( token, TOKEN_EOF );\n\n\tBOOST_CHECK( state.tokenizing_header_ );\n\tBOOST_CHECK_EQUAL( state.offset_, 1 );\n\tBOOST_CHECK( state.messages_.empty() );\n\tBOOST_CHECK( state.errors_.empty() );\n}\n\n\nBOOST_AUTO_TEST_CASE(simple)\n{\n\tconst auto input = Message::from_human_readable(\"A|A+\");\n\tconst auto copy(input);\n\tconst char* matches[] = { &input[0], &input[3], \"\" };\n\tstd::size_t sizes[] = { 3, 1, 1 };\n\n\tconst deepstream_token tokens[] = {\n\t\tTOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF\n\t};\n\n\tconst std::size_t num_tokens = sizeof(tokens) \/ sizeof(tokens[0]);\n\n\n\tdeepstream_parser_state state( ©[0], copy.size() );\n\n\tfor(std::size_t i = 0; i < num_tokens; ++i)\n\t{\n\t\tint ret = state.handle_token(tokens[i], matches[i], sizes[i]);\n\n\t\tBOOST_CHECK_EQUAL( ret, tokens[i] );\n\n\t\tBOOST_CHECK_EQUAL( state.messages_.size(), 1 );\n\t\tBOOST_CHECK( state.errors_.empty() );\n\n\t\tstd::size_t offset = std::accumulate( sizes, sizes+i+1, 0 );\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset );\n\t}\n\n\tMessage& msg = state.messages_.front();\n\n\tBOOST_CHECK( msg.base_ == copy.data() );\n\tBOOST_CHECK_EQUAL( msg.offset_, 0 );\n\tBOOST_CHECK_EQUAL( msg.size_, input.size() );\n\n\tBOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH );\n\tBOOST_CHECK_EQUAL( msg.action(), Action::REQUEST );\n\tBOOST_CHECK( msg.is_ack() );\n\n\tBOOST_CHECK( msg.arguments_.empty() );\n}\n\n\nBOOST_AUTO_TEST_CASE(concatenated_messages)\n{\n\tconst char STRING[] = \"E|L|listen+E|S|event+\";\n\n\tconst auto input = Message::from_human_readable(STRING);\n\tconst auto copy(input);\n\n\tconst deepstream_token tokens[] = {\n\t\tTOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR,\n\t\tTOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR,\n\t\tTOKEN_EOF\n\t};\n\n\tconst std::size_t num_tokens = sizeof(tokens) \/ sizeof(tokens[0]);\n\n\tconst std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 };\n\tconst char* matches[num_tokens] = {\n\t\t&input[ 0], &input[3], &input[10],\n\t\t&input[11], &input[14], &input[20],\n\t\t\"\"\n\t};\n\n\n\tdeepstream_parser_state state( ©[0], copy.size() );\n\n\tfor(std::size_t i = 0; i < num_tokens; ++i)\n\t{\n\t\tstd::size_t offset = std::accumulate( matchlens, matchlens+i, 0 );\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset );\n\n\t\tint ret = state.handle_token(tokens[i], matches[i], matchlens[i]);\n\n\t\tBOOST_CHECK_EQUAL( ret, tokens[i] );\n\n\t\tBOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 );\n\t\tBOOST_CHECK( state.errors_.empty() );\n\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] );\n\t}\n\n\tfor(const Message& msg : state.messages_)\n\t{\n\t\tBOOST_CHECK( msg.base_ == copy.data() );\n\n\t\tBOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT );\n\t\tBOOST_CHECK( !msg.is_ack() );\n\n\t\tBOOST_CHECK_EQUAL( msg.arguments_.size(), 1 );\n\t}\n\n\tBOOST_CHECK_EQUAL( state.messages_.size(), 2 );\n\n\tconst Message& msg_f = state.messages_.front();\n\tBOOST_CHECK_EQUAL( msg_f.offset(), 0 );\n\tBOOST_CHECK_EQUAL( msg_f.size(), 11 );\n\tBOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT );\n\tBOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN );\n\n\tconst Location& arg_f = msg_f.arguments_.front();\n\n\tBOOST_CHECK_EQUAL( arg_f.offset_, 4 );\n\tBOOST_CHECK_EQUAL( arg_f.length_, 6 );\n\tBOOST_CHECK( !strncmp(&input[arg_f.offset_], \"listen\", arg_f.length_) );\n\n\n\tconst Message& msg_b = state.messages_.back();\n\tBOOST_CHECK_EQUAL( msg_b.offset(), 11 );\n\tBOOST_CHECK_EQUAL( msg_b.size(), 10 );\n\tBOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT );\n\tBOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE );\n\n\tconst Location& arg_b = msg_b.arguments_.front();\n\n\tBOOST_CHECK_EQUAL( arg_b.offset_, 15 );\n\tBOOST_CHECK_EQUAL( arg_b.length_, 5 );\n\tBOOST_CHECK( !strncmp(&input[arg_b.offset_], \"event\", arg_b.length_) );\n}\n\n\n\nBOOST_AUTO_TEST_CASE(invalid_number_of_arguments)\n{\n\tconst char STRING[] = \"E|A|L|l+\";\n\n\tconst auto input = Message::from_human_readable(STRING);\n\tconst auto copy(input);\n\n\tconst deepstream_token TOKENS[] = {\n\t\tTOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF\n\t};\n\n\tconst std::size_t NUM_TOKENS = sizeof(TOKENS) \/ sizeof(TOKENS[0]);\n\n\tconst std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 };\n\tconst char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], \"\" };\n\n\n\tdeepstream_parser_state state( ©[0], copy.size() );\n\n\tfor(std::size_t i = 0; i < NUM_TOKENS; ++i)\n\t{\n\t\tstd::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 );\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset );\n\n\t\tint ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]);\n\n\t\tBOOST_CHECK_EQUAL( ret, TOKENS[i] );\n\n\t\tBOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 );\n\t\tBOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 );\n\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] );\n\t}\n\n\n\tconst Error& e = state.errors_.front();\n\n\tBOOST_CHECK_EQUAL( e.location_.offset_, 0 );\n\tBOOST_CHECK_EQUAL( e.location_.length_, 8 );\n\tBOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS );\n}\n\n}\n}\nParser: more strict tests\/*\n * Copyright 2016-2017 deepstreamHub 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#define BOOST_TEST_MAIN\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n\n\/\/ Remarks:\n\/\/ - Do not use BOOST_CHECK_EQUAL() to compare const char* variables as\n\/\/ Boost.Test attempts to be smart by calling std::strcmp()\n\/\/ [with Boost 1.53, see boost\/test\/impl\/test_tools.ipp:383, equal_impl()].\n\/\/ In this file, const char* variables do not always reference null-terminated\n\/\/ strings, e.g., when using std::vector::data(). If this happens,\n\/\/ Valgrind may detect invalid reads.\n\n\nnamespace deepstream {\nnamespace parser\n{\n\nBOOST_AUTO_TEST_CASE(empty_string)\n{\n\tdeepstream_parser_state state(\"\", 0);\n\n\tint token = state.handle_token(TOKEN_EOF, \"\\0\", 1);\n\tBOOST_CHECK_EQUAL( token, TOKEN_EOF );\n\n\tBOOST_CHECK( state.tokenizing_header_ );\n\tBOOST_CHECK_EQUAL( state.offset_, 1 );\n\tBOOST_CHECK( state.messages_.empty() );\n\tBOOST_CHECK( state.errors_.empty() );\n}\n\n\nBOOST_AUTO_TEST_CASE(simple)\n{\n\tconst auto input = Message::from_human_readable(\"A|A+\");\n\tconst auto copy(input);\n\tconst char* matches[] = { &input[0], &input[3], \"\" };\n\tstd::size_t sizes[] = { 3, 1, 1 };\n\n\tconst deepstream_token tokens[] = {\n\t\tTOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF\n\t};\n\n\tconst std::size_t num_tokens = sizeof(tokens) \/ sizeof(tokens[0]);\n\n\n\tdeepstream_parser_state state( ©[0], copy.size() );\n\n\tfor(std::size_t i = 0; i < num_tokens; ++i)\n\t{\n\t\tbool tokenizing_header = state.tokenizing_header_;\n\t\tBOOST_CHECK( (i==0||i==2) ? tokenizing_header : !tokenizing_header );\n\n\t\tint ret = state.handle_token(tokens[i], matches[i], sizes[i]);\n\n\t\tBOOST_CHECK_EQUAL( ret, tokens[i] );\n\n\t\tBOOST_CHECK_EQUAL( state.messages_.size(), 1 );\n\t\tBOOST_CHECK( state.errors_.empty() );\n\n\t\tstd::size_t offset = std::accumulate( sizes, sizes+i+1, 0 );\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset );\n\t}\n\n\tMessage& msg = state.messages_.front();\n\n\tBOOST_CHECK( msg.base_ == copy.data() );\n\tBOOST_CHECK_EQUAL( msg.offset_, 0 );\n\tBOOST_CHECK_EQUAL( msg.size_, input.size() );\n\n\tBOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH );\n\tBOOST_CHECK_EQUAL( msg.action(), Action::REQUEST );\n\tBOOST_CHECK( msg.is_ack() );\n\n\tBOOST_CHECK( msg.arguments_.empty() );\n}\n\n\nBOOST_AUTO_TEST_CASE(concatenated_messages)\n{\n\tconst char STRING[] = \"E|L|listen+E|S|event+\";\n\n\tconst auto input = Message::from_human_readable(STRING);\n\tconst auto copy(input);\n\n\tconst deepstream_token tokens[] = {\n\t\tTOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR,\n\t\tTOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR,\n\t\tTOKEN_EOF\n\t};\n\n\tconst std::size_t num_tokens = sizeof(tokens) \/ sizeof(tokens[0]);\n\n\tconst std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 };\n\tconst char* matches[num_tokens] = {\n\t\t&input[ 0], &input[3], &input[10],\n\t\t&input[11], &input[14], &input[20],\n\t\t\"\"\n\t};\n\n\n\tdeepstream_parser_state state( ©[0], copy.size() );\n\n\tfor(std::size_t i = 0; i < num_tokens; ++i)\n\t{\n\t\tBOOST_CHECK( (i==0||i==3||i==6) ?\n\t\t\tstate.tokenizing_header_ :\n\t\t\t!state.tokenizing_header_\n\t\t);\n\n\t\tstd::size_t offset = std::accumulate( matchlens, matchlens+i, 0 );\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset );\n\n\t\tint ret = state.handle_token(tokens[i], matches[i], matchlens[i]);\n\n\t\tBOOST_CHECK_EQUAL( ret, tokens[i] );\n\n\t\tBOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 );\n\t\tBOOST_CHECK( state.errors_.empty() );\n\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] );\n\t}\n\n\tBOOST_CHECK( state.tokenizing_header_ );\n\n\tfor(const Message& msg : state.messages_)\n\t{\n\t\tBOOST_CHECK( msg.base_ == copy.data() );\n\n\t\tBOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT );\n\t\tBOOST_CHECK( !msg.is_ack() );\n\n\t\tBOOST_CHECK_EQUAL( msg.arguments_.size(), 1 );\n\t}\n\n\tBOOST_CHECK_EQUAL( state.messages_.size(), 2 );\n\n\tconst Message& msg_f = state.messages_.front();\n\tBOOST_CHECK_EQUAL( msg_f.offset(), 0 );\n\tBOOST_CHECK_EQUAL( msg_f.size(), 11 );\n\tBOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT );\n\tBOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN );\n\n\tconst Location& arg_f = msg_f.arguments_.front();\n\n\tBOOST_CHECK_EQUAL( arg_f.offset_, 4 );\n\tBOOST_CHECK_EQUAL( arg_f.length_, 6 );\n\tBOOST_CHECK( !strncmp(&input[arg_f.offset_], \"listen\", arg_f.length_) );\n\n\n\tconst Message& msg_b = state.messages_.back();\n\tBOOST_CHECK_EQUAL( msg_b.offset(), 11 );\n\tBOOST_CHECK_EQUAL( msg_b.size(), 10 );\n\tBOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT );\n\tBOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE );\n\n\tconst Location& arg_b = msg_b.arguments_.front();\n\n\tBOOST_CHECK_EQUAL( arg_b.offset_, 15 );\n\tBOOST_CHECK_EQUAL( arg_b.length_, 5 );\n\tBOOST_CHECK( !strncmp(&input[arg_b.offset_], \"event\", arg_b.length_) );\n}\n\n\n\nBOOST_AUTO_TEST_CASE(invalid_number_of_arguments)\n{\n\tconst char STRING[] = \"E|A|L|l+\";\n\n\tconst auto input = Message::from_human_readable(STRING);\n\tconst auto copy(input);\n\n\tconst deepstream_token TOKENS[] = {\n\t\tTOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF\n\t};\n\n\tconst std::size_t NUM_TOKENS = sizeof(TOKENS) \/ sizeof(TOKENS[0]);\n\n\tconst std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 };\n\tconst char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], \"\" };\n\n\n\tdeepstream_parser_state state( ©[0], copy.size() );\n\n\tfor(std::size_t i = 0; i < NUM_TOKENS; ++i)\n\t{\n\t\tbool tokenizing_header = state.tokenizing_header_;\n\t\tBOOST_CHECK( (i==0||i==3) ? tokenizing_header : !tokenizing_header );\n\n\t\tstd::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 );\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset );\n\n\t\tint ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]);\n\n\t\tBOOST_CHECK_EQUAL( ret, TOKENS[i] );\n\n\t\tBOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 );\n\t\tBOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 );\n\n\t\tBOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] );\n\t}\n\n\n\tconst Error& e = state.errors_.front();\n\n\tBOOST_CHECK_EQUAL( e.location_.offset_, 0 );\n\tBOOST_CHECK_EQUAL( e.location_.length_, 8 );\n\tBOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS );\n}\n\n}\n}\n<|endoftext|>"} {"text":"#include \"lextrans.h\"\n\n#include \n\n#include \"filelib.h\"\n#include \"hg.h\"\n#include \"tdict.h\"\n#include \"grammar.h\"\n#include \"sentence_metadata.h\"\n\nusing namespace std;\n\nstruct LexicalTransImpl {\n LexicalTransImpl(const boost::program_options::variables_map& conf) :\n use_null(conf.count(\"lexcrf_use_null\") > 0),\n kXCAT(TD::Convert(\"X\")*-1),\n kNULL(TD::Convert(\"\")),\n kBINARY(new TRule(\"[X] ||| [X,1] [X,2] ||| [1] [2]\")),\n kGOAL_RULE(new TRule(\"[Goal] ||| [X,1] ||| [1]\")) {\n vector gfiles = conf[\"grammar\"].as >();\n assert(gfiles.size() == 1);\n ReadFile rf(gfiles.front());\n TextGrammar *tg = new TextGrammar;\n grammar.reset(tg);\n istream* in = rf.stream();\n int lc = 0;\n bool flag = false;\n while(*in) {\n string line;\n getline(*in, line);\n if (line.empty()) continue;\n ++lc;\n TRulePtr r(TRule::CreateRulePhrasetable(line));\n tg->AddRule(r);\n if (lc % 50000 == 0) { cerr << '.'; flag = true; }\n if (lc % 2000000 == 0) { cerr << \" [\" << lc << \"]\\n\"; flag = false; }\n }\n if (flag) cerr << endl;\n cerr << \"Loaded \" << lc << \" rules\\n\";\n }\n\n void BuildTrellis(const Lattice& lattice, const SentenceMetadata& smeta, Hypergraph* forest) {\n const int e_len = smeta.GetTargetLength();\n assert(e_len > 0);\n const int f_len = lattice.size();\n \/\/ hack to tell the feature function system how big the sentence pair is\n const int f_start = (use_null ? -1 : 0);\n int prev_node_id = -1;\n for (int i = 0; i < e_len; ++i) { \/\/ for each word in the *target*\n Hypergraph::Node* node = forest->AddNode(kXCAT);\n const int new_node_id = node->id_;\n for (int j = f_start; j < f_len; ++j) { \/\/ for each word in the source\n const WordID src_sym = (j < 0 ? kNULL : lattice[j][0].label);\n const GrammarIter* gi = grammar->GetRoot()->Extend(src_sym);\n if (!gi) {\n cerr << \"No translations found for: \" << TD::Convert(src_sym) << \"\\n\";\n abort();\n }\n const RuleBin* rb = gi->GetRules();\n assert(rb);\n for (int k = 0; k < rb->GetNumRules(); ++k) {\n TRulePtr rule = rb->GetIthRule(k);\n Hypergraph::Edge* edge = forest->AddEdge(rule, Hypergraph::TailNodeVector());\n edge->i_ = j;\n edge->j_ = j+1;\n edge->prev_i_ = i;\n edge->prev_j_ = i+1;\n edge->feature_values_ += edge->rule_->GetFeatureValues();\n forest->ConnectEdgeToHeadNode(edge->id_, new_node_id);\n }\n }\n if (prev_node_id >= 0) {\n const int comb_node_id = forest->AddNode(kXCAT)->id_;\n Hypergraph::TailNodeVector tail(2, prev_node_id);\n tail[1] = new_node_id;\n Hypergraph::Edge* edge = forest->AddEdge(kBINARY, tail);\n forest->ConnectEdgeToHeadNode(edge->id_, comb_node_id);\n prev_node_id = comb_node_id;\n } else {\n prev_node_id = new_node_id;\n }\n }\n Hypergraph::TailNodeVector tail(1, forest->nodes_.size() - 1);\n Hypergraph::Node* goal = forest->AddNode(TD::Convert(\"Goal\")*-1);\n Hypergraph::Edge* hg_edge = forest->AddEdge(kGOAL_RULE, tail);\n forest->ConnectEdgeToHeadNode(hg_edge, goal);\n }\n\n private:\n const bool use_null;\n const WordID kXCAT;\n const WordID kNULL;\n const TRulePtr kBINARY;\n const TRulePtr kGOAL_RULE;\n GrammarPtr grammar;\n};\n\nLexicalTrans::LexicalTrans(const boost::program_options::variables_map& conf) :\n pimpl_(new LexicalTransImpl(conf)) {}\n\nbool LexicalTrans::TranslateImpl(const string& input,\n SentenceMetadata* smeta,\n const vector& weights,\n Hypergraph* forest) {\n Lattice& lattice = smeta->src_lattice_;\n LatticeTools::ConvertTextOrPLF(input, &lattice);\n if (!lattice.IsSentence()) {\n \/\/ lexical models make independence assumptions\n \/\/ that don't work with lattices or conf nets\n cerr << \"LexicalTrans: cannot deal with lattice source input!\\n\";\n abort();\n }\n smeta->SetSourceLength(lattice.size());\n pimpl_->BuildTrellis(lattice, *smeta, forest);\n forest->is_linear_chain_ = true;\n forest->Reweight(weights);\n return true;\n}\n\nfix typo#include \"lextrans.h\"\n\n#include \n\n#include \"filelib.h\"\n#include \"hg.h\"\n#include \"tdict.h\"\n#include \"grammar.h\"\n#include \"sentence_metadata.h\"\n\nusing namespace std;\n\nstruct LexicalTransImpl {\n LexicalTransImpl(const boost::program_options::variables_map& conf) :\n use_null(conf.count(\"lextrans_use_null\") > 0),\n kXCAT(TD::Convert(\"X\")*-1),\n kNULL(TD::Convert(\"\")),\n kBINARY(new TRule(\"[X] ||| [X,1] [X,2] ||| [1] [2]\")),\n kGOAL_RULE(new TRule(\"[Goal] ||| [X,1] ||| [1]\")) {\n vector gfiles = conf[\"grammar\"].as >();\n assert(gfiles.size() == 1);\n ReadFile rf(gfiles.front());\n TextGrammar *tg = new TextGrammar;\n grammar.reset(tg);\n istream* in = rf.stream();\n int lc = 0;\n bool flag = false;\n while(*in) {\n string line;\n getline(*in, line);\n if (line.empty()) continue;\n ++lc;\n TRulePtr r(TRule::CreateRulePhrasetable(line));\n tg->AddRule(r);\n if (lc % 50000 == 0) { cerr << '.'; flag = true; }\n if (lc % 2000000 == 0) { cerr << \" [\" << lc << \"]\\n\"; flag = false; }\n }\n if (flag) cerr << endl;\n cerr << \"Loaded \" << lc << \" rules\\n\";\n }\n\n void BuildTrellis(const Lattice& lattice, const SentenceMetadata& smeta, Hypergraph* forest) {\n const int e_len = smeta.GetTargetLength();\n assert(e_len > 0);\n const int f_len = lattice.size();\n \/\/ hack to tell the feature function system how big the sentence pair is\n const int f_start = (use_null ? -1 : 0);\n int prev_node_id = -1;\n for (int i = 0; i < e_len; ++i) { \/\/ for each word in the *target*\n Hypergraph::Node* node = forest->AddNode(kXCAT);\n const int new_node_id = node->id_;\n for (int j = f_start; j < f_len; ++j) { \/\/ for each word in the source\n const WordID src_sym = (j < 0 ? kNULL : lattice[j][0].label);\n const GrammarIter* gi = grammar->GetRoot()->Extend(src_sym);\n if (!gi) {\n cerr << \"No translations found for: \" << TD::Convert(src_sym) << \"\\n\";\n abort();\n }\n const RuleBin* rb = gi->GetRules();\n assert(rb);\n for (int k = 0; k < rb->GetNumRules(); ++k) {\n TRulePtr rule = rb->GetIthRule(k);\n Hypergraph::Edge* edge = forest->AddEdge(rule, Hypergraph::TailNodeVector());\n edge->i_ = j;\n edge->j_ = j+1;\n edge->prev_i_ = i;\n edge->prev_j_ = i+1;\n edge->feature_values_ += edge->rule_->GetFeatureValues();\n forest->ConnectEdgeToHeadNode(edge->id_, new_node_id);\n }\n }\n if (prev_node_id >= 0) {\n const int comb_node_id = forest->AddNode(kXCAT)->id_;\n Hypergraph::TailNodeVector tail(2, prev_node_id);\n tail[1] = new_node_id;\n Hypergraph::Edge* edge = forest->AddEdge(kBINARY, tail);\n forest->ConnectEdgeToHeadNode(edge->id_, comb_node_id);\n prev_node_id = comb_node_id;\n } else {\n prev_node_id = new_node_id;\n }\n }\n Hypergraph::TailNodeVector tail(1, forest->nodes_.size() - 1);\n Hypergraph::Node* goal = forest->AddNode(TD::Convert(\"Goal\")*-1);\n Hypergraph::Edge* hg_edge = forest->AddEdge(kGOAL_RULE, tail);\n forest->ConnectEdgeToHeadNode(hg_edge, goal);\n }\n\n private:\n const bool use_null;\n const WordID kXCAT;\n const WordID kNULL;\n const TRulePtr kBINARY;\n const TRulePtr kGOAL_RULE;\n GrammarPtr grammar;\n};\n\nLexicalTrans::LexicalTrans(const boost::program_options::variables_map& conf) :\n pimpl_(new LexicalTransImpl(conf)) {}\n\nbool LexicalTrans::TranslateImpl(const string& input,\n SentenceMetadata* smeta,\n const vector& weights,\n Hypergraph* forest) {\n Lattice& lattice = smeta->src_lattice_;\n LatticeTools::ConvertTextOrPLF(input, &lattice);\n if (!lattice.IsSentence()) {\n \/\/ lexical models make independence assumptions\n \/\/ that don't work with lattices or conf nets\n cerr << \"LexicalTrans: cannot deal with lattice source input!\\n\";\n abort();\n }\n smeta->SetSourceLength(lattice.size());\n pimpl_->BuildTrellis(lattice, *smeta, forest);\n forest->is_linear_chain_ = true;\n forest->Reweight(weights);\n return true;\n}\n\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 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 \"main.h\"\n\ntemplate void verifySizeOf(const MatrixType&)\n{\n typedef typename MatrixType::Scalar Scalar;\n if (MatrixType::RowsAtCompileTime!=Dynamic && MatrixType::ColsAtCompileTime!=Dynamic)\n VERIFY(sizeof(MatrixType)==static_cast(sizeof(Scalar))*MatrixType::SizeAtCompileTime);\n else\n VERIFY(sizeof(MatrixType)==sizeof(Scalar*) + 2 * sizeof(typename MatrixType::Index));\n}\n\nvoid test_sizeof()\n{\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Matrix4d()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(MatrixXcf(3, 3)) );\n CALL_SUBTEST(verifySizeOf(MatrixXi(8, 12)) );\n CALL_SUBTEST(verifySizeOf(MatrixXcd(20, 20)) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n \n VERIFY(sizeof(std::complex) == 2*sizeof(float));\n VERIFY(sizeof(std::complex) == 2*sizeof(double));\n}\nfix icc warning #68\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 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 \"main.h\"\n\ntemplate void verifySizeOf(const MatrixType&)\n{\n typedef typename MatrixType::Scalar Scalar;\n if (MatrixType::RowsAtCompileTime!=Dynamic && MatrixType::ColsAtCompileTime!=Dynamic)\n VERIFY(sizeof(MatrixType)==sizeof(Scalar)*size_t(MatrixType::SizeAtCompileTime));\n else\n VERIFY(sizeof(MatrixType)==sizeof(Scalar*) + 2 * sizeof(typename MatrixType::Index));\n}\n\nvoid test_sizeof()\n{\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Matrix4d()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(MatrixXcf(3, 3)) );\n CALL_SUBTEST(verifySizeOf(MatrixXi(8, 12)) );\n CALL_SUBTEST(verifySizeOf(MatrixXcd(20, 20)) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n \n VERIFY(sizeof(std::complex) == 2*sizeof(float));\n VERIFY(sizeof(std::complex) == 2*sizeof(double));\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n\n#if defined(LUG_SYSTEM_ANDROID)\n #include \n#else\n #include \n#endif\n\nauto createKeyEnumMap() {\n std::unordered_map returnValue;\n\n returnValue[lug::Window::Keyboard::Key::Unknown] = \"Unknown\";\n\n \/\/ Basic keys\n returnValue[lug::Window::Keyboard::Key::A] = \"A\";\n returnValue[lug::Window::Keyboard::Key::B] = \"B\";\n returnValue[lug::Window::Keyboard::Key::C] = \"C\";\n returnValue[lug::Window::Keyboard::Key::D] = \"D\";\n returnValue[lug::Window::Keyboard::Key::E] = \"E\";\n returnValue[lug::Window::Keyboard::Key::F] = \"F\";\n returnValue[lug::Window::Keyboard::Key::G] = \"G\";\n returnValue[lug::Window::Keyboard::Key::H] = \"H\";\n returnValue[lug::Window::Keyboard::Key::I] = \"I\";\n returnValue[lug::Window::Keyboard::Key::J] = \"J\";\n returnValue[lug::Window::Keyboard::Key::K] = \"K\";\n returnValue[lug::Window::Keyboard::Key::L] = \"L\";\n returnValue[lug::Window::Keyboard::Key::M] = \"M\";\n returnValue[lug::Window::Keyboard::Key::N] = \"N\";\n returnValue[lug::Window::Keyboard::Key::O] = \"O\";\n returnValue[lug::Window::Keyboard::Key::P] = \"P\";\n returnValue[lug::Window::Keyboard::Key::Q] = \"Q\";\n returnValue[lug::Window::Keyboard::Key::R] = \"R\";\n returnValue[lug::Window::Keyboard::Key::S] = \"S\";\n returnValue[lug::Window::Keyboard::Key::T] = \"T\";\n returnValue[lug::Window::Keyboard::Key::U] = \"U\";\n returnValue[lug::Window::Keyboard::Key::V] = \"V\";\n returnValue[lug::Window::Keyboard::Key::W] = \"W\";\n returnValue[lug::Window::Keyboard::Key::X] = \"X\";\n returnValue[lug::Window::Keyboard::Key::Y] = \"Y\";\n returnValue[lug::Window::Keyboard::Key::Z] = \"Z\";\n\n returnValue[lug::Window::Keyboard::Key::Num0] = \"Num0\";\n returnValue[lug::Window::Keyboard::Key::Num1] = \"Num1\";\n returnValue[lug::Window::Keyboard::Key::Num2] = \"Num2\";\n returnValue[lug::Window::Keyboard::Key::Num3] = \"Num3\";\n returnValue[lug::Window::Keyboard::Key::Num4] = \"Num4\";\n returnValue[lug::Window::Keyboard::Key::Num5] = \"Num5\";\n returnValue[lug::Window::Keyboard::Key::Num6] = \"Num6\";\n returnValue[lug::Window::Keyboard::Key::Num7] = \"Num7\";\n returnValue[lug::Window::Keyboard::Key::Num8] = \"Num8\";\n returnValue[lug::Window::Keyboard::Key::Num9] = \"Num9\";\n\n \/\/ Modifiers\n returnValue[lug::Window::Keyboard::Key::LControl] = \"LControl\";\n returnValue[lug::Window::Keyboard::Key::LShift] = \"LShift\";\n returnValue[lug::Window::Keyboard::Key::LAlt] = \"LAlt\";\n returnValue[lug::Window::Keyboard::Key::LSystem] = \"LSystem\";\n returnValue[lug::Window::Keyboard::Key::RControl] = \"RControl\";\n returnValue[lug::Window::Keyboard::Key::RShift] = \"RShift\";\n returnValue[lug::Window::Keyboard::Key::RAlt] = \"RAlt\";\n returnValue[lug::Window::Keyboard::Key::RSystem] = \"RSystem\";\n\n \/\/ Advanced keys\n returnValue[lug::Window::Keyboard::Key::Menu] = \"Menu\";\n returnValue[lug::Window::Keyboard::Key::LBracket] = \"LBracket\";\n returnValue[lug::Window::Keyboard::Key::RBracket] = \"RBracket\";\n returnValue[lug::Window::Keyboard::Key::SemiColon] = \"SemiColon\";\n returnValue[lug::Window::Keyboard::Key::Comma] = \"Comma\";\n returnValue[lug::Window::Keyboard::Key::Period] = \"Period\";\n returnValue[lug::Window::Keyboard::Key::Quote] = \"Quote\";\n returnValue[lug::Window::Keyboard::Key::Slash] = \"Slash\";\n returnValue[lug::Window::Keyboard::Key::BackSlash] = \"BackSlash\";\n returnValue[lug::Window::Keyboard::Key::Tilde] = \"Tilde\";\n returnValue[lug::Window::Keyboard::Key::Equal] = \"Equal\";\n returnValue[lug::Window::Keyboard::Key::Dash] = \"Dash\";\n returnValue[lug::Window::Keyboard::Key::Space] = \"Space\";\n returnValue[lug::Window::Keyboard::Key::Return] = \"Return\";\n returnValue[lug::Window::Keyboard::Key::BackSpace] = \"BackSpace\";\n returnValue[lug::Window::Keyboard::Key::Tab] = \"Tab\";\n returnValue[lug::Window::Keyboard::Key::PageUp] = \"PageUp\";\n returnValue[lug::Window::Keyboard::Key::PageDown] = \"PageDown\";\n returnValue[lug::Window::Keyboard::Key::End] = \"End\";\n returnValue[lug::Window::Keyboard::Key::Home] = \"Home\";\n returnValue[lug::Window::Keyboard::Key::Insert] = \"Insert\";\n returnValue[lug::Window::Keyboard::Key::Delete] = \"Delete\";\n returnValue[lug::Window::Keyboard::Key::Add] = \"Add\";\n returnValue[lug::Window::Keyboard::Key::Subtract] = \"Subtract\";\n returnValue[lug::Window::Keyboard::Key::Multiply] = \"Multiply\";\n returnValue[lug::Window::Keyboard::Key::Divide] = \"Divide\";\n returnValue[lug::Window::Keyboard::Key::Left] = \"Left\";\n returnValue[lug::Window::Keyboard::Key::Right] = \"Right\";\n returnValue[lug::Window::Keyboard::Key::Up] = \"Up\";\n returnValue[lug::Window::Keyboard::Key::Down] = \"Down\";\n returnValue[lug::Window::Keyboard::Key::Pause] = \"Pause\";\n returnValue[lug::Window::Keyboard::Key::CapsLock] = \"CapsLock\";\n returnValue[lug::Window::Keyboard::Key::Escape] = \"Escape\";\n\n \/\/ AZERTY Specifics\n returnValue[lug::Window::Keyboard::Key::Twosuperior] = \"Twosuperior\";\n returnValue[lug::Window::Keyboard::Key::Ampersand] = \"Ampersand\";\n returnValue[lug::Window::Keyboard::Key::Eacute] = \"Eacute\";\n returnValue[lug::Window::Keyboard::Key::QuoteDouble] = \"QuoteDouble\";\n returnValue[lug::Window::Keyboard::Key::LParen] = \"LParen\";\n returnValue[lug::Window::Keyboard::Key::Egrave] = \"Egrave\";\n returnValue[lug::Window::Keyboard::Key::Underscore] = \"Underscore\";\n returnValue[lug::Window::Keyboard::Key::Ccedilla] = \"Ccedilla\";\n returnValue[lug::Window::Keyboard::Key::Agrave] = \"Agrave\";\n returnValue[lug::Window::Keyboard::Key::RParen] = \"RParen\";\n returnValue[lug::Window::Keyboard::Key::DeadCircumflex] = \"DeadCircumflex\";\n returnValue[lug::Window::Keyboard::Key::Ugrave] = \"Ugrave\";\n returnValue[lug::Window::Keyboard::Key::Asterisk] = \"Asterisk\";\n returnValue[lug::Window::Keyboard::Key::Dollar] = \"Dollar\";\n returnValue[lug::Window::Keyboard::Key::Colon] = \"Colon\";\n returnValue[lug::Window::Keyboard::Key::Exclam] = \"Exclam\";\n returnValue[lug::Window::Keyboard::Key::Less] = \"Less\";\n returnValue[lug::Window::Keyboard::Key::Greater] = \"Greater\";\n\n \/\/ Numpad\n returnValue[lug::Window::Keyboard::Key::Numpad0] = \"Numpad0\";\n returnValue[lug::Window::Keyboard::Key::Numpad1] = \"Numpad1\";\n returnValue[lug::Window::Keyboard::Key::Numpad2] = \"Numpad2\";\n returnValue[lug::Window::Keyboard::Key::Numpad3] = \"Numpad3\";\n returnValue[lug::Window::Keyboard::Key::Numpad4] = \"Numpad4\";\n returnValue[lug::Window::Keyboard::Key::Numpad5] = \"Numpad5\";\n returnValue[lug::Window::Keyboard::Key::Numpad6] = \"Numpad6\";\n returnValue[lug::Window::Keyboard::Key::Numpad7] = \"Numpad7\";\n returnValue[lug::Window::Keyboard::Key::Numpad8] = \"Numpad8\";\n returnValue[lug::Window::Keyboard::Key::Numpad9] = \"Numpad9\";\n\n \/\/ Function keys\n returnValue[lug::Window::Keyboard::Key::F1] = \"F1\";\n returnValue[lug::Window::Keyboard::Key::F2] = \"F2\";\n returnValue[lug::Window::Keyboard::Key::F3] = \"F3\";\n returnValue[lug::Window::Keyboard::Key::F4] = \"F4\";\n returnValue[lug::Window::Keyboard::Key::F5] = \"F5\";\n returnValue[lug::Window::Keyboard::Key::F6] = \"F6\";\n returnValue[lug::Window::Keyboard::Key::F7] = \"F7\";\n returnValue[lug::Window::Keyboard::Key::F8] = \"F8\";\n returnValue[lug::Window::Keyboard::Key::F9] = \"F9\";\n returnValue[lug::Window::Keyboard::Key::F10] = \"F10\";\n returnValue[lug::Window::Keyboard::Key::F11] = \"F11\";\n returnValue[lug::Window::Keyboard::Key::F12] = \"F12\";\n returnValue[lug::Window::Keyboard::Key::F13] = \"F13\";\n returnValue[lug::Window::Keyboard::Key::F14] = \"F14\";\n returnValue[lug::Window::Keyboard::Key::F15] = \"F15\";\n\n return returnValue;\n}\n\nauto createButtonEnumMap() {\n std::unordered_map returnValue;\n\n \/\/ Function keys\n returnValue[lug::Window::Mouse::Button::Left] = \"Left\";\n returnValue[lug::Window::Mouse::Button::Right] = \"Right\";\n returnValue[lug::Window::Mouse::Button::Middle] = \"Middle\";\n returnValue[lug::Window::Mouse::Button::XButton1] = \"XButton1\";\n returnValue[lug::Window::Mouse::Button::XButton2] = \"XButton2\";\n\n return returnValue;\n}\n\nint main() {\n auto window = lug::Window::Window::create({\n 800, \/\/ width\n 600, \/\/ height\n \"Default Window\", \/\/ title\n lug::Window::Style::Default \/\/ style\n });\n\n\n auto logger = lug::System::Logger::makeLogger(\"LugdunumSamples\");\n\n auto keyEnumMap = createKeyEnumMap();\n\n auto buttonEnumMap = createButtonEnumMap();\n\n#if defined(LUG_SYSTEM_ANDROID)\n auto handler = lug::System::Logger::makeHandler(\"LogCat\");\n#else\n auto handler = lug::System::Logger::makeHandler(\"Stdout\");\n#endif\n\n logger->addHandler(handler);\n LUG_LOG.addHandler(handler);\n\n if (!window) {\n logger->fatal(\"Window was not created\");\n return 1;\n }\n\n logger->info(\"Window was created successfully\");\n\n window->setKeyRepeat(true);\n\n \/\/ While window is open execute the following\n while (window->isOpen()) {\n lug::Window::Event event;\n while (window->pollEvent(event)) {\n logger->info(\"Event received: {}\", static_cast(event.type));\n\n if (event.type == lug::Window::Event::Type::Close) {\n logger->info(\"Closing the app\");\n window->close();\n }\n\n if (event.type == lug::Window::Event::Type::KeyPressed && event.key.code == lug::Window::Keyboard::Key::Escape) {\n logger->info(\"Closing the app (escape)\");\n window->close();\n }\n\n if (event.type == lug::Window::Event::Type::KeyPressed\n && event.key.code == lug::Window::Keyboard::Key::Q && event.key.ctrl) {\n logger->info(\"Closing the app (ctrl+Q)\");\n window->close();\n }\n\n\/\/ \/\/ Checking to see if mouse position is stored correctly\n\/\/ {\n\/\/ uint32_t x;\n\/\/ uint32_t y;\n\/\/\n\/\/ window->getMousePos(x, y);\n\/\/ logger->info(\"Mouse is at position {} {}\", x, y);\n\/\/ }\n\n \/\/ Checking KeyPressed events\n if (event.type == lug::Window::Event::Type::KeyPressed) {\n logger->info(keyEnumMap[event.key.code] + \" is pressed\");\n }\n\n \/\/ Checking KeyReleased events\n if (event.type == lug::Window::Event::Type::KeyReleased) {\n logger->info(keyEnumMap[event.key.code] + \" is released\");\n }\n\n \/\/ Checking ButtonPressed events\n if (event.type == lug::Window::Event::Type::ButtonPressed) {\n logger->info(buttonEnumMap[event.button.code] + \" is pressed at position {} {}\", event.button.coord.x, event.button.coord.y);\n }\n\n \/\/ Checking ButtonReleased events\n if (event.type == lug::Window::Event::Type::ButtonReleased) {\n logger->info(buttonEnumMap[event.button.code] + \" is released at position {} {}\", event.button.coord.x, event.button.coord.y);\n }\n \n\/\/ \/\/ Checking MouseWheel events\n\/\/ if (event.type == lug::Window::Event::Type::MouseWheel) {\n\/\/ logger->info(\"Mouse scroll wheel offset {} {}\", event.button.scrollOffset.xOffset, event.button.scrollOffset.yOffset);\n\/\/ if (event.button.ctrl) {\n\/\/ logger->info(\"MODIFIER CTRL\");\n\/\/ }\n\/\/ if (event.button.shift) {\n\/\/ logger->info(\"MODIFIER SHIFT\");\n\/\/ }\n\/\/ }\n\n\/\/ \/\/ Checking MouseMoved events\n\/\/ if (event.type == lug::Window::Event::Type::MouseMoved) {\n\/\/ logger->info(\"Mouse moved at position {} {}\", event.button.coord.x, event.button.coord.y);\n\/\/ }\n\n if (event.type == lug::Window::Event::Type::CharEntered) {\n logger->info(\"Char event received: {}\", static_cast(event.character.val));\n }\n\n \/\/ Checking to see if any special keys are pressed\n if (event.type == lug::Window::Event::Type::KeyPressed ||\n event.type == lug::Window::Event::Type::KeyReleased) {\n if (event.key.ctrl) {\n logger->info(\"MODIFIER CTRL\");\n }\n if (event.key.alt) {\n logger->info(\"MODIFIER ALT\");\n }\n if (event.key.shift) {\n logger->info(\"MODIFIER SHIFT\");\n }\n if (event.key.system) {\n logger->info(\"MODIFIER SYSTEM\");\n }\n }\n\n }\n\n\/\/ \/\/ Checking that keys states are correctly set\n\/\/ for (auto it = keyEnumMap.begin(); it != keyEnumMap.end(); ++it) {\n\/\/ if (window->isKeyPressed(it->first)) {\n\/\/ logger->info(it->second + \" is set to pressed\");\n\/\/ }\n\/\/ }\n\n\/\/ \/\/ Checking that mouse button states are correctly set\n\/\/ for (auto it = buttonEnumMap.begin(); it != buttonEnumMap.end(); ++it) {\n\/\/ if (window->isMousePressed(it->first)) {\n\/\/ logger->info(it->second + \" is set to pressed\");\n\/\/ }\n\/\/ }\n }\n\n return 0;\n}\nAvoid MouseMoved spam#include \n\n#include \n#include \n#include \n#include \n\n#if defined(LUG_SYSTEM_ANDROID)\n #include \n#else\n #include \n#endif\n\nauto createKeyEnumMap() {\n std::unordered_map returnValue;\n\n returnValue[lug::Window::Keyboard::Key::Unknown] = \"Unknown\";\n\n \/\/ Basic keys\n returnValue[lug::Window::Keyboard::Key::A] = \"A\";\n returnValue[lug::Window::Keyboard::Key::B] = \"B\";\n returnValue[lug::Window::Keyboard::Key::C] = \"C\";\n returnValue[lug::Window::Keyboard::Key::D] = \"D\";\n returnValue[lug::Window::Keyboard::Key::E] = \"E\";\n returnValue[lug::Window::Keyboard::Key::F] = \"F\";\n returnValue[lug::Window::Keyboard::Key::G] = \"G\";\n returnValue[lug::Window::Keyboard::Key::H] = \"H\";\n returnValue[lug::Window::Keyboard::Key::I] = \"I\";\n returnValue[lug::Window::Keyboard::Key::J] = \"J\";\n returnValue[lug::Window::Keyboard::Key::K] = \"K\";\n returnValue[lug::Window::Keyboard::Key::L] = \"L\";\n returnValue[lug::Window::Keyboard::Key::M] = \"M\";\n returnValue[lug::Window::Keyboard::Key::N] = \"N\";\n returnValue[lug::Window::Keyboard::Key::O] = \"O\";\n returnValue[lug::Window::Keyboard::Key::P] = \"P\";\n returnValue[lug::Window::Keyboard::Key::Q] = \"Q\";\n returnValue[lug::Window::Keyboard::Key::R] = \"R\";\n returnValue[lug::Window::Keyboard::Key::S] = \"S\";\n returnValue[lug::Window::Keyboard::Key::T] = \"T\";\n returnValue[lug::Window::Keyboard::Key::U] = \"U\";\n returnValue[lug::Window::Keyboard::Key::V] = \"V\";\n returnValue[lug::Window::Keyboard::Key::W] = \"W\";\n returnValue[lug::Window::Keyboard::Key::X] = \"X\";\n returnValue[lug::Window::Keyboard::Key::Y] = \"Y\";\n returnValue[lug::Window::Keyboard::Key::Z] = \"Z\";\n\n returnValue[lug::Window::Keyboard::Key::Num0] = \"Num0\";\n returnValue[lug::Window::Keyboard::Key::Num1] = \"Num1\";\n returnValue[lug::Window::Keyboard::Key::Num2] = \"Num2\";\n returnValue[lug::Window::Keyboard::Key::Num3] = \"Num3\";\n returnValue[lug::Window::Keyboard::Key::Num4] = \"Num4\";\n returnValue[lug::Window::Keyboard::Key::Num5] = \"Num5\";\n returnValue[lug::Window::Keyboard::Key::Num6] = \"Num6\";\n returnValue[lug::Window::Keyboard::Key::Num7] = \"Num7\";\n returnValue[lug::Window::Keyboard::Key::Num8] = \"Num8\";\n returnValue[lug::Window::Keyboard::Key::Num9] = \"Num9\";\n\n \/\/ Modifiers\n returnValue[lug::Window::Keyboard::Key::LControl] = \"LControl\";\n returnValue[lug::Window::Keyboard::Key::LShift] = \"LShift\";\n returnValue[lug::Window::Keyboard::Key::LAlt] = \"LAlt\";\n returnValue[lug::Window::Keyboard::Key::LSystem] = \"LSystem\";\n returnValue[lug::Window::Keyboard::Key::RControl] = \"RControl\";\n returnValue[lug::Window::Keyboard::Key::RShift] = \"RShift\";\n returnValue[lug::Window::Keyboard::Key::RAlt] = \"RAlt\";\n returnValue[lug::Window::Keyboard::Key::RSystem] = \"RSystem\";\n\n \/\/ Advanced keys\n returnValue[lug::Window::Keyboard::Key::Menu] = \"Menu\";\n returnValue[lug::Window::Keyboard::Key::LBracket] = \"LBracket\";\n returnValue[lug::Window::Keyboard::Key::RBracket] = \"RBracket\";\n returnValue[lug::Window::Keyboard::Key::SemiColon] = \"SemiColon\";\n returnValue[lug::Window::Keyboard::Key::Comma] = \"Comma\";\n returnValue[lug::Window::Keyboard::Key::Period] = \"Period\";\n returnValue[lug::Window::Keyboard::Key::Quote] = \"Quote\";\n returnValue[lug::Window::Keyboard::Key::Slash] = \"Slash\";\n returnValue[lug::Window::Keyboard::Key::BackSlash] = \"BackSlash\";\n returnValue[lug::Window::Keyboard::Key::Tilde] = \"Tilde\";\n returnValue[lug::Window::Keyboard::Key::Equal] = \"Equal\";\n returnValue[lug::Window::Keyboard::Key::Dash] = \"Dash\";\n returnValue[lug::Window::Keyboard::Key::Space] = \"Space\";\n returnValue[lug::Window::Keyboard::Key::Return] = \"Return\";\n returnValue[lug::Window::Keyboard::Key::BackSpace] = \"BackSpace\";\n returnValue[lug::Window::Keyboard::Key::Tab] = \"Tab\";\n returnValue[lug::Window::Keyboard::Key::PageUp] = \"PageUp\";\n returnValue[lug::Window::Keyboard::Key::PageDown] = \"PageDown\";\n returnValue[lug::Window::Keyboard::Key::End] = \"End\";\n returnValue[lug::Window::Keyboard::Key::Home] = \"Home\";\n returnValue[lug::Window::Keyboard::Key::Insert] = \"Insert\";\n returnValue[lug::Window::Keyboard::Key::Delete] = \"Delete\";\n returnValue[lug::Window::Keyboard::Key::Add] = \"Add\";\n returnValue[lug::Window::Keyboard::Key::Subtract] = \"Subtract\";\n returnValue[lug::Window::Keyboard::Key::Multiply] = \"Multiply\";\n returnValue[lug::Window::Keyboard::Key::Divide] = \"Divide\";\n returnValue[lug::Window::Keyboard::Key::Left] = \"Left\";\n returnValue[lug::Window::Keyboard::Key::Right] = \"Right\";\n returnValue[lug::Window::Keyboard::Key::Up] = \"Up\";\n returnValue[lug::Window::Keyboard::Key::Down] = \"Down\";\n returnValue[lug::Window::Keyboard::Key::Pause] = \"Pause\";\n returnValue[lug::Window::Keyboard::Key::CapsLock] = \"CapsLock\";\n returnValue[lug::Window::Keyboard::Key::Escape] = \"Escape\";\n\n \/\/ AZERTY Specifics\n returnValue[lug::Window::Keyboard::Key::Twosuperior] = \"Twosuperior\";\n returnValue[lug::Window::Keyboard::Key::Ampersand] = \"Ampersand\";\n returnValue[lug::Window::Keyboard::Key::Eacute] = \"Eacute\";\n returnValue[lug::Window::Keyboard::Key::QuoteDouble] = \"QuoteDouble\";\n returnValue[lug::Window::Keyboard::Key::LParen] = \"LParen\";\n returnValue[lug::Window::Keyboard::Key::Egrave] = \"Egrave\";\n returnValue[lug::Window::Keyboard::Key::Underscore] = \"Underscore\";\n returnValue[lug::Window::Keyboard::Key::Ccedilla] = \"Ccedilla\";\n returnValue[lug::Window::Keyboard::Key::Agrave] = \"Agrave\";\n returnValue[lug::Window::Keyboard::Key::RParen] = \"RParen\";\n returnValue[lug::Window::Keyboard::Key::DeadCircumflex] = \"DeadCircumflex\";\n returnValue[lug::Window::Keyboard::Key::Ugrave] = \"Ugrave\";\n returnValue[lug::Window::Keyboard::Key::Asterisk] = \"Asterisk\";\n returnValue[lug::Window::Keyboard::Key::Dollar] = \"Dollar\";\n returnValue[lug::Window::Keyboard::Key::Colon] = \"Colon\";\n returnValue[lug::Window::Keyboard::Key::Exclam] = \"Exclam\";\n returnValue[lug::Window::Keyboard::Key::Less] = \"Less\";\n returnValue[lug::Window::Keyboard::Key::Greater] = \"Greater\";\n\n \/\/ Numpad\n returnValue[lug::Window::Keyboard::Key::Numpad0] = \"Numpad0\";\n returnValue[lug::Window::Keyboard::Key::Numpad1] = \"Numpad1\";\n returnValue[lug::Window::Keyboard::Key::Numpad2] = \"Numpad2\";\n returnValue[lug::Window::Keyboard::Key::Numpad3] = \"Numpad3\";\n returnValue[lug::Window::Keyboard::Key::Numpad4] = \"Numpad4\";\n returnValue[lug::Window::Keyboard::Key::Numpad5] = \"Numpad5\";\n returnValue[lug::Window::Keyboard::Key::Numpad6] = \"Numpad6\";\n returnValue[lug::Window::Keyboard::Key::Numpad7] = \"Numpad7\";\n returnValue[lug::Window::Keyboard::Key::Numpad8] = \"Numpad8\";\n returnValue[lug::Window::Keyboard::Key::Numpad9] = \"Numpad9\";\n\n \/\/ Function keys\n returnValue[lug::Window::Keyboard::Key::F1] = \"F1\";\n returnValue[lug::Window::Keyboard::Key::F2] = \"F2\";\n returnValue[lug::Window::Keyboard::Key::F3] = \"F3\";\n returnValue[lug::Window::Keyboard::Key::F4] = \"F4\";\n returnValue[lug::Window::Keyboard::Key::F5] = \"F5\";\n returnValue[lug::Window::Keyboard::Key::F6] = \"F6\";\n returnValue[lug::Window::Keyboard::Key::F7] = \"F7\";\n returnValue[lug::Window::Keyboard::Key::F8] = \"F8\";\n returnValue[lug::Window::Keyboard::Key::F9] = \"F9\";\n returnValue[lug::Window::Keyboard::Key::F10] = \"F10\";\n returnValue[lug::Window::Keyboard::Key::F11] = \"F11\";\n returnValue[lug::Window::Keyboard::Key::F12] = \"F12\";\n returnValue[lug::Window::Keyboard::Key::F13] = \"F13\";\n returnValue[lug::Window::Keyboard::Key::F14] = \"F14\";\n returnValue[lug::Window::Keyboard::Key::F15] = \"F15\";\n\n return returnValue;\n}\n\nauto createButtonEnumMap() {\n std::unordered_map returnValue;\n\n \/\/ Function keys\n returnValue[lug::Window::Mouse::Button::Left] = \"Left\";\n returnValue[lug::Window::Mouse::Button::Right] = \"Right\";\n returnValue[lug::Window::Mouse::Button::Middle] = \"Middle\";\n returnValue[lug::Window::Mouse::Button::XButton1] = \"XButton1\";\n returnValue[lug::Window::Mouse::Button::XButton2] = \"XButton2\";\n\n return returnValue;\n}\n\nint main() {\n auto window = lug::Window::Window::create({\n 800, \/\/ width\n 600, \/\/ height\n \"Default Window\", \/\/ title\n lug::Window::Style::Default \/\/ style\n });\n\n\n auto logger = lug::System::Logger::makeLogger(\"LugdunumSamples\");\n\n auto keyEnumMap = createKeyEnumMap();\n\n auto buttonEnumMap = createButtonEnumMap();\n\n#if defined(LUG_SYSTEM_ANDROID)\n auto handler = lug::System::Logger::makeHandler(\"LogCat\");\n#else\n auto handler = lug::System::Logger::makeHandler(\"Stdout\");\n#endif\n\n logger->addHandler(handler);\n LUG_LOG.addHandler(handler);\n\n if (!window) {\n logger->fatal(\"Window was not created\");\n return 1;\n }\n\n logger->info(\"Window was created successfully\");\n\n window->setKeyRepeat(true);\n\n \/\/ While window is open execute the following\n while (window->isOpen()) {\n lug::Window::Event event;\n while (window->pollEvent(event)) {\n \/*\n * AVOID MOUSE MOVE SPAM !!!\n *\/\n if (event.type != lug::Window::Event::Type::MouseMoved) {\n logger->info(\"Event received: {}\", static_cast(event.type));\n }\n\n if (event.type == lug::Window::Event::Type::Close) {\n logger->info(\"Closing the app\");\n window->close();\n }\n\n if (event.type == lug::Window::Event::Type::KeyPressed && event.key.code == lug::Window::Keyboard::Key::Escape) {\n logger->info(\"Closing the app (escape)\");\n window->close();\n }\n\n if (event.type == lug::Window::Event::Type::KeyPressed\n && event.key.code == lug::Window::Keyboard::Key::Q && event.key.ctrl) {\n logger->info(\"Closing the app (ctrl+Q)\");\n window->close();\n }\n\n\/\/ \/\/ Checking to see if mouse position is stored correctly\n\/\/ {\n\/\/ uint32_t x;\n\/\/ uint32_t y;\n\/\/\n\/\/ window->getMousePos(x, y);\n\/\/ logger->info(\"Mouse is at position {} {}\", x, y);\n\/\/ }\n\n \/\/ Checking KeyPressed events\n if (event.type == lug::Window::Event::Type::KeyPressed) {\n logger->info(keyEnumMap[event.key.code] + \" is pressed\");\n }\n\n \/\/ Checking KeyReleased events\n if (event.type == lug::Window::Event::Type::KeyReleased) {\n logger->info(keyEnumMap[event.key.code] + \" is released\");\n }\n\n \/\/ Checking ButtonPressed events\n if (event.type == lug::Window::Event::Type::ButtonPressed) {\n logger->info(buttonEnumMap[event.button.code] + \" is pressed at position {} {}\", event.button.coord.x, event.button.coord.y);\n }\n\n \/\/ Checking ButtonReleased events\n if (event.type == lug::Window::Event::Type::ButtonReleased) {\n logger->info(buttonEnumMap[event.button.code] + \" is released at position {} {}\", event.button.coord.x, event.button.coord.y);\n }\n \n \/\/ Checking MouseWheel events\n if (event.type == lug::Window::Event::Type::MouseWheel) {\n logger->info(\"Mouse scroll wheel offset {} {}\", event.button.scrollOffset.xOffset, event.button.scrollOffset.yOffset);\n if (event.button.ctrl) {\n logger->info(\"MODIFIER CTRL\");\n }\n if (event.button.shift) {\n logger->info(\"MODIFIER SHIFT\");\n }\n }\n\n if (event.type == lug::Window::Event::Type::MouseLeave) {\n logger->info(\"Mouse just left the window.\");\n if (event.button.ctrl) {\n logger->info(\"MODIFIER CTRL\");\n }\n if (event.button.shift) {\n logger->info(\"MODIFIER SHIFT\");\n }\n }\n if (event.type == lug::Window::Event::Type::MouseEnter) {\n logger->info(\"Mouse just entered the window.\");\n if (event.button.ctrl) {\n logger->info(\"MODIFIER CTRL\");\n }\n if (event.button.shift) {\n logger->info(\"MODIFIER SHIFT\");\n }\n }\n\n\/\/ \/\/ Checking MouseMoved events\n\/\/ if (event.type == lug::Window::Event::Type::MouseMoved) {\n\/\/ logger->info(\"Mouse moved at position {} {}\", event.button.coord.x, event.button.coord.y);\n\/\/ }\n\n if (event.type == lug::Window::Event::Type::CharEntered) {\n logger->info(\"Char event received: {}\", static_cast(event.character.val));\n }\n\n \/\/ Checking to see if any special keys are pressed\n if (event.type == lug::Window::Event::Type::KeyPressed ||\n event.type == lug::Window::Event::Type::KeyReleased) {\n if (event.key.ctrl) {\n logger->info(\"MODIFIER CTRL\");\n }\n if (event.key.alt) {\n logger->info(\"MODIFIER ALT\");\n }\n if (event.key.shift) {\n logger->info(\"MODIFIER SHIFT\");\n }\n if (event.key.system) {\n logger->info(\"MODIFIER SYSTEM\");\n }\n }\n\n }\n\n\/\/ \/\/ Checking that keys states are correctly set\n\/\/ for (auto it = keyEnumMap.begin(); it != keyEnumMap.end(); ++it) {\n\/\/ if (window->isKeyPressed(it->first)) {\n\/\/ logger->info(it->second + \" is set to pressed\");\n\/\/ }\n\/\/ }\n\n\/\/ \/\/ Checking that mouse button states are correctly set\n\/\/ for (auto it = buttonEnumMap.begin(); it != buttonEnumMap.end(); ++it) {\n\/\/ if (window->isMousePressed(it->first)) {\n\/\/ logger->info(it->second + \" is set to pressed\");\n\/\/ }\n\/\/ }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, 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 Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\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 * $Id$\n *\n *\/\n\n#ifndef PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_\n#define PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_\n\n#include \n#include \"pcl\/sample_consensus\/prosac.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Variable naming uses capital letters to make the comparison with the original paper easier\ntemplate bool \npcl::ProgressiveSampleConsensus::computeModel (int debug_verbosity_level)\n{\n \/\/ Warn and exit if no threshold was set\n if (threshold_ == DBL_MAX)\n {\n PCL_ERROR (\"[pcl::ProgressiveSampleConsensus::computeModel] No threshold set!\\n\");\n return (false);\n }\n\n \/\/ Initialize some PROSAC constants\n float T_N = 200000;\n unsigned int N = sac_model_->indices_->size ();\n unsigned int m = sac_model_->getSampleSize ();\n float T_n = T_N;\n for (unsigned int i = 0; i < m; ++i)\n T_n *= (float)(m - i) \/ (float)(N - i);\n float T_prime_n = 1;\n unsigned int I_N_best = 0;\n float n = m;\n\n \/\/ Define the n_Start coefficients from Section 2.2\n float n_star = N;\n unsigned int I_n_star = 0;\n float epsilon_n_star = (float)I_n_star \/ n_star;\n unsigned int k_n_star = T_N;\n\n \/\/ Compute the I_n_star_min of Equation 8\n std::vector I_n_star_min (N);\n\n \/\/ Initialize the usual RANSAC parameters\n iterations_ = 0;\n\n std::vector inliers;\n std::vector selection;\n Eigen::VectorXf model_coefficients;\n\n \/\/ We will increase the pool so the indices_ vector can only contain m elements at first\n std::vector index_pool;\n index_pool.reserve (N);\n for (unsigned int i = 0; i < n; ++i)\n index_pool.push_back (sac_model_->indices_->operator[](i));\n\n \/\/ Iterate\n while ((unsigned int)iterations_ < k_n_star)\n {\n \/\/ Choose the samples\n\n \/\/ Step 1\n \/\/ According to Equation 5 in the text text, not the algorithm\n if ((iterations_ == T_prime_n) && (n < n_star))\n {\n \/\/ Increase the pool\n ++n;\n if (n >= N)\n break;\n index_pool.push_back (sac_model_->indices_->at(n - 1));\n \/\/ Update other variables\n float T_n_minus_1 = T_n;\n T_n *= (float)(n + 1) \/ (float)(n + 1 - m);\n T_prime_n += ceil(T_n - T_n_minus_1);\n }\n\n \/\/ Step 2\n sac_model_->indices_->swap (index_pool);\n selection.clear ();\n sac_model_->getSamples (iterations_, selection);\n if (T_prime_n < iterations_)\n {\n selection.pop_back ();\n selection.push_back (sac_model_->indices_->at(n - 1));\n }\n\n \/\/ Make sure we use the right indices for testing\n sac_model_->indices_->swap (index_pool);\n\n if (selection.empty ())\n {\n PCL_ERROR (\"[pcl::ProgressiveSampleConsensus::computeModel] No samples could be selected!\\n\");\n break;\n }\n\n \/\/ Search for inliers in the point cloud for the current model\n if (!sac_model_->computeModelCoefficients (selection, model_coefficients))\n {\n ++iterations_;\n continue;\n }\n\n \/\/ Select the inliers that are within threshold_ from the model\n inliers.clear ();\n sac_model_->selectWithinDistance (model_coefficients, threshold_, inliers);\n\n unsigned int I_N = inliers.size ();\n\n \/\/ If we find more inliers than before\n if (I_N > I_N_best)\n {\n I_N_best = I_N;\n\n \/\/ Save the current model\/inlier\/coefficients selection as being the best so far\n inliers_ = inliers;\n model_ = selection;\n model_coefficients_ = model_coefficients;\n\n \/\/ We estimate I_n_star for different possible values of n_star by using the inliers\n std::sort (inliers.begin (), inliers.end ());\n\n \/\/ Try to find a better n_star\n \/\/ We minimize k_n_star and therefore maximize epsilon_n_star = I_n_star \/ n_star\n unsigned int possible_n_star_best = N, I_possible_n_star_best = I_N;\n float epsilon_possible_n_star_best = (float)I_possible_n_star_best \/ possible_n_star_best;\n\n \/\/ We only need to compute possible better epsilon_n_star for when _n is just about to be removed an inlier\n unsigned int I_possible_n_star = I_N;\n for (std::vector::const_reverse_iterator last_inlier = inliers.rbegin (); last_inlier != inliers.rend (); ++last_inlier, --I_possible_n_star)\n {\n \/\/ The best possible_n_star for a given I_possible_n_star is the index of the last inlier\n unsigned int possible_n_star = (*last_inlier) + 1;\n if (possible_n_star <= m)\n break;\n\n \/\/ If we find a better epsilon_n_star\n float epsilon_possible_n_star = (float)I_possible_n_star \/ possible_n_star;\n \/\/ Make sure we have a better epsilon_possible_n_star\n if ((epsilon_possible_n_star > epsilon_n_star) && (epsilon_possible_n_star > epsilon_possible_n_star_best))\n {\n using namespace boost::math;\n \/\/ Typo in Equation 7, not (n-m choose i-m) but (n choose i-m)\n unsigned int\n I_possible_n_star_min = m\n + ceil (quantile (complement (binomial_distribution(possible_n_star, 0.1), 0.05)));\n \/\/ If Equation 9 is not verified, exit\n if (I_possible_n_star < I_possible_n_star_min)\n break;\n\n possible_n_star_best = possible_n_star;\n I_possible_n_star_best = I_possible_n_star;\n epsilon_possible_n_star_best = epsilon_possible_n_star;\n }\n }\n\n \/\/ Check if we get a better epsilon\n if (epsilon_possible_n_star_best > epsilon_n_star)\n {\n \/\/ update the best value\n epsilon_n_star = epsilon_possible_n_star_best;\n\n \/\/ Compute the new k_n_star\n float bottom_log = 1 - std::pow (epsilon_n_star, static_cast(m));\n if (bottom_log == 0)\n k_n_star = 1;\n else if (bottom_log == 1)\n k_n_star = T_N;\n else\n k_n_star = (int)ceil (log(0.05) \/ log (bottom_log));\n \/\/ It seems weird to have very few iterations, so do have a few (totally empirical)\n k_n_star = (std::max)(k_n_star, 2 * m);\n }\n }\n\n ++iterations_;\n if (debug_verbosity_level > 1)\n PCL_DEBUG (\"[pcl::ProgressiveSampleConsensus::computeModel] Trial %d out of %d: %d inliers (best is: %d so far).\\n\", iterations_, k_n_star, I_N, I_N_best);\n if (iterations_ > max_iterations_)\n {\n if (debug_verbosity_level > 0)\n PCL_DEBUG (\"[pcl::ProgressiveSampleConsensus::computeModel] RANSAC reached the maximum number of trials.\\n\");\n break;\n }\n }\n\n if (debug_verbosity_level > 0)\n PCL_DEBUG (\"[pcl::ProgressiveSampleConsensus::computeModel] Model: %lu size, %d inliers.\\n\", (unsigned long)model_.size (), I_N_best);\n\n if (model_.empty ())\n {\n inliers_.clear ();\n return (false);\n }\n\n \/\/ Get the set of inliers that correspond to the best model found so far\n \/\/sac_model_->selectWithinDistance (model_coefficients_, threshold_, inliers_);\n return (true);\n}\n\n#define PCL_INSTANTIATE_ProgressiveSampleConsensus(T) template class PCL_EXPORTS pcl::ProgressiveSampleConsensus;\n\n#endif \/\/ PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_\nfriendlier PROSAC for pathCC\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2009, 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 Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\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 * $Id$\n *\n *\/\n\n#ifndef PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_\n#define PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_\n\n#include \n#include \"pcl\/sample_consensus\/prosac.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Variable naming uses capital letters to make the comparison with the original paper easier\ntemplate bool \npcl::ProgressiveSampleConsensus::computeModel (int debug_verbosity_level)\n{\n \/\/ Warn and exit if no threshold was set\n if (threshold_ == DBL_MAX)\n {\n PCL_ERROR (\"[pcl::ProgressiveSampleConsensus::computeModel] No threshold set!\\n\");\n return (false);\n }\n\n \/\/ Initialize some PROSAC constants\n float T_N = 200000;\n unsigned int N = sac_model_->indices_->size ();\n unsigned int m = sac_model_->getSampleSize ();\n float T_n = T_N;\n for (unsigned int i = 0; i < m; ++i)\n T_n *= (float)(m - i) \/ (float)(N - i);\n float T_prime_n = 1;\n unsigned int I_N_best = 0;\n float n = m;\n\n \/\/ Define the n_Start coefficients from Section 2.2\n float n_star = N;\n unsigned int I_n_star = 0;\n float epsilon_n_star = (float)I_n_star \/ n_star;\n unsigned int k_n_star = T_N;\n\n \/\/ Compute the I_n_star_min of Equation 8\n std::vector I_n_star_min (N);\n\n \/\/ Initialize the usual RANSAC parameters\n iterations_ = 0;\n\n std::vector inliers;\n std::vector selection;\n Eigen::VectorXf model_coefficients;\n\n \/\/ We will increase the pool so the indices_ vector can only contain m elements at first\n std::vector index_pool;\n index_pool.reserve (N);\n for (unsigned int i = 0; i < n; ++i)\n index_pool.push_back (sac_model_->indices_->operator[](i));\n\n \/\/ Iterate\n while ((unsigned int)iterations_ < k_n_star)\n {\n \/\/ Choose the samples\n\n \/\/ Step 1\n \/\/ According to Equation 5 in the text text, not the algorithm\n if ((iterations_ == T_prime_n) && (n < n_star))\n {\n \/\/ Increase the pool\n ++n;\n if (n >= N)\n break;\n index_pool.push_back (sac_model_->indices_->at(n - 1));\n \/\/ Update other variables\n float T_n_minus_1 = T_n;\n T_n *= (float)(n + 1) \/ (float)(n + 1 - m);\n T_prime_n += ceil(T_n - T_n_minus_1);\n }\n\n \/\/ Step 2\n sac_model_->indices_->swap (index_pool);\n selection.clear ();\n sac_model_->getSamples (iterations_, selection);\n if (T_prime_n < iterations_)\n {\n selection.pop_back ();\n selection.push_back (sac_model_->indices_->at(n - 1));\n }\n\n \/\/ Make sure we use the right indices for testing\n sac_model_->indices_->swap (index_pool);\n\n if (selection.empty ())\n {\n PCL_ERROR (\"[pcl::ProgressiveSampleConsensus::computeModel] No samples could be selected!\\n\");\n break;\n }\n\n \/\/ Search for inliers in the point cloud for the current model\n if (!sac_model_->computeModelCoefficients (selection, model_coefficients))\n {\n ++iterations_;\n continue;\n }\n\n \/\/ Select the inliers that are within threshold_ from the model\n inliers.clear ();\n sac_model_->selectWithinDistance (model_coefficients, threshold_, inliers);\n\n unsigned int I_N = inliers.size ();\n\n \/\/ If we find more inliers than before\n if (I_N > I_N_best)\n {\n I_N_best = I_N;\n\n \/\/ Save the current model\/inlier\/coefficients selection as being the best so far\n inliers_ = inliers;\n model_ = selection;\n model_coefficients_ = model_coefficients;\n\n \/\/ We estimate I_n_star for different possible values of n_star by using the inliers\n std::sort (inliers.begin (), inliers.end ());\n\n \/\/ Try to find a better n_star\n \/\/ We minimize k_n_star and therefore maximize epsilon_n_star = I_n_star \/ n_star\n unsigned int possible_n_star_best = N, I_possible_n_star_best = I_N;\n float epsilon_possible_n_star_best = (float)I_possible_n_star_best \/ possible_n_star_best;\n\n \/\/ We only need to compute possible better epsilon_n_star for when _n is just about to be removed an inlier\n unsigned int I_possible_n_star = I_N;\n for (std::vector::const_reverse_iterator last_inlier = inliers.rbegin (), \n inliers_end = inliers.rend (); \n last_inlier != inliers_end; \n ++last_inlier, --I_possible_n_star)\n {\n \/\/ The best possible_n_star for a given I_possible_n_star is the index of the last inlier\n unsigned int possible_n_star = (*last_inlier) + 1;\n if (possible_n_star <= m)\n break;\n\n \/\/ If we find a better epsilon_n_star\n float epsilon_possible_n_star = (float)I_possible_n_star \/ possible_n_star;\n \/\/ Make sure we have a better epsilon_possible_n_star\n if ((epsilon_possible_n_star > epsilon_n_star) && (epsilon_possible_n_star > epsilon_possible_n_star_best))\n {\n using namespace boost::math;\n \/\/ Typo in Equation 7, not (n-m choose i-m) but (n choose i-m)\n unsigned int\n I_possible_n_star_min = m\n + ceil (quantile (complement (binomial_distribution(possible_n_star, 0.1), 0.05)));\n \/\/ If Equation 9 is not verified, exit\n if (I_possible_n_star < I_possible_n_star_min)\n break;\n\n possible_n_star_best = possible_n_star;\n I_possible_n_star_best = I_possible_n_star;\n epsilon_possible_n_star_best = epsilon_possible_n_star;\n }\n }\n\n \/\/ Check if we get a better epsilon\n if (epsilon_possible_n_star_best > epsilon_n_star)\n {\n \/\/ update the best value\n epsilon_n_star = epsilon_possible_n_star_best;\n\n \/\/ Compute the new k_n_star\n float bottom_log = 1 - std::pow (epsilon_n_star, static_cast(m));\n if (bottom_log == 0)\n k_n_star = 1;\n else if (bottom_log == 1)\n k_n_star = T_N;\n else\n k_n_star = (int)ceil (log(0.05) \/ log (bottom_log));\n \/\/ It seems weird to have very few iterations, so do have a few (totally empirical)\n k_n_star = (std::max)(k_n_star, 2 * m);\n }\n }\n\n ++iterations_;\n if (debug_verbosity_level > 1)\n PCL_DEBUG (\"[pcl::ProgressiveSampleConsensus::computeModel] Trial %d out of %d: %d inliers (best is: %d so far).\\n\", iterations_, k_n_star, I_N, I_N_best);\n if (iterations_ > max_iterations_)\n {\n if (debug_verbosity_level > 0)\n PCL_DEBUG (\"[pcl::ProgressiveSampleConsensus::computeModel] RANSAC reached the maximum number of trials.\\n\");\n break;\n }\n }\n\n if (debug_verbosity_level > 0)\n PCL_DEBUG (\"[pcl::ProgressiveSampleConsensus::computeModel] Model: %lu size, %d inliers.\\n\", (unsigned long)model_.size (), I_N_best);\n\n if (model_.empty ())\n {\n inliers_.clear ();\n return (false);\n }\n\n \/\/ Get the set of inliers that correspond to the best model found so far\n \/\/sac_model_->selectWithinDistance (model_coefficients_, threshold_, inliers_);\n return (true);\n}\n\n#define PCL_INSTANTIATE_ProgressiveSampleConsensus(T) template class PCL_EXPORTS pcl::ProgressiveSampleConsensus;\n\n#endif \/\/ PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_\n<|endoftext|>"} {"text":"#include \"test.h\"\n\n#include \"include\/config.h\"\n#include \"geo\/point2.h\"\n#include \"geo\/vector2.h\"\n\nusing namespace std;\nusing namespace valhalla::geo;\n\nnamespace {\n\nvoid TryDotProduct(const Vector2& a, const Vector2& b, float expected) {\n float result = a.Dot(b);\n if (expected != result)\n throw runtime_error(\"DotProduct test failed\");\n}\n\nvoid TestDotProduct() {\n TryDotProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f);\n TryDotProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 0.0f);\n}\n\nvoid TryCrossProduct(const Vector2& a, const Vector2& b, float expected) {\n float result = a.Cross(b);\n if (expected != result)\n throw runtime_error(\"CrossProduct test failed\");\n}\n\nvoid TestCrossProduct() {\n TryCrossProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f);\n TryCrossProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 50.0f);\n}\n\nvoid TryPerpendicular(const Vector2& a, const Vector2& expected) {\n Vector2 result = a.GetPerpendicular();\n if (!(expected == result))\n throw runtime_error(\"Perpendicular test failed\");\n}\n\nvoid TestPerpendicular() {\n TryPerpendicular(Vector2(3.0f, 4.0f), Vector2(-4.0f, 3.0f));\n}\n\nvoid TryNorm(const Vector2& a, float expected) {\n float result = a.Norm();\n if (expected != result)\n throw runtime_error(\"Norm test failed\");\n}\n\nvoid TestNorm() {\n TryNorm(Vector2(3.0f, 4.0f), 5.0f);\n TryNorm(Vector2(6.0f, 8.0f), 10.0f);\n}\n\nvoid TryNormSquared(const Vector2& a, float expected) {\n float result = a.NormSquared();\n if (expected != result)\n throw runtime_error(\"NormSquared test failed\");\n}\n\nvoid TestNormSquared() {\n TryNormSquared(Vector2(3.0f, 4.0f), 25.0f);\n TryNormSquared(Vector2(6.0f, 8.0f), 100.0f);\n}\n\nvoid TryNormalize(Vector2& a, const Vector2& expected) {\n a.Normalize();\n if (!(expected == a))\n throw runtime_error(\"Normalize test failed\");\n}\n\nvoid TestNormalize() {\n Vector2 v(3.0f, 4.0f);\n TryNormalize(v, Vector2(3.0f \/ 5.0f, 4.0f \/ 5.0f));\n Vector2 w(6.0f, 8.0f);\n TryNormalize(w, Vector2(6.0f \/ 10.0f, 8.0f \/ 10.0f));\n}\n\nvoid TryComponent(const Vector2& a, const Vector2& b, float expected) {\n float result = a.Component(b);\n if (expected != result)\n throw runtime_error(\"Component test failed\");\n}\n\nvoid TestComponent() {\n TryComponent(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), 0.5f);\n TryComponent(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), 2.0f);\n}\n\nvoid TryProjection(const Vector2& a, const Vector2& b,\n const Vector2& expected) {\n Vector2 result = a.Projection(b);\n if (!(expected == result))\n throw runtime_error(\"Projection test failed\");\n}\n\nvoid TestProjection() {\n TryProjection(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f));\n TryProjection(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f));\n TryProjection(Vector2(2.0f, 1.0f), Vector2(-3.0f, 4.0f),\n Vector2(6.0f \/ 25.0f, -8.0f \/ 25.0f));\n}\n\nvoid TryAngleBetween(const Vector2& a, const Vector2& b, float expected) {\n float result = (a.AngleBetween(b) * kDegPerRad);\n if (expected != result)\n throw runtime_error(\"AngleBetween test failed\");\n}\n\nvoid TestAngleBetween() {\n TryAngleBetween(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 45.0f);\n TryAngleBetween(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 90.0f);\n}\n\nvoid TryReflect(const Vector2& a, const Vector2& b, const Vector2& expected) {\n Vector2 result = a.Reflect(b);\n if (!(expected == result))\n throw runtime_error(\"Reflect test failed\");\n}\n\nvoid TestReflect() {\n Vector2 n1 { 0.0f, 2.0f };\n n1.Normalize();\n TryReflect(Vector2(4.0f, -2.0f), n1, Vector2(4.0f, 2.0f));\n Vector2 n2 { -3.0f, 0.0f };\n n2.Normalize();\n TryReflect(Vector2(3.0f, -4.0f), n2, Vector2(-3.0f, -4.0f));\n}\n\n}\n\nint main() {\n test::suite suite(\"vector2\");\n\n \/\/ Dot Product\n suite.test(TEST_CASE(TestDotProduct));\n\n \/\/ Cross Product\n suite.test(TEST_CASE(TestCrossProduct));\n\n \/\/ Perpendicular\n suite.test(TEST_CASE(TestPerpendicular));\n\n \/\/ Norm\n suite.test(TEST_CASE(TestNorm));\n\n \/\/ NormSquared\n suite.test(TEST_CASE(TestNormSquared));\n\n \/\/ Normalize\n suite.test(TEST_CASE(TestNormalize));\n\n \/\/ Component\n suite.test(TEST_CASE(TestComponent));\n\n \/\/ Projection\n suite.test(TEST_CASE(TestProjection));\n\n \/\/ Angle Between\n suite.test(TEST_CASE(TestAngleBetween));\n\n \/\/ Reflect\n suite.test(TEST_CASE(TestReflect));\n\n return suite.tear_down();\n}\nAdded ctor and op assignment unit tests as follows:#include \"test.h\"\n\n#include \"include\/config.h\"\n#include \"geo\/point2.h\"\n#include \"geo\/vector2.h\"\n\nusing namespace std;\nusing namespace valhalla::geo;\n\nnamespace {\n\nvoid TestCtorDefault() {\n Vector2 target;\n Vector2 expected { 0.0f, 0.0f };\n if (!(expected == target))\n throw runtime_error(\"CtorDefault test failed\");\n}\n\nvoid TryCtorPoint2(const Point2& pt, const Vector2& expected) {\n Vector2 result(pt);\n if (!(expected == result))\n throw runtime_error(\"CtorPoint2 test failed\");\n}\n\nvoid TestCtorPoint2() {\n TryCtorPoint2(Point2(3.0f, 0.0f), Vector2(3.0f, 0.0f));\n TryCtorPoint2(Point2(-8.0f, 6.0f), Vector2(-8.0f, 6.0f));\n}\n\nvoid TryCtorFloatFloat(const float x, const float y, const Vector2& expected) {\n Vector2 result(x, y);\n if (!(expected == result))\n throw runtime_error(\"CtorFloatFloat test failed\");\n}\n\nvoid TestCtorFloatFloat() {\n TryCtorFloatFloat(3.0f, 0.0f, Vector2(3.0f, 0.0f));\n TryCtorFloatFloat(-8.0f, 6.0f, Vector2(-8.0f, 6.0f));\n}\n\nvoid TryCtorPoint2Point2(const Point2& from, const Point2& to,\n const Vector2& expected) {\n Vector2 result(from, to);\n if (!(expected == result))\n throw runtime_error(\"CtorPoint2Point2 test failed\");\n}\n\nvoid TestCtorPoint2Point2() {\n TryCtorPoint2Point2(Point2(4.0f, 0.0f), Point2(3.0f, 3.0f),\n Vector2(-1.0f, 3.0f));\n TryCtorPoint2Point2(Point2(4.0f, 2.0f), Point2(4.0f, -2.0f),\n Vector2(0.0f, -4.0f));\n}\n\nvoid TryCtorVector2(const Vector2& v, const Vector2& expected) {\n Vector2 result(v);\n if (!(expected == result))\n throw runtime_error(\"CtorVector2 test failed\");\n}\n\nvoid TestCtorVector2() {\n TryCtorVector2(Vector2(3.0f, 0.0f), Vector2(3.0f, 0.0f));\n TryCtorVector2(Vector2(-8.0f, 6.0f), Vector2(-8.0f, 6.0f));\n}\n\nvoid TryOpAssignment(const Vector2& v, const Vector2& expected) {\n Vector2 result;\n result = v;\n if (!(expected == result))\n throw runtime_error(\"OpAssignment test failed\");\n}\n\nvoid TestOpAssignment() {\n TryOpAssignment(Vector2(3.0f, 0.0f), Vector2(3.0f, 0.0f));\n TryOpAssignment(Vector2(-8.0f, 6.0f), Vector2(-8.0f, 6.0f));\n}\n\nvoid TryDotProduct(const Vector2& a, const Vector2& b, float expected) {\n float result = a.Dot(b);\n if (expected != result)\n throw runtime_error(\"DotProduct test failed\");\n}\n\nvoid TestDotProduct() {\n TryDotProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f);\n TryDotProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 0.0f);\n}\n\nvoid TryCrossProduct(const Vector2& a, const Vector2& b, float expected) {\n float result = a.Cross(b);\n if (expected != result)\n throw runtime_error(\"CrossProduct test failed\");\n}\n\nvoid TestCrossProduct() {\n TryCrossProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f);\n TryCrossProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 50.0f);\n}\n\nvoid TryPerpendicular(const Vector2& a, const Vector2& expected) {\n Vector2 result = a.GetPerpendicular();\n if (!(expected == result))\n throw runtime_error(\"Perpendicular test failed\");\n}\n\nvoid TestPerpendicular() {\n TryPerpendicular(Vector2(3.0f, 4.0f), Vector2(-4.0f, 3.0f));\n}\n\nvoid TryNorm(const Vector2& a, float expected) {\n float result = a.Norm();\n if (expected != result)\n throw runtime_error(\"Norm test failed\");\n}\n\nvoid TestNorm() {\n TryNorm(Vector2(3.0f, 4.0f), 5.0f);\n TryNorm(Vector2(6.0f, 8.0f), 10.0f);\n}\n\nvoid TryNormSquared(const Vector2& a, float expected) {\n float result = a.NormSquared();\n if (expected != result)\n throw runtime_error(\"NormSquared test failed\");\n}\n\nvoid TestNormSquared() {\n TryNormSquared(Vector2(3.0f, 4.0f), 25.0f);\n TryNormSquared(Vector2(6.0f, 8.0f), 100.0f);\n}\n\nvoid TryNormalize(Vector2& a, const Vector2& expected) {\n a.Normalize();\n if (!(expected == a))\n throw runtime_error(\"Normalize test failed\");\n}\n\nvoid TestNormalize() {\n Vector2 v(3.0f, 4.0f);\n TryNormalize(v, Vector2(3.0f \/ 5.0f, 4.0f \/ 5.0f));\n Vector2 w(6.0f, 8.0f);\n TryNormalize(w, Vector2(6.0f \/ 10.0f, 8.0f \/ 10.0f));\n}\n\nvoid TryComponent(const Vector2& a, const Vector2& b, float expected) {\n float result = a.Component(b);\n if (expected != result)\n throw runtime_error(\"Component test failed\");\n}\n\nvoid TestComponent() {\n TryComponent(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), 0.5f);\n TryComponent(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), 2.0f);\n}\n\nvoid TryProjection(const Vector2& a, const Vector2& b,\n const Vector2& expected) {\n Vector2 result = a.Projection(b);\n if (!(expected == result))\n throw runtime_error(\"Projection test failed\");\n}\n\nvoid TestProjection() {\n TryProjection(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f));\n TryProjection(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f));\n TryProjection(Vector2(2.0f, 1.0f), Vector2(-3.0f, 4.0f),\n Vector2(6.0f \/ 25.0f, -8.0f \/ 25.0f));\n}\n\nvoid TryAngleBetween(const Vector2& a, const Vector2& b, float expected) {\n float result = (a.AngleBetween(b) * kDegPerRad);\n if (expected != result)\n throw runtime_error(\"AngleBetween test failed\");\n}\n\nvoid TestAngleBetween() {\n TryAngleBetween(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 45.0f);\n TryAngleBetween(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 90.0f);\n}\n\nvoid TryReflect(const Vector2& a, const Vector2& b, const Vector2& expected) {\n Vector2 result = a.Reflect(b);\n if (!(expected == result))\n throw runtime_error(\"Reflect test failed\");\n}\n\nvoid TestReflect() {\n Vector2 n1 { 0.0f, 2.0f };\n n1.Normalize();\n TryReflect(Vector2(4.0f, -2.0f), n1, Vector2(4.0f, 2.0f));\n Vector2 n2 { -3.0f, 0.0f };\n n2.Normalize();\n TryReflect(Vector2(3.0f, -4.0f), n2, Vector2(-3.0f, -4.0f));\n}\n\n}\n\nint main() {\n test::suite suite(\"vector2\");\n\n \/\/ Ctor default\n suite.test(TEST_CASE(TestCtorDefault));\n\n \/\/ Ctor Point2\n suite.test(TEST_CASE(TestCtorPoint2));\n\n \/\/ Ctor float, float\n suite.test(TEST_CASE(TestCtorFloatFloat));\n\n \/\/ Ctor Point2, Point2\n suite.test(TEST_CASE(TestCtorPoint2Point2));\n\n \/\/ Ctor Vector2\n suite.test(TEST_CASE(TestCtorVector2));\n\n \/\/ Op Assignment\n suite.test(TEST_CASE(TestOpAssignment));\n\n \/\/ Dot Product\n suite.test(TEST_CASE(TestDotProduct));\n\n \/\/ Cross Product\n suite.test(TEST_CASE(TestCrossProduct));\n\n \/\/ Perpendicular\n suite.test(TEST_CASE(TestPerpendicular));\n\n \/\/ Norm\n suite.test(TEST_CASE(TestNorm));\n\n \/\/ NormSquared\n suite.test(TEST_CASE(TestNormSquared));\n\n \/\/ Normalize\n suite.test(TEST_CASE(TestNormalize));\n\n \/\/ Component\n suite.test(TEST_CASE(TestComponent));\n\n \/\/ Projection\n suite.test(TEST_CASE(TestProjection));\n\n \/\/ Angle Between\n suite.test(TEST_CASE(TestAngleBetween));\n\n \/\/ Reflect\n suite.test(TEST_CASE(TestReflect));\n\n return suite.tear_down();\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-2014 Torus Knot Software Ltd\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 \"OgreShaderPrecompiledHeaders.h\"\n#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS\n\n#define SGX_LIB_NORMALMAP \"SGXLib_NormalMap\"\n#define SGX_FUNC_FETCHNORMAL \"SGX_FetchNormal\"\n\nnamespace Ogre {\nnamespace RTShader {\n\n\/************************************************************************\/\n\/* *\/\n\/************************************************************************\/\nconst String SRS_NORMALMAP = \"NormalMap\";\n\n\/\/-----------------------------------------------------------------------\nNormalMapLighting::NormalMapLighting()\n{\n mNormalMapSamplerIndex = 0;\n mVSTexCoordSetIndex = 0;\n mNormalMapSpace = NMS_TANGENT;\n mNormalMapSampler = TextureManager::getSingleton().createSampler();\n mNormalMapSampler->setMipmapBias(-1.0);\n}\n\n\/\/-----------------------------------------------------------------------\nconst String& NormalMapLighting::getType() const\n{\n return SRS_NORMALMAP;\n}\n\/\/-----------------------------------------------------------------------\nbool NormalMapLighting::createCpuSubPrograms(ProgramSet* programSet)\n{\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Function* vsMain = vsProgram->getEntryPointFunction();\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n Function* psMain = psProgram->getEntryPointFunction();\n\n vsProgram->addDependency(FFP_LIB_TRANSFORM);\n\n psProgram->addDependency(FFP_LIB_TRANSFORM);\n psProgram->addDependency(FFP_LIB_TEXTURING);\n psProgram->addDependency(SGX_LIB_NORMALMAP);\n\n \/\/ Resolve texture coordinates.\n auto vsInTexcoord = vsMain->resolveInputParameter(\n Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2);\n auto vsOutTexcoord = vsMain->resolveOutputParameter(\n Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2);\n auto psInTexcoord = psMain->resolveInputParameter(vsOutTexcoord);\n\n \/\/ Resolve normal.\n auto vsInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE);\n auto vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE);\n auto viewNormal = psMain->resolveInputParameter(vsOutNormal);\n auto newViewNormal = psMain->resolveLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE);\n\n \/\/ insert before lighting stage\n auto vstage = vsMain->getStage(FFP_PS_COLOUR_BEGIN + 1);\n auto fstage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 1);\n\n \/\/ Output texture coordinates.\n vstage.assign(vsInTexcoord, vsOutTexcoord);\n\n \/\/ Add the normal fetch function invocation\n auto normalMapSampler = psProgram->resolveParameter(GCT_SAMPLER2D, \"gNormalMapSampler\", mNormalMapSamplerIndex);\n fstage.callFunction(SGX_FUNC_FETCHNORMAL, normalMapSampler, psInTexcoord, newViewNormal);\n\n if (mNormalMapSpace & NMS_TANGENT)\n {\n auto vsInTangent = vsMain->resolveInputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE);\n auto vsOutTangent = vsMain->resolveOutputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE);\n auto psInTangent = psMain->resolveInputParameter(vsOutTangent);\n\n \/\/ transform normal & tangent\n auto normalMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX);\n vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInNormal, vsOutNormal);\n vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInTangent, vsOutTangent);\n\n \/\/ transform normal\n fstage.callFunction(\"SGX_TransformNormal\", {In(viewNormal), In(psInTangent), InOut(newViewNormal)});\n }\n else if (mNormalMapSpace & NMS_OBJECT)\n {\n \/\/ transform normal in FS\n auto normalMatrix = psProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX);\n fstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, newViewNormal, newViewNormal);\n }\n\n if (mNormalMapSpace == NMS_PARALLAX)\n {\n \/\/ assuming: lighting stage computed this\n auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE);\n auto viewPos = psMain->resolveInputParameter(vsOutViewPos);\n\n \/\/ TODO: user specificed scale and bias\n fstage.callFunction(\"SGX_Generate_Parallax_Texcoord\", {In(normalMapSampler), In(psInTexcoord), In(viewPos),\n In(Vector2(0.04, -0.02)), Out(psInTexcoord)});\n\n \/\/ overwrite texcoord0 unconditionally, only one texcoord set is supported with parallax mapping\n \/\/ we are before FFP_PS_TEXTURING, so the new value will be used\n auto texcoord0 = psMain->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2);\n fstage.assign(psInTexcoord, texcoord0);\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid NormalMapLighting::copyFrom(const SubRenderState& rhs)\n{\n const NormalMapLighting& rhsLighting = static_cast(rhs);\n\n mNormalMapSpace = rhsLighting.mNormalMapSpace;\n mNormalMapTextureName = rhsLighting.mNormalMapTextureName;\n mNormalMapSampler = rhsLighting.mNormalMapSampler;\n}\n\n\/\/-----------------------------------------------------------------------\nbool NormalMapLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass)\n{\n TextureUnitState* normalMapTexture = dstPass->createTextureUnitState();\n\n normalMapTexture->setTextureName(mNormalMapTextureName);\n normalMapTexture->setSampler(mNormalMapSampler);\n mNormalMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1;\n\n return true;\n}\n\nbool NormalMapLighting::setParameter(const String& name, const String& value)\n{\n\tif(name == \"normalmap_space\")\n\t{\n \/\/ Normal map defines normals in tangent space.\n if (value == \"tangent_space\")\n {\n setNormalMapSpace(NMS_TANGENT);\n return true;\n }\n \/\/ Normal map defines normals in object space.\n if (value == \"object_space\")\n {\n setNormalMapSpace(NMS_OBJECT);\n return true;\n }\n if (value == \"parallax\")\n {\n setNormalMapSpace(NMS_PARALLAX);\n return true;\n }\n\t\treturn false;\n\t}\n\n\tif(name == \"texture\")\n\t{\n\t\tmNormalMapTextureName = value;\n\t\treturn true;\n\t}\n\n\tif(name == \"texcoord_index\")\n\t{\n\t\tsetTexCoordIndex(StringConverter::parseInt(value));\n\t\treturn true;\n\t}\n\n if(name == \"sampler\")\n {\n auto sampler = TextureManager::getSingleton().getSampler(value);\n if(!sampler)\n return false;\n mNormalMapSampler = sampler;\n return true;\n }\n\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------\nconst String& NormalMapLightingFactory::getType() const\n{\n return SRS_NORMALMAP;\n}\n\n\/\/-----------------------------------------------------------------------\nSubRenderState* NormalMapLightingFactory::createInstance(ScriptCompiler* compiler, \n PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)\n{\n if (prop->name == \"lighting_stage\")\n {\n if(prop->values.size() >= 2)\n {\n String strValue;\n AbstractNodeList::const_iterator it = prop->values.begin();\n \n \/\/ Read light model type.\n if(false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n return NULL;\n }\n\n \/\/ Case light model type is normal map\n if (strValue == \"normal_map\")\n {\n ++it;\n if (false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line);\n return NULL;\n }\n\n \n SubRenderState* subRenderState = createOrRetrieveInstance(translator);\n NormalMapLighting* normalMapSubRenderState = static_cast(subRenderState);\n \n normalMapSubRenderState->setParameter(\"texture\", strValue);\n\n \n \/\/ Read normal map space type.\n if (prop->values.size() >= 3)\n { \n ++it;\n if (false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line);\n return NULL;\n }\n\n if(!normalMapSubRenderState->setParameter(\"normalmap_space\", strValue))\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n return NULL;\n }\n }\n\n \/\/ Read texture coordinate index.\n if (prop->values.size() >= 4)\n { \n unsigned int textureCoordinateIndex = 0;\n\n ++it;\n if (SGScriptTranslator::getUInt(*it, &textureCoordinateIndex))\n {\n normalMapSubRenderState->setTexCoordIndex(textureCoordinateIndex);\n }\n }\n\n \/\/ Read texture filtering format.\n if (prop->values.size() >= 5)\n {\n ++it;\n if (false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line);\n return NULL;\n }\n\n \/\/ sampler reference\n if(!normalMapSubRenderState->setParameter(\"sampler\", strValue))\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n return NULL;\n }\n }\n \n return subRenderState; \n }\n }\n }\n\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid NormalMapLightingFactory::writeInstance(MaterialSerializer* ser, \n SubRenderState* subRenderState, \n Pass* srcPass, Pass* dstPass)\n{\n NormalMapLighting* normalMapSubRenderState = static_cast(subRenderState);\n\n ser->writeAttribute(4, \"lighting_stage\");\n ser->writeValue(\"normal_map\");\n ser->writeValue(normalMapSubRenderState->getNormalMapTextureName()); \n \n if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_TANGENT)\n {\n ser->writeValue(\"tangent_space\");\n }\n else if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_OBJECT)\n {\n ser->writeValue(\"object_space\");\n }\n\n ser->writeValue(StringConverter::toString(normalMapSubRenderState->getTexCoordIndex()));\n}\n\n\/\/-----------------------------------------------------------------------\nSubRenderState* NormalMapLightingFactory::createInstanceImpl()\n{\n return OGRE_NEW NormalMapLighting;\n}\n\n}\n}\n\n#endif\nRTSS: NormalMap - we must normalise tangents & normals in VS\/*\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-2014 Torus Knot Software Ltd\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 \"OgreShaderPrecompiledHeaders.h\"\n#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS\n\n#define SGX_LIB_NORMALMAP \"SGXLib_NormalMap\"\n#define SGX_FUNC_FETCHNORMAL \"SGX_FetchNormal\"\n\nnamespace Ogre {\nnamespace RTShader {\n\n\/************************************************************************\/\n\/* *\/\n\/************************************************************************\/\nconst String SRS_NORMALMAP = \"NormalMap\";\n\n\/\/-----------------------------------------------------------------------\nNormalMapLighting::NormalMapLighting()\n{\n mNormalMapSamplerIndex = 0;\n mVSTexCoordSetIndex = 0;\n mNormalMapSpace = NMS_TANGENT;\n mNormalMapSampler = TextureManager::getSingleton().createSampler();\n mNormalMapSampler->setMipmapBias(-1.0);\n}\n\n\/\/-----------------------------------------------------------------------\nconst String& NormalMapLighting::getType() const\n{\n return SRS_NORMALMAP;\n}\n\/\/-----------------------------------------------------------------------\nbool NormalMapLighting::createCpuSubPrograms(ProgramSet* programSet)\n{\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Function* vsMain = vsProgram->getEntryPointFunction();\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n Function* psMain = psProgram->getEntryPointFunction();\n\n vsProgram->addDependency(FFP_LIB_TRANSFORM);\n\n psProgram->addDependency(FFP_LIB_TRANSFORM);\n psProgram->addDependency(FFP_LIB_TEXTURING);\n psProgram->addDependency(SGX_LIB_NORMALMAP);\n\n \/\/ Resolve texture coordinates.\n auto vsInTexcoord = vsMain->resolveInputParameter(\n Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2);\n auto vsOutTexcoord = vsMain->resolveOutputParameter(\n Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2);\n auto psInTexcoord = psMain->resolveInputParameter(vsOutTexcoord);\n\n \/\/ Resolve normal.\n auto vsInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE);\n auto vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE);\n auto viewNormal = psMain->resolveInputParameter(vsOutNormal);\n auto newViewNormal = psMain->resolveLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE);\n\n \/\/ insert before lighting stage\n auto vstage = vsMain->getStage(FFP_PS_COLOUR_BEGIN + 1);\n auto fstage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 1);\n\n \/\/ Output texture coordinates.\n vstage.assign(vsInTexcoord, vsOutTexcoord);\n\n \/\/ Add the normal fetch function invocation\n auto normalMapSampler = psProgram->resolveParameter(GCT_SAMPLER2D, \"gNormalMapSampler\", mNormalMapSamplerIndex);\n fstage.callFunction(SGX_FUNC_FETCHNORMAL, normalMapSampler, psInTexcoord, newViewNormal);\n\n if (mNormalMapSpace & NMS_TANGENT)\n {\n auto vsInTangent = vsMain->resolveInputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE);\n auto vsOutTangent = vsMain->resolveOutputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE);\n auto psInTangent = psMain->resolveInputParameter(vsOutTangent);\n\n \/\/ transform normal & tangent\n auto normalMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX);\n vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInNormal, vsOutNormal);\n vstage.callBuiltin(\"normalize\", vsOutNormal, vsOutNormal);\n vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInTangent, vsOutTangent);\n vstage.callBuiltin(\"normalize\", vsOutTangent, vsOutTangent);\n\n \/\/ transform normal\n fstage.callFunction(\"SGX_TransformNormal\", {In(viewNormal), In(psInTangent), InOut(newViewNormal)});\n }\n else if (mNormalMapSpace & NMS_OBJECT)\n {\n \/\/ transform normal in FS\n auto normalMatrix = psProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX);\n fstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, newViewNormal, newViewNormal);\n }\n\n if (mNormalMapSpace == NMS_PARALLAX)\n {\n \/\/ assuming: lighting stage computed this\n auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE);\n auto viewPos = psMain->resolveInputParameter(vsOutViewPos);\n\n \/\/ TODO: user specificed scale and bias\n fstage.callFunction(\"SGX_Generate_Parallax_Texcoord\", {In(normalMapSampler), In(psInTexcoord), In(viewPos),\n In(Vector2(0.04, -0.02)), Out(psInTexcoord)});\n\n \/\/ overwrite texcoord0 unconditionally, only one texcoord set is supported with parallax mapping\n \/\/ we are before FFP_PS_TEXTURING, so the new value will be used\n auto texcoord0 = psMain->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2);\n fstage.assign(psInTexcoord, texcoord0);\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid NormalMapLighting::copyFrom(const SubRenderState& rhs)\n{\n const NormalMapLighting& rhsLighting = static_cast(rhs);\n\n mNormalMapSpace = rhsLighting.mNormalMapSpace;\n mNormalMapTextureName = rhsLighting.mNormalMapTextureName;\n mNormalMapSampler = rhsLighting.mNormalMapSampler;\n}\n\n\/\/-----------------------------------------------------------------------\nbool NormalMapLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass)\n{\n TextureUnitState* normalMapTexture = dstPass->createTextureUnitState();\n\n normalMapTexture->setTextureName(mNormalMapTextureName);\n normalMapTexture->setSampler(mNormalMapSampler);\n mNormalMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1;\n\n return true;\n}\n\nbool NormalMapLighting::setParameter(const String& name, const String& value)\n{\n\tif(name == \"normalmap_space\")\n\t{\n \/\/ Normal map defines normals in tangent space.\n if (value == \"tangent_space\")\n {\n setNormalMapSpace(NMS_TANGENT);\n return true;\n }\n \/\/ Normal map defines normals in object space.\n if (value == \"object_space\")\n {\n setNormalMapSpace(NMS_OBJECT);\n return true;\n }\n if (value == \"parallax\")\n {\n setNormalMapSpace(NMS_PARALLAX);\n return true;\n }\n\t\treturn false;\n\t}\n\n\tif(name == \"texture\")\n\t{\n\t\tmNormalMapTextureName = value;\n\t\treturn true;\n\t}\n\n\tif(name == \"texcoord_index\")\n\t{\n\t\tsetTexCoordIndex(StringConverter::parseInt(value));\n\t\treturn true;\n\t}\n\n if(name == \"sampler\")\n {\n auto sampler = TextureManager::getSingleton().getSampler(value);\n if(!sampler)\n return false;\n mNormalMapSampler = sampler;\n return true;\n }\n\n\treturn false;\n}\n\n\/\/-----------------------------------------------------------------------\nconst String& NormalMapLightingFactory::getType() const\n{\n return SRS_NORMALMAP;\n}\n\n\/\/-----------------------------------------------------------------------\nSubRenderState* NormalMapLightingFactory::createInstance(ScriptCompiler* compiler, \n PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator)\n{\n if (prop->name == \"lighting_stage\")\n {\n if(prop->values.size() >= 2)\n {\n String strValue;\n AbstractNodeList::const_iterator it = prop->values.begin();\n \n \/\/ Read light model type.\n if(false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n return NULL;\n }\n\n \/\/ Case light model type is normal map\n if (strValue == \"normal_map\")\n {\n ++it;\n if (false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line);\n return NULL;\n }\n\n \n SubRenderState* subRenderState = createOrRetrieveInstance(translator);\n NormalMapLighting* normalMapSubRenderState = static_cast(subRenderState);\n \n normalMapSubRenderState->setParameter(\"texture\", strValue);\n\n \n \/\/ Read normal map space type.\n if (prop->values.size() >= 3)\n { \n ++it;\n if (false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line);\n return NULL;\n }\n\n if(!normalMapSubRenderState->setParameter(\"normalmap_space\", strValue))\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n return NULL;\n }\n }\n\n \/\/ Read texture coordinate index.\n if (prop->values.size() >= 4)\n { \n unsigned int textureCoordinateIndex = 0;\n\n ++it;\n if (SGScriptTranslator::getUInt(*it, &textureCoordinateIndex))\n {\n normalMapSubRenderState->setTexCoordIndex(textureCoordinateIndex);\n }\n }\n\n \/\/ Read texture filtering format.\n if (prop->values.size() >= 5)\n {\n ++it;\n if (false == SGScriptTranslator::getString(*it, &strValue))\n {\n compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line);\n return NULL;\n }\n\n \/\/ sampler reference\n if(!normalMapSubRenderState->setParameter(\"sampler\", strValue))\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n return NULL;\n }\n }\n \n return subRenderState; \n }\n }\n }\n\n return NULL;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid NormalMapLightingFactory::writeInstance(MaterialSerializer* ser, \n SubRenderState* subRenderState, \n Pass* srcPass, Pass* dstPass)\n{\n NormalMapLighting* normalMapSubRenderState = static_cast(subRenderState);\n\n ser->writeAttribute(4, \"lighting_stage\");\n ser->writeValue(\"normal_map\");\n ser->writeValue(normalMapSubRenderState->getNormalMapTextureName()); \n \n if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_TANGENT)\n {\n ser->writeValue(\"tangent_space\");\n }\n else if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_OBJECT)\n {\n ser->writeValue(\"object_space\");\n }\n\n ser->writeValue(StringConverter::toString(normalMapSubRenderState->getTexCoordIndex()));\n}\n\n\/\/-----------------------------------------------------------------------\nSubRenderState* NormalMapLightingFactory::createInstanceImpl()\n{\n return OGRE_NEW NormalMapLighting;\n}\n\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*------------ant.cpp---------------------------------------------------------\/\/\n*\n* ants -- We have them\n*\n* Purpose: Figure out ant pathing to food. I want food.\n*\n*-----------------------------------------------------------------------------*\/\n\n#include \n#include \n\n\/*----------------------------------------------------------------------------\/\/\n* STRUCTS\n*-----------------------------------------------------------------------------*\/\n\nconst int n = 5;\n\nstruct coord{\n int x, y;\n};\n\nstruct ant{\n coord pos;\n std::vector phepath, antpath;\n int step;\n};\n\nstruct grid{\n bool wall[n][n];\n coord prize;\n};\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(){\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINES\n*-----------------------------------------------------------------------------*\/\nupdating generation 1 pathing.\/*------------ant.cpp---------------------------------------------------------\/\/\n*\n* ants -- We have them\n*\n* Purpose: Figure out ant pathing to food. I want food.\n*\n*-----------------------------------------------------------------------------*\/\n\n#include \n#include \n#include \n\n\/*----------------------------------------------------------------------------\/\/\n* STRUCTS\n*-----------------------------------------------------------------------------*\/\n\n\/\/ grid size\nconst int n = 5;\n\n\/\/ structs for ant movement\nstruct coord{\n int x, y;\n};\n\nstruct ant{\n coord pos;\n std::vector phepath, antpath;\n int step;\n};\n\nstruct grid{\n bool wall[n][n];\n coord prize;\n};\n\n\/\/ Functions for ant movement\n\/\/ Chooses step\nant step1(ant curr, grid landscape, coord spawn_point);\n\nant step(ant curr, grid landscape, coord spawn_point);\n\n\/\/ Generates ants\nstd::vector gen_ants(coord spawn_point);\n\n\/\/ Moves simulation every timestep\nstd::vector move(std::vector ants, grid landscape);\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(){\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINES\n*-----------------------------------------------------------------------------*\/\n\n\/\/ Chooses step\nant step1(ant curr, grid landscape, coord spawn_point){\n\n coord next_step[3];\n coord up, down, left, right, next;\n int pcount = 0;\n\n up.x = curr.pos.x; up.y = curr.pos.y + 1;\n down.x = curr.pos.x; down.y = curr.pos.y - 1;\n left.x = curr.pos.x - 1; left.y = curr.pos.y;\n right.x = curr.pos.x + 1; right.y = curr.pos.y;\n\n \/\/ determine possible movement\n for (int i = 0; i < 4; i++){\n switch(i){\n \/\/ up case\n case 0:\n if (up.x == curr.antpath.back().x &&\n up.y == curr.antpath.back().y){\n }\n else{\n next_step[pcount] = up;\n pcount++;\n }\n break;\n\n \/\/ down case\n case 1:\n if (down.x == curr.antpath.back().x &&\n down.y == curr.antpath.back().y){\n }\n else{\n next_step[pcount] = down;\n pcount++;\n }\n break;\n\n \/\/ left case\n case 2:\n if (left.x == curr.antpath.back().x &&\n left.y == curr.antpath.back().y){\n }\n else{\n next_step[pcount] = left;\n pcount++;\n }\n break;\n\n \/\/ right case\n case 3:\n if (right.x == curr.antpath.back().x &&\n right.y == curr.antpath.back().y){\n }\n else{\n next_step[pcount] = right;\n pcount++;\n }\n break;\n\n }\n\n }\n\n static std::random_device rd;\n int seed = rd();\n static std::mt19937 gen(seed);\n\n std::uniform_int_distribution ant_distribution(0,3);\n\n next = next_step[ant_distribution(gen)];\n\n curr.antpath.push_back(curr.pos);\n curr.pos = next;\n\n return curr;\n\n}\n\n<|endoftext|>"} {"text":"\/**\n* @file CleanRoleDecision.h\n*\n* @author Schahin Tofangchi<\/a>\n*\/\n\n#include \"CleanRoleDecision.h\"\n#include \n#include \n\n#include \n#include \n\nusing namespace std;\n\n\nCleanRoleDecision::CleanRoleDecision()\n{\n getDebugParameterList().add(¶meters);\n\n DEBUG_REQUEST_REGISTER(\"RoleDecision:min_ball_distance\", \"draws the circle of the min. ball distance to be recognized as different balls between first\/second striker.\", false);\n}\n\nCleanRoleDecision::~CleanRoleDecision()\n{\n getDebugParameterList().remove(¶meters);\n}\n\nvoid CleanRoleDecision::execute() {\n computeStrikers();\n\n \/\/ reset second striker decision, if we doesn't want to use the second striker\n if(!parameters.useSecondStriker) {\n getRoleDecisionModel().secondStriker = std::numeric_limits::max();\n }\n}\/\/end execute\n\nvoid CleanRoleDecision::computeStrikers()\n{\n \/\/ skip \"first frame\"! (until i add myself to teamcomm)\n if(getTeamMessage().data.find(getPlayerInfo().playerNumber) == getTeamMessage().data.end()) { return; }\n\n \/\/ container storing robots, which want to be striker, sorted by their playernumber and their time to ball\n std::map possible_striker;\n\n \/\/ iterate over all robots(messages)\n for (auto const& i : getTeamMessage().data) {\n unsigned int robotNumber = i.first;\n const TeamMessageData& msg = i.second;\n\n \/\/ if striker lost the ball, he gets a time bonus before he lost the ball completely ...\n double loose_ball_bonus = msg.playerNumber == getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0;\n\n \/\/ check if the robot is able to play and sees the ball\n bool isRobotInactive = !getTeamMessagePlayersState().isPlaying(robotNumber)\n || msg.ballAge < 0 \/\/Ball was never seen\n || (msg.ballAge + getFrameInfo().getTimeSince(msg.frameInfo.getTime()) > parameters.maxBallLostTime + loose_ball_bonus); \/\/Ball isn't fresh\n\n \/\/ ignore inactive robots\n if(robotNumber != getPlayerInfo().playerNumber && isRobotInactive) { continue; }\n\n \/\/ for all active robots, which sees the ball AND previously announced to want to be striker OR is striker ...\n if (msg.custom.wantsToBeStriker || msg.custom.wasStriker) {\n \/\/ ... remember them as possible striker with their time to ball\n possible_striker[robotNumber] = msg.custom.timeToBall;\n }\n }\/\/end for\n\n \/\/ get my own message\n auto ownMessage = getTeamMessage().data.at(getPlayerInfo().playerNumber);\n \/\/ i want to be striker, if i'm not the goalie and i'm \"active\" (not fallen\/penalized, see the ball)!!!\n getRoleDecisionModel().wantsToBeStriker = ownMessage.playerNumber != 1\n && getTeamMessagePlayersState().isPlaying(getPlayerInfo().playerNumber)\n && !(ownMessage.ballAge < 0\n || (ownMessage.ballAge + getFrameInfo().getTimeSince(ownMessage.frameInfo.getTime()) > parameters.maxBallLostTime + (getPlayerInfo().playerNumber==getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0)));\n\n \/\/ if i'm striker, i get a time bonus!\n \/\/ NOTE: ownTimeToBall can be negative if the robot is close to ball (!)\n double ownTimeToBall = static_cast(ownMessage.custom.timeToBall) - (ownMessage.custom.wasStriker ? 300.0 : 0.0);\n\n \/\/ clear for new striker decision\n getRoleDecisionModel().resetStriker();\n (this->*parameters.strikerSelectionFunction)(possible_striker, ownTimeToBall);\n\n\n PLOT(std::string(\"CleanRoleDecision:FirstStrikerDecision\"), getRoleDecisionModel().firstStriker);\n PLOT(std::string(\"CleanRoleDecision:SecondStrikerDecision\"), getRoleDecisionModel().secondStriker);\n PLOT(std::string(\"CleanRoleDecision:PossibleStriker\"), static_cast(possible_striker.size()));\n}\n\nvoid CleanRoleDecision::strikerSelectionByNumber(std::map& possible_striker, double& ownTimeToBall)\n{\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/If two robots want to be striker, the one with a smaller number is favoured => is the first in the map!!\n \/\/ NOTE: we're doesn't using 'timeToBall' as decision criteria by intention!\n \/\/ if goalie is striker, he get's the first striker\n if(getRoleDecisionModel().firstStriker == std::numeric_limits::max()) {\n getRoleDecisionModel().firstStriker = it->first;\n } else if (getRoleDecisionModel().secondStriker == std::numeric_limits::max()) {\n getRoleDecisionModel().secondStriker = it->first;\n }\n \/\/ if there's a robot closer to the ball than myself, i don't want to be striker!\n if(it->second < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nvoid CleanRoleDecision::strikerSelectionByTime(std::map& possible_striker, double &ownTimeToBall)\n{\n unsigned int stFastest = std::numeric_limits::max(); \/\/ time to ball of the fastest player\n unsigned int ndFastest = std::numeric_limits::max(); \/\/ time to ball of the second fastest player\n\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/ current player faster?\n if(it->second < stFastest) {\n \/\/ is there already a \"fastest\" striker ... but the current player is faster\n if(getRoleDecisionModel().firstStriker != std::numeric_limits::max()) {\n \/\/ make the previous player the \"second fastest\" player\n getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker;\n ndFastest = stFastest;\n }\n \/\/ set the fastest player\n getRoleDecisionModel().firstStriker = it->first;\n stFastest = it->second;\n } else if (it->second < ndFastest) {\n \/\/ set the second fastest player\n getRoleDecisionModel().secondStriker = it->first;\n ndFastest = it->second;\n }\n \/\/ if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker!\n if(ndFastest < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nvoid CleanRoleDecision::strikerSelectionByTimeExceptGoalie(std::map& possible_striker, double &ownTimeToBall)\n{\n unsigned int stFastest = std::numeric_limits::max(); \/\/ time to ball of the fastest player\n unsigned int ndFastest = std::numeric_limits::max(); \/\/ time to ball of the second fastest player\n\n \/\/ NOTE: if the goalie is one of the \"possible striker\", it gets set as first strike! (sorted map!)\n \/\/ and doesn't change, even if someone is faster (condition!)\n \/\/ ATTENTION: we're iterating from the smallest player number to the highest!\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/ is current player clearly faster?\n if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) {\n \/\/ is there already a \"fastest\" striker ... but the current player is faster\n if(getRoleDecisionModel().firstStriker != std::numeric_limits::max()) {\n \/\/ make the previous player the \"second fastest\" player\n getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker;\n ndFastest = stFastest;\n }\n \/\/ set the fastest player\n getRoleDecisionModel().firstStriker = it->first;\n stFastest = it->second;\n } else if (it->second < ndFastest && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest) {\n \/\/ set the second (clearly) fastest player\n getRoleDecisionModel().secondStriker = it->first;\n ndFastest = it->second;\n }\n \/\/ if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker!\n if(ndFastest < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nvoid CleanRoleDecision::strikerSelectionByTimeExceptGoalieWithBallCompare(std::map& possible_striker, double &ownTimeToBall)\n{\n unsigned int stFastest = std::numeric_limits::max(); \/\/ time to ball of the fastest player\n unsigned int ndFastest = std::numeric_limits::max(); \/\/ time to ball of the second fastest player\n\n \/\/ NOTE: if the goalie is one of the \"possible striker\", it gets set as first strike! (sorted map!)\n \/\/ and doesn't change, even if someone is faster (condition!)\n \/\/ ATTENTION: we're iterating from the smallest player number to the highest!\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/ is current player clearly faster?\n if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) {\n \/\/ is there already a \"fastest\" striker ... but the current player is faster\n if(getRoleDecisionModel().firstStriker != std::numeric_limits::max() && isSecondStrikerDifferentFromFirst(getRoleDecisionModel().firstStriker, it->first)) {\n \/\/ make the previous player the \"second fastest\" player, if they see different balls\n getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker;\n ndFastest = stFastest;\n }\n \/\/ set the fastest player\n getRoleDecisionModel().firstStriker = it->first;\n stFastest = it->second;\n } else if (it->second < ndFastest && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest && isSecondStrikerDifferentFromFirst(getRoleDecisionModel().firstStriker, it->first)) {\n \/\/ make the previous player the \"second fastest\" player, if they see different balls\n getRoleDecisionModel().secondStriker = it->first;\n ndFastest = it->second;\n }\n \/\/ if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker!\n if(ndFastest < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nbool CleanRoleDecision::isSecondStrikerDifferentFromFirst(unsigned int firstNumber, unsigned int secondNumber) {\n \/\/ retrieve the message of the players\n const auto& first = getTeamMessage().data.at(firstNumber);\n const auto& second = getTeamMessage().data.at(secondNumber);\n \/\/ get the global ball position\n Vector2d firstBall = first.pose * first.ballPosition;\n Vector2d secondBall = second.pose * second.ballPosition;\n \/\/ check if the ball distance is greater than the given parameter distance radius\n double r = parameters.radius(first.ballPosition, second.ballPosition);\n\n DEBUG_REQUEST(\"RoleDecision:min_ball_distance\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"000000\", 30);\n CIRCLE(firstBall.x, firstBall.y, r);\n TEXT_DRAWING(firstBall.x, firstBall.y, secondNumber);\n );\n\n return ((firstBall - secondBall).abs2() > r*r);\n}\nbetter description\/info of the drawing\/**\n* @file CleanRoleDecision.h\n*\n* @author Schahin Tofangchi<\/a>\n*\/\n\n#include \"CleanRoleDecision.h\"\n#include \n#include \n\n#include \n#include \n\nusing namespace std;\n\n\nCleanRoleDecision::CleanRoleDecision()\n{\n getDebugParameterList().add(¶meters);\n\n DEBUG_REQUEST_REGISTER(\n \"RoleDecision:min_ball_distance\",\n \"Draws the distance in which the balls of the first and second striker are recognized as identical (only with strikerSelection = 3).\",\n false\n );\n}\n\nCleanRoleDecision::~CleanRoleDecision()\n{\n getDebugParameterList().remove(¶meters);\n}\n\nvoid CleanRoleDecision::execute() {\n computeStrikers();\n\n \/\/ reset second striker decision, if we doesn't want to use the second striker\n if(!parameters.useSecondStriker) {\n getRoleDecisionModel().secondStriker = std::numeric_limits::max();\n }\n}\/\/end execute\n\nvoid CleanRoleDecision::computeStrikers()\n{\n \/\/ skip \"first frame\"! (until i add myself to teamcomm)\n if(getTeamMessage().data.find(getPlayerInfo().playerNumber) == getTeamMessage().data.end()) { return; }\n\n \/\/ container storing robots, which want to be striker, sorted by their playernumber and their time to ball\n std::map possible_striker;\n\n \/\/ iterate over all robots(messages)\n for (auto const& i : getTeamMessage().data) {\n unsigned int robotNumber = i.first;\n const TeamMessageData& msg = i.second;\n\n \/\/ if striker lost the ball, he gets a time bonus before he lost the ball completely ...\n double loose_ball_bonus = msg.playerNumber == getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0;\n\n \/\/ check if the robot is able to play and sees the ball\n bool isRobotInactive = !getTeamMessagePlayersState().isPlaying(robotNumber)\n || msg.ballAge < 0 \/\/Ball was never seen\n || (msg.ballAge + getFrameInfo().getTimeSince(msg.frameInfo.getTime()) > parameters.maxBallLostTime + loose_ball_bonus); \/\/Ball isn't fresh\n\n \/\/ ignore inactive robots\n if(robotNumber != getPlayerInfo().playerNumber && isRobotInactive) { continue; }\n\n \/\/ for all active robots, which sees the ball AND previously announced to want to be striker OR is striker ...\n if (msg.custom.wantsToBeStriker || msg.custom.wasStriker) {\n \/\/ ... remember them as possible striker with their time to ball\n possible_striker[robotNumber] = msg.custom.timeToBall;\n }\n }\/\/end for\n\n \/\/ get my own message\n auto ownMessage = getTeamMessage().data.at(getPlayerInfo().playerNumber);\n \/\/ i want to be striker, if i'm not the goalie and i'm \"active\" (not fallen\/penalized, see the ball)!!!\n getRoleDecisionModel().wantsToBeStriker = ownMessage.playerNumber != 1\n && getTeamMessagePlayersState().isPlaying(getPlayerInfo().playerNumber)\n && !(ownMessage.ballAge < 0\n || (ownMessage.ballAge + getFrameInfo().getTimeSince(ownMessage.frameInfo.getTime()) > parameters.maxBallLostTime + (getPlayerInfo().playerNumber==getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0)));\n\n \/\/ if i'm striker, i get a time bonus!\n \/\/ NOTE: ownTimeToBall can be negative if the robot is close to ball (!)\n double ownTimeToBall = static_cast(ownMessage.custom.timeToBall) - (ownMessage.custom.wasStriker ? 300.0 : 0.0);\n\n \/\/ clear for new striker decision\n getRoleDecisionModel().resetStriker();\n (this->*parameters.strikerSelectionFunction)(possible_striker, ownTimeToBall);\n\n\n PLOT(std::string(\"CleanRoleDecision:FirstStrikerDecision\"), getRoleDecisionModel().firstStriker);\n PLOT(std::string(\"CleanRoleDecision:SecondStrikerDecision\"), getRoleDecisionModel().secondStriker);\n PLOT(std::string(\"CleanRoleDecision:PossibleStriker\"), static_cast(possible_striker.size()));\n}\n\nvoid CleanRoleDecision::strikerSelectionByNumber(std::map& possible_striker, double& ownTimeToBall)\n{\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/If two robots want to be striker, the one with a smaller number is favoured => is the first in the map!!\n \/\/ NOTE: we're doesn't using 'timeToBall' as decision criteria by intention!\n \/\/ if goalie is striker, he get's the first striker\n if(getRoleDecisionModel().firstStriker == std::numeric_limits::max()) {\n getRoleDecisionModel().firstStriker = it->first;\n } else if (getRoleDecisionModel().secondStriker == std::numeric_limits::max()) {\n getRoleDecisionModel().secondStriker = it->first;\n }\n \/\/ if there's a robot closer to the ball than myself, i don't want to be striker!\n if(it->second < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nvoid CleanRoleDecision::strikerSelectionByTime(std::map& possible_striker, double &ownTimeToBall)\n{\n unsigned int stFastest = std::numeric_limits::max(); \/\/ time to ball of the fastest player\n unsigned int ndFastest = std::numeric_limits::max(); \/\/ time to ball of the second fastest player\n\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/ current player faster?\n if(it->second < stFastest) {\n \/\/ is there already a \"fastest\" striker ... but the current player is faster\n if(getRoleDecisionModel().firstStriker != std::numeric_limits::max()) {\n \/\/ make the previous player the \"second fastest\" player\n getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker;\n ndFastest = stFastest;\n }\n \/\/ set the fastest player\n getRoleDecisionModel().firstStriker = it->first;\n stFastest = it->second;\n } else if (it->second < ndFastest) {\n \/\/ set the second fastest player\n getRoleDecisionModel().secondStriker = it->first;\n ndFastest = it->second;\n }\n \/\/ if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker!\n if(ndFastest < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nvoid CleanRoleDecision::strikerSelectionByTimeExceptGoalie(std::map& possible_striker, double &ownTimeToBall)\n{\n unsigned int stFastest = std::numeric_limits::max(); \/\/ time to ball of the fastest player\n unsigned int ndFastest = std::numeric_limits::max(); \/\/ time to ball of the second fastest player\n\n \/\/ NOTE: if the goalie is one of the \"possible striker\", it gets set as first strike! (sorted map!)\n \/\/ and doesn't change, even if someone is faster (condition!)\n \/\/ ATTENTION: we're iterating from the smallest player number to the highest!\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/ is current player clearly faster?\n if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) {\n \/\/ is there already a \"fastest\" striker ... but the current player is faster\n if(getRoleDecisionModel().firstStriker != std::numeric_limits::max()) {\n \/\/ make the previous player the \"second fastest\" player\n getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker;\n ndFastest = stFastest;\n }\n \/\/ set the fastest player\n getRoleDecisionModel().firstStriker = it->first;\n stFastest = it->second;\n } else if (it->second < ndFastest && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest) {\n \/\/ set the second (clearly) fastest player\n getRoleDecisionModel().secondStriker = it->first;\n ndFastest = it->second;\n }\n \/\/ if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker!\n if(ndFastest < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nvoid CleanRoleDecision::strikerSelectionByTimeExceptGoalieWithBallCompare(std::map& possible_striker, double &ownTimeToBall)\n{\n unsigned int stFastest = std::numeric_limits::max(); \/\/ time to ball of the fastest player\n unsigned int ndFastest = std::numeric_limits::max(); \/\/ time to ball of the second fastest player\n\n \/\/ NOTE: if the goalie is one of the \"possible striker\", it gets set as first strike! (sorted map!)\n \/\/ and doesn't change, even if someone is faster (condition!)\n \/\/ ATTENTION: we're iterating from the smallest player number to the highest!\n for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) {\n \/\/ is current player clearly faster?\n if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) {\n \/\/ is there already a \"fastest\" striker ... but the current player is faster\n if(getRoleDecisionModel().firstStriker != std::numeric_limits::max() && isSecondStrikerDifferentFromFirst(it->first, getRoleDecisionModel().firstStriker)) {\n \/\/ make the previous player the \"second fastest\" player, if they see different balls\n getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker;\n ndFastest = stFastest;\n }\n \/\/ set the fastest player\n getRoleDecisionModel().firstStriker = it->first;\n stFastest = it->second;\n } else if (it->second < ndFastest\n && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest\n && isSecondStrikerDifferentFromFirst(getRoleDecisionModel().firstStriker, it->first))\n {\n \/\/ make the previous player the \"second fastest\" player, if they see different balls\n getRoleDecisionModel().secondStriker = it->first;\n ndFastest = it->second;\n }\n \/\/ if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker!\n if(ndFastest < ownTimeToBall) {\n getRoleDecisionModel().wantsToBeStriker = false;\n }\n }\n}\n\nbool CleanRoleDecision::isSecondStrikerDifferentFromFirst(unsigned int firstNumber, unsigned int secondNumber) {\n \/\/ retrieve the message of the players\n const auto& first = getTeamMessage().data.at(firstNumber);\n const auto& second = getTeamMessage().data.at(secondNumber);\n \/\/ get the global ball position\n Vector2d firstBall = first.pose * first.ballPosition;\n Vector2d secondBall = second.pose * second.ballPosition;\n \/\/ check if the ball distance is greater than the given parameter distance radius\n double r = parameters.radius(first.ballPosition, second.ballPosition);\n\n DEBUG_REQUEST(\"RoleDecision:min_ball_distance\",\n FIELD_DRAWING_CONTEXT;\n PEN(\"000000\", 30);\n CIRCLE(firstBall.x, firstBall.y, r);\n TEXT_DRAWING(firstBall.x, firstBall.y+60, secondNumber);\n TEXT_DRAWING(firstBall.x, firstBall.y-60, r);\n );\n\n return ((firstBall - secondBall).abs2() > r*r);\n}\n<|endoftext|>"} {"text":"\/\/#####################################################################\n\/\/ Module math\n\/\/#####################################################################\n#include \n\nvoid wrap_math() {\n OTHER_WRAP(uint128)\n OTHER_WRAP(numeric_limits)\n}\nutility\/module: Wrap integer_log for Python\/\/#####################################################################\n\/\/ Module math\n\/\/#####################################################################\n#include \n#include \nusing namespace other;\n\nvoid wrap_math() {\n OTHER_WRAP(uint128)\n OTHER_WRAP(numeric_limits)\n OTHER_FUNCTION_2(integer_log,static_cast(integer_log));\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ API.cpp\n\/\/ miniSQL\n\/\/\n\/\/ Created by Kael on 11\/3\/14.\n\/\/ Copyright (c) 2014 Xinyuan Lu. All rights reserved.\n\/\/\n\n\/\/ v2.0, see comment in \"APT.h\"\n\n#include \"API.h\"\n\nRecordinfo API::dealCmd(sqlcommand& sql){\n\t\/\/ 使用get方法更好,这里先直接调用public\n\tswitch(sql.sqlType){\n\t\tcase 0:\n\t\treturn select(sql);\n\t\tbreak;\n\t\tcase 1:\n\t\treturn del(sql);\n\t\tbreak;\n\t\tcase 2:\n\t\treturn insert(sql);\n\t\tbreak;\n\t\tcase 3:\n\t\treturn createTable(sql);\n\t\tbreak;\n\t\tcase 4:\n\t\treturn createIndex(sql);\n\t\tbreak;\n\t\tcase 5:\n\t\treturn dropTable(sql);\n\t\tbreak;\n\t\tcase 6:\n\t\treturn dropIndex(sql);\n\t\tbreak;\n\t}\n\treturn Recordinfo();\n}\n\nint API::AttrCount(std::string tablename){\n\treturn catalogmanager->AttrCount(tablename);\n}\nbool API::TableExists(std::string tablename){\n\treturn catalogmanager->TableExists(tablename);\n}\nbool API::IndexExists(std::string indexname){\n\treturn catalogmanager->IndexExists(indexname);\n}\nbool API::AttrExists(std::string attrname,std::string tablename){\n\treturn catalogmanager->AttrExists(attrname, tablename);\n}\n\n\/\/ 以下所有的都需要错误输入的检查?\nRecordinfo API::select(sqlcommand& sql){\n\t\/\/ 先到catalog查看是否有index\n\t\/\/ 如果有就用,然后作intersection\n\t\/\/ 如果没有,直接交给record?\n\t\/\/ 可以减少数据传递的overhead\n\tbool flag=false;\n std::vector >::iterator conditioni;\n\tRecordinfo result;\n \n\tint IndexAttrType=0x7fff;\n\n\tfor(conditioni=sql.conditions.begin(); conditionihasIndex(sql.tablename, (*conditioni).at(0));\n\t\tif(flag) {\n\t\t\tIndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0));\n\t\t\tbreak;\n\t\t}\n\t}\n \n \/\/ 需要商量\n Table table=catalogmanager->getTable(sql.tablename);\n \n\tif(!flag) {\n\t\tstd::vector slots;\n\t\tresult=recordmanager->Select_Record(sql, table, false, slots);\n\t}\n\telse{\n\t\tValue *v=NULL;\n\t\tswitch(IndexAttrType){\n\t\t\tcase 0:\n\t\t\tv=new Value(IndexAttrType, std::stoi((*conditioni).at(2)));\n\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\tv=new Value(IndexAttrType, (*conditioni).at(2));\n\t\t\tbreak;\n\t\t\tcase -1:\n\t\t\tv=new Value(IndexAttrType, std::stof((*conditioni).at(2)));\n\t\t\tbreak;\n\t\t}\n\t\tIndexManager *indexmanager=new IndexManager();\n \n std::vector s;\n\t\tif((*conditioni).at(1)==\"<\") s=indexmanager->_FindSmall((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<=\") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">\") s=indexmanager->_FindBigger((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">=\") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<>\") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"=\") s.push_back(indexmanager->select((*conditioni).at(0), *v));\n if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){\n delete v;\n return Recordinfo(false, \"Cannot find the record!\", Result(), 0);\n }\n result=recordmanager->Select_Record(sql, table, true, s);\n\t\t\/\/ 然后开始剩下的暴力获取\n sql.conditions.erase(conditioni);\n Recordinfo result2=recordmanager->Select_Record(sql, table, false, s);\n \/\/ and\n result.AND(result2);\n\t\tdelete v;\n\t}\n return result;\n}\n\nRecordinfo API::del(sqlcommand& sql){\n bool flag=false;\n \/\/\tint n=-1;\t\/\/ 记录第几个是index\n std::vector >::iterator conditioni;\n Recordinfo result;\n \n int IndexAttrType=0x7fff;\n \n for(conditioni=sql.conditions.begin(); conditionihasIndex(sql.tablename, (*conditioni).at(0));\n if(flag) {\n IndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0));\n break;\n }\n }\n \n \/\/ 需要商量\n Table table=catalogmanager->getTable(sql.tablename);\n \n if(!flag) {\n std::vector slots;\n result=recordmanager->Delete_Record(sql, table, false, slots);\n }\n else{\n Value *v=NULL;\n switch(IndexAttrType){\n case 0:v=new Value(IndexAttrType, std::stoi((*conditioni).at(2)));break;\n case 1:v=new Value(IndexAttrType, (*conditioni).at(2));break;\n case -1:v=new Value(IndexAttrType, std::stof((*conditioni).at(2)));break;\n }\n \n std::vector s;\n if((*conditioni).at(1)==\"<\") s=indexmanager->_FindSmall((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<=\") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">\") s=indexmanager->_FindBigger((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">=\") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<>\") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"=\") s.push_back(indexmanager->select((*conditioni).at(0), *v));\n if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){\n delete v;\n return Recordinfo(false, \"Cannot find the record!\", Result(), 0);\n }\n result=recordmanager->Delete_Record(sql, table, true, s);\n \/\/ 然后开始剩下的暴力获取\n sql.conditions.erase(conditioni);\n Recordinfo result2=recordmanager->Select_Record(sql, table, false, s);\n \/\/ and\n result.AND(result2);\n delete v;\n }\n return result;\n}\n\nRecordinfo API::insert(sqlcommand& sql){\n\t\/\/ 为什么insert也要有sqlcommand????\n \/\/ 插入index\n \n Recordinfo result;\n Table table=catalogmanager->getTable(sql.tablename);\n int block_id;\n int record_id;\n \n \/\/ check primary\n std::string primarykey=catalogmanager->pkOnTable(sql.tablename);\n if(primarykey==\"Table not found in CatalogBlocks!\"){\n result=Recordinfo(false, primarykey, Result(), 0);\n return result;\n }\n else{\n for(int i=0; iisUnique(sql.tablename, i) || catalogmanager->isPK(sql.tablename, i)){\n std::string attrname=catalogmanager->getAttrName(sql.tablename, i);\n \/\/ 如果有索引就用索引,并且更新索引\n if(catalogmanager->hasIndex(sql.tablename, attrname)){\n std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname);\n int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey);\n Value *v=NULL;\n switch(AttrType){\n case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break;\n case 1:v=new Value(AttrType, (sql.colValue).at(i));break;\n case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break;\n }\n slot s=indexmanager->select(indexname, *v);\n if(s.block_id!=-1){\n Recordinfo result=Recordinfo(false, \"The unique key value has existed!\", Result(), 0);\n delete v;\n return result;\n }\n delete v;\n }\n \/\/ 没有索引直接查询\n sqlcommand tempsql=sql;\n tempsql.sqlType=0;\n tempsql.conditions={{attrname, \"=\", sql.colValue[i]}};\n tempsql.selectInfo={\"*\"};\n Recordinfo r=recordmanager->Select_Record(tempsql, table, 0, std::vector());\n if(r.successful){\n result=Recordinfo(false, \"The unique key value has existed!\", Result(), 0);\n return result;\n }\n }\n }\n \n result=recordmanager->Insert_Record(sql, table, block_id, record_id);\n \/\/插入索引\n slot s=slot(block_id, record_id);\n for(int i=0; igetAttrName(sql.tablename, i);\n if(catalogmanager->hasIndex(sql.tablename, attrname)){\n std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname);\n int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey);\n Value *v=NULL;\n switch(AttrType){\n case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break;\n case 1:v=new Value(AttrType, (sql.colValue).at(i));break;\n case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break;\n }\n indexmanager->_insert(indexname, *v, s);\n }\n }\n \/\/ 解决可能的返回错误?\n return result;\n }\n}\n\nRecordinfo API::createTable(sqlcommand& sql){\n catalogmanager->insertTable(sql);\n std::string pk;\n std::string tablename=sql.createTableInfo[0].at(0);\n if((pk=catalogmanager->pkOnTable(tablename))!=\"No primary key on this table!\"){\n \/\/ 可以创建空的index吧?\n indexmanager->CreateIndex(tablename+\"$\"+pk, catalogmanager->getAttrType(tablename, pk), std::vector(0), std::vector(0));\n \n sqlcommand tempsql=sqlcommand();\n tempsql.sqlType=4;\n tempsql.indexname=tablename+\"$\"+pk;\n tempsql.setCreateIndexInfo(tablename, pk);\n catalogmanager->insertIndex(tempsql);\n }\n return Recordinfo(); \/\/ further improve\n}\n\nRecordinfo API::createIndex(sqlcommand& sql){\n\tstd::string tablename=sql.createIndexInfo[1];\n std::string indexname=sql.createIndexInfo[0];\n int attrtype=catalogmanager->getAttrType(tablename, sql.createIndexInfo[2]);\n indexmanager->CreateIndex(sql.indexname, attrtype, std::vector(), std::vector());\n \n catalogmanager->insertIndex(sql);\n return Recordinfo(); \/\/ further improve\n}\n\n\/\/ turn to Catalog find all index and\n\/\/ drop index\n\/\/ dropCatalog\n\/\/ drop all records\nRecordinfo API::dropTable(sqlcommand& sql){\n std::string tablename=sql.tablename;\n \n for(int i=0; iAttrCount(tablename); i++){\n std::string attrname=catalogmanager->getAttrName(tablename, i);\n if(catalogmanager->hasIndex(tablename, attrname)){\n indexmanager->DropIndex(catalogmanager->getIndexName(tablename, attrname));\n catalogmanager->dropIndex(catalogmanager->getIndexName(tablename, attrname));\n }\n }\n catalogmanager->dropTable(sql.tablename);\n return Recordinfo(); \/\/ further improve\n}\n\nRecordinfo API::dropIndex(sqlcommand& sql){\n catalogmanager->dropIndex(sql.indexname);\n indexmanager->DropIndex(sql.indexname);\n return Recordinfo(); \/\/ further improve\n \/\/ catalog\n}update API\/\/\n\/\/ API.cpp\n\/\/ miniSQL\n\/\/\n\/\/ Created by Kael on 11\/3\/14.\n\/\/ Copyright (c) 2014 Xinyuan Lu. All rights reserved.\n\/\/\n\n\/\/ v2.0, see comment in \"APT.h\"\n\n#include \"API.h\"\n\nRecordinfo API::dealCmd(sqlcommand& sql){\n\t\/\/ 使用get方法更好,这里先直接调用public\n\tswitch(sql.sqlType){\n\t\tcase 0:\n\t\treturn select(sql);\n\t\tbreak;\n\t\tcase 1:\n\t\treturn del(sql);\n\t\tbreak;\n\t\tcase 2:\n\t\treturn insert(sql);\n\t\tbreak;\n\t\tcase 3:\n\t\treturn createTable(sql);\n\t\tbreak;\n\t\tcase 4:\n\t\treturn createIndex(sql);\n\t\tbreak;\n\t\tcase 5:\n\t\treturn dropTable(sql);\n\t\tbreak;\n\t\tcase 6:\n\t\treturn dropIndex(sql);\n\t\tbreak;\n\t}\n\treturn Recordinfo();\n}\n\nint API::AttrCount(std::string tablename){\n\treturn catalogmanager->AttrCount(tablename);\n}\nbool API::TableExists(std::string tablename){\n\treturn catalogmanager->TableExists(tablename);\n}\nbool API::IndexExists(std::string indexname){\n\treturn catalogmanager->IndexExists(indexname);\n}\nbool API::AttrExists(std::string attrname,std::string tablename){\n\treturn catalogmanager->AttrExists(attrname, tablename);\n}\n\n\/\/ 以下所有的都需要错误输入的检查?\nRecordinfo API::select(sqlcommand& sql){\n\t\/\/ 先到catalog查看是否有index\n\t\/\/ 如果有就用,然后作intersection\n\t\/\/ 如果没有,直接交给record?\n\t\/\/ 可以减少数据传递的overhead\n\tbool flag=false;\n std::vector >::iterator conditioni;\n\tRecordinfo result;\n \n\tint IndexAttrType=0x7fff;\n\n\tfor(conditioni=sql.conditions.begin(); conditionihasIndex(sql.tablename, (*conditioni).at(0));\n\t\tif(flag) {\n\t\t\tIndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0));\n\t\t\tbreak;\n\t\t}\n\t}\n \n \/\/ 需要商量\n Table table=catalogmanager->getTable(sql.tablename);\n \n\tif(!flag) {\n\t\tstd::vector slots;\n\t\tresult=recordmanager->Select_Record(sql, table, false, slots);\n\t}\n\telse{\n\t\tValue *v=NULL;\n\t\tswitch(IndexAttrType){\n\t\t\tcase 0:\n\t\t\tv=new Value(IndexAttrType, std::stoi((*conditioni).at(2)));\n\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\tv=new Value(IndexAttrType, (*conditioni).at(2));\n\t\t\tbreak;\n\t\t\tcase -1:\n\t\t\tv=new Value(IndexAttrType, std::stof((*conditioni).at(2)));\n\t\t\tbreak;\n\t\t}\n\t\tIndexManager *indexmanager=new IndexManager();\n \n std::vector s;\n\t\tif((*conditioni).at(1)==\"<\") s=indexmanager->_FindSmall((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<=\") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">\") s=indexmanager->_FindBigger((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">=\") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<>\") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"=\") s.push_back(indexmanager->select((*conditioni).at(0), *v));\n if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){\n delete v;\n return Recordinfo(false, \"Cannot find the record!\", Result(), 0);\n }\n result=recordmanager->Select_Record(sql, table, true, s);\n\t\t\/\/ 然后开始剩下的暴力获取\n sql.conditions.erase(conditioni);\n Recordinfo result2=recordmanager->Select_Record(sql, table, false, s);\n \/\/ and\n result.AND(result2);\n\t\tdelete v;\n\t}\n return result;\n}\n\nRecordinfo API::del(sqlcommand& sql){\n bool flag=false;\n \/\/\tint n=-1;\t\/\/ 记录第几个是index\n std::vector >::iterator conditioni;\n Recordinfo result;\n \n int IndexAttrType=0x7fff;\n \n for(conditioni=sql.conditions.begin(); conditionihasIndex(sql.tablename, (*conditioni).at(0));\n if(flag) {\n IndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0));\n break;\n }\n }\n \n \/\/ 需要商量\n Table table=catalogmanager->getTable(sql.tablename);\n \n if(!flag) {\n std::vector slots;\n result=recordmanager->Delete_Record(sql, table, false, slots);\n }\n else{\n Value *v=NULL;\n switch(IndexAttrType){\n case 0:v=new Value(IndexAttrType, std::stoi((*conditioni).at(2)));break;\n case 1:v=new Value(IndexAttrType, (*conditioni).at(2));break;\n case -1:v=new Value(IndexAttrType, std::stof((*conditioni).at(2)));break;\n }\n \n std::vector s;\n if((*conditioni).at(1)==\"<\") s=indexmanager->_FindSmall((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<=\") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">\") s=indexmanager->_FindBigger((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\">=\") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"<>\") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v);\n else if((*conditioni).at(1)==\"=\") s.push_back(indexmanager->select((*conditioni).at(0), *v));\n if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){\n delete v;\n return Recordinfo(false, \"Cannot find the record!\", Result(), 0);\n }\n result=recordmanager->Delete_Record(sql, table, true, s);\n \/\/ 然后开始剩下的暴力获取\n sql.conditions.erase(conditioni);\n Recordinfo result2=recordmanager->Select_Record(sql, table, false, s);\n \/\/ and\n result.AND(result2);\n delete v;\n }\n return result;\n}\n\nRecordinfo API::insert(sqlcommand& sql){\n\t\/\/ 为什么insert也要有sqlcommand????\n \/\/ 插入index\n \n Recordinfo result;\n Table table=catalogmanager->getTable(sql.tablename);\n int block_id;\n int record_id;\n \n \/\/ check primary\n std::string primarykey=catalogmanager->pkOnTable(sql.tablename);\n if(primarykey==\"Table not found in CatalogBlocks!\"){\n result=Recordinfo(false, primarykey, Result(), 0);\n return result;\n }\n else{\n for(int i=0; iisUnique(sql.tablename, i) || catalogmanager->isPK(sql.tablename, i)){\n std::string attrname=catalogmanager->getAttrName(sql.tablename, i);\n \/\/ 如果有索引就用索引,并且更新索引\n if(catalogmanager->hasIndex(sql.tablename, attrname)){\n std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname);\n int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey);\n Value *v=NULL;\n switch(AttrType){\n case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break;\n case 1:v=new Value(AttrType, (sql.colValue).at(i));break;\n case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break;\n }\n slot s=indexmanager->select(indexname, *v);\n if(s.block_id!=-1){\n Recordinfo result=Recordinfo(false, \"The unique key value has existed!\", Result(), 0);\n delete v;\n return result;\n }\n delete v;\n }\n \/\/ 没有索引直接查询\n sqlcommand tempsql=sql;\n tempsql.sqlType=0;\n tempsql.conditions={{attrname, \"=\", sql.colValue[i]}};\n tempsql.selectInfo={\"*\"};\n Recordinfo r=recordmanager->Select_Record(tempsql, table, 0, std::vector());\n if(r.successful){\n result=Recordinfo(false, \"The unique key value has existed!\", Result(), 0);\n return result;\n }\n }\n }\n \n result=recordmanager->Insert_Record(sql, table, block_id, record_id);\n \/\/插入索引\n slot s=slot(block_id, record_id);\n for(int i=0; igetAttrName(sql.tablename, i);\n if(catalogmanager->hasIndex(sql.tablename, attrname)){\n std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname);\n int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey);\n Value *v=NULL;\n switch(AttrType){\n case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break;\n case 1:v=new Value(AttrType, (sql.colValue).at(i));break;\n case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break;\n }\n indexmanager->_insert(indexname, *v, s);\n }\n }\n \/\/ 解决可能的返回错误?\n return result;\n }\n}\n\nRecordinfo API::createTable(sqlcommand& sql){\n catalogmanager->insertTable(sql);\n std::string pk;\n std::string tablename=sql.createTableInfo[0].at(0);\n if((pk=catalogmanager->pkOnTable(tablename))!=\"No primary key on this table!\"){\n \/\/ 可以创建空的index吧?\n indexmanager->CreateIndex(tablename+\"$\"+pk, catalogmanager->getAttrType(tablename, pk), std::vector(0), std::vector(0));\n \n sqlcommand tempsql=sqlcommand();\n tempsql.sqlType=4;\n tempsql.indexname=tablename+\"$\"+pk;\n tempsql.setCreateIndexInfo(tablename, pk);\n catalogmanager->insertIndex(tempsql);\n }\n return Recordinfo(); \/\/ further improve\n}\n\nRecordinfo API::createIndex(sqlcommand& sql){\n\tstd::string tablename=sql.createIndexInfo[1];\n std::string indexname=sql.createIndexInfo[0];\n int attrtype=catalogmanager->getAttrType(tablename, sql.createIndexInfo[2]);\n catalogmanager->insertIndex(sql);\n indexmanager->CreateIndex(sql.indexname, attrtype, std::vector(), std::vector());\n \/\/ insert all records to index\n sqlcommand tempsql=sqlcommand();\n tempsql.sqlType=0;\n tempsql.selectInfo=std::vector();\n tempsql.selectInfo.push_back(sql.createIndexInfo[2]);\n tempsql.tablename=tablename;\n tempsql.conditions=std::vector >();\n Table temptable=catalogmanager->getTable(tablename);\n std::vector tempslot=std::vector();\n Recordinfo result=recordmanager->Select_Record(tempsql, temptable, 0, tempslot);\n for(int i=0;i_insert(indexname, v, tempslot[i]);\n }\n \n return Recordinfo(); \/\/ further improve\n}\n\n\/\/ turn to Catalog find all index and\n\/\/ drop index\n\/\/ dropCatalog\n\/\/ drop all records\nRecordinfo API::dropTable(sqlcommand& sql){\n std::string tablename=sql.tablename;\n \n \/\/ delete all records\n sqlcommand tempsql=sqlcommand();\n tempsql.sqlType=1;\n tempsql.conditions=std::vector >();\n tempsql.tablename=sql.tablename;\n Table temptable=catalogmanager->getTable(sql.tablename);\n recordmanager->Delete_Record(tempsql, temptable, 0, std::vector());\n \n \/\/ delete all indexes\n for(int i=0; iAttrCount(tablename); i++){\n std::string attrname=catalogmanager->getAttrName(tablename, i);\n if(catalogmanager->hasIndex(tablename, attrname)){\n indexmanager->DropIndex(catalogmanager->getIndexName(tablename, attrname));\n catalogmanager->dropIndex(catalogmanager->getIndexName(tablename, attrname));\n }\n }\n \/\/ delete catalog\n catalogmanager->dropTable(sql.tablename);\n return Recordinfo(); \/\/ further improve\n}\n\nRecordinfo API::dropIndex(sqlcommand& sql){\n catalogmanager->dropIndex(sql.indexname);\n indexmanager->DropIndex(sql.indexname);\n return Recordinfo(); \/\/ further improve\n \/\/ catalog\n}<|endoftext|>"} {"text":"class TrieNode {\npublic:\n bool isKey;\n TrieNode* children[26];\n TrieNode(): isKey(false) {\n memset(children, NULL, sizeof(TrieNode*) * 26);\n }\n};\n\nclass WordDictionary {\npublic:\n WordDictionary() {\n root = new TrieNode();\n }\n\n \/\/ Adds a word into the data structure.\n void addWord(string word) {\n TrieNode* run = root;\n for (char c : word) {\n if (!(run -> children[c - 'a']))\n run -> children[c - 'a'] = new TrieNode();\n run = run -> children[c - 'a'];\n }\n run -> isKey = true;\n }\n\n \/\/ Returns if the word is in the data structure. A word could\n \/\/ contain the dot character '.' to represent any one letter.\n bool search(string word) {\n return query(word.c_str(), root);\n }\n\nprivate:\n TrieNode* root;\n\n bool query(const char* word, TrieNode* node) {\n TrieNode* run = node;\n for (int i = 0; word[i]; i++) {\n if (run && word[i] != '.')\n run = run -> children[word[i] - 'a'];\n else if (run && word[i] == '.') {\n TrieNode* tmp = run;\n for (int j = 0; j < 26; j++) {\n run = tmp -> children[j];\n if (query(word + i + 1, run))\n return true;\n }\n }\n else break;\n }\n return run && run -> isKey;\n }\n};\n\n\/\/ Your WordDictionary object will be instantiated and called as such:\n\/\/ WordDictionary wordDictionary;\n\/\/ wordDictionary.addWord(\"word\");\n\/\/ wordDictionary.search(\"pattern\");Update 211.cpp\/*\n * Trie\n *\n *\/\nclass TrieNode {\npublic:\n bool isKey;\n TrieNode* children[26];\n TrieNode(): isKey(false) {\n memset(children, NULL, sizeof(TrieNode*) * 26);\n }\n};\n\nclass WordDictionary {\npublic:\n WordDictionary() {\n root = new TrieNode();\n }\n\n \/\/ Adds a word into the data structure.\n void addWord(string word) {\n TrieNode* run = root;\n for (char c : word) {\n if (!(run -> children[c - 'a']))\n run -> children[c - 'a'] = new TrieNode();\n run = run -> children[c - 'a'];\n }\n run -> isKey = true;\n }\n\n \/\/ Returns if the word is in the data structure. A word could\n \/\/ contain the dot character '.' to represent any one letter.\n bool search(string word) {\n return query(word.c_str(), root);\n }\n\nprivate:\n TrieNode* root;\n\n bool query(const char* word, TrieNode* node) {\n TrieNode* run = node;\n for (int i = 0; word[i]; i++) {\n if (run && word[i] != '.')\n run = run -> children[word[i] - 'a'];\n else if (run && word[i] == '.') {\n TrieNode* tmp = run;\n for (int j = 0; j < 26; j++) {\n run = tmp -> children[j];\n if (query(word + i + 1, run))\n return true;\n }\n }\n else break;\n }\n return run && run -> isKey;\n }\n};\n\n\/\/ Conclusion:\n\/\/\n\/\/\n\/\/\n\n\n\n<|endoftext|>"} {"text":"\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Michael Egli\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 * \\author Michael Egli\n * \\copyright Michael Egli\n * \\date 11-Jul-2015\n *\n * \\file cpptime.cpp\n *\n * See the description in the header file for for more information.\n *\n *\/\n\n\/\/ Includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"cpptime.h\"\n\nnamespace\n{\nusing scoped_m = std::unique_lock;\n\n\/\/ Prototypes\nCppTime::timer_id next_id();\n\n\/\/ Use to terminate the timer thread.\nbool done = false;\n\/\/ The index variable used to construct the timer_id.\nuint64_t cur_id = 0;\n\n\/\/ Locking & Co\nstd::mutex m;\nstd::condition_variable cond;\nstd::thread worker;\n\n\/\/ The event structure that holds the information about a timer.\nstruct Event {\n\tCppTime::timer_id id;\n\tCppTime::timestamp start;\n\tCppTime::duration period;\n\tCppTime::handler_t handler;\n\tbool valid;\n\tEvent()\n\t : id(0),\n\t start(CppTime::duration::zero()),\n\t period(CppTime::duration::zero()),\n\t handler(nullptr),\n\t valid(false)\n\t{\n\t}\n\ttemplate \n\tEvent(CppTime::timer_id id, CppTime::timestamp start, CppTime::duration period, Func &&handler)\n\t : id(id), start(start), period(period), handler(std::forward(handler)), valid(true)\n\t{\n\t}\n\tEvent(Event &&r) noexcept : id(r.id),\n\t start(r.start),\n\t period(r.period),\n\t handler(std::move(r.handler)),\n\t valid(r.valid)\n\t{\n\t}\n\tEvent &operator=(Event &&ev) noexcept\n\t{\n\t\tif(this != &ev) {\n\t\t\tid = ev.id;\n\t\t\tstart = ev.start;\n\t\t\tperiod = ev.period;\n\t\t\thandler = std::move(ev.handler);\n\t\t\tvalid = ev.valid;\n\t\t}\n\t\treturn *this;\n\t}\n\tEvent(const Event &r) = delete;\n\tEvent &operator=(const Event &r) = delete;\n};\n\n\/\/ A time event structure that holds the next timeout and a reference to its\n\/\/ Event struct.\nstruct Time_event {\n\tCppTime::timestamp next;\n\tCppTime::timer_id ref;\n};\n\ninline bool operator<(const Time_event &l, const Time_event &r)\n{\n\treturn l.next < r.next;\n}\n\n\/\/ The vector that holds all active events.\nstd::vector events;\n\/\/ Sorted queue that has the next timeout at its top.\nstd::priority_queue time_events;\n\n\/\/ A list of ids to be re-used. If possible, ids are used from this pool.\nstd::stack free_ids;\n\n\/\/ Returns the next free id. First, we check the free ids before creating a new\n\/\/ one.\nCppTime::timer_id next_id()\n{\n\tif(free_ids.empty()) {\n\t\treturn cur_id++;\n\t}\n\tCppTime::timer_id id = free_ids.top();\n\tfree_ids.pop();\n\treturn id;\n}\n\n\/\/ The thread main entry points. This is an endless loop until the `done` flag\n\/\/ is set to false.\n\/\/ TODO cleanup code to make it more readable (less if-else blocks).\nvoid run()\n{\n\tscoped_m lock(m);\n\n\twhile(!done) {\n\n\t\tif(time_events.empty()) {\n\t\t\t\/\/ Wait for work\n\t\t\tcond.wait(lock);\n\t\t} else {\n\t\t\tauto te = time_events.top();\n\t\t\tif(CppTime::clock::now() >= te.next) {\n\n\t\t\t\t\/\/ Remove time event\n\t\t\t\ttime_events.pop();\n\t\t\t\tEvent &ev = events[te.ref];\n\n\t\t\t\tif(!ev.valid) {\n\t\t\t\t\t\/\/ Return the id if the event is no longer valid.\n\t\t\t\t\tfree_ids.push(te.ref);\n\t\t\t\t} else {\n\n\t\t\t\t\t\/\/ Invoke the handler\n\t\t\t\t\tlock.unlock();\n\t\t\t\t\tev.handler(te.ref);\n\t\t\t\t\tlock.lock();\n\n\t\t\t\t\tif(!ev.valid) {\n\t\t\t\t\t\t\/\/ The callback removed the event.\n\t\t\t\t\t\tfree_ids.push(te.ref);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(ev.period.count() > 0) {\n\t\t\t\t\t\t\tte.next += ev.period;\n\t\t\t\t\t\t\ttime_events.push(te);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tev.valid = false;\n\t\t\t\t\t\t\tfree_ids.push(te.ref);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcond.wait_until(lock, te.next);\n\t\t\t}\n\t\t}\n\t}\n}\n\n} \/\/ end anonymous namespace\n\nnamespace CppTime\n{\n\nvoid start(size_t expected)\n{\n\tscoped_m lock(m);\n\tdone = false;\n\tif(expected > 0) {\n\t\tevents.resize(expected);\n\t}\n\tworker = std::thread(&run);\n}\n\nvoid stop()\n{\n\tscoped_m lock(m);\n\tdone = true;\n\tevents.clear();\n\twhile(!time_events.empty()) {\n\t\ttime_events.pop();\n\t}\n\tcond.notify_all();\n\tlock.unlock();\n\tworker.join();\n}\n\ntimer_id add(const timestamp &when, handler_t &&handler, const duration &period)\n{\n\tscoped_m lock(m);\n\ttimer_id id = next_id();\n\tEvent e(id, when, period, std::move(handler));\n\tif(events.size() <= id) {\n\t\tevents.resize(id + 1);\n\t}\n\tevents.insert(events.begin() + id, std::move(e));\n\ttime_events.push(Time_event{e.start, e.id});\n\tcond.notify_all();\n\treturn e.id;\n}\n\nbool remove(timer_id id)\n{\n\tscoped_m lock(m);\n\tif(events.size() < id) {\n\t\treturn false;\n\t}\n\tevents[id].valid = false;\n\treturn true;\n}\n\n} \/\/ end namespace CppTime\nDo not use the value from the moved object for the timer_id.\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Michael Egli\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 * \\author Michael Egli\n * \\copyright Michael Egli\n * \\date 11-Jul-2015\n *\n * \\file cpptime.cpp\n *\n * See the description in the header file for for more information.\n *\n *\/\n\n\/\/ Includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"cpptime.h\"\n\nnamespace\n{\nusing scoped_m = std::unique_lock;\n\n\/\/ Prototypes\nCppTime::timer_id next_id();\n\n\/\/ Use to terminate the timer thread.\nbool done = false;\n\/\/ The index variable used to construct the timer_id.\nuint64_t cur_id = 0;\n\n\/\/ Locking & Co\nstd::mutex m;\nstd::condition_variable cond;\nstd::thread worker;\n\n\/\/ The event structure that holds the information about a timer.\nstruct Event {\n\tCppTime::timer_id id;\n\tCppTime::timestamp start;\n\tCppTime::duration period;\n\tCppTime::handler_t handler;\n\tbool valid;\n\tEvent()\n\t : id(0),\n\t start(CppTime::duration::zero()),\n\t period(CppTime::duration::zero()),\n\t handler(nullptr),\n\t valid(false)\n\t{\n\t}\n\ttemplate \n\tEvent(CppTime::timer_id id, CppTime::timestamp start, CppTime::duration period, Func &&handler)\n\t : id(id), start(start), period(period), handler(std::forward(handler)), valid(true)\n\t{\n\t}\n\tEvent(Event &&r) noexcept : id(r.id),\n\t start(r.start),\n\t period(r.period),\n\t handler(std::move(r.handler)),\n\t valid(r.valid)\n\t{\n\t}\n\tEvent &operator=(Event &&ev) noexcept\n\t{\n\t\tif(this != &ev) {\n\t\t\tid = ev.id;\n\t\t\tstart = ev.start;\n\t\t\tperiod = ev.period;\n\t\t\thandler = std::move(ev.handler);\n\t\t\tvalid = ev.valid;\n\t\t}\n\t\treturn *this;\n\t}\n\tEvent(const Event &r) = delete;\n\tEvent &operator=(const Event &r) = delete;\n};\n\n\/\/ A time event structure that holds the next timeout and a reference to its\n\/\/ Event struct.\nstruct Time_event {\n\tCppTime::timestamp next;\n\tCppTime::timer_id ref;\n};\n\ninline bool operator<(const Time_event &l, const Time_event &r)\n{\n\treturn l.next < r.next;\n}\n\n\/\/ The vector that holds all active events.\nstd::vector events;\n\/\/ Sorted queue that has the next timeout at its top.\nstd::priority_queue time_events;\n\n\/\/ A list of ids to be re-used. If possible, ids are used from this pool.\nstd::stack free_ids;\n\n\/\/ Returns the next free id. First, we check the free ids before creating a new\n\/\/ one.\nCppTime::timer_id next_id()\n{\n\tif(free_ids.empty()) {\n\t\treturn cur_id++;\n\t}\n\tCppTime::timer_id id = free_ids.top();\n\tfree_ids.pop();\n\treturn id;\n}\n\n\/\/ The thread main entry points. This is an endless loop until the `done` flag\n\/\/ is set to false.\n\/\/ TODO cleanup code to make it more readable (less if-else blocks).\nvoid run()\n{\n\tscoped_m lock(m);\n\n\twhile(!done) {\n\n\t\tif(time_events.empty()) {\n\t\t\t\/\/ Wait for work\n\t\t\tcond.wait(lock);\n\t\t} else {\n\t\t\tauto te = time_events.top();\n\t\t\tif(CppTime::clock::now() >= te.next) {\n\n\t\t\t\t\/\/ Remove time event\n\t\t\t\ttime_events.pop();\n\t\t\t\tEvent &ev = events[te.ref];\n\n\t\t\t\tif(!ev.valid) {\n\t\t\t\t\t\/\/ Return the id if the event is no longer valid.\n\t\t\t\t\tfree_ids.push(te.ref);\n\t\t\t\t} else {\n\n\t\t\t\t\t\/\/ Invoke the handler\n\t\t\t\t\tlock.unlock();\n\t\t\t\t\tev.handler(te.ref);\n\t\t\t\t\tlock.lock();\n\n\t\t\t\t\tif(!ev.valid) {\n\t\t\t\t\t\t\/\/ The callback removed the event.\n\t\t\t\t\t\tfree_ids.push(te.ref);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif(ev.period.count() > 0) {\n\t\t\t\t\t\t\tte.next += ev.period;\n\t\t\t\t\t\t\ttime_events.push(te);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tev.valid = false;\n\t\t\t\t\t\t\tfree_ids.push(te.ref);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcond.wait_until(lock, te.next);\n\t\t\t}\n\t\t}\n\t}\n}\n\n} \/\/ end anonymous namespace\n\nnamespace CppTime\n{\n\nvoid start(size_t expected)\n{\n\tscoped_m lock(m);\n\tdone = false;\n\tif(expected > 0) {\n\t\tevents.resize(expected);\n\t}\n\tworker = std::thread(&run);\n}\n\nvoid stop()\n{\n\tscoped_m lock(m);\n\tdone = true;\n\tevents.clear();\n\twhile(!time_events.empty()) {\n\t\ttime_events.pop();\n\t}\n\tcond.notify_all();\n\tlock.unlock();\n\tworker.join();\n}\n\ntimer_id add(const timestamp &when, handler_t &&handler, const duration &period)\n{\n\tscoped_m lock(m);\n\ttimer_id id = next_id();\n\tEvent e(id, when, period, std::move(handler));\n\tif(events.size() <= id) {\n\t\tevents.resize(id + 1);\n\t}\n\tevents.insert(events.begin() + id, std::move(e));\n\ttime_events.push(Time_event{e.start, id});\n\tcond.notify_all();\n\treturn id;\n}\n\nbool remove(timer_id id)\n{\n\tscoped_m lock(m);\n\tif(events.size() < id) {\n\t\treturn false;\n\t}\n\tevents[id].valid = false;\n\treturn true;\n}\n\n} \/\/ end namespace CppTime\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Traits\n{\n \/**\n * @brief P.F.M\n *\n * @see N3911\n *\/\n template\n using void_t = void;\n\n \/**\n * @brief Strips constness and volatility from rvalues.\n *\/\n template\n using unqualified_t = std::remove_cv_t>;\n\n \/**\n * Base case for the testing of STD compatible container types.\n *\/\n template<\n typename \/*Type*\/,\n typename = void\n >\n struct is_printable_as_container : std::false_type\n {\n };\n\n \/**\n * @brief Specialization to ensure that Standard Library compatible containers that have\n * `begin()`, `end()`, and `empty()` member functions, as well as the `value_type` and\n * `iterator` typedefs are treated as printable containers.\n *\/\n template\n struct is_printable_as_container<\n Type,\n void_t<\n decltype(std::declval().begin()),\n decltype(std::declval().end()),\n decltype(std::declval().empty()),\n typename Type::value_type,\n typename Type::iterator\n >\n > : public std::true_type\n {\n };\n\n \/**\n * @brief Specialization to treat std::pair<...> as a printable container type.\n *\/\n template<\n typename FirstType,\n typename SecondType\n >\n struct is_printable_as_container> : public std::true_type\n {\n };\n\n \/**\n * @brief Specialization to treat arrays as printable container types.\n *\/\n template<\n typename ArrayType,\n std::size_t ArraySize\n >\n struct is_printable_as_container : public std::true_type\n {\n };\n\n \/**\n * @brief Narrow character array specialization in order to ensure that we print character arrays\n * as string and not as delimiter containers.\n *\/\n template\n struct is_printable_as_container : public std::false_type\n {\n };\n\n \/**\n * @brief Wide character array specialization in order to ensure that we print character arrays\n * as string and not as delimiter containers.\n *\/\n template\n struct is_printable_as_container : public std::false_type\n {\n };\n\n \/**\n * @brief String specialization in order to ensure that we treat strings as nothing more than strings.\n *\/\n template<\n typename CharacterType,\n typename TraitsType,\n typename AllocatorType\n >\n struct is_printable_as_container<\n std::basic_string<\n CharacterType,\n TraitsType,\n AllocatorType\n >\n > : public std::false_type\n {\n };\n\n \/**\n * @brief Helper variable template.\n *\/\n template\n constexpr bool is_printable_as_container_v = is_printable_as_container::value;\n}\n\nnamespace Printer\n{\n \/**\n * Convenience struct to neatly wrap up all the additional characters we'll need in order to\n * print out the containers.\n *\/\n template\n struct delimiter_values\n {\n using type = DelimiterType;\n\n const type* prefix;\n const type* delimiter;\n const type* postfix;\n };\n\n \/**\n *\n *\/\n template<\n typename \/*ContainerType*\/,\n typename DelimiterType\n >\n struct delimiters\n {\n using type = delimiter_values;\n\n static const type values;\n };\n\n \/**\n * Default narrow delimiters for any container type that isn't specialized.\n *\/\n template\n struct delimiters\n {\n using type = delimiter_values;\n\n static constexpr type values = { \"[\", \", \", \"]\" };\n };\n\n \/**\n * Default wide delimiters for any container type that isn't specialized.\n *\/\n template\n struct delimiters\n {\n using type = delimiter_values;\n\n static constexpr type values = { L\"[\", L\", \", L\"]\" };\n };\n\n \/**\n * Narrow character specialization for std::set<...>.\n *\/\n template<\n typename Type,\n typename ComparatorType,\n typename AllocatorType\n >\n struct delimiters, char>\n {\n static constexpr delimiter_values values = { \"{\", \", \", \"}\" };\n };\n\n \/**\n * Wide character specialization for std::set<...>.\n *\/\n template<\n typename Type,\n typename ComparatorType,\n typename AllocatorType\n >\n struct delimiters, wchar_t>\n {\n static constexpr delimiter_values values = { L\"{\", L\", \", L\"}\" };\n };\n\n \/**\n * Narrow character specialization for std::pair<...>.\n *\/\n template<\n typename FirstType,\n typename SecondType\n >\n struct delimiters, char>\n {\n static constexpr delimiter_values values = { \"(\", \", \", \")\" };\n };\n\n \/**\n * Wide character specialization for std::pair<...>.\n *\/\n template<\n typename FirstType,\n typename SecondType\n >\n struct delimiters, wchar_t>\n {\n static constexpr delimiter_values values = { L\"(\", L\", \", L\")\" };\n };\n\n \/**\n * Narrow character specialization for std::tuple<...>.\n *\/\n template\n struct delimiters, char>\n {\n static constexpr delimiter_values values = { \"<\", \", \", \">\" };\n };\n\n \/**\n * Wide character specialization for std::tuple<...>.\n *\/\n template\n struct delimiters, wchar_t>\n {\n static constexpr delimiter_values values = { L\"<\", L\", \", L\">\" };\n };\n\n \/\/\/**\n \/\/* @brief Base specialization for std::tuple<...>.\n \/\/*\/\n \/\/template<\n \/\/ typename ContainerType,\n \/\/ typename TupleType,\n \/\/ typename CharacterType,\n \/\/ typename TraitsType\n \/\/>\n \/\/void PrintingHelper(\n \/\/ std::basic_ostream& stream,\n \/\/ const std::tuple& container)\n \/\/{\n \/\/ stream << std::get<0>(container);\n \/\/}\n\n \/\/\/**\n \/\/* @brief Recursive specialization for std::tuple<...>.\n \/\/*\/\n \/\/template<\n \/\/ typename FirstTupleType,\n \/\/ typename... RemainingTupleTypes,\n \/\/ typename CharacterType,\n \/\/ typename TraitsType\n \/\/>\n \/\/void PrintingHelper(\n \/\/ std::basic_ostream& stream,\n \/\/ const std::tuple& container)\n \/\/{\n \/\/ static constexpr auto delimiters =\n \/\/ Printer::delimiters, CharacterType>::values;\n\n \/\/ stream << std::get<0>(container) << delimiters.delimiter;\n \/\/ PrintingHelper(stream, container);\n \/\/}\n\n \/**\n * see http:\/\/stackoverflow.com\/questions\/6245735\/pretty-print-stdtuple\/6245777\n *\/\n template<\n typename CharacterType,\n typename TraitsType,\n typename Tuple,\n std::size_t... IndexSequence\n >\n void print_tuple_impl(\n std::basic_ostream& stream,\n const Tuple& tuple,\n std::index_sequence)\n {\n static constexpr auto delimiters =\n Printer::delimiters, CharacterType>::values;\n\n using swallow = int[]; \/\/ guarantees left to right order\n\n (void) swallow {\n 0,\n (void (stream\n << (IndexSequence == 0 ? \"\" : delimiters.delimiter)\n << std::get(tuple)), 0)...\n };\n }\n\n\n \/**\n * @brief Printing specialization suitable for most container types.\n *\/\n template<\n typename ContainerType,\n typename CharacterType,\n typename TraitsType\n >\n void PrintingHelper(\n std::basic_ostream& stream,\n const ContainerType& container)\n {\n static constexpr auto delimiters = Printer::delimiters::values;\n\n if (container.empty())\n {\n return;\n }\n\n auto begin = std::begin(container);\n stream << delimiters.prefix << *begin;\n std::advance(begin, 1);\n\n std::for_each(begin, std::end(container),\n [&stream] (const auto& value)\n {\n stream << delimiters.delimiter << value;\n });\n\n stream << delimiters.postfix;\n }\n\n \/**\n * @brief Printing specialization for std::pair<...>.\n *\/\n template<\n typename FirstType,\n typename SecondType,\n typename CharacterType,\n typename TraitsType\n >\n void PrintingHelper(\n std::basic_ostream& stream,\n const std::pair& container)\n {\n static constexpr auto delimiters =\n Printer::delimiters<\n Traits::unqualified_t,\n CharacterType\n >::values;\n\n stream\n << delimiters.prefix\n << container.first\n << delimiters.delimiter\n << container.second\n << delimiters.postfix;\n }\n\n \/**\n * @brief Main class that will print out the container with the help of various templated\n * helper functions.\n *\/\n template<\n typename ContainerType,\n typename CharacterType,\n typename TraitsType\n >\n class ContainerPrinter\n {\n public:\n ContainerPrinter(const ContainerType& container)\n : m_container{ container }\n {\n }\n\n inline void PrintTo(std::basic_ostream& stream) const\n {\n PrintingHelper(stream, m_container);\n }\n\n private:\n const ContainerType& m_container;\n };\n}\n\n\/**\n* @brief Overload of the stream output operator for compatible containers.\n*\/\ntemplate<\n typename ContainerType,\n typename CharacterType,\n typename TraitsType,\n typename = std::enable_if_t>\n>\nauto& operator<<(\n std::basic_ostream& stream,\n const ContainerType& container)\n{\n Printer::ContainerPrinter(container).PrintTo(stream);\n\n return stream;\n}\nGot std::tuple<...> Printing Working#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Traits\n{\n \/**\n * @brief P.F.M\n *\n * @see N3911\n *\/\n template\n using void_t = void;\n\n \/**\n * @brief Strips constness and volatility from rvalues.\n *\/\n template\n using unqualified_t = std::remove_cv_t>;\n\n \/**\n * Base case for the testing of STD compatible container types.\n *\/\n template<\n typename \/*Type*\/,\n typename = void\n >\n struct is_printable_as_container : std::false_type\n {\n };\n\n \/**\n * @brief Specialization to ensure that Standard Library compatible containers that have\n * `begin()`, `end()`, and `empty()` member functions, as well as the `value_type` and\n * `iterator` typedefs are treated as printable containers.\n *\/\n template\n struct is_printable_as_container<\n Type,\n void_t<\n decltype(std::declval().begin()),\n decltype(std::declval().end()),\n decltype(std::declval().empty()),\n typename Type::value_type,\n typename Type::iterator\n >\n > : public std::true_type\n {\n };\n\n \/**\n * @brief Specialization to treat std::pair<...> as a printable container type.\n *\/\n template<\n typename FirstType,\n typename SecondType\n >\n struct is_printable_as_container> : public std::true_type\n {\n };\n\n \/**\n * @brief Specialization to treat std::tuple<...> as a printable container type.\n *\/\n template\n struct is_printable_as_container> : public std::true_type\n {\n };\n\n \/**\n * @brief Specialization to treat arrays as printable container types.\n *\/\n template<\n typename ArrayType,\n std::size_t ArraySize\n >\n struct is_printable_as_container : public std::true_type\n {\n };\n\n \/**\n * @brief Narrow character array specialization in order to ensure that we print character arrays\n * as string and not as delimiter containers.\n *\/\n template\n struct is_printable_as_container : public std::false_type\n {\n };\n\n \/**\n * @brief Wide character array specialization in order to ensure that we print character arrays\n * as string and not as delimiter containers.\n *\/\n template\n struct is_printable_as_container : public std::false_type\n {\n };\n\n \/**\n * @brief String specialization in order to ensure that we treat strings as nothing more than strings.\n *\/\n template<\n typename CharacterType,\n typename TraitsType,\n typename AllocatorType\n >\n struct is_printable_as_container<\n std::basic_string<\n CharacterType,\n TraitsType,\n AllocatorType\n >\n > : public std::false_type\n {\n };\n\n \/**\n * @brief Helper variable template.\n *\/\n template\n constexpr bool is_printable_as_container_v = is_printable_as_container::value;\n}\n\nnamespace Printer\n{\n \/**\n * Convenience struct to neatly wrap up all the additional characters we'll need in order to\n * print out the containers.\n *\/\n template\n struct delimiter_values\n {\n using type = DelimiterType;\n\n const type* prefix;\n const type* delimiter;\n const type* postfix;\n };\n\n \/**\n *\n *\/\n template<\n typename \/*ContainerType*\/,\n typename DelimiterType\n >\n struct delimiters\n {\n using type = delimiter_values;\n\n static const type values;\n };\n\n \/**\n * Default narrow delimiters for any container type that isn't specialized.\n *\/\n template\n struct delimiters\n {\n using type = delimiter_values;\n\n static constexpr type values = { \"[\", \", \", \"]\" };\n };\n\n \/**\n * Default wide delimiters for any container type that isn't specialized.\n *\/\n template\n struct delimiters\n {\n using type = delimiter_values;\n\n static constexpr type values = { L\"[\", L\", \", L\"]\" };\n };\n\n \/**\n * Narrow character specialization for std::set<...>.\n *\/\n template<\n typename Type,\n typename ComparatorType,\n typename AllocatorType\n >\n struct delimiters, char>\n {\n static constexpr delimiter_values values = { \"{\", \", \", \"}\" };\n };\n\n \/**\n * Wide character specialization for std::set<...>.\n *\/\n template<\n typename Type,\n typename ComparatorType,\n typename AllocatorType\n >\n struct delimiters, wchar_t>\n {\n static constexpr delimiter_values values = { L\"{\", L\", \", L\"}\" };\n };\n\n \/**\n * Narrow character specialization for std::pair<...>.\n *\/\n template<\n typename FirstType,\n typename SecondType\n >\n struct delimiters, char>\n {\n static constexpr delimiter_values values = { \"(\", \", \", \")\" };\n };\n\n \/**\n * Wide character specialization for std::pair<...>.\n *\/\n template<\n typename FirstType,\n typename SecondType\n >\n struct delimiters, wchar_t>\n {\n static constexpr delimiter_values values = { L\"(\", L\", \", L\")\" };\n };\n\n \/**\n * Narrow character specialization for std::tuple<...>.\n *\/\n template\n struct delimiters, char>\n {\n static constexpr delimiter_values values = { \"<\", \", \", \">\" };\n };\n\n \/**\n * Wide character specialization for std::tuple<...>.\n *\/\n template\n struct delimiters, wchar_t>\n {\n static constexpr delimiter_values values = { L\"<\", L\", \", L\">\" };\n };\n\n \/**\n * @brief Helper template to unpack and print tuple arguments.\n *\/\n template<\n typename TupleType,\n std::size_t N,\n typename... Args\n >\n struct TuplePrinter\n {\n template<\n typename CharacterType,\n typename TraitsType,\n typename DelimiterValues\n >\n static void Print(\n std::basic_ostream& stream,\n const TupleType& container,\n const DelimiterValues& delimiters)\n {\n TuplePrinter::Print(stream, container, delimiters);\n\n stream\n << delimiters.delimiter\n << std::get(container);\n }\n };\n\n \/**\n * @brief Helper template to unpack and print tuple arguments.\n *\/\n template\n struct TuplePrinter\n {\n template<\n typename CharacterType,\n typename TraitsType,\n typename DelimiterValues\n >\n static void Print(\n std::basic_ostream& stream,\n const TupleType& tuple,\n const DelimiterValues& delimiters)\n {\n stream << std::get<0>(tuple);\n }\n };\n\n \/**\n * @brief Recursive specialization for std::tuple<...>.\n *\n * @see http:\/\/en.cppreference.com\/w\/cpp\/utility\/tuple\/tuple_cat\n *\/\n template<\n typename CharacterType,\n typename TraitsType,\n typename... Args\n >\n void PrintingHelper(\n std::basic_ostream& stream,\n const std::tuple& container)\n {\n static constexpr auto delimiters =\n Printer::delimiters, CharacterType>::values;\n\n stream << delimiters.prefix;\n TuplePrinter::Print(stream, container, delimiters);\n stream << delimiters.postfix;\n }\n\n \/**\n * @brief Printing specialization suitable for most container types.\n *\/\n template<\n typename ContainerType,\n typename CharacterType,\n typename TraitsType\n >\n void PrintingHelper(\n std::basic_ostream& stream,\n const ContainerType& container)\n {\n static constexpr auto delimiters = Printer::delimiters::values;\n\n if (container.empty())\n {\n return;\n }\n\n auto begin = std::begin(container);\n stream << delimiters.prefix << *begin;\n std::advance(begin, 1);\n\n std::for_each(begin, std::end(container),\n [&stream] (const auto& value)\n {\n stream << delimiters.delimiter << value;\n });\n\n stream << delimiters.postfix;\n }\n\n \/**\n * @brief Printing specialization for std::pair<...>.\n *\/\n template<\n typename FirstType,\n typename SecondType,\n typename CharacterType,\n typename TraitsType\n >\n void PrintingHelper(\n std::basic_ostream& stream,\n const std::pair& container)\n {\n static constexpr auto delimiters =\n Printer::delimiters<\n Traits::unqualified_t,\n CharacterType\n >::values;\n\n stream\n << delimiters.prefix\n << container.first\n << delimiters.delimiter\n << container.second\n << delimiters.postfix;\n }\n\n \/**\n * @brief Main class that will print out the container with the help of various templated\n * helper functions.\n *\/\n template<\n typename ContainerType,\n typename CharacterType,\n typename TraitsType\n >\n class ContainerPrinter\n {\n public:\n ContainerPrinter(const ContainerType& container)\n : m_container{ container }\n {\n }\n\n inline void PrintTo(std::basic_ostream& stream) const\n {\n PrintingHelper(stream, m_container);\n }\n\n private:\n const ContainerType& m_container;\n };\n}\n\n\/**\n* @brief Overload of the stream output operator for compatible containers.\n*\/\ntemplate<\n typename ContainerType,\n typename CharacterType,\n typename TraitsType,\n typename = std::enable_if_t>\n>\nauto& operator<<(\n std::basic_ostream& stream,\n const ContainerType& container)\n{\n Printer::ContainerPrinter(container).PrintTo(stream);\n\n return stream;\n}\n<|endoftext|>"} {"text":"\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace gl;\n\nnamespace gloperate\n{\n\nCameraCollisionCapability::CameraCollisionCapability()\n: m_fbo(nullptr)\n, m_size(1024)\n, m_samplingSize(1)\n{\n\n}\n\nCameraCollisionCapability::~CameraCollisionCapability()\n{\n\n}\n\nvoid CameraCollisionCapability::setCollisionFBO(globjects::ref_ptr collisionFBO, size_t texSize)\n{\n m_fbo = collisionFBO;\n m_size = texSize;\n}\n\nvoid CameraCollisionCapability::setSamplingSize(size_t samplingSize)\n{\n m_samplingSize = samplingSize;\n}\n\nfloat CameraCollisionCapability::getDistance(const glm::vec3 &dir) const\n{\n if(!m_fbo)\n {\n return std::numeric_limits::max();\n }\n\n float xAbs = std::abs(dir.x);\n float yAbs = std::abs(dir.y);\n float zAbs = std::abs(dir.z);\n float main, u, v;\n GLenum face;\n\n if(xAbs == 0 && yAbs == 0 && zAbs == 0)\n {\n return std::numeric_limits::max();\n }\n\n \/\/Find the correct axis to sample\n if(xAbs > yAbs && xAbs > zAbs)\n {\n face = GL_COLOR_ATTACHMENT0;\n main = dir.x; u = -dir.z; v = -dir.y;\n } else if(yAbs > zAbs)\n {\n face = GL_COLOR_ATTACHMENT2;\n main = dir.y; u = dir.x; v = dir.z;\n } else\n {\n face = GL_COLOR_ATTACHMENT4;\n main = dir.z; u = -dir.x; v = -dir.y;\n }\n\n \/\/Find the correct orientation on this axis\n face = face + static_cast(std::signbit(main));\n\n \/\/Sample the coordinates\n glm::vec2 uv{u\/std::abs(main), v\/std::abs(main)};\n glm::ivec2 i_uv = uv * static_cast(m_size\/2)+static_cast(m_size\/2);\n std::vector buf(m_samplingSize*m_samplingSize);\n\n m_fbo->bind();\n\n std::array sampleRange{i_uv.x,i_uv.y,m_samplingSize,m_samplingSize};\n m_fbo->readPixels(face, sampleRange,GL_RGB,GL_FLOAT,buf.data());\n\n m_fbo->unbind();\n\n return buf[0].x;\n}\n\n\n} \/\/ namespace gloperate\nFinal fix for collision sampling\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace gl;\n\nnamespace gloperate\n{\n\nCameraCollisionCapability::CameraCollisionCapability()\n: m_fbo(nullptr)\n, m_size(1024)\n, m_samplingSize(1)\n{\n\n}\n\nCameraCollisionCapability::~CameraCollisionCapability()\n{\n\n}\n\nvoid CameraCollisionCapability::setCollisionFBO(globjects::ref_ptr collisionFBO, size_t texSize)\n{\n m_fbo = collisionFBO;\n m_size = texSize;\n}\n\nvoid CameraCollisionCapability::setSamplingSize(size_t samplingSize)\n{\n m_samplingSize = samplingSize;\n}\n\nfloat CameraCollisionCapability::getDistance(const glm::vec3 &dir) const\n{\n if(!m_fbo)\n {\n return std::numeric_limits::max();\n }\n\n float xAbs = std::abs(dir.x);\n float yAbs = std::abs(dir.y);\n float zAbs = std::abs(dir.z);\n float main, u, v;\n GLenum face;\n\n if(xAbs == 0 && yAbs == 0 && zAbs == 0)\n {\n return std::numeric_limits::max();\n }\n\n \/\/ Find the correct axis to sample\n if(xAbs > yAbs && xAbs > zAbs)\n {\n face = GL_COLOR_ATTACHMENT0;\n main = dir.x; u = -dir.z; v = -dir.y;\n } else if(yAbs > zAbs)\n {\n auto sign = std::signbit(dir.y) ? -1 : 1;\n\n face = GL_COLOR_ATTACHMENT2;\n main = dir.y; u = dir.x; v = sign *dir.z;\n\n } else\n {\n face = GL_COLOR_ATTACHMENT4;\n main = dir.z; u = -dir.x; v = -dir.y;\n }\n\n \/\/ Find the correct orientation on this axis\n face = face + static_cast(std::signbit(main));\n\n \/\/ Sample the coordinates\n glm::vec2 uv{u\/std::abs(main), v\/std::abs(main)};\n glm::ivec2 i_uv = uv * static_cast(m_size\/2)+static_cast(m_size\/2);\n std::vector buf(m_samplingSize*m_samplingSize);\n\n m_fbo->bind();\n\n std::array sampleRange{i_uv.x,i_uv.y,m_samplingSize,m_samplingSize};\n m_fbo->readPixels(face, sampleRange,GL_RGB,GL_FLOAT,buf.data());\n\n m_fbo->unbind();\n\n return buf[0].x;\n}\n\n\n} \/\/ namespace gloperate\n<|endoftext|>"} {"text":"\/\/ [WriteFile Name=LoadWfsXmlQuery, Category=Layers]\n\/\/ [Legal]\n\/\/ Copyright 2019 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#include \"LoadWfsXmlQuery.h\"\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"FeatureLayer.h\"\n#include \"WfsFeatureTable.h\"\n\nusing namespace Esri::ArcGISRuntime;\n\nnamespace\n{\n static const QString xmlQueryString = R\"(\n \n \n \n \n Trees:SCIENTIFIC<\/fes:ValueReference>\n Tilia *<\/fes:Literal>\n <\/fes:PropertyIsLike>\n <\/fes:Filter>\n <\/wfs:Query>\n <\/wfs:GetFeature>\n )\";\n}\n\nLoadWfsXmlQuery::LoadWfsXmlQuery(QObject* parent \/* = nullptr *\/):\n QObject(parent),\n m_map(new Map(Basemap::navigationVector(this), this))\n{\n \/\/ create WFS Feature Table\n const QUrl featureTableUrl(\"https:\/\/dservices2.arcgis.com\/ZQgQTuoyBrtmoGdP\/arcgis\/services\/Seattle_Downtown_Features\/WFSServer?service=wfs&request=getcapabilities\");\n WfsFeatureTable* wfsFeatureTable = new WfsFeatureTable(featureTableUrl,\n \"Seattle_Downtown_Features:Trees\",\n this);\n wfsFeatureTable->setFeatureRequestMode(FeatureRequestMode::ManualCache);\n\n \/\/ connect to feature table doneLoading signal\n connect(wfsFeatureTable, &WfsFeatureTable::doneLoading, this, [wfsFeatureTable, this](Error e)\n {\n if (!e.isEmpty())\n return;\n\n \/\/ populate the table with XML Query\n wfsFeatureTable->populateFromService(xmlQueryString, true);\n\n \/\/ set the viewpoint to the center of the extent\n m_mapView->setViewpointGeometry(wfsFeatureTable->extent(), 50);\n });\n\n \/\/ create Feature Layer\n FeatureLayer* featureLayer = new FeatureLayer(wfsFeatureTable, this);\n\n \/\/ add layer to the map\n m_map->operationalLayers()->append(featureLayer);\n}\n\nLoadWfsXmlQuery::~LoadWfsXmlQuery() = default;\n\nvoid LoadWfsXmlQuery::init()\n{\n \/\/ Register the map view for QML\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"MapView\");\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"LoadWfsXmlQuerySample\");\n}\n\nMapQuickView* LoadWfsXmlQuery::mapView() const\n{\n return m_mapView;\n}\n\n\/\/ Set the view (created in QML)\nvoid LoadWfsXmlQuery::setMapView(MapQuickView* mapView)\n{\n if (!mapView || mapView == m_mapView)\n return;\n\n m_mapView = mapView;\n m_mapView->setMap(m_map);\n\n emit mapViewChanged();\n}\nreformatting query\/\/ [WriteFile Name=LoadWfsXmlQuery, Category=Layers]\n\/\/ [Legal]\n\/\/ Copyright 2019 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#include \"LoadWfsXmlQuery.h\"\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"FeatureLayer.h\"\n#include \"WfsFeatureTable.h\"\n\nusing namespace Esri::ArcGISRuntime;\n\nnamespace\n{\n const QString xmlQueryString = R\"(\n \n \n \n \n Trees:SCIENTIFIC<\/fes:ValueReference>\n Tilia *<\/fes:Literal>\n <\/fes:PropertyIsLike>\n <\/fes:Filter>\n <\/wfs:Query>\n <\/wfs:GetFeature>)\";\n}\n\nLoadWfsXmlQuery::LoadWfsXmlQuery(QObject* parent \/* = nullptr *\/):\n QObject(parent),\n m_map(new Map(Basemap::navigationVector(this), this))\n{\n \/\/ create WFS Feature Table\n const QUrl featureTableUrl(\"https:\/\/dservices2.arcgis.com\/ZQgQTuoyBrtmoGdP\/arcgis\/services\/Seattle_Downtown_Features\/WFSServer?service=wfs&request=getcapabilities\");\n WfsFeatureTable* wfsFeatureTable = new WfsFeatureTable(featureTableUrl,\n \"Seattle_Downtown_Features:Trees\",\n this);\n wfsFeatureTable->setFeatureRequestMode(FeatureRequestMode::ManualCache);\n\n \/\/ connect to feature table doneLoading signal\n connect(wfsFeatureTable, &WfsFeatureTable::doneLoading, this, [wfsFeatureTable, this](Error e)\n {\n if (!e.isEmpty())\n return;\n\n \/\/ populate the table with XML Query\n wfsFeatureTable->populateFromService(xmlQueryString, true);\n\n \/\/ set the viewpoint to the center of the extent\n m_mapView->setViewpointGeometry(wfsFeatureTable->extent(), 50);\n });\n\n \/\/ create Feature Layer\n FeatureLayer* featureLayer = new FeatureLayer(wfsFeatureTable, this);\n\n \/\/ add layer to the map\n m_map->operationalLayers()->append(featureLayer);\n}\n\nLoadWfsXmlQuery::~LoadWfsXmlQuery() = default;\n\nvoid LoadWfsXmlQuery::init()\n{\n \/\/ Register the map view for QML\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"MapView\");\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"LoadWfsXmlQuerySample\");\n}\n\nMapQuickView* LoadWfsXmlQuery::mapView() const\n{\n return m_mapView;\n}\n\n\/\/ Set the view (created in QML)\nvoid LoadWfsXmlQuery::setMapView(MapQuickView* mapView)\n{\n if (!mapView || mapView == m_mapView)\n return;\n\n m_mapView = mapView;\n m_mapView->setMap(m_map);\n\n emit mapViewChanged();\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\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 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see . *\n\\******************************************************************************\/\n\n\n#include \n#include \"cppa\/to_string.hpp\"\n\n#include \"cppa\/self.hpp\"\n#include \"cppa\/detail\/invokable.hpp\"\n#include \"cppa\/abstract_event_based_actor.hpp\"\n\nnamespace cppa {\n\nabstract_event_based_actor::abstract_event_based_actor()\n : super(super::blocked)\n{\n \/\/m_mailbox_pos = m_mailbox.cache().end();\n}\n\nvoid abstract_event_based_actor::dequeue(behavior&)\n{\n quit(exit_reason::unallowed_function_call);\n}\n\nvoid abstract_event_based_actor::dequeue(partial_function&)\n{\n quit(exit_reason::unallowed_function_call);\n}\n\nauto abstract_event_based_actor::handle_message(mailbox_element& node) -> handle_message_result\n{\n CPPA_REQUIRE(m_loop_stack.empty() == false);\n auto& bhvr = *(m_loop_stack.back());\n switch (filter_msg(node.msg))\n {\n case normal_exit_signal:\n case expired_timeout_message:\n return drop_msg;\n\n case timeout_message:\n m_has_pending_timeout_request = false;\n CPPA_REQUIRE(bhvr.timeout().valid());\n bhvr.handle_timeout();\n if (!m_loop_stack.empty())\n {\n auto& next_bhvr = *(m_loop_stack.back());\n request_timeout(next_bhvr.timeout());\n }\n return msg_handled;\n\n default:\n break;\n }\n std::swap(m_last_dequeued, node.msg);\n std::swap(m_last_sender, node.sender);\n \/\/m_last_dequeued = node.msg;\n \/\/m_last_sender = node.sender;\n \/\/ make sure no timeout is handled incorrectly in a nested receive\n ++m_active_timeout_id;\n if ((bhvr.get_partial_function())(m_last_dequeued))\n {\n m_last_dequeued.reset();\n m_last_sender.reset();\n \/\/ we definitely don't have a pending timeout now\n m_has_pending_timeout_request = false;\n return msg_handled;\n }\n \/\/ no match, restore members\n --m_active_timeout_id;\n std::swap(m_last_dequeued, node.msg);\n std::swap(m_last_sender, node.sender);\n return cache_msg;\n}\n\nvoid abstract_event_based_actor::resume(util::fiber*, scheduler::callback* cb)\n{\n auto done_cb = [&]()\n {\n m_state.store(abstract_scheduled_actor::done);\n m_loop_stack.clear();\n on_exit();\n cb->exec_done();\n };\n self.set(this);\n try\n {\n std::unique_ptr e;\n for (;;)\n {\n e.reset(m_mailbox.try_pop());\n if (!e)\n {\n m_state.store(abstract_scheduled_actor::about_to_block);\n CPPA_MEMORY_BARRIER();\n if (m_mailbox.can_fetch_more() == false)\n {\n switch (compare_exchange_state(abstract_scheduled_actor::about_to_block,\n abstract_scheduled_actor::blocked))\n {\n case abstract_scheduled_actor::ready:\n {\n break;\n }\n case abstract_scheduled_actor::blocked:\n {\n return;\n }\n default: exit(7); \/\/ illegal state\n };\n }\n }\n else\n {\n switch (handle_message(*e))\n {\n case drop_msg:\n {\n break; \/\/ nop\n }\n case msg_handled:\n {\n if (m_loop_stack.empty())\n {\n done_cb();\n return;\n }\n \/\/ try to match cached messages before receiving new ones\n auto i = m_cache.begin();\n while (i != m_cache.end())\n {\n switch (handle_message(*(*i)))\n {\n case drop_msg:\n {\n i = m_cache.erase(i);\n break;\n }\n case msg_handled:\n {\n m_cache.erase(i);\n if (m_loop_stack.empty())\n {\n done_cb();\n return;\n }\n i = m_cache.begin();\n break;\n }\n case cache_msg:\n {\n ++i;\n break;\n }\n default: exit(7); \/\/ illegal state\n }\n }\n break;\n }\n case cache_msg:\n {\n m_cache.push_back(std::move(e));\n break;\n }\n default: exit(7); \/\/ illegal state\n }\n }\n }\n }\n catch (actor_exited& what)\n {\n cleanup(what.reason());\n }\n catch (...)\n {\n cleanup(exit_reason::unhandled_exception);\n }\n done_cb();\n}\n\nvoid abstract_event_based_actor::on_exit()\n{\n}\n\n} \/\/ namespace cppa\nremoved obsolete code\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\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 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see . *\n\\******************************************************************************\/\n\n\n#include \n#include \"cppa\/to_string.hpp\"\n\n#include \"cppa\/self.hpp\"\n#include \"cppa\/detail\/invokable.hpp\"\n#include \"cppa\/abstract_event_based_actor.hpp\"\n\nnamespace cppa {\n\nabstract_event_based_actor::abstract_event_based_actor()\n : super(super::blocked)\n{\n \/\/m_mailbox_pos = m_mailbox.cache().end();\n}\n\nvoid abstract_event_based_actor::dequeue(behavior&)\n{\n quit(exit_reason::unallowed_function_call);\n}\n\nvoid abstract_event_based_actor::dequeue(partial_function&)\n{\n quit(exit_reason::unallowed_function_call);\n}\n\nauto abstract_event_based_actor::handle_message(mailbox_element& node) -> handle_message_result\n{\n CPPA_REQUIRE(m_loop_stack.empty() == false);\n auto& bhvr = *(m_loop_stack.back());\n switch (filter_msg(node.msg))\n {\n case normal_exit_signal:\n case expired_timeout_message:\n return drop_msg;\n\n case timeout_message:\n m_has_pending_timeout_request = false;\n CPPA_REQUIRE(bhvr.timeout().valid());\n bhvr.handle_timeout();\n if (!m_loop_stack.empty())\n {\n auto& next_bhvr = *(m_loop_stack.back());\n request_timeout(next_bhvr.timeout());\n }\n return msg_handled;\n\n default:\n break;\n }\n std::swap(m_last_dequeued, node.msg);\n std::swap(m_last_sender, node.sender);\n \/\/m_last_dequeued = node.msg;\n \/\/m_last_sender = node.sender;\n if ((bhvr.get_partial_function())(m_last_dequeued))\n {\n m_last_dequeued.reset();\n m_last_sender.reset();\n \/\/ we definitely don't have a pending timeout now\n m_has_pending_timeout_request = false;\n return msg_handled;\n }\n \/\/ no match, restore members\n std::swap(m_last_dequeued, node.msg);\n std::swap(m_last_sender, node.sender);\n return cache_msg;\n}\n\nvoid abstract_event_based_actor::resume(util::fiber*, scheduler::callback* cb)\n{\n auto done_cb = [&]()\n {\n m_state.store(abstract_scheduled_actor::done);\n m_loop_stack.clear();\n on_exit();\n cb->exec_done();\n };\n self.set(this);\n try\n {\n std::unique_ptr e;\n for (;;)\n {\n e.reset(m_mailbox.try_pop());\n if (!e)\n {\n m_state.store(abstract_scheduled_actor::about_to_block);\n CPPA_MEMORY_BARRIER();\n if (m_mailbox.can_fetch_more() == false)\n {\n switch (compare_exchange_state(abstract_scheduled_actor::about_to_block,\n abstract_scheduled_actor::blocked))\n {\n case abstract_scheduled_actor::ready:\n {\n break;\n }\n case abstract_scheduled_actor::blocked:\n {\n return;\n }\n default: exit(7); \/\/ illegal state\n };\n }\n }\n else\n {\n switch (handle_message(*e))\n {\n case drop_msg:\n {\n break; \/\/ nop\n }\n case msg_handled:\n {\n if (m_loop_stack.empty())\n {\n done_cb();\n return;\n }\n \/\/ try to match cached messages before receiving new ones\n auto i = m_cache.begin();\n while (i != m_cache.end())\n {\n switch (handle_message(*(*i)))\n {\n case drop_msg:\n {\n i = m_cache.erase(i);\n break;\n }\n case msg_handled:\n {\n m_cache.erase(i);\n if (m_loop_stack.empty())\n {\n done_cb();\n return;\n }\n i = m_cache.begin();\n break;\n }\n case cache_msg:\n {\n ++i;\n break;\n }\n default: exit(7); \/\/ illegal state\n }\n }\n break;\n }\n case cache_msg:\n {\n m_cache.push_back(std::move(e));\n break;\n }\n default: exit(7); \/\/ illegal state\n }\n }\n }\n }\n catch (actor_exited& what)\n {\n cleanup(what.reason());\n }\n catch (...)\n {\n cleanup(exit_reason::unhandled_exception);\n }\n done_cb();\n}\n\nvoid abstract_event_based_actor::on_exit()\n{\n}\n\n} \/\/ namespace cppa\n<|endoftext|>"} {"text":"#include \"OI.h\"\n#include \"Commands\/ControlIntakeWheels.h\"\n#include \"Subsystems\/IntakeWheel.h\"\n#include \"Misc\/ToggleClass.h\"\n\n\/\/\/ Default constructor of the class.\nControlIntakeWheels::ControlIntakeWheels()\n{\n\tIntakeArmPosition = new Toggle(false,true);\n\tRequires(IntakeWheel::GetInstance());\n}\n\n\/\/\/ Called just before this Command runs the first time.\nvoid ControlIntakeWheels::Initialize()\n{\n\tIntakeWheel::GetInstance()->SpinIntake(0);\n}\n\n\nvoid ControlIntakeWheels::Execute()\n{\n\tOI* oi = OI::GetInstance();\n\n\t\/\/In and out control for the intake bar\n\tif(oi->gamepad->GetRawButton(BTN_INTAKE))\n\t{\n\t\tIntakeWheel::GetInstance()->SpinIntake(Preferences::GetInstance()->GetDouble(\"Intake Speed\",1));\n\t}else if(oi->gamepad->GetRawButton(BTN_OUTAKE)){\n\t\tIntakeWheel::GetInstance()->SpinIntake(-Preferences::GetInstance()->GetDouble(\"Intake Speed\",1));\n\t}else{\n\t\tIntakeWheel::GetInstance()->SpinIntake(0);\n\t}\n}\n\n\/\/\/ Make this return true when this Command no longer needs to run execute().\n\/\/\/ \\return always false since this is the default command and should never finish.\nbool ControlIntakeWheels::IsFinished()\n{\n\treturn false;\n}\n\n\/\/\/ Called once after isFinished returns true\nvoid ControlIntakeWheels::End()\n{\n\tIntakeWheel::GetInstance()->SpinIntake(0);\n}\n\n\/\/\/ Called when another command which requires one or more of the same\n\/\/\/ subsystems is scheduled to run\nvoid ControlIntakeWheels::Interrupted()\n{\n\tEnd();\n}\nAdded a second throttle specifically for intake wheels out.#include \"OI.h\"\n#include \"Commands\/ControlIntakeWheels.h\"\n#include \"Subsystems\/IntakeWheel.h\"\n#include \"Misc\/ToggleClass.h\"\n\n\/\/\/ Default constructor of the class.\nControlIntakeWheels::ControlIntakeWheels()\n{\n\tIntakeArmPosition = new Toggle(false,true);\n\tRequires(IntakeWheel::GetInstance());\n}\n\n\/\/\/ Called just before this Command runs the first time.\nvoid ControlIntakeWheels::Initialize()\n{\n\tIntakeWheel::GetInstance()->SpinIntake(0);\n}\n\n\nvoid ControlIntakeWheels::Execute()\n{\n\tOI* oi = OI::GetInstance();\n\n\t\/\/In and out control for the intake bar\n\tif(oi->gamepad->GetRawButton(BTN_INTAKE))\n\t{\n\t\tIntakeWheel::GetInstance()->SpinIntake(Preferences::GetInstance()->GetDouble(\"Intake Speed\",1));\n\t}else if(oi->gamepad->GetRawButton(BTN_OUTAKE)){\n\t\tIntakeWheel::GetInstance()->SpinIntake(Preferences::GetInstance()->GetDouble(\"Intake Speed Out\",-1));\n\t}else{\n\t\tIntakeWheel::GetInstance()->SpinIntake(0);\n\t}\n}\n\n\/\/\/ Make this return true when this Command no longer needs to run execute().\n\/\/\/ \\return always false since this is the default command and should never finish.\nbool ControlIntakeWheels::IsFinished()\n{\n\treturn false;\n}\n\n\/\/\/ Called once after isFinished returns true\nvoid ControlIntakeWheels::End()\n{\n\tIntakeWheel::GetInstance()->SpinIntake(0);\n}\n\n\/\/\/ Called when another command which requires one or more of the same\n\/\/\/ subsystems is scheduled to run\nvoid ControlIntakeWheels::Interrupted()\n{\n\tEnd();\n}\n<|endoftext|>"} {"text":"\n\n#ifndef ONI_VICON_RECORDER_ONI_RECORDER_HPP\n#define ONI_VICON_RECORDER_ONI_RECORDER_HPP\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"kinect.h\"\n\n#define KINECT_IMAGE_COLS 640\n#define KINECT_IMAGE_ROWS 480\n\n#define KINECT_RGB_FOCAL_LENGTH_DEFAULT 525\n#define KINECT_RGB_CENTER_COL_DEFAULT 320\n#define KINECT_RGB_CENTER_ROW_DEFAULT 240\n#define KINECT_IR_FOCAL_LENGTH_DEFAULT 580\n#define KINECT_IR_CENTER_COL_DEFAULT 320\n#define KINECT_IR_CENTER_ROW_DEFAULT 240\n#define KINECT_RGB_TO_IR_X_DEFAULT (-0.0254)\n#define KINECT_RGB_TO_IR_Y_DEFAULT (-0.00013)\n#define KINECT_RGB_TO_IR_Z_DEFAULT (-0.00218)\n#define KINECT_RGB_TO_IR_ROLL_DEFAULT 0.0 \/\/ rad\n#define KINECT_RGB_TO_IR_PITCH_DEFAULT 0.0 \/\/ rad\n#define KINECT_RGB_TO_IR_YAW_DEFAULT 0.0 \/\/ rad\n\n#define KINECT_VENDOR_ID 0x45e\n#define XTION_VENDOR_ID 0x1d27\n\n#define CHECK_RC(rc, what)\t\t\t\t\t\t\t\t\t \\\nif (rc != XN_STATUS_OK)\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\t\t\\\n ROS_ERROR(\"%s failed: %s\\n\", what, xnGetStatusString(rc)); \\\n return false;\t\t\t\t\t\t\t\t\t\t\t\t\\\n}\n\nclass OniRecorder\n{\npublic:\n\n\npublic:\n OniRecorder(ros::NodeHandle& node_handle);\n ~OniRecorder();\n\n void changeDeptSensorModeCB(const oni_vicon_recorder::ChangeDepthSensorModeGoalConstPtr &goal);\n void runDepthSensorCB(const oni_vicon_recorder::RunDepthSensorGoalConstPtr& goal);\n bool closeDevice();\n\n bool startRecording(std::string file);\n bool stopRecording();\n int countFrames();\n bool isRecording();\n\n\n std::map getSupportedModes(const DepthGenerator *generator);\n std::vector getSupportedModeList(const std::map& mode_map);\n XnMapOutputMode getCurrentMode(const DepthGenerator *generator) const;\n std::string getModeName(const XnMapOutputMode& mode) const;\n\nprivate:\n ros::NodeHandle node_handle_;\n kinect_t* kinect_;\n Recorder recorder_;\n bool recording_;\n bool running_;\n int frames;\n boost::shared_mutex frameLock_;\n std::map modes_;\n\n actionlib::SimpleActionServer<\n oni_vicon_recorder::RunDepthSensorAction> run_depth_sensor_as_;\n actionlib::SimpleActionServer<\n oni_vicon_recorder::ChangeDepthSensorModeAction> change_depth_sensor_mode_as_;\n};\n\n#endif\nAdded former rosbuild arm_rgbd package as rgbd_sensor catkin package\n\n#ifndef ONI_VICON_RECORDER_ONI_RECORDER_HPP\n#define ONI_VICON_RECORDER_ONI_RECORDER_HPP\n\n#include \n#include \n#include \n\n#include \n#include \n\n\/\/ ROS\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"kinect.h\"\n\n#define KINECT_IMAGE_COLS 640\n#define KINECT_IMAGE_ROWS 480\n\n#define KINECT_RGB_FOCAL_LENGTH_DEFAULT 525\n#define KINECT_RGB_CENTER_COL_DEFAULT 320\n#define KINECT_RGB_CENTER_ROW_DEFAULT 240\n#define KINECT_IR_FOCAL_LENGTH_DEFAULT 580\n#define KINECT_IR_CENTER_COL_DEFAULT 320\n#define KINECT_IR_CENTER_ROW_DEFAULT 240\n#define KINECT_RGB_TO_IR_X_DEFAULT (-0.0254)\n#define KINECT_RGB_TO_IR_Y_DEFAULT (-0.00013)\n#define KINECT_RGB_TO_IR_Z_DEFAULT (-0.00218)\n#define KINECT_RGB_TO_IR_ROLL_DEFAULT 0.0 \/\/ rad\n#define KINECT_RGB_TO_IR_PITCH_DEFAULT 0.0 \/\/ rad\n#define KINECT_RGB_TO_IR_YAW_DEFAULT 0.0 \/\/ rad\n\n#define KINECT_VENDOR_ID 0x45e\n#define XTION_VENDOR_ID 0x1d27\n\n#define CHECK_RC(rc, what)\t\t\t\t\t\t\t\t\t \\\nif (rc != XN_STATUS_OK)\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\t\t\\\n ROS_ERROR(\"%s failed: %s\\n\", what, xnGetStatusString(rc)); \\\n return false;\t\t\t\t\t\t\t\t\t\t\t\t\\\n}\n\nclass OniRecorder\n{\npublic:\n\n\npublic:\n OniRecorder(ros::NodeHandle& node_handle);\n ~OniRecorder();\n\n void changeDeptSensorModeCB(const oni_vicon_recorder::ChangeDepthSensorModeGoalConstPtr &goal);\n void runDepthSensorCB(const oni_vicon_recorder::RunDepthSensorGoalConstPtr& goal);\n bool closeDevice();\n\n bool startRecording(std::string file);\n bool stopRecording();\n int countFrames();\n bool isRecording();\n\n\n std::map getSupportedModes(const DepthGenerator *generator);\n std::vector getSupportedModeList(const std::map& mode_map);\n XnMapOutputMode getCurrentMode(const DepthGenerator *generator) const;\n std::string getModeName(const XnMapOutputMode& mode) const;\n\nprivate:\n ros::NodeHandle node_handle_;\n kinect_t* kinect_;\n Recorder recorder_;\n bool recording_;\n bool running_;\n int frames;\n boost::shared_mutex frameLock_;\n std::map modes_;\n\n actionlib::SimpleActionServer<\n oni_vicon_recorder::RunDepthSensorAction> run_depth_sensor_as_;\n actionlib::SimpleActionServer<\n oni_vicon_recorder::ChangeDepthSensorModeAction> change_depth_sensor_mode_as_;\n\n image_transport::ImageTransport* it_;\n std::string camera_name_;\n std::string frame_id_;\n sensor_msgs::Image gray_image_;\n sensor_msgs::CameraInfo depth_cam_info_;\n\n std::string calib_url_;\n\n \/\/ Standard parameters\n bool bus_reset_;\n std::string bayer_pattern_;\n std::string encoding_;\n std::string guid_;\n int iso_speed_;\n std::string video_mode_;\n\n inline bool isDepthStreamRequired() const;\n\n sensor_msgs::CameraInfoPtr fillCameraInfo (ros::Time time, bool is_rgb);\n void subscriberChangedEvent ();\n\n bool calibration_valid_;\n bool calibration_loaded_;\n\n \/\/ Publishers Camera Info\n ros::Publisher pub_depth_info_;\n \/\/ Publishers Images\n image_transport::Publisher pub_gray_image_;\n image_transport::Publisher pub_depth_image_;\n \/\/ Publishers Point Clouds\n ros::Publisher pub_disp_image_;\n ros::Publisher pub_point_cloud_;\n ros::Publisher pub_point_cloud_rgb_;\n\n \/\/ publish methods\n void publishGrayImage (ros::Time time);\n void publishDepthImage (ros::Time time);\n void publishDisparity (ros::Time time);\n void publishXYZPointCloud (ros::Time time);\n\n std::string depth_frame_id_;\n unsigned image_width_;\n unsigned image_height_;\n unsigned depth_width_;\n unsigned depth_height_;\n};\n\n#endif\n<|endoftext|>"} {"text":"#include \"MP3DataProvider.h\"\n#include \"Utils.h\"\n#include \"id3v2lib.h\"\n\nextern \"C\"\n{\n#include \"minimp3\/minimp3.h\"\n}\n\nclMP3DataProvider::clMP3DataProvider( const std::shared_ptr& Data )\n: m_Data( Data )\n, m_Format()\n, m_DecodingBuffer( MP3_MAX_SAMPLES_PER_FRAME * 16 )\n, m_BufferUsed( 0 )\n, m_StreamPos( 0 )\n, m_InitialStreamPos( 0 )\n, m_IsEndOfStream( false )\n, m_MP3Decoder( mp3_create() )\n{\n\tLoadMP3Info();\n\n\tm_Format.m_NumChannels = m_MP3Info.channels;\n\tm_Format.m_SamplesPerSecond = m_MP3Info.sample_rate;\n\tm_Format.m_BitsPerSample = 16;\n}\n\nclMP3DataProvider::~clMP3DataProvider()\n{\n\tmp3_done( (mp3_decoder_t*)m_MP3Decoder );\n}\n\nvoid clMP3DataProvider::SkipTags()\n{\n\tID3v2_header* ID3TagHeader = get_tag_header_with_buffer(\n\t\treinterpret_cast( m_Data->GetDataPtr() + m_StreamPos ),\n\t\tstatic_cast( m_Data->GetDataSize() - m_StreamPos )\n\t);\n\n\tif ( ID3TagHeader )\n\t{\n\t\tm_StreamPos += ID3TagHeader->tag_size;\n\t\tfree( ID3TagHeader );\n\t}\n}\n\nvoid clMP3DataProvider::LoadMP3Info()\n{\n\tSkipTags();\n\n\tint byteCount = mp3_decode(\n\t\t(mp3_decoder_t*)m_MP3Decoder,\n\t\tm_Data ? const_cast( m_Data->GetDataPtr() + m_StreamPos ) : nullptr,\n\t\tm_Data ? m_Data->GetDataSize() - m_StreamPos: 0,\n\t\t(signed short*)m_DecodingBuffer.data(),\n\t\t&m_MP3Info\n\t);\n\n\tm_StreamPos += byteCount;\n\tm_InitialStreamPos = m_StreamPos;\n}\n\nconst uint8_t* clMP3DataProvider::GetWaveData() const\n{\n\treturn m_DecodingBuffer.data();\n}\n\nsize_t clMP3DataProvider::GetWaveDataSize() const\n{\n\treturn m_BufferUsed;\n}\n\nint clMP3DataProvider::DecodeFromFile( size_t BytesRead )\n{\n\tif ( m_IsEndOfStream || !m_Data )\n\t{\n\t\treturn 0;\n\t}\n\n\tsize_t ByteCount = mp3_decode(\n\t\t(mp3_decoder_t*)m_MP3Decoder,\n\t\tconst_cast( m_Data->GetDataPtr() + m_StreamPos ),\n\t\tm_Data->GetDataSize() - m_StreamPos,\n\t\t(signed short*)( m_DecodingBuffer.data() + BytesRead ),\n\t\t&m_MP3Info\n\t);\n\n\tm_Format.m_NumChannels = m_MP3Info.channels;\n\tm_Format.m_SamplesPerSecond = m_MP3Info.sample_rate;\n\n\tm_StreamPos += ByteCount;\n\n\tif ( m_StreamPos >= m_Data->GetDataSize() || !ByteCount )\n\t{\n\t\tm_IsEndOfStream = true;\n\t}\n\n\treturn m_MP3Info.audio_bytes;\n}\n\nsize_t clMP3DataProvider::StreamWaveData( size_t Size )\n{\n\tif ( m_IsEndOfStream )\n\t{\n\t\treturn 0;\n\t}\n\n\tsize_t OldSize = m_DecodingBuffer.size();\n\n\tif ( Size > OldSize )\n\t{\n\t\tm_DecodingBuffer.resize( Size, 0 );\n\t}\n\n\tsize_t BytesRead = 0;\n\n\twhile ( BytesRead + MP3_MAX_SAMPLES_PER_FRAME * 2 < Size )\n\t{\n\t\tint Ret = DecodeFromFile( BytesRead );\n\n\t\tif ( Ret > 0 )\n\t\t{\n\t\t\tBytesRead += Ret;\n\t\t}\n\t\telse if ( Ret == 0 )\n\t\t{\n\t\t\tm_IsEndOfStream = true;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ there is no audio data in this frame, just skip it\n\t\t}\n\t}\t\t\t\t\t\t\t\t\t\n\n\tm_BufferUsed = BytesRead;\n\n\treturn m_BufferUsed;\n}\n\nvoid clMP3DataProvider::Seek( float Seconds )\n{\n\tmp3_done( (mp3_decoder_t*)m_MP3Decoder );\n\tm_MP3Decoder = mp3_create();\n\n\tm_StreamPos = 0;\n\tm_IsEndOfStream = false;\n\n\tLoadMP3Info();\n}\nOS X: compilation fix#include \"MP3DataProvider.h\"\n#include \"Utils.h\"\n#include \"id3v2lib.h\"\n\nextern \"C\"\n{\n#include \"minimp3\/minimp3.h\"\n}\n\nclMP3DataProvider::clMP3DataProvider( const std::shared_ptr& Data )\n: m_Data( Data )\n, m_Format()\n, m_DecodingBuffer( MP3_MAX_SAMPLES_PER_FRAME * 16 )\n, m_BufferUsed( 0 )\n, m_StreamPos( 0 )\n, m_InitialStreamPos( 0 )\n, m_IsEndOfStream( false )\n, m_MP3Decoder( mp3_create() )\n{\n\tLoadMP3Info();\n\n\tm_Format.m_NumChannels = m_MP3Info.channels;\n\tm_Format.m_SamplesPerSecond = m_MP3Info.sample_rate;\n\tm_Format.m_BitsPerSample = 16;\n}\n\nclMP3DataProvider::~clMP3DataProvider()\n{\n\tmp3_done( (mp3_decoder_t*)m_MP3Decoder );\n}\n\nvoid clMP3DataProvider::SkipTags()\n{\n\tID3v2_header* ID3TagHeader = get_tag_header_with_buffer(\n\t\treinterpret_cast( m_Data->GetDataPtr() + m_StreamPos ),\n\t\tstatic_cast( m_Data->GetDataSize() - m_StreamPos )\n\t);\n\n\tif ( ID3TagHeader )\n\t{\n\t\tm_StreamPos += ID3TagHeader->tag_size;\n\t\tdelete_header( ID3TagHeader );\n\t}\n}\n\nvoid clMP3DataProvider::LoadMP3Info()\n{\n\tSkipTags();\n\n\tint byteCount = mp3_decode(\n\t\t(mp3_decoder_t*)m_MP3Decoder,\n\t\tm_Data ? const_cast( m_Data->GetDataPtr() + m_StreamPos ) : nullptr,\n\t\tm_Data ? m_Data->GetDataSize() - m_StreamPos: 0,\n\t\t(signed short*)m_DecodingBuffer.data(),\n\t\t&m_MP3Info\n\t);\n\n\tm_StreamPos += byteCount;\n\tm_InitialStreamPos = m_StreamPos;\n}\n\nconst uint8_t* clMP3DataProvider::GetWaveData() const\n{\n\treturn m_DecodingBuffer.data();\n}\n\nsize_t clMP3DataProvider::GetWaveDataSize() const\n{\n\treturn m_BufferUsed;\n}\n\nint clMP3DataProvider::DecodeFromFile( size_t BytesRead )\n{\n\tif ( m_IsEndOfStream || !m_Data )\n\t{\n\t\treturn 0;\n\t}\n\n\tsize_t ByteCount = mp3_decode(\n\t\t(mp3_decoder_t*)m_MP3Decoder,\n\t\tconst_cast( m_Data->GetDataPtr() + m_StreamPos ),\n\t\tm_Data->GetDataSize() - m_StreamPos,\n\t\t(signed short*)( m_DecodingBuffer.data() + BytesRead ),\n\t\t&m_MP3Info\n\t);\n\n\tm_Format.m_NumChannels = m_MP3Info.channels;\n\tm_Format.m_SamplesPerSecond = m_MP3Info.sample_rate;\n\n\tm_StreamPos += ByteCount;\n\n\tif ( m_StreamPos >= m_Data->GetDataSize() || !ByteCount )\n\t{\n\t\tm_IsEndOfStream = true;\n\t}\n\n\treturn m_MP3Info.audio_bytes;\n}\n\nsize_t clMP3DataProvider::StreamWaveData( size_t Size )\n{\n\tif ( m_IsEndOfStream )\n\t{\n\t\treturn 0;\n\t}\n\n\tsize_t OldSize = m_DecodingBuffer.size();\n\n\tif ( Size > OldSize )\n\t{\n\t\tm_DecodingBuffer.resize( Size, 0 );\n\t}\n\n\tsize_t BytesRead = 0;\n\n\twhile ( BytesRead + MP3_MAX_SAMPLES_PER_FRAME * 2 < Size )\n\t{\n\t\tint Ret = DecodeFromFile( BytesRead );\n\n\t\tif ( Ret > 0 )\n\t\t{\n\t\t\tBytesRead += Ret;\n\t\t}\n\t\telse if ( Ret == 0 )\n\t\t{\n\t\t\tm_IsEndOfStream = true;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ there is no audio data in this frame, just skip it\n\t\t}\n\t}\t\t\t\t\t\t\t\t\t\n\n\tm_BufferUsed = BytesRead;\n\n\treturn m_BufferUsed;\n}\n\nvoid clMP3DataProvider::Seek( float Seconds )\n{\n\tmp3_done( (mp3_decoder_t*)m_MP3Decoder );\n\tm_MP3Decoder = mp3_create();\n\n\tm_StreamPos = 0;\n\tm_IsEndOfStream = false;\n\n\tLoadMP3Info();\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n *\/\n#pragma once\n\n#include \"bi\/common\/TypeParameterised.hpp\"\n#include \"bi\/io\/indentable_ostream.hpp\"\n\nnamespace bi {\n\/**\n * C++ code generator.\n *\n * @ingroup io\n *\/\nclass CppBaseGenerator: public indentable_ostream {\npublic:\n CppBaseGenerator(std::ostream& base, const int level = 0,\n const bool header = false);\n\n using indentable_ostream::visit;\n\n virtual void visit(const Name* o);\n\n virtual void visit(const ExpressionList* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Parentheses* o);\n virtual void visit(const Sequence* o);\n virtual void visit(const Cast* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Assign* o);\n virtual void visit(const Slice* o);\n virtual void visit(const Query* o);\n virtual void visit(const Get* o);\n virtual void visit(const LambdaFunction* o);\n virtual void visit(const Span* o);\n virtual void visit(const Index* o);\n virtual void visit(const Range* o);\n virtual void visit(const Member* o);\n virtual void visit(const Global* o);\n virtual void visit(const This* o);\n virtual void visit(const Super* o);\n virtual void visit(const Nil* o);\n virtual void visit(const Parameter* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n\n virtual void visit(const File* o);\n virtual void visit(const GlobalVariable* o);\n virtual void visit(const LocalVariable* o);\n virtual void visit(const MemberVariable* o);\n virtual void visit(const Function* o);\n virtual void visit(const Fiber* o);\n virtual void visit(const MemberFunction* o);\n virtual void visit(const MemberFiber* o);\n virtual void visit(const Program* o);\n virtual void visit(const BinaryOperator* o);\n virtual void visit(const UnaryOperator* o);\n virtual void visit(const AssignmentOperator* o);\n virtual void visit(const ConversionOperator* o);\n virtual void visit(const Basic* o);\n virtual void visit(const Class* o);\n virtual void visit(const Generic* o);\n virtual void visit(const Assume* o);\n virtual void visit(const ExpressionStatement* o);\n virtual void visit(const If* o);\n virtual void visit(const For* o);\n virtual void visit(const While* o);\n virtual void visit(const DoWhile* o);\n virtual void visit(const Assert* o);\n virtual void visit(const Return* o);\n virtual void visit(const Yield* o);\n virtual void visit(const Raw* o);\n virtual void visit(const StatementList* o);\n\n virtual void visit(const EmptyType* o);\n virtual void visit(const ArrayType* o);\n virtual void visit(const TupleType* o);\n virtual void visit(const FunctionType* o);\n virtual void visit(const FiberType* o);\n virtual void visit(const OptionalType* o);\n virtual void visit(const ClassType* o);\n virtual void visit(const BasicType* o);\n virtual void visit(const GenericType* o);\n virtual void visit(const MemberType* o);\n virtual void visit(const UnknownType* o);\n virtual void visit(const TypeList* o);\n\nprotected:\n \/**\n * Generate code for template parameters (`template<...>`).\n *\/\n template\n void genTemplateParams(const ObjectType* o);\n\n \/**\n * Generate code for template arguments (`<...>`).\n *\/\n template\n void genTemplateArgs(const ObjectType* o);\n\n \/**\n * Generate the initialization of a variable, including the call to the\n * constructor and\/or assignment of the initial value.\n *\/\n template\n void genInit(const T* o);\n\n \/**\n * Generate macro to put function call on stack trace.\n *\/\n void genTraceFunction(const std::string& name, const Location* loc);\n\n \/**\n * Generate macro to update line on stack trace.\n *\/\n void genTraceLine(const Location* loc);\n\n \/*\n * Generate arguments for function calls with appropriate casts where\n * necessary.\n *\/\n void genArgs(const Expression* args, const Type* types);\n void genLeftArg(const Call* o);\n void genRightArg(const Call* o);\n void genSingleArg(const Call* o);\n void genArg(const Expression* arg, const Type* type);\n\n \/**\n * Output header instead of source?\n *\/\n bool header;\n\n \/**\n * Are we on the left side of an assignment statement?\n *\/\n int inAssign;\n\n \/**\n * Are we inside a constructor?\n *\/\n int inConstructor;\n\n \/**\n * Are we inside the body of a lambda function?\n *\/\n int inLambda;\n\n \/**\n * Are we inside a sequence?\n *\/\n int inSequence;\n};\n}\n\ntemplate\nvoid bi::CppBaseGenerator::genInit(const T* o) {\n if (o->type->isArray()) {\n ArrayType* type = dynamic_cast(o->type->canonical());\n assert(type);\n if (!o->brackets->isEmpty()) {\n if (!o->value->isEmpty()) {\n middle(\" = \");\n if (o->value->type->isConvertible(*type)) {\n middle(o->value);\n } else {\n middle(\"libbirch::make_array_and_assign<\" << type->single << \">(\");\n if (!o->isValue()) {\n middle(\"context_, \");\n }\n middle(\"libbirch::make_shape(\" << o->brackets << ')');\n middle(\", \" << o->value << ')');\n }\n } else {\n middle(\" = libbirch::make_array<\" << type->single << \">(\");\n if (!o->isValue()) {\n middle(\"context_, \");\n }\n middle(\"libbirch::make_shape(\" << o->brackets << ')');\n if (!o->args->isEmpty()) {\n middle(\", \" << o->args);\n }\n middle(')');\n }\n } else if (!o->value->isEmpty()) {\n middle(\" = \" << o->value);\n }\n } else if (o->type->isClass()) {\n if (!o->value->isEmpty()) {\n middle(\"(context_, \" << o->value << ')');\n } else {\n middle(\" = libbirch::make_pointer<\" << o->type << \">(context_\");\n if (!o->args->isEmpty()) {\n middle(\", \" << o->args);\n }\n middle(\")\");\n }\n } else if (!o->value->isEmpty()) {\n middle('(');\n if (!o->type->isValue()) {\n middle(\"context_, \");\n }\n middle(o->value << ')');\n }\n}\n\ntemplate\nvoid bi::CppBaseGenerator::genTemplateParams(const ObjectType* o) {\n if (o->isGeneric()) {\n start(\"template<\");\n if (!o->isBound()) {\n for (auto iter = o->typeParams->begin(); iter != o->typeParams->end();\n ++iter) {\n if (iter != o->typeParams->begin()) {\n middle(\", \");\n }\n middle(\"class \" << *iter);\n }\n }\n finish('>');\n }\n}\n\ntemplate\nvoid bi::CppBaseGenerator::genTemplateArgs(const ObjectType* o) {\n if (o->isGeneric()) {\n middle('<' << o->typeParams << '>');\n }\n}\nFixed C++ code generation for initializing lambda function variables.\/**\n * @file\n *\/\n#pragma once\n\n#include \"bi\/common\/TypeParameterised.hpp\"\n#include \"bi\/io\/indentable_ostream.hpp\"\n\nnamespace bi {\n\/**\n * C++ code generator.\n *\n * @ingroup io\n *\/\nclass CppBaseGenerator: public indentable_ostream {\npublic:\n CppBaseGenerator(std::ostream& base, const int level = 0,\n const bool header = false);\n\n using indentable_ostream::visit;\n\n virtual void visit(const Name* o);\n\n virtual void visit(const ExpressionList* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Literal* o);\n virtual void visit(const Parentheses* o);\n virtual void visit(const Sequence* o);\n virtual void visit(const Cast* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Call* o);\n virtual void visit(const Assign* o);\n virtual void visit(const Slice* o);\n virtual void visit(const Query* o);\n virtual void visit(const Get* o);\n virtual void visit(const LambdaFunction* o);\n virtual void visit(const Span* o);\n virtual void visit(const Index* o);\n virtual void visit(const Range* o);\n virtual void visit(const Member* o);\n virtual void visit(const Global* o);\n virtual void visit(const This* o);\n virtual void visit(const Super* o);\n virtual void visit(const Nil* o);\n virtual void visit(const Parameter* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const Identifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n virtual void visit(const OverloadedIdentifier* o);\n\n virtual void visit(const File* o);\n virtual void visit(const GlobalVariable* o);\n virtual void visit(const LocalVariable* o);\n virtual void visit(const MemberVariable* o);\n virtual void visit(const Function* o);\n virtual void visit(const Fiber* o);\n virtual void visit(const MemberFunction* o);\n virtual void visit(const MemberFiber* o);\n virtual void visit(const Program* o);\n virtual void visit(const BinaryOperator* o);\n virtual void visit(const UnaryOperator* o);\n virtual void visit(const AssignmentOperator* o);\n virtual void visit(const ConversionOperator* o);\n virtual void visit(const Basic* o);\n virtual void visit(const Class* o);\n virtual void visit(const Generic* o);\n virtual void visit(const Assume* o);\n virtual void visit(const ExpressionStatement* o);\n virtual void visit(const If* o);\n virtual void visit(const For* o);\n virtual void visit(const While* o);\n virtual void visit(const DoWhile* o);\n virtual void visit(const Assert* o);\n virtual void visit(const Return* o);\n virtual void visit(const Yield* o);\n virtual void visit(const Raw* o);\n virtual void visit(const StatementList* o);\n\n virtual void visit(const EmptyType* o);\n virtual void visit(const ArrayType* o);\n virtual void visit(const TupleType* o);\n virtual void visit(const FunctionType* o);\n virtual void visit(const FiberType* o);\n virtual void visit(const OptionalType* o);\n virtual void visit(const ClassType* o);\n virtual void visit(const BasicType* o);\n virtual void visit(const GenericType* o);\n virtual void visit(const MemberType* o);\n virtual void visit(const UnknownType* o);\n virtual void visit(const TypeList* o);\n\nprotected:\n \/**\n * Generate code for template parameters (`template<...>`).\n *\/\n template\n void genTemplateParams(const ObjectType* o);\n\n \/**\n * Generate code for template arguments (`<...>`).\n *\/\n template\n void genTemplateArgs(const ObjectType* o);\n\n \/**\n * Generate the initialization of a variable, including the call to the\n * constructor and\/or assignment of the initial value.\n *\/\n template\n void genInit(const T* o);\n\n \/**\n * Generate macro to put function call on stack trace.\n *\/\n void genTraceFunction(const std::string& name, const Location* loc);\n\n \/**\n * Generate macro to update line on stack trace.\n *\/\n void genTraceLine(const Location* loc);\n\n \/*\n * Generate arguments for function calls with appropriate casts where\n * necessary.\n *\/\n void genArgs(const Expression* args, const Type* types);\n void genLeftArg(const Call* o);\n void genRightArg(const Call* o);\n void genSingleArg(const Call* o);\n void genArg(const Expression* arg, const Type* type);\n\n \/**\n * Output header instead of source?\n *\/\n bool header;\n\n \/**\n * Are we on the left side of an assignment statement?\n *\/\n int inAssign;\n\n \/**\n * Are we inside a constructor?\n *\/\n int inConstructor;\n\n \/**\n * Are we inside the body of a lambda function?\n *\/\n int inLambda;\n\n \/**\n * Are we inside a sequence?\n *\/\n int inSequence;\n};\n}\n\ntemplate\nvoid bi::CppBaseGenerator::genInit(const T* o) {\n if (o->type->isArray()) {\n ArrayType* type = dynamic_cast(o->type->canonical());\n assert(type);\n if (!o->brackets->isEmpty()) {\n if (!o->value->isEmpty()) {\n middle(\" = \");\n if (o->value->type->isConvertible(*type)) {\n middle(o->value);\n } else {\n middle(\"libbirch::make_array_and_assign<\" << type->single << \">(\");\n if (!o->isValue()) {\n middle(\"context_, \");\n }\n middle(\"libbirch::make_shape(\" << o->brackets << ')');\n middle(\", \" << o->value << ')');\n }\n } else {\n middle(\" = libbirch::make_array<\" << type->single << \">(\");\n if (!o->isValue()) {\n middle(\"context_, \");\n }\n middle(\"libbirch::make_shape(\" << o->brackets << ')');\n if (!o->args->isEmpty()) {\n middle(\", \" << o->args);\n }\n middle(')');\n }\n } else if (!o->value->isEmpty()) {\n middle(\" = \" << o->value);\n }\n } else if (o->type->isClass()) {\n if (!o->value->isEmpty()) {\n middle(\"(context_, \" << o->value << ')');\n } else {\n middle(\" = libbirch::make_pointer<\" << o->type << \">(context_\");\n if (!o->args->isEmpty()) {\n middle(\", \" << o->args);\n }\n middle(\")\");\n }\n } else if (!o->value->isEmpty()) {\n middle('(');\n if (!o->type->isValue() && !o->type->isFunction()) {\n middle(\"context_, \");\n }\n middle(o->value << ')');\n }\n}\n\ntemplate\nvoid bi::CppBaseGenerator::genTemplateParams(const ObjectType* o) {\n if (o->isGeneric()) {\n start(\"template<\");\n if (!o->isBound()) {\n for (auto iter = o->typeParams->begin(); iter != o->typeParams->end();\n ++iter) {\n if (iter != o->typeParams->begin()) {\n middle(\", \");\n }\n middle(\"class \" << *iter);\n }\n }\n finish('>');\n }\n}\n\ntemplate\nvoid bi::CppBaseGenerator::genTemplateArgs(const ObjectType* o) {\n if (o->isGeneric()) {\n middle('<' << o->typeParams << '>');\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: testhelper.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: dbo $ $Date: 2001-05-08 15:55: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#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"testhelper.hxx\"\n\nusing namespace rtl;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\n\n#if (defined UNX) || (defined OS2)\nint main( int argc, char * argv[] )\n#else\nint __cdecl main( int argc, char * argv[] )\n#endif\n{\n Reference< XMultiServiceFactory > xMgr( createRegistryServiceFactory(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"cpputest.rdb\") ) ) );\n\n sal_Bool bSucc = sal_False;\n try\n {\n Reference< XImplementationRegistration > xImplReg(\n xMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.registry.ImplementationRegistration\") ) ),\n UNO_QUERY );\n OSL_ENSURE( xImplReg.is(), \"### no impl reg!\" );\n\n#ifdef UNX\n#define REG_PREFIX \"lib\"\n#ifdef MACOSX\n#define DLL_POSTFIX \".dylib.framework\"\n#else\n#define DLL_POSTFIX \".so\"\n#endif\n#else\n#define REG_PREFIX \"\"\n#define DLL_POSTFIX \".dll\"\n#endif\n OString aLibName( REG_PREFIX );\n aLibName += \"corefl\";\n#ifndef OS2\n aLibName += DLL_POSTFIX;\n#endif\n xImplReg->registerImplementation(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.loader.SharedLibrary\") ),\n OUString::createFromAscii( aLibName.getStr() ),\n Reference< XSimpleRegistry >() );\n\n testPropertyTypeHelper();\n testidlclass( xMgr );\n test_PropertySetHelper();\n test_ImplHelper( xMgr );\n test_interfacecontainer();\n }\n catch (Exception & rExc)\n {\n OSL_ENSURE( sal_False, \"### exception occured!\" );\n OString aMsg( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_TRACE( \"### exception occured: \" );\n OSL_TRACE( aMsg.getStr() );\n OSL_TRACE( \"\\n\" );\n }\n\n Reference< XComponent >( xMgr, UNO_QUERY )->dispose();\n\n printf( \"Test finished\\n\" );\n return 0;\n}\ncontext tests\/*************************************************************************\n *\n * $RCSfile: testhelper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: dbo $ $Date: 2001-06-01 11:47:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"testhelper.hxx\"\n\nusing namespace rtl;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\n\n#if (defined UNX) || (defined OS2)\nint main( int argc, char * argv[] )\n#else\nint __cdecl main( int argc, char * argv[] )\n#endif\n{\n Reference< XMultiComponentFactory > xMgr( createRegistryServiceFactory(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"cpputest.rdb\") ) ), UNO_QUERY );\n Reference< XComponentContext > xInitialContext;\n OSL_VERIFY( Reference< beans::XPropertySet >( xMgr, UNO_QUERY )->getPropertyValue(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"DefaultContext\") ) ) >>= xInitialContext );\n\n ContextEntry_Init aEntry;\n aEntry.bLateInitService = false;\n aEntry.name = OUString( RTL_CONSTASCII_USTRINGPARAM(\"bla, bla\") );\n aEntry.value = makeAny( (sal_Int32)5 );\n Reference< XComponentContext > xContext( createComponentContext( &aEntry, 1, xInitialContext ) );\n OSL_ASSERT( xContext->getServiceManager() == xMgr );\n\n sal_Bool bSucc = sal_False;\n try\n {\n Reference< XImplementationRegistration > xImplReg(\n xMgr->createInstanceWithContext(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.registry.ImplementationRegistration\") ),\n xContext ),\n UNO_QUERY );\n OSL_ENSURE( xImplReg.is(), \"### no impl reg!\" );\n\n#ifdef UNX\n#define REG_PREFIX \"lib\"\n#ifdef MACOSX\n#define DLL_POSTFIX \".dylib.framework\"\n#else\n#define DLL_POSTFIX \".so\"\n#endif\n#else\n#define REG_PREFIX \"\"\n#define DLL_POSTFIX \".dll\"\n#endif\n OString aLibName( REG_PREFIX );\n aLibName += \"corefl\";\n#ifndef OS2\n aLibName += DLL_POSTFIX;\n#endif\n xImplReg->registerImplementation(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.loader.SharedLibrary\") ),\n OUString::createFromAscii( aLibName.getStr() ),\n Reference< XSimpleRegistry >() );\n\n Reference< XMultiServiceFactory > x( xMgr, UNO_QUERY );\n testPropertyTypeHelper();\n testidlclass( x );\n test_PropertySetHelper();\n test_ImplHelper( x );\n test_interfacecontainer();\n }\n catch (Exception & rExc)\n {\n OSL_ENSURE( sal_False, \"### exception occured!\" );\n OString aMsg( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_TRACE( \"### exception occured: \" );\n OSL_TRACE( aMsg.getStr() );\n OSL_TRACE( \"\\n\" );\n }\n\n OSL_VERIFY( xContext->getValueByName(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"bla, bla\") ) ) == (sal_Int32)5 );\n Reference< XComponent >( xInitialContext, UNO_QUERY )->dispose();\n\n printf( \"Test finished\\n\" );\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 Bauhaus-Universitaet Weimar\n\/\/ This Software is distributed under the Modified BSD License, see license.txt.\n\/\/\n\/\/ Virtual Reality and Visualization Research Group \n\/\/ Faculty of Media, Bauhaus-Universitaet Weimar\n\/\/ http:\/\/www.uni-weimar.de\/medien\/vr\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace lamure\n{\nnamespace ren\n{\n\ngpu_context::\ngpu_context(const context_t context_id)\n: context_id_(context_id),\n is_created_(false),\n temp_buffer_a_(nullptr),\n temp_buffer_b_(nullptr),\n primary_buffer_(nullptr),\n temporary_storages_(temporary_storages(nullptr, nullptr)),\n temporary_storages_provenance_(temporary_storages(nullptr, nullptr)),\n upload_budget_in_nodes_(LAMURE_DEFAULT_UPLOAD_BUDGET),\n render_budget_in_nodes_(LAMURE_DEFAULT_VIDEO_MEMORY_BUDGET) {\n\n}\n\n\ngpu_context::\n~gpu_context() {\n temporary_storages_ = temporary_storages(nullptr, nullptr);\n temporary_storages_provenance_ = temporary_storages(nullptr, nullptr);\n\n if (temp_buffer_a_) {\n delete temp_buffer_a_;\n temp_buffer_a_ = nullptr;\n }\n\n if (temp_buffer_b_) {\n delete temp_buffer_b_;\n temp_buffer_b_ = nullptr;\n }\n\n if (primary_buffer_) {\n delete primary_buffer_;\n primary_buffer_ = nullptr;\n }\n\n}\n\nvoid gpu_context::\ncreate(scm::gl::render_device_ptr device) {\n assert(device);\n if (is_created_) {\n return;\n }\n is_created_ = true;\n\n test_video_memory(device);\n\n model_database* database = model_database::get_instance();\n\n temp_buffer_a_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false);\n temp_buffer_b_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false);\n primary_buffer_ = new gpu_access(device, render_budget_in_nodes_, database->get_primitives_per_node(), true);\n\n map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_A, device);\n map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_B, device);\n}\n\nvoid gpu_context::\ntest_video_memory(scm::gl::render_device_ptr device) {\n model_database* database = model_database::get_instance();\n policy* policy = policy::get_instance();\n\n float safety = 0.75;\n size_t video_ram_free_in_mb = gpu_access::query_video_memory_in_mb(device) * safety;\n\n size_t render_budget_in_mb = policy->render_budget_in_mb();\n\n if(policy->out_of_core_budget_in_mb() == 0)\n {\n std::cout << \"##### Total free video memory (\" << video_ram_free_in_mb << \" MB) will be used for the render budget #####\" << std::endl;\n render_budget_in_mb = video_ram_free_in_mb;\n }\n else if(video_ram_free_in_mb < render_budget_in_mb)\n {\n std::cout << \"##### The specified render budget is too large! \" << video_ram_free_in_mb << \" MB will be used for the render budget #####\" << std::endl;\n render_budget_in_mb = video_ram_free_in_mb;\n } \n else \n {\n std::cout << \"##### \" << policy->render_budget_in_mb() << \" MB will be used for the render budget #####\" << std::endl;\n }\n\n long node_size_total = database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size();\n render_budget_in_nodes_ = (render_budget_in_mb * 1024 * 1024) \/ node_size_total;\n \/\/ std::cout << \"RENDER1: \" << render_budget_in_mb << std::endl;\n \/\/ std::cout << \"RENDER1: \" << render_budget_in_mb * 0.75 << std::endl;\n \/\/ std::cout << \"RENDER1: \" << node_size_total << std::endl;\n \/\/ std::cout << \"RENDER1: \" << (render_budget_in_mb * 0.75) \/ node_size_total << std::endl;\n \/\/ std::cout << \"RENDER1: \" << render_budget_in_nodes_ << std::endl;\n\n \/\/ render_budget_in_mb = policy->render_budget_in_mb();\n\n\n \/\/ \/\/ render_budget_in_mb = render_budget_in_mb < LAMURE_MIN_VIDEO_MEMORY_BUDGET ? LAMURE_MIN_VIDEO_MEMORY_BUDGET : render_budget_in_mb;\n \/\/ render_budget_in_mb = render_budget_in_mb > video_ram_free_in_mb * 0.75 ? video_ram_free_in_mb * 0.75 : render_budget_in_mb;\n\n\n \/\/ render_budget_in_nodes_ = (render_budget_in_mb * 1024u * 1024u) \/ (database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size());\n \/\/ std::cout << \"RENDER2: \" << render_budget_in_nodes_ << std::endl;\n\n size_t max_upload_budget_in_mb = policy->max_upload_budget_in_mb();\n max_upload_budget_in_mb = max_upload_budget_in_mb < LAMURE_MIN_UPLOAD_BUDGET ? LAMURE_MIN_UPLOAD_BUDGET : max_upload_budget_in_mb;\n max_upload_budget_in_mb = max_upload_budget_in_mb > video_ram_free_in_mb * 0.125 ? video_ram_free_in_mb * 0.125 : max_upload_budget_in_mb;\n size_t max_upload_budget_in_nodes = (max_upload_budget_in_mb * 1024u * 1024u) \/ database->get_slot_size();\n upload_budget_in_nodes_ = max_upload_budget_in_nodes;\n \n\n#if 1\n \/\/ upload_budget_in_nodes_ = max_upload_budget_in_nodes\/4;\n\n#else\n gpu_access* test_temp = new gpu_access(device, 1, database->surfels_per_node(), false);\n gpu_access* test_main = new gpu_access(device, 1, database->surfels_per_node(), true);\n LodPointCloud::serializedsurfel* node_data = (LodPointCloud::serializedsurfel*)new char[size_of_node_in_bytes];\n memset((char*)node_data, 0, size_of_node_in_bytes);\n char* mapped_temp = test_temp->map(device);\n memcpy(mapped_temp, node_data, size_of_node_in_bytes);\n test_temp->unmap(device);\n\n auto frame_duration_in_ns = boost::timer::nanosecond_type(16.0 * 1000 * 1000);\n\n boost::timer::cpu_timer upload_timer;\n\n unsigned int iteration = 0;\n while (true) {\n\n upload_timer.start();\n\n for (unsigned int i = 0; i < upload_budget_in_nodes_; ++i) {\n size_t offset_in_temp_VBO = 0;\n size_t offset_in_render_VBO = 0;\n device->main_context()->copy_buffer_data(test_main->buffer(), test_temp->buffer(), offset_in_render_VBO, offset_in_temp_VBO, size_of_node_in_bytes);\n }\n\n upload_timer.stop();\n\n boost::timer::cpu_times const elapsed(upload_timer.elapsed());\n boost::timer::nanosecond_type const elapsed_ns(elapsed.system + elapsed.user);\n\n if (iteration++ > 1) {\n if (elapsed_ns < frame_duration_in_ns) {\n if (upload_budget_in_nodes_ < max_upload_budget_in_nodes) {\n ++upload_budget_in_nodes_;\n }\n else {\n break;\n }\n }\n else {\n break;\n }\n }\n\n\n }\n\n delete test_temp;\n delete test_main;\n delete[] node_data;\n\n device->main_context()->apply();\n#endif\n\n#ifdef LAMURE_ENABLE_INFO\n std::cout << \"lamure: context \" << context_id_ << \" render budget (MB): \" << render_budget_in_mb << std::endl;\n std::cout << \"lamure: context \" << context_id_ << \" upload budget (MB): \" << max_upload_budget_in_mb << std::endl;\n#endif\n\n}\n\nscm::gl::buffer_ptr gpu_context::\nget_context_buffer(scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n return primary_buffer_->get_buffer();\n}\n\nscm::gl::vertex_array_ptr gpu_context::\nget_context_memory(bvh::primitive_type type, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n return primary_buffer_->get_memory(type);\n}\n\nvoid gpu_context::\nmap_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n switch (buffer) {\n case cut_database_record::temporary_buffer::BUFFER_A:\n if (!temp_buffer_a_->is_mapped()) {\n temporary_storages_.storage_a_ = temp_buffer_a_->map(device);\n temporary_storages_provenance_.storage_a_ = temp_buffer_a_->map_provenance(device);\n }\n return;\n break;\n\n case cut_database_record::temporary_buffer::BUFFER_B:\n if (!temp_buffer_b_->is_mapped()) {\n temporary_storages_.storage_b_ = temp_buffer_b_->map(device);\n temporary_storages_provenance_.storage_b_ = temp_buffer_b_->map_provenance(device);\n }\n return;\n break;\n\n default: break;\n }\n\n throw std::runtime_error(\n \"lamure: Failed to map temporary buffer on context: \" + context_id_);\n\n}\n\nvoid gpu_context::\nunmap_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n switch (buffer) {\n case cut_database_record::temporary_buffer::BUFFER_A:\n if (temp_buffer_a_->is_mapped()) {\n temp_buffer_a_->unmap(device);\n temp_buffer_a_->unmap_provenance(device);\n }\n break;\n\n case cut_database_record::temporary_buffer::BUFFER_B:\n if (temp_buffer_b_->is_mapped()) {\n temp_buffer_b_->unmap(device);\n temp_buffer_b_->unmap_provenance(device);\n }\n break;\n\n default: break;\n }\n}\n\n\/\/returns true if any node has been uploaded; false otherwise\nbool gpu_context::\nupdate_primary_buffer(const cut_database_record::temporary_buffer& from_buffer, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n model_database* database = model_database::get_instance();\n\n cut_database* cuts = cut_database::get_instance();\n\n size_t uploaded_nodes = 0;\n\n switch (from_buffer) {\n case cut_database_record::temporary_buffer::BUFFER_A:\n {\n if (temp_buffer_a_->is_mapped()) {\n throw std::runtime_error(\n \"lamure: gpu_context::Failed to transfer nodes into main memory on context: \" + context_id_);\n }\n std::vector& transfer_descr_list = cuts->get_updated_set(context_id_);\n if (!transfer_descr_list.empty()) {\n uploaded_nodes += transfer_descr_list.size();\n\n for (const auto& transfer_desc : transfer_descr_list)\n {\n size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size();\n size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size();\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer(), \n temp_buffer_a_->get_buffer(), \n offset_in_render_VBO, \n offset_in_temp_VBO, \n database->get_slot_size()\n );\n\n\n size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data);\n size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data);\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer_provenance(), \n temp_buffer_a_->get_buffer_provenance(), \n offset_in_render_VBO_provenance, \n offset_in_temp_VBO_provenance, \n database->get_primitives_per_node() * sizeof(provenance_data)\n );\n }\n }\n break;\n }\n\n case cut_database_record::temporary_buffer::BUFFER_B:\n {\n if (temp_buffer_b_->is_mapped()) {\n throw std::runtime_error(\n \"lamure: gpu_context::Failed to transfer nodes into main memory on context: \" + context_id_);\n }\n std::vector& transfer_descr_list = cuts->get_updated_set(context_id_);\n if (!transfer_descr_list.empty()) {\n uploaded_nodes += transfer_descr_list.size();\n\n for (const auto& transfer_desc : transfer_descr_list) {\n size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size();\n size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size();\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer(), \n temp_buffer_b_->get_buffer(), \n offset_in_render_VBO, \n offset_in_temp_VBO, \n database->get_slot_size()\n );\n\n\n size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data);\n size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data);\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer_provenance(), \n temp_buffer_b_->get_buffer_provenance(), \n offset_in_render_VBO_provenance, \n offset_in_temp_VBO_provenance, \n database->get_primitives_per_node() * sizeof(provenance_data)\n );\n }\n }\n break;\n }\n default: break;\n\n }\n\n return uploaded_nodes != 0;\n}\n\n\n\n}\n}\n*improved budget-usage\/\/ Copyright (c) 2014 Bauhaus-Universitaet Weimar\n\/\/ This Software is distributed under the Modified BSD License, see license.txt.\n\/\/\n\/\/ Virtual Reality and Visualization Research Group \n\/\/ Faculty of Media, Bauhaus-Universitaet Weimar\n\/\/ http:\/\/www.uni-weimar.de\/medien\/vr\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace lamure\n{\nnamespace ren\n{\n\ngpu_context::\ngpu_context(const context_t context_id)\n: context_id_(context_id),\n is_created_(false),\n temp_buffer_a_(nullptr),\n temp_buffer_b_(nullptr),\n primary_buffer_(nullptr),\n temporary_storages_(temporary_storages(nullptr, nullptr)),\n temporary_storages_provenance_(temporary_storages(nullptr, nullptr)),\n upload_budget_in_nodes_(LAMURE_DEFAULT_UPLOAD_BUDGET),\n render_budget_in_nodes_(LAMURE_DEFAULT_VIDEO_MEMORY_BUDGET) {\n\n}\n\n\ngpu_context::\n~gpu_context() {\n temporary_storages_ = temporary_storages(nullptr, nullptr);\n temporary_storages_provenance_ = temporary_storages(nullptr, nullptr);\n\n if (temp_buffer_a_) {\n delete temp_buffer_a_;\n temp_buffer_a_ = nullptr;\n }\n\n if (temp_buffer_b_) {\n delete temp_buffer_b_;\n temp_buffer_b_ = nullptr;\n }\n\n if (primary_buffer_) {\n delete primary_buffer_;\n primary_buffer_ = nullptr;\n }\n\n}\n\nvoid gpu_context::\ncreate(scm::gl::render_device_ptr device) {\n assert(device);\n if (is_created_) {\n return;\n }\n is_created_ = true;\n\n test_video_memory(device);\n\n model_database* database = model_database::get_instance();\n\n temp_buffer_a_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false);\n temp_buffer_b_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false);\n primary_buffer_ = new gpu_access(device, render_budget_in_nodes_, database->get_primitives_per_node(), true);\n\n map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_A, device);\n map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_B, device);\n}\n\nvoid gpu_context::\ntest_video_memory(scm::gl::render_device_ptr device) {\n model_database* database = model_database::get_instance();\n policy* policy = policy::get_instance();\n\n float safety = 0.75;\n size_t video_ram_free_in_mb = gpu_access::query_video_memory_in_mb(device) * safety;\n\n size_t render_budget_in_mb = policy->render_budget_in_mb();\n\n if(policy->out_of_core_budget_in_mb() == 0)\n {\n std::cout << \"##### Total free video memory (\" << video_ram_free_in_mb << \" MB) will be used for the render budget #####\" << std::endl;\n render_budget_in_mb = video_ram_free_in_mb;\n }\n else if(video_ram_free_in_mb < render_budget_in_mb)\n {\n std::cout << \"##### The specified render budget is too large! \" << video_ram_free_in_mb << \" MB will be used for the render budget #####\" << std::endl;\n render_budget_in_mb = video_ram_free_in_mb;\n } \n else \n {\n std::cout << \"##### \" << policy->render_budget_in_mb() << \" MB will be used for the render budget #####\" << std::endl;\n }\n\n long node_size_total = database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size();\n render_budget_in_nodes_ = (render_budget_in_mb * 1024 * 1024) \/ node_size_total;\n\n \/\/ render_budget_in_mb = policy->render_budget_in_mb();\n\n\n \/\/ \/\/ render_budget_in_mb = render_budget_in_mb < LAMURE_MIN_VIDEO_MEMORY_BUDGET ? LAMURE_MIN_VIDEO_MEMORY_BUDGET : render_budget_in_mb;\n \/\/ render_budget_in_mb = render_budget_in_mb > video_ram_free_in_mb * 0.75 ? video_ram_free_in_mb * 0.75 : render_budget_in_mb;\n\n\n \/\/ render_budget_in_nodes_ = (render_budget_in_mb * 1024u * 1024u) \/ (database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size());\n \/\/ std::cout << \"RENDER2: \" << render_budget_in_nodes_ << std::endl;\n\n size_t max_upload_budget_in_mb = policy->max_upload_budget_in_mb();\n max_upload_budget_in_mb = max_upload_budget_in_mb < LAMURE_MIN_UPLOAD_BUDGET ? LAMURE_MIN_UPLOAD_BUDGET : max_upload_budget_in_mb;\n max_upload_budget_in_mb = max_upload_budget_in_mb > video_ram_free_in_mb * 0.125 ? video_ram_free_in_mb * 0.125 : max_upload_budget_in_mb;\n \n upload_budget_in_nodes_ = (max_upload_budget_in_mb * 1024u * 1024u) \/ node_size_total;\n \n\n#if 1\n \/\/ upload_budget_in_nodes_ = max_upload_budget_in_nodes\/4;\n\n#else\n gpu_access* test_temp = new gpu_access(device, 1, database->surfels_per_node(), false);\n gpu_access* test_main = new gpu_access(device, 1, database->surfels_per_node(), true);\n LodPointCloud::serializedsurfel* node_data = (LodPointCloud::serializedsurfel*)new char[size_of_node_in_bytes];\n memset((char*)node_data, 0, size_of_node_in_bytes);\n char* mapped_temp = test_temp->map(device);\n memcpy(mapped_temp, node_data, size_of_node_in_bytes);\n test_temp->unmap(device);\n\n auto frame_duration_in_ns = boost::timer::nanosecond_type(16.0 * 1000 * 1000);\n\n boost::timer::cpu_timer upload_timer;\n\n unsigned int iteration = 0;\n while (true) {\n\n upload_timer.start();\n\n for (unsigned int i = 0; i < upload_budget_in_nodes_; ++i) {\n size_t offset_in_temp_VBO = 0;\n size_t offset_in_render_VBO = 0;\n device->main_context()->copy_buffer_data(test_main->buffer(), test_temp->buffer(), offset_in_render_VBO, offset_in_temp_VBO, size_of_node_in_bytes);\n }\n\n upload_timer.stop();\n\n boost::timer::cpu_times const elapsed(upload_timer.elapsed());\n boost::timer::nanosecond_type const elapsed_ns(elapsed.system + elapsed.user);\n\n if (iteration++ > 1) {\n if (elapsed_ns < frame_duration_in_ns) {\n if (upload_budget_in_nodes_ < max_upload_budget_in_nodes) {\n ++upload_budget_in_nodes_;\n }\n else {\n break;\n }\n }\n else {\n break;\n }\n }\n\n\n }\n\n delete test_temp;\n delete test_main;\n delete[] node_data;\n\n device->main_context()->apply();\n#endif\n\n#ifdef LAMURE_ENABLE_INFO\n std::cout << \"lamure: context \" << context_id_ << \" render budget (MB): \" << render_budget_in_mb << std::endl;\n std::cout << \"lamure: context \" << context_id_ << \" upload budget (MB): \" << max_upload_budget_in_mb << std::endl;\n#endif\n\n}\n\nscm::gl::buffer_ptr gpu_context::\nget_context_buffer(scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n return primary_buffer_->get_buffer();\n}\n\nscm::gl::vertex_array_ptr gpu_context::\nget_context_memory(bvh::primitive_type type, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n return primary_buffer_->get_memory(type);\n}\n\nvoid gpu_context::\nmap_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n switch (buffer) {\n case cut_database_record::temporary_buffer::BUFFER_A:\n if (!temp_buffer_a_->is_mapped()) {\n temporary_storages_.storage_a_ = temp_buffer_a_->map(device);\n temporary_storages_provenance_.storage_a_ = temp_buffer_a_->map_provenance(device);\n }\n return;\n break;\n\n case cut_database_record::temporary_buffer::BUFFER_B:\n if (!temp_buffer_b_->is_mapped()) {\n temporary_storages_.storage_b_ = temp_buffer_b_->map(device);\n temporary_storages_provenance_.storage_b_ = temp_buffer_b_->map_provenance(device);\n }\n return;\n break;\n\n default: break;\n }\n\n throw std::runtime_error(\n \"lamure: Failed to map temporary buffer on context: \" + context_id_);\n\n}\n\nvoid gpu_context::\nunmap_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n switch (buffer) {\n case cut_database_record::temporary_buffer::BUFFER_A:\n if (temp_buffer_a_->is_mapped()) {\n temp_buffer_a_->unmap(device);\n temp_buffer_a_->unmap_provenance(device);\n }\n break;\n\n case cut_database_record::temporary_buffer::BUFFER_B:\n if (temp_buffer_b_->is_mapped()) {\n temp_buffer_b_->unmap(device);\n temp_buffer_b_->unmap_provenance(device);\n }\n break;\n\n default: break;\n }\n}\n\n\/\/returns true if any node has been uploaded; false otherwise\nbool gpu_context::\nupdate_primary_buffer(const cut_database_record::temporary_buffer& from_buffer, scm::gl::render_device_ptr device) {\n if (!is_created_)\n create(device);\n\n assert(device);\n\n model_database* database = model_database::get_instance();\n\n cut_database* cuts = cut_database::get_instance();\n\n size_t uploaded_nodes = 0;\n\n switch (from_buffer) {\n case cut_database_record::temporary_buffer::BUFFER_A:\n {\n if (temp_buffer_a_->is_mapped()) {\n throw std::runtime_error(\n \"lamure: gpu_context::Failed to transfer nodes into main memory on context: \" + context_id_);\n }\n std::vector& transfer_descr_list = cuts->get_updated_set(context_id_);\n if (!transfer_descr_list.empty()) {\n uploaded_nodes += transfer_descr_list.size();\n\n for (const auto& transfer_desc : transfer_descr_list)\n {\n size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size();\n size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size();\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer(), \n temp_buffer_a_->get_buffer(), \n offset_in_render_VBO, \n offset_in_temp_VBO, \n database->get_slot_size()\n );\n\n\n size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data);\n size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data);\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer_provenance(), \n temp_buffer_a_->get_buffer_provenance(), \n offset_in_render_VBO_provenance, \n offset_in_temp_VBO_provenance, \n database->get_primitives_per_node() * sizeof(provenance_data)\n );\n }\n }\n break;\n }\n\n case cut_database_record::temporary_buffer::BUFFER_B:\n {\n if (temp_buffer_b_->is_mapped()) {\n throw std::runtime_error(\n \"lamure: gpu_context::Failed to transfer nodes into main memory on context: \" + context_id_);\n }\n std::vector& transfer_descr_list = cuts->get_updated_set(context_id_);\n if (!transfer_descr_list.empty()) {\n uploaded_nodes += transfer_descr_list.size();\n\n for (const auto& transfer_desc : transfer_descr_list) {\n size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size();\n size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size();\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer(), \n temp_buffer_b_->get_buffer(), \n offset_in_render_VBO, \n offset_in_temp_VBO, \n database->get_slot_size()\n );\n\n\n size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data);\n size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data);\n device->main_context()->copy_buffer_data(\n primary_buffer_->get_buffer_provenance(), \n temp_buffer_b_->get_buffer_provenance(), \n offset_in_render_VBO_provenance, \n offset_in_temp_VBO_provenance, \n database->get_primitives_per_node() * sizeof(provenance_data)\n );\n }\n }\n break;\n }\n default: break;\n\n }\n\n return uploaded_nodes != 0;\n}\n\n\n\n}\n}\n<|endoftext|>"} {"text":"#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nusing boost::filesystem::remove_all;\n\nvoid test_swarm()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48000, 49000));\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49000, 50000));\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50000, 51000));\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 = 40000;\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\tses1.set_settings(settings);\n\tses2.set_settings(settings);\n\tses3.set_settings(settings);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::disabled;\n\tpes.in_enc_policy = pe_settings::disabled;\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);\t\n\n\tfloat sum_dl_rate2 = 0.f;\n\tfloat sum_dl_rate3 = 0.f;\n\tint count_dl_rates2 = 0;\n\tint count_dl_rates3 = 0;\n\n\tfor (int i = 0; i < 65; ++i)\n\t{\n\t\tstd::auto_ptr a;\n\t\ta = ses1.pop_alert();\n\t\tif (a.get())\n\t\t\tstd::cerr << \"ses1: \" << a->msg() << \"\\n\";\n\n\t\ta = ses2.pop_alert();\n\t\tif (a.get())\n\t\t\tstd::cerr << \"ses2: \" << a->msg() << \"\\n\";\n\n\t\ta = ses3.pop_alert();\n\t\tif (a.get())\n\t\t\tstd::cerr << \"ses3: \" << a->msg() << \"\\n\";\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\tif (st2.progress < 1.f && st2.progress > 0.3f)\n\t\t{\n\t\t\tsum_dl_rate2 += st2.download_payload_rate;\n\t\t\t++count_dl_rates2;\n\t\t}\n\t\tif (st3.progress < 1.f && st3.progress > 0.3f)\n\t\t{\n\t\t\tsum_dl_rate3 += st3.download_rate;\n\t\t\t++count_dl_rates3;\n\t\t}\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<< \"\\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<< 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\tfloat average2 = sum_dl_rate2 \/ float(count_dl_rates2);\n\tfloat average3 = sum_dl_rate3 \/ float(count_dl_rates3);\n\n\tstd::cerr << \"average rate: \" << (average2 \/ 1000.f) << \"kB\/s - \"\n\t\t<< (average3 \/ 1000.f) << \"kB\/s\" << std::endl;\n\n\tTEST_CHECK(std::fabs(average2 - float(rate_limit)) < 3000.f);\n\tTEST_CHECK(std::fabs(average3 - float(rate_limit)) < 3000.f);\n\tif (tor2.is_seed() && tor3.is_seed()) std::cerr << \"done\\n\";\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\tusing namespace boost::filesystem;\n\n\t\/\/ in case the previous run was terminated\n\ttry { remove_all(\".\/tmp1\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp2\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp3\"); } catch (std::exception&) {}\n\n\ttest_swarm();\n\t\n\tremove_all(\".\/tmp1\");\n\tremove_all(\".\/tmp2\");\n\tremove_all(\".\/tmp3\");\n\n\treturn 0;\n}\n\nmore output in test_swarm#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/session_settings.hpp\"\n#include \"libtorrent\/hasher.hpp\"\n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nusing boost::filesystem::remove_all;\n\nvoid test_swarm()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48000, 49000));\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49000, 50000));\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50000, 51000));\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 = 40000;\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\tses1.set_settings(settings);\n\tses2.set_settings(settings);\n\tses3.set_settings(settings);\n\n#ifndef TORRENT_DISABLE_ENCRYPTION\n\tpe_settings pes;\n\tpes.out_enc_policy = pe_settings::disabled;\n\tpes.in_enc_policy = pe_settings::disabled;\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);\t\n\n\tfloat sum_dl_rate2 = 0.f;\n\tfloat sum_dl_rate3 = 0.f;\n\tint count_dl_rates2 = 0;\n\tint count_dl_rates3 = 0;\n\n\tfor (int i = 0; i < 65; ++i)\n\t{\n\t\tstd::auto_ptr a;\n\t\ta = ses1.pop_alert();\n\t\tif (a.get())\n\t\t\tstd::cerr << \"ses1: \" << a->msg() << \"\\n\";\n\n\t\ta = ses2.pop_alert();\n\t\tif (a.get())\n\t\t\tstd::cerr << \"ses2: \" << a->msg() << \"\\n\";\n\n\t\ta = ses3.pop_alert();\n\t\tif (a.get())\n\t\t\tstd::cerr << \"ses3: \" << a->msg() << \"\\n\";\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\tif (st2.progress < 1.f && st2.progress > 0.3f)\n\t\t{\n\t\t\tsum_dl_rate2 += st2.download_payload_rate;\n\t\t\t++count_dl_rates2;\n\t\t}\n\t\tif (st3.progress < 1.f && st3.progress > 0.3f)\n\t\t{\n\t\t\tsum_dl_rate3 += st3.download_rate;\n\t\t\t++count_dl_rates3;\n\t\t}\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\tfloat average2 = sum_dl_rate2 \/ float(count_dl_rates2);\n\tfloat average3 = sum_dl_rate3 \/ float(count_dl_rates3);\n\n\tstd::cerr << \"average rate: \" << (average2 \/ 1000.f) << \"kB\/s - \"\n\t\t<< (average3 \/ 1000.f) << \"kB\/s\" << std::endl;\n\n\tTEST_CHECK(std::fabs(average2 - float(rate_limit)) < 3000.f);\n\tTEST_CHECK(std::fabs(average3 - float(rate_limit)) < 3000.f);\n\tif (tor2.is_seed() && tor3.is_seed()) std::cerr << \"done\\n\";\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\tusing namespace boost::filesystem;\n\n\t\/\/ in case the previous run was terminated\n\ttry { remove_all(\".\/tmp1\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp2\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp3\"); } catch (std::exception&) {}\n\n\ttest_swarm();\n\t\n\tremove_all(\".\/tmp1\");\n\tremove_all(\".\/tmp2\");\n\tremove_all(\".\/tmp3\");\n\n\treturn 0;\n}\n\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\/alert_types.hpp\"\n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nusing boost::filesystem::remove_all;\nusing boost::filesystem::exists;\n\nvoid test_swarm()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48000, 49000));\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49000, 50000));\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50000, 51000));\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 = 100000;\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#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\t\/\/ test using piece sizes smaller than 16kB\n\tboost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, \"_swarm\", 8 * 1024);\t\n\n\tses1.set_alert_mask(alert::all_categories & ~alert::progress_notification);\n\tses2.set_alert_mask(alert::all_categories & ~alert::progress_notification);\n\tses3.set_alert_mask(alert::all_categories & ~alert::progress_notification);\n\n\tfloat sum_dl_rate2 = 0.f;\n\tfloat sum_dl_rate3 = 0.f;\n\tint count_dl_rates2 = 0;\n\tint count_dl_rates3 = 0;\n\n\tfor (int i = 0; i < 30; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\");\n\t\tprint_alerts(ses2, \"ses2\");\n\t\tprint_alerts(ses3, \"ses3\");\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\tif (st2.progress < 1.f && st2.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate2 += st2.download_payload_rate;\n\t\t\t++count_dl_rates2;\n\t\t}\n\t\tif (st3.progress < 1.f && st3.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate3 += st3.download_rate;\n\t\t\t++count_dl_rates3;\n\t\t}\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\tfloat average2 = sum_dl_rate2 \/ float(count_dl_rates2);\n\tfloat average3 = sum_dl_rate3 \/ float(count_dl_rates3);\n\n\tstd::cerr << average2 << std::endl;\n\tstd::cerr << \"average rate: \" << (average2 \/ 1000.f) << \"kB\/s - \"\n\t\t<< (average3 \/ 1000.f) << \"kB\/s\" << std::endl;\n\n\tTEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit \/ 11.f);\n\tTEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit \/ 11.f);\n\tif (tor2.is_seed() && tor3.is_seed()) std::cerr << \"done\\n\";\n\n\t\/\/ make sure the files are deleted\n\tses1.remove_torrent(tor1, session::delete_files);\n\tses2.remove_torrent(tor2, session::delete_files);\n\tses3.remove_torrent(tor3, session::delete_files);\n\n\tstd::auto_ptr a = ses1.pop_alert();\n\tptime end = time_now() + seconds(20);\n\twhile (a.get() == 0 || dynamic_cast(a.get()) == 0)\n\t{\n\t\tif (ses1.wait_for_alert(end - time_now()) == 0)\n\t\t{\n\t\t\tstd::cerr << \"wait_for_alert() expired\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\ta = ses1.pop_alert();\n\t\tassert(a.get());\n\t\tstd::cerr << a->message() << std::endl;\n\t}\n\n\tTEST_CHECK(dynamic_cast(a.get()) != 0);\n\n\t\/\/ there shouldn't be any alerts generated from now on\n\t\/\/ make sure that the timer in wait_for_alert() works\n\t\/\/ this should time out (ret == 0) and it should take\n\t\/\/ about 2 seconds\n\tptime start = time_now();\n\talert const* ret = ses1.wait_for_alert(seconds(2));\n\tTEST_CHECK(ret == 0);\n\tif (ret != 0) std::cerr << ret->message() << std::endl;\n\tTEST_CHECK(time_now() - start < seconds(3));\n\tTEST_CHECK(time_now() - start > seconds(2));\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\tusing namespace boost::filesystem;\n\n\t\/\/ in case the previous run was terminated\n\ttry { remove_all(\".\/tmp1_swarm\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp2_swarm\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp3_swarm\"); } catch (std::exception&) {}\n\n\ttest_swarm();\n\t\n\ttest_sleep(2000);\n\tTEST_CHECK(!exists(\".\/tmp1_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp2_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp3_swarm\/temporary\"));\n\n\tremove_all(\".\/tmp1_swarm\");\n\tremove_all(\".\/tmp2_swarm\");\n\tremove_all(\".\/tmp3_swarm\");\n\n\treturn 0;\n}\n\nfixed test_swarm\/*\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\/alert_types.hpp\"\n#include \n#include \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n\nusing boost::filesystem::remove_all;\nusing boost::filesystem::exists;\n\nvoid test_swarm()\n{\n\tusing namespace libtorrent;\n\n\tsession ses1(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(48000, 49000));\n\tsession ses2(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(49000, 50000));\n\tsession ses3(fingerprint(\"LT\", 0, 1, 0, 0), std::make_pair(50000, 51000));\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 = 100000;\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#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\t\/\/ test using piece sizes smaller than 16kB\n\tboost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, \"_swarm\", 8 * 1024);\t\n\n\tses1.set_alert_mask(alert::all_categories & ~alert::progress_notification);\n\tses2.set_alert_mask(alert::all_categories & ~alert::progress_notification);\n\tses3.set_alert_mask(alert::all_categories & ~alert::progress_notification);\n\n\tfloat sum_dl_rate2 = 0.f;\n\tfloat sum_dl_rate3 = 0.f;\n\tint count_dl_rates2 = 0;\n\tint count_dl_rates3 = 0;\n\n\tfor (int i = 0; i < 30; ++i)\n\t{\n\t\tprint_alerts(ses1, \"ses1\");\n\t\tprint_alerts(ses2, \"ses2\");\n\t\tprint_alerts(ses3, \"ses3\");\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\tif (st2.progress < 1.f && st2.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate2 += st2.download_payload_rate;\n\t\t\t++count_dl_rates2;\n\t\t}\n\t\tif (st3.progress < 1.f && st3.progress > 0.5f)\n\t\t{\n\t\t\tsum_dl_rate3 += st3.download_rate;\n\t\t\t++count_dl_rates3;\n\t\t}\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\tfloat average2 = sum_dl_rate2 \/ float(count_dl_rates2);\n\tfloat average3 = sum_dl_rate3 \/ float(count_dl_rates3);\n\n\tstd::cerr << average2 << std::endl;\n\tstd::cerr << \"average rate: \" << (average2 \/ 1000.f) << \"kB\/s - \"\n\t\t<< (average3 \/ 1000.f) << \"kB\/s\" << std::endl;\n\n\tTEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit \/ 11.f);\n\tTEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit \/ 11.f);\n\tif (tor2.is_seed() && tor3.is_seed()) std::cerr << \"done\\n\";\n\n\t\/\/ make sure the files are deleted\n\tses1.remove_torrent(tor1, session::delete_files);\n\tses2.remove_torrent(tor2, session::delete_files);\n\tses3.remove_torrent(tor3, session::delete_files);\n\n\tstd::auto_ptr a = ses1.pop_alert();\n\tptime end = time_now() + seconds(20);\n\twhile (a.get() == 0 || dynamic_cast(a.get()) == 0)\n\t{\n\t\tif (ses1.wait_for_alert(end - time_now()) == 0)\n\t\t{\n\t\t\tstd::cerr << \"wait_for_alert() expired\" << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\ta = ses1.pop_alert();\n\t\tassert(a.get());\n\t\tstd::cerr << a->message() << std::endl;\n\t}\n\n\tTEST_CHECK(dynamic_cast(a.get()) != 0);\n\n\t\/\/ there shouldn't be any alerts generated from now on\n\t\/\/ make sure that the timer in wait_for_alert() works\n\t\/\/ this should time out (ret == 0) and it should take\n\t\/\/ about 2 seconds\n\tptime start = time_now();\n\talert const* ret;\n\twhile (ret = ses1.wait_for_alert(seconds(2)))\n\t{\n\t\ta = ses1.pop_alert();\n\t\tstd::cerr << ret->message() << std::endl;\n\t\tstart = time_now();\n\t}\n\tTEST_CHECK(time_now() - start < seconds(3));\n\tTEST_CHECK(time_now() - start >= seconds(2));\n}\n\nint test_main()\n{\n\tusing namespace libtorrent;\n\tusing namespace boost::filesystem;\n\n\t\/\/ in case the previous run was terminated\n\ttry { remove_all(\".\/tmp1_swarm\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp2_swarm\"); } catch (std::exception&) {}\n\ttry { remove_all(\".\/tmp3_swarm\"); } catch (std::exception&) {}\n\n\ttest_swarm();\n\t\n\ttest_sleep(2000);\n\tTEST_CHECK(!exists(\".\/tmp1_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp2_swarm\/temporary\"));\n\tTEST_CHECK(!exists(\".\/tmp3_swarm\/temporary\"));\n\n\tremove_all(\".\/tmp1_swarm\");\n\tremove_all(\".\/tmp2_swarm\");\n\tremove_all(\".\/tmp3_swarm\");\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"#include \"animation_system.h\"\n#include \"animation\/animation.h\"\n#include \"engine\/base_proxy_allocator.h\"\n#include \"engine\/blob.h\"\n#include \"engine\/crc32.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/json_serializer.h\"\n#include \"engine\/lua_wrapper.h\"\n#include \"engine\/profiler.h\"\n#include \"engine\/property_descriptor.h\"\n#include \"engine\/property_register.h\"\n#include \"engine\/resource_manager.h\"\n#include \"engine\/universe\/universe.h\"\n#include \"renderer\/model.h\"\n#include \"renderer\/pose.h\"\n#include \"renderer\/render_scene.h\"\n#include \n\n\nnamespace Lumix\n{\n\nstatic const ComponentType ANIMABLE_TYPE = PropertyRegister::getComponentType(\"animable\");\nstatic const ResourceType ANIMATION_TYPE(\"animation\");\n\nnamespace FS\n{\nclass FileSystem;\n};\n\nclass Animation;\nclass Engine;\nclass JsonSerializer;\nclass Universe;\n\n\nenum class AnimationSceneVersion : int\n{\n\tFIRST,\n\tREFACTOR,\n\n\tLATEST\n};\n\n\nstruct AnimationSceneImpl : public AnimationScene\n{\n\tfriend struct AnimationSystemImpl;\n\n\tstruct Animable\n\t{\n\t\tfloat time;\n\t\tfloat time_scale;\n\t\tfloat start_time;\n\t\tAnimation* animation;\n\t\tEntity entity;\n\t};\n\n\n\tstruct Mixer\n\t{\n\t\tstruct Input\n\t\t{\n\t\t\tAnimation* animation = nullptr;\n\t\t\tfloat time = 0.0f;\n\t\t\tfloat weight = 0.0f;\n\t\t};\n\n\t\tInput inputs[8];\n\t\tEntity entity;\n\t};\n\n\tAnimationSceneImpl(IPlugin& anim_system, Engine& engine, Universe& universe, IAllocator& allocator)\n\t\t: m_universe(universe)\n\t\t, m_engine(engine)\n\t\t, m_anim_system(anim_system)\n\t\t, m_animables(allocator)\n\t\t, m_mixers(allocator)\n\t{\n\t\tm_universe.entityDestroyed().bind(this);\n\t\tm_is_game_running = false;\n\t\tm_render_scene = static_cast(universe.getScene(crc32(\"renderer\")));\n\t\tuniverse.registerComponentTypeScene(ANIMABLE_TYPE, this);\n\t\tASSERT(m_render_scene);\n\t}\n\n\n\t~AnimationSceneImpl()\n\t{\n\t\tm_universe.entityDestroyed().unbind(this);\n\t}\n\n\n\tvoid onEntityDestroyed(Entity entity)\n\t{\n\t\tm_mixers.erase(entity);\n\t}\n\n\n\tvoid clear() override\n\t{\n\t\tfor (Mixer& mixer : m_mixers)\n\t\t{\n\t\t\tfor (auto& input : mixer.inputs)\n\t\t\t{\n\t\t\t\tunloadAnimation(input.animation);\n\t\t\t}\n\t\t}\n\t\tm_mixers.clear();\n\n\t\tfor (Animable& animable : m_animables)\n\t\t{\n\t\t\tunloadAnimation(animable.animation);\n\t\t}\n\t\tm_animables.clear();\n\t}\n\n\n\tfloat getAnimationLength(int animation_idx)\n\t{\n\t\tauto* animation = static_cast(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr);\n\t\tif (animation) return animation->getLength();\n\t\treturn 0;\n\t}\n\n\n\tvoid mixAnimation(Entity entity, int animation_idx, int input_idx, float time, float weight)\n\t{\n\t\tauto* animation = static_cast(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr);\n\t\tint mixer_idx = m_mixers.find(entity);\n\t\tif (mixer_idx < 0)\n\t\t{\n\t\t\tMixer& mixer = m_mixers.insert(entity);\n\t\t\tmixer.entity = entity;\n\t\t\tmixer_idx = m_mixers.find(entity);\n\t\t}\n\t\tMixer& mixer = m_mixers.at(mixer_idx);\n\t\tauto& input = mixer.inputs[input_idx];\n\t\tinput.animation = animation;\n\t\tinput.time = time;\n\t\tinput.weight = weight;\n\t}\n\n\n\tfloat getAnimableTime(ComponentHandle cmp) override\n\t{\n\t\treturn m_animables[{cmp.index}].time;\n\t}\n\n\n\tvoid setAnimableTime(ComponentHandle cmp, float time) override\n\t{\n\t\tm_animables[{cmp.index}].time = time;\n\t}\n\n\n\tAnimation* getAnimableAnimation(ComponentHandle cmp) override\n\t{\n\t\treturn m_animables[{cmp.index}].animation;\n\t}\n\n\t\n\tvoid startGame() override { m_is_game_running = true; }\n\tvoid stopGame() override { m_is_game_running = false; }\n\tUniverse& getUniverse() override { return m_universe; }\n\n\n\tComponentHandle getComponent(Entity entity, ComponentType type) override\n\t{\n\t\tif (type == ANIMABLE_TYPE)\n\t\t{\n\t\t\tif (m_animables.find(entity) < 0) return INVALID_COMPONENT;\n\t\t\treturn {entity.index};\n\t\t}\n\t\treturn INVALID_COMPONENT;\n\t}\n\n\n\tComponentHandle createComponent(ComponentType type, Entity entity) override\n\t{\n\t\tif (type == ANIMABLE_TYPE) return createAnimable(entity);\n\t\treturn INVALID_COMPONENT;\n\t}\n\n\n\tvoid unloadAnimation(Animation* animation)\n\t{\n\t\tif (!animation) return;\n\n\t\tanimation->getResourceManager().unload(*animation);\n\t}\n\n\n\tvoid destroyComponent(ComponentHandle component, ComponentType type) override\n\t{\n\t\tif (type == ANIMABLE_TYPE)\n\t\t{\n\t\t\tEntity entity = {component.index};\n\t\t\tauto& animable = m_animables[entity];\n\t\t\tunloadAnimation(animable.animation);\n\t\t\tm_animables.erase(entity);\n\t\t\tm_universe.destroyComponent(entity, type, this, component);\n\t\t}\n\t}\n\n\n\tvoid serialize(OutputBlob& serializer) override\n\t{\n\t\tserializer.write((int32)m_animables.size());\n\t\tfor (const Animable& animable : m_animables)\n\t\t{\n\t\t\tserializer.write(animable.entity);\n\t\t\tserializer.write(animable.time_scale);\n\t\t\tserializer.write(animable.start_time);\n\t\t\tserializer.writeString(animable.animation ? animable.animation->getPath().c_str() : \"\");\n\t\t}\n\t}\n\n\n\tint getVersion() const override { return (int)AnimationSceneVersion::LATEST; }\n\n\n\tvoid deserialize(InputBlob& serializer, int version) override\n\t{\n\t\tint32 count;\n\t\tserializer.read(count);\n\t\tm_animables.reserve(count);\n\t\tfor (int i = 0; i < count; ++i)\n\t\t{\n\t\t\tAnimable animable;\n\t\t\tserializer.read(animable.entity);\n\t\t\tbool free = false;\n\t\t\tif (version <= (int)AnimationSceneVersion::FIRST)\n\t\t\t{\n\t\t\t\tserializer.read(animable.time);\n\t\t\t\tserializer.read(free);\n\t\t\t\tanimable.time_scale = 1;\n\t\t\t\tanimable.start_time = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint32 flags = 0;\n\t\t\t\tif(version <= (int)AnimationSceneVersion::REFACTOR) serializer.read(flags);\n\t\t\t\tfree = flags != 0;\n\t\t\t\tserializer.read(animable.time_scale);\n\t\t\t\tserializer.read(animable.start_time);\n\t\t\t\tanimable.time = animable.start_time;\n\t\t\t}\n\n\t\t\tchar path[MAX_PATH_LENGTH];\n\t\t\tserializer.readString(path, sizeof(path));\n\t\t\tanimable.animation = path[0] == '\\0' ? nullptr : loadAnimation(Path(path));\n\t\t\tif (!free)\n\t\t\t{\n\t\t\t\tm_animables.insert(animable.entity, animable);\n\t\t\t\tComponentHandle cmp = {animable.entity.index};\n\t\t\t\tm_universe.addComponent(animable.entity, ANIMABLE_TYPE, this, cmp);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tfloat getTimeScale(ComponentHandle cmp) { return m_animables[{cmp.index}].time_scale; }\n\tvoid setTimeScale(ComponentHandle cmp, float time_scale) { m_animables[{cmp.index}].time_scale = time_scale; }\n\tfloat getStartTime(ComponentHandle cmp) { return m_animables[{cmp.index}].start_time; }\n\tvoid setStartTime(ComponentHandle cmp, float time) { m_animables[{cmp.index}].start_time = time; }\n\n\n\tPath getAnimation(ComponentHandle cmp)\n\t{\n\t\tconst auto& animable = m_animables[{cmp.index}];\n\t\treturn animable.animation ? animable.animation->getPath() : Path(\"\");\n\t}\n\n\n\tvoid setAnimation(ComponentHandle cmp, const Path& path)\n\t{\n\t\tauto& animable = m_animables[{cmp.index}];\n\t\tunloadAnimation(animable.animation);\n\t\tanimable.animation = loadAnimation(path);\n\t\tanimable.time = 0;\n\t}\n\n\n\tvoid updateMixer(Mixer& mixer, float time_delta)\n\t{\n\t\tComponentHandle renderable = m_render_scene->getRenderableComponent(mixer.entity);\n\t\tif (renderable == INVALID_COMPONENT) return;\n\n\t\tauto* pose = m_render_scene->getPose(renderable);\n\t\tauto* model = m_render_scene->getRenderableModel(renderable);\n\n\t\tif (!pose) return;\n\t\tif (!model->isReady()) return;\n\n\t\tmodel->getPose(*pose);\n\t\tpose->computeRelative(*model);\n\n\t\tfor (int i = 0; i < lengthOf(mixer.inputs); ++i)\n\t\t{\n\t\t\tMixer::Input& input = mixer.inputs[i];\n\t\t\tif (!input.animation) break;\n\t\t\tASSERT(input.animation->isReady());\n\t\t\tif (i == 0)\n\t\t\t{\n\t\t\t\tinput.animation->getRelativePose(input.time, *pose, *model);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tinput.animation->getRelativePose(input.time, *pose, *model, input.weight);\n\t\t\t}\n\t\t\tinput.animation = nullptr;\n\t\t}\n\t\tpose->computeAbsolute(*model);\n\t}\n\n\n\tvoid updateAnimable(Animable& animable, float time_delta)\n\t{\n\t\tif (!animable.animation || !animable.animation->isReady()) return;\n\t\tComponentHandle renderable = m_render_scene->getRenderableComponent(animable.entity);\n\t\tif (renderable == INVALID_COMPONENT) return;\n\n\t\tauto* pose = m_render_scene->getPose(renderable);\n\t\tauto* model = m_render_scene->getRenderableModel(renderable);\n\n\t\tif (!pose) return;\n\t\tif (!model->isReady()) return;\n\n\t\tmodel->getPose(*pose);\n\t\tpose->computeRelative(*model);\n\t\tanimable.animation->getRelativePose(animable.time, *pose, *model);\n\t\tpose->computeAbsolute(*model);\n\n\t\tfloat t = animable.time + time_delta * animable.time_scale;\n\t\tfloat l = animable.animation->getLength();\n\t\twhile (t > l)\n\t\t{\n\t\t\tt -= l;\n\t\t}\n\t\tanimable.time = t;\n\t}\n\n\n\tvoid updateAnimable(ComponentHandle cmp, float time_delta) override\n\t{\n\t\tAnimable& animable = m_animables[{cmp.index}];\n\t\tupdateAnimable(animable, time_delta);\n\t}\n\n\n\tvoid update(float time_delta, bool paused) override\n\t{\n\t\tPROFILE_FUNCTION();\n\t\tif (!m_is_game_running) return;\n\n\t\tfor (Mixer& mixer : m_mixers)\n\t\t{\n\t\t\tAnimationSceneImpl::updateMixer(mixer, time_delta);\n\t\t}\n\n\t\tfor (Animable& animable : m_animables)\n\t\t{\n\t\t\tAnimationSceneImpl::updateAnimable(animable, time_delta);\n\t\t}\n\t}\n\n\n\tAnimation* loadAnimation(const Path& path)\n\t{\n\t\tResourceManager& rm = m_engine.getResourceManager();\n\t\treturn static_cast(rm.get(ANIMATION_TYPE)->load(path));\n\t}\n\t\n\n\tComponentHandle createAnimable(Entity entity)\n\t{\n\t\tAnimable& animable = m_animables.insert(entity);\n\t\tanimable.time = 0;\n\t\tanimable.animation = nullptr;\n\t\tanimable.entity = entity;\n\t\tanimable.time_scale = 1;\n\t\tanimable.start_time = 0;\n\n\t\tComponentHandle cmp = {entity.index};\n\t\tm_universe.addComponent(entity, ANIMABLE_TYPE, this, cmp);\n\t\treturn cmp;\n\t}\n\n\n\tIPlugin& getPlugin() const override { return m_anim_system; }\n\n\n\tUniverse& m_universe;\n\tIPlugin& m_anim_system;\n\tEngine& m_engine;\n\tAssociativeArray m_animables;\n\tAssociativeArray m_mixers;\n\tRenderScene* m_render_scene;\n\tbool m_is_game_running;\n};\n\n\nstruct AnimationSystemImpl : public IPlugin\n{\n\texplicit AnimationSystemImpl(Engine& engine)\n\t\t: m_allocator(engine.getAllocator())\n\t\t, m_engine(engine)\n\t\t, animation_manager(m_allocator)\n\t{\n\t\tanimation_manager.create(ANIMATION_TYPE, m_engine.getResourceManager());\n\n\t\tPropertyRegister::add(\"animable\",\n\t\t\tLUMIX_NEW(m_allocator, ResourcePropertyDescriptor)(\"Animation\",\n\t\t\t\t&AnimationSceneImpl::getAnimation,\n\t\t\t\t&AnimationSceneImpl::setAnimation,\n\t\t\t\t\"Animation (*.ani)\",\n\t\t\t\tANIMATION_TYPE));\n\t\tPropertyRegister::add(\"animable\",\n\t\t\tLUMIX_NEW(m_allocator, DecimalPropertyDescriptor)(\n\t\t\t\t\"Start time\", &AnimationSceneImpl::getStartTime, &AnimationSceneImpl::setStartTime, 0, FLT_MAX, 0.1f));\n\t\tPropertyRegister::add(\"animable\",\n\t\t\tLUMIX_NEW(m_allocator, DecimalPropertyDescriptor)(\n\t\t\t\t\"Time scale\", &AnimationSceneImpl::getTimeScale, &AnimationSceneImpl::setTimeScale, 0, FLT_MAX, 0.1f));\n\n\t\tregisterLuaAPI();\n\t}\n\n\n\tvoid registerLuaAPI()\n\t{\n\t\tlua_State* L = m_engine.getState();\n\t\t#define REGISTER_FUNCTION(name) \\\n\t\tdo {\\\n\t\t\tauto f = &LuaWrapper::wrapMethod; \\\n\t\t\tLuaWrapper::createSystemFunction(L, \"Animation\", #name, f); \\\n\t\t} while(false) \\\n\n\t\tREGISTER_FUNCTION(mixAnimation);\n\t\tREGISTER_FUNCTION(getAnimationLength);\n\n\t\t#undef REGISTER_FUNCTION\n\t}\n\n\n\tIScene* createScene(Universe& ctx) override\n\t{\n\t\treturn LUMIX_NEW(m_allocator, AnimationSceneImpl)(*this, m_engine, ctx, m_allocator);\n\t}\n\n\n\tvoid destroyScene(IScene* scene) override { LUMIX_DELETE(m_allocator, scene); }\n\n\n\tconst char* getName() const override { return \"animation\"; }\n\n\n\tLumix::IAllocator& m_allocator;\n\tEngine& m_engine;\n\tAnimationManager animation_manager;\n\nprivate:\n\tvoid operator=(const AnimationSystemImpl&);\n\tAnimationSystemImpl(const AnimationSystemImpl&);\n};\n\n\nLUMIX_PLUGIN_ENTRY(animation)\n{\n\treturn LUMIX_NEW(engine.getAllocator(), AnimationSystemImpl)(engine);\n}\n}\nfixed crash when mixing animation that does not exist#include \"animation_system.h\"\n#include \"animation\/animation.h\"\n#include \"engine\/base_proxy_allocator.h\"\n#include \"engine\/blob.h\"\n#include \"engine\/crc32.h\"\n#include \"engine\/engine.h\"\n#include \"engine\/json_serializer.h\"\n#include \"engine\/lua_wrapper.h\"\n#include \"engine\/profiler.h\"\n#include \"engine\/property_descriptor.h\"\n#include \"engine\/property_register.h\"\n#include \"engine\/resource_manager.h\"\n#include \"engine\/universe\/universe.h\"\n#include \"renderer\/model.h\"\n#include \"renderer\/pose.h\"\n#include \"renderer\/render_scene.h\"\n#include \n\n\nnamespace Lumix\n{\n\nstatic const ComponentType ANIMABLE_TYPE = PropertyRegister::getComponentType(\"animable\");\nstatic const ResourceType ANIMATION_TYPE(\"animation\");\n\nnamespace FS\n{\nclass FileSystem;\n};\n\nclass Animation;\nclass Engine;\nclass JsonSerializer;\nclass Universe;\n\n\nenum class AnimationSceneVersion : int\n{\n\tFIRST,\n\tREFACTOR,\n\n\tLATEST\n};\n\n\nstruct AnimationSceneImpl : public AnimationScene\n{\n\tfriend struct AnimationSystemImpl;\n\n\tstruct Animable\n\t{\n\t\tfloat time;\n\t\tfloat time_scale;\n\t\tfloat start_time;\n\t\tAnimation* animation;\n\t\tEntity entity;\n\t};\n\n\n\tstruct Mixer\n\t{\n\t\tstruct Input\n\t\t{\n\t\t\tAnimation* animation = nullptr;\n\t\t\tfloat time = 0.0f;\n\t\t\tfloat weight = 0.0f;\n\t\t};\n\n\t\tInput inputs[8];\n\t\tEntity entity;\n\t};\n\n\tAnimationSceneImpl(IPlugin& anim_system, Engine& engine, Universe& universe, IAllocator& allocator)\n\t\t: m_universe(universe)\n\t\t, m_engine(engine)\n\t\t, m_anim_system(anim_system)\n\t\t, m_animables(allocator)\n\t\t, m_mixers(allocator)\n\t{\n\t\tm_universe.entityDestroyed().bind(this);\n\t\tm_is_game_running = false;\n\t\tm_render_scene = static_cast(universe.getScene(crc32(\"renderer\")));\n\t\tuniverse.registerComponentTypeScene(ANIMABLE_TYPE, this);\n\t\tASSERT(m_render_scene);\n\t}\n\n\n\t~AnimationSceneImpl()\n\t{\n\t\tm_universe.entityDestroyed().unbind(this);\n\t}\n\n\n\tvoid onEntityDestroyed(Entity entity)\n\t{\n\t\tm_mixers.erase(entity);\n\t}\n\n\n\tvoid clear() override\n\t{\n\t\tfor (Mixer& mixer : m_mixers)\n\t\t{\n\t\t\tfor (auto& input : mixer.inputs)\n\t\t\t{\n\t\t\t\tunloadAnimation(input.animation);\n\t\t\t}\n\t\t}\n\t\tm_mixers.clear();\n\n\t\tfor (Animable& animable : m_animables)\n\t\t{\n\t\t\tunloadAnimation(animable.animation);\n\t\t}\n\t\tm_animables.clear();\n\t}\n\n\n\tfloat getAnimationLength(int animation_idx)\n\t{\n\t\tauto* animation = static_cast(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr);\n\t\tif (animation) return animation->getLength();\n\t\treturn 0;\n\t}\n\n\n\tvoid mixAnimation(Entity entity, int animation_idx, int input_idx, float time, float weight)\n\t{\n\t\tauto* animation = static_cast(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr);\n\t\tint mixer_idx = m_mixers.find(entity);\n\t\tif (mixer_idx < 0)\n\t\t{\n\t\t\tMixer& mixer = m_mixers.insert(entity);\n\t\t\tmixer.entity = entity;\n\t\t\tmixer_idx = m_mixers.find(entity);\n\t\t}\n\t\tMixer& mixer = m_mixers.at(mixer_idx);\n\t\tauto& input = mixer.inputs[input_idx];\n\t\tinput.animation = animation;\n\t\tinput.time = time;\n\t\tinput.weight = weight;\n\t}\n\n\n\tfloat getAnimableTime(ComponentHandle cmp) override\n\t{\n\t\treturn m_animables[{cmp.index}].time;\n\t}\n\n\n\tvoid setAnimableTime(ComponentHandle cmp, float time) override\n\t{\n\t\tm_animables[{cmp.index}].time = time;\n\t}\n\n\n\tAnimation* getAnimableAnimation(ComponentHandle cmp) override\n\t{\n\t\treturn m_animables[{cmp.index}].animation;\n\t}\n\n\t\n\tvoid startGame() override { m_is_game_running = true; }\n\tvoid stopGame() override { m_is_game_running = false; }\n\tUniverse& getUniverse() override { return m_universe; }\n\n\n\tComponentHandle getComponent(Entity entity, ComponentType type) override\n\t{\n\t\tif (type == ANIMABLE_TYPE)\n\t\t{\n\t\t\tif (m_animables.find(entity) < 0) return INVALID_COMPONENT;\n\t\t\treturn {entity.index};\n\t\t}\n\t\treturn INVALID_COMPONENT;\n\t}\n\n\n\tComponentHandle createComponent(ComponentType type, Entity entity) override\n\t{\n\t\tif (type == ANIMABLE_TYPE) return createAnimable(entity);\n\t\treturn INVALID_COMPONENT;\n\t}\n\n\n\tvoid unloadAnimation(Animation* animation)\n\t{\n\t\tif (!animation) return;\n\n\t\tanimation->getResourceManager().unload(*animation);\n\t}\n\n\n\tvoid destroyComponent(ComponentHandle component, ComponentType type) override\n\t{\n\t\tif (type == ANIMABLE_TYPE)\n\t\t{\n\t\t\tEntity entity = {component.index};\n\t\t\tauto& animable = m_animables[entity];\n\t\t\tunloadAnimation(animable.animation);\n\t\t\tm_animables.erase(entity);\n\t\t\tm_universe.destroyComponent(entity, type, this, component);\n\t\t}\n\t}\n\n\n\tvoid serialize(OutputBlob& serializer) override\n\t{\n\t\tserializer.write((int32)m_animables.size());\n\t\tfor (const Animable& animable : m_animables)\n\t\t{\n\t\t\tserializer.write(animable.entity);\n\t\t\tserializer.write(animable.time_scale);\n\t\t\tserializer.write(animable.start_time);\n\t\t\tserializer.writeString(animable.animation ? animable.animation->getPath().c_str() : \"\");\n\t\t}\n\t}\n\n\n\tint getVersion() const override { return (int)AnimationSceneVersion::LATEST; }\n\n\n\tvoid deserialize(InputBlob& serializer, int version) override\n\t{\n\t\tint32 count;\n\t\tserializer.read(count);\n\t\tm_animables.reserve(count);\n\t\tfor (int i = 0; i < count; ++i)\n\t\t{\n\t\t\tAnimable animable;\n\t\t\tserializer.read(animable.entity);\n\t\t\tbool free = false;\n\t\t\tif (version <= (int)AnimationSceneVersion::FIRST)\n\t\t\t{\n\t\t\t\tserializer.read(animable.time);\n\t\t\t\tserializer.read(free);\n\t\t\t\tanimable.time_scale = 1;\n\t\t\t\tanimable.start_time = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint32 flags = 0;\n\t\t\t\tif(version <= (int)AnimationSceneVersion::REFACTOR) serializer.read(flags);\n\t\t\t\tfree = flags != 0;\n\t\t\t\tserializer.read(animable.time_scale);\n\t\t\t\tserializer.read(animable.start_time);\n\t\t\t\tanimable.time = animable.start_time;\n\t\t\t}\n\n\t\t\tchar path[MAX_PATH_LENGTH];\n\t\t\tserializer.readString(path, sizeof(path));\n\t\t\tanimable.animation = path[0] == '\\0' ? nullptr : loadAnimation(Path(path));\n\t\t\tif (!free)\n\t\t\t{\n\t\t\t\tm_animables.insert(animable.entity, animable);\n\t\t\t\tComponentHandle cmp = {animable.entity.index};\n\t\t\t\tm_universe.addComponent(animable.entity, ANIMABLE_TYPE, this, cmp);\n\t\t\t}\n\t\t}\n\t}\n\n\n\tfloat getTimeScale(ComponentHandle cmp) { return m_animables[{cmp.index}].time_scale; }\n\tvoid setTimeScale(ComponentHandle cmp, float time_scale) { m_animables[{cmp.index}].time_scale = time_scale; }\n\tfloat getStartTime(ComponentHandle cmp) { return m_animables[{cmp.index}].start_time; }\n\tvoid setStartTime(ComponentHandle cmp, float time) { m_animables[{cmp.index}].start_time = time; }\n\n\n\tPath getAnimation(ComponentHandle cmp)\n\t{\n\t\tconst auto& animable = m_animables[{cmp.index}];\n\t\treturn animable.animation ? animable.animation->getPath() : Path(\"\");\n\t}\n\n\n\tvoid setAnimation(ComponentHandle cmp, const Path& path)\n\t{\n\t\tauto& animable = m_animables[{cmp.index}];\n\t\tunloadAnimation(animable.animation);\n\t\tanimable.animation = loadAnimation(path);\n\t\tanimable.time = 0;\n\t}\n\n\n\tvoid updateMixer(Mixer& mixer, float time_delta)\n\t{\n\t\tComponentHandle renderable = m_render_scene->getRenderableComponent(mixer.entity);\n\t\tif (renderable == INVALID_COMPONENT) return;\n\n\t\tauto* pose = m_render_scene->getPose(renderable);\n\t\tauto* model = m_render_scene->getRenderableModel(renderable);\n\n\t\tif (!pose) return;\n\t\tif (!model->isReady()) return;\n\n\t\tmodel->getPose(*pose);\n\t\tpose->computeRelative(*model);\n\n\t\tfor (int i = 0; i < lengthOf(mixer.inputs); ++i)\n\t\t{\n\t\t\tMixer::Input& input = mixer.inputs[i];\n\t\t\tif (!input.animation || !input.animation->isReady()) break;\n\t\t\tif (i == 0)\n\t\t\t{\n\t\t\t\tinput.animation->getRelativePose(input.time, *pose, *model);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tinput.animation->getRelativePose(input.time, *pose, *model, input.weight);\n\t\t\t}\n\t\t\tinput.animation = nullptr;\n\t\t}\n\t\tpose->computeAbsolute(*model);\n\t}\n\n\n\tvoid updateAnimable(Animable& animable, float time_delta)\n\t{\n\t\tif (!animable.animation || !animable.animation->isReady()) return;\n\t\tComponentHandle renderable = m_render_scene->getRenderableComponent(animable.entity);\n\t\tif (renderable == INVALID_COMPONENT) return;\n\n\t\tauto* pose = m_render_scene->getPose(renderable);\n\t\tauto* model = m_render_scene->getRenderableModel(renderable);\n\n\t\tif (!pose) return;\n\t\tif (!model->isReady()) return;\n\n\t\tmodel->getPose(*pose);\n\t\tpose->computeRelative(*model);\n\t\tanimable.animation->getRelativePose(animable.time, *pose, *model);\n\t\tpose->computeAbsolute(*model);\n\n\t\tfloat t = animable.time + time_delta * animable.time_scale;\n\t\tfloat l = animable.animation->getLength();\n\t\twhile (t > l)\n\t\t{\n\t\t\tt -= l;\n\t\t}\n\t\tanimable.time = t;\n\t}\n\n\n\tvoid updateAnimable(ComponentHandle cmp, float time_delta) override\n\t{\n\t\tAnimable& animable = m_animables[{cmp.index}];\n\t\tupdateAnimable(animable, time_delta);\n\t}\n\n\n\tvoid update(float time_delta, bool paused) override\n\t{\n\t\tPROFILE_FUNCTION();\n\t\tif (!m_is_game_running) return;\n\n\t\tfor (Mixer& mixer : m_mixers)\n\t\t{\n\t\t\tAnimationSceneImpl::updateMixer(mixer, time_delta);\n\t\t}\n\n\t\tfor (Animable& animable : m_animables)\n\t\t{\n\t\t\tAnimationSceneImpl::updateAnimable(animable, time_delta);\n\t\t}\n\t}\n\n\n\tAnimation* loadAnimation(const Path& path)\n\t{\n\t\tResourceManager& rm = m_engine.getResourceManager();\n\t\treturn static_cast(rm.get(ANIMATION_TYPE)->load(path));\n\t}\n\t\n\n\tComponentHandle createAnimable(Entity entity)\n\t{\n\t\tAnimable& animable = m_animables.insert(entity);\n\t\tanimable.time = 0;\n\t\tanimable.animation = nullptr;\n\t\tanimable.entity = entity;\n\t\tanimable.time_scale = 1;\n\t\tanimable.start_time = 0;\n\n\t\tComponentHandle cmp = {entity.index};\n\t\tm_universe.addComponent(entity, ANIMABLE_TYPE, this, cmp);\n\t\treturn cmp;\n\t}\n\n\n\tIPlugin& getPlugin() const override { return m_anim_system; }\n\n\n\tUniverse& m_universe;\n\tIPlugin& m_anim_system;\n\tEngine& m_engine;\n\tAssociativeArray m_animables;\n\tAssociativeArray m_mixers;\n\tRenderScene* m_render_scene;\n\tbool m_is_game_running;\n};\n\n\nstruct AnimationSystemImpl : public IPlugin\n{\n\texplicit AnimationSystemImpl(Engine& engine)\n\t\t: m_allocator(engine.getAllocator())\n\t\t, m_engine(engine)\n\t\t, animation_manager(m_allocator)\n\t{\n\t\tanimation_manager.create(ANIMATION_TYPE, m_engine.getResourceManager());\n\n\t\tPropertyRegister::add(\"animable\",\n\t\t\tLUMIX_NEW(m_allocator, ResourcePropertyDescriptor)(\"Animation\",\n\t\t\t\t&AnimationSceneImpl::getAnimation,\n\t\t\t\t&AnimationSceneImpl::setAnimation,\n\t\t\t\t\"Animation (*.ani)\",\n\t\t\t\tANIMATION_TYPE));\n\t\tPropertyRegister::add(\"animable\",\n\t\t\tLUMIX_NEW(m_allocator, DecimalPropertyDescriptor)(\n\t\t\t\t\"Start time\", &AnimationSceneImpl::getStartTime, &AnimationSceneImpl::setStartTime, 0, FLT_MAX, 0.1f));\n\t\tPropertyRegister::add(\"animable\",\n\t\t\tLUMIX_NEW(m_allocator, DecimalPropertyDescriptor)(\n\t\t\t\t\"Time scale\", &AnimationSceneImpl::getTimeScale, &AnimationSceneImpl::setTimeScale, 0, FLT_MAX, 0.1f));\n\n\t\tregisterLuaAPI();\n\t}\n\n\n\tvoid registerLuaAPI()\n\t{\n\t\tlua_State* L = m_engine.getState();\n\t\t#define REGISTER_FUNCTION(name) \\\n\t\tdo {\\\n\t\t\tauto f = &LuaWrapper::wrapMethod; \\\n\t\t\tLuaWrapper::createSystemFunction(L, \"Animation\", #name, f); \\\n\t\t} while(false) \\\n\n\t\tREGISTER_FUNCTION(mixAnimation);\n\t\tREGISTER_FUNCTION(getAnimationLength);\n\n\t\t#undef REGISTER_FUNCTION\n\t}\n\n\n\tIScene* createScene(Universe& ctx) override\n\t{\n\t\treturn LUMIX_NEW(m_allocator, AnimationSceneImpl)(*this, m_engine, ctx, m_allocator);\n\t}\n\n\n\tvoid destroyScene(IScene* scene) override { LUMIX_DELETE(m_allocator, scene); }\n\n\n\tconst char* getName() const override { return \"animation\"; }\n\n\n\tLumix::IAllocator& m_allocator;\n\tEngine& m_engine;\n\tAnimationManager animation_manager;\n\nprivate:\n\tvoid operator=(const AnimationSystemImpl&);\n\tAnimationSystemImpl(const AnimationSystemImpl&);\n};\n\n\nLUMIX_PLUGIN_ENTRY(animation)\n{\n\treturn LUMIX_NEW(engine.getAllocator(), AnimationSystemImpl)(engine);\n}\n}\n<|endoftext|>"} {"text":"\/\/ RosterSystem.cpp\n\/\/ Created by Evan Almonte\n\/\/\n#include \"RosterSystem.hpp\"\n#include \"Roster.hpp\"\n#include \"RSFileManager.hpp\"\n#include \"Student.hpp\"\n#include \"Utilities.hpp\"\n#include \n\nusing std::cout;\nusing std::cin;\nusing std::string;\n\nnamespace RosterSystemUtils {\n\tint getMenuOptSelection (int start, int end);\n\tchar getLoginOptSelection ( );\n}\nconst string RosterSystem::menuOpts[numOfMenuOpts] = {\n\t\"Create a new Roster\",\n\t\"Drop a Roster\",\n\t\"Display Roster Information\",\n\t\"Display All Rosters\",\n\t\"Select a Roster\"\n};\nconst string RosterSystem::selectOpts[numOfSelectOpts] = {\n\t\"Add a New Student\",\n\t\"Remove a Student\",\n\t\"Update a Student\",\n\t\"List All Students\"\n};\n\nRosterSystem::RosterSystem( ) : loginStatus(NOT_LOGGED), rListSz(0), rListCap(0), rosterList(nullptr),\n eListSz(0), eListCap(0), enrollmentList(nullptr) {}\n\nRosterSystem::~RosterSystem( ) {\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\tdelete rosterList[i];\n\t}\n\tdelete[] rosterList;\n\tfor (int i = 0; i < eListSz; ++i) {\n\t\tdelete enrollmentList[i];\n\t}\n\tdelete[] enrollmentList;\n}\n\nvoid RosterSystem::loginMenu( ) {\n\tclearScreen ( );\n\tloginStatus = USER;\n\tcout << \"********************************\\n\";\n\tcout << \" Welcome To SchoolManager v.1 \\n\";\n\tcout << \"********************************\\n\";\n\tcout << \"A) Supervisor Mode\\n\";\n\tcout << \"B) User Mode\\n\";\n\tcout << \"C) Exit\\n\";\n\tcout << \"Please choose an option: \";\n\tchar choice = RosterSystemUtils::getLoginOptSelection ( );\n\tswitch(choice) {\n\t\tcase 'A':\n\t\tcase 'a': {\n\t\t\tRosterSystem::RSFileManager userDatabase (\"Database.txt\", false);\n\t\t\tloginStatus = userDatabase.attemptLogin ( );\n\t\t}\n\t\tcase 'B':\n\t\tcase 'b':\n\t\t\tmainMenu ( );\n\t\t\tloginMenu ( );\n\t\t\tbreak;\n\t\tcase 'C':\n\t\tcase 'c':\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Invalid choice please try again.\\n\";\n\t\t\tcout << \"Press ENTER to continue . . .\";\n\t\t\tcin.get ( );\n\t\t\tloginMenu ( );\n\t}\n}\n\nvoid RosterSystem::mainMenu( ) {\n\tclearScreen ( );\n\tcout << \"******************************\\n\";\n\tcout << \" Main Menu \\n\";\n\tcout << \"******************************\\n\";\n\tint startOption = 1, endOption;\n\tif (loginStatus == SUPERVISOR) {\n\t\tendOption = numOfMenuOpts;\n\t\tdisplayAdminMenu();\n\t} else {\n\t\tendOption = 1;\n\t\tdisplayUserMenu();\n\t}\n\tcout << \"Please choose an option(q to Quit): \";\n\tint choice = RosterSystemUtils::getMenuOptSelection(startOption, endOption);\n\n\tif (choice == 1 && loginStatus != SUPERVISOR) {\n\t\tchoice = 5;\n\t}\n\n\tswitch (choice) {\n\t\tcase 1:\n\t\t\taddRoster();\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\t{\n\t\t\t\tstring courseNumber;\n\t\t\t\tcout << \"Please enter the rosters course number: \";\n\t\t\t\tgetline(cin, courseNumber);\n\t\t\t\tremoveRoster(courseNumber);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\t{\n\t\t\t\tcout << \"Please enter the rosters course number: \";\n\t\t\t\tstring courseNumber;\n\t\t\t\tgetline(cin, courseNumber);\n\t\t\t\tdisplayRoster(courseNumber);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tdisplayAllRosters();\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\t{\n\t\t\t\tstring courseNumber;\n\t\t\t\tcout << \"Please enter the rosters course number: \";\n\t\t\t\tgetline(cin, courseNumber);\n\t\t\t\tselectRoster(courseNumber);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Exiting to login menu.\\n\";\n\t\t\treturn;\n\t}\n\tcout << \"Press ENTER to continue . . .\";\n\tcin.get();\n\tmainMenu();\n}\n\nvoid RosterSystem::displayAdminMenu( ) {\n\tfor (int i = 0; i < numOfMenuOpts; ++i) {\n\t\tcout << i + 1 << \") \" << menuOpts[i] << \"\\n\";\n\t}\n}\n\nvoid RosterSystem::displayUserMenu( ) {\n\tint i = numOfMenuOpts - 1;\n\tcout << i + 1 << \") \" << menuOpts[numOfMenuOpts - 1] << \"\\n\";\n}\n\nvoid RosterSystem::addToEnrollmentList(Student* aStudent) {\n\tif (eListSz == eListCap) {\n\t\tgrowEnrollmentList();\n\t}\n\tenrollmentList[eListSz++] = aStudent;\n}\n\nvoid RosterSystem::addToEnrollmentAndRoster(Roster& selectedRoster) {\n\tclearScreen();\n\tif (eListSz == eListCap) {\n\t\tgrowEnrollmentList();\n\t}\n\tStudent* aStudent = new Student;\n\tcout << \"******************************\\n\";\n\tcout << \" New Student Added \\n\";\n\tcout << \"******************************\\n\";\n\tcin >> *aStudent;\n\tenrollmentList[eListSz++] = aStudent;\n\tselectedRoster.addStudent(aStudent);\n}\n\nint RosterSystem::findRoster(std::string courseCode) const {\n\tif (rListSz == 0) {\n\t\tcout << \"There are no rosters in the system.\\n\";\n\t\treturn EMPTY_LIST;\n\t}\n\tint foundIndex = NOT_FOUND;\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\tif (courseCode == rosterList[i]->getCourseCode()) {\n\t\t\tfoundIndex = i;\n\t\t}\n\t}\n\tif(foundIndex == NOT_FOUND) {\n\t\tcout << \"No roster with a course number of: \" << courseCode << \" was found.\\n\";\n\t}\n\treturn foundIndex;\n}\n\nvoid RosterSystem::addRoster( ) {\n\tclearScreen();\n\tif (rListSz == rListCap) {\n\t\tgrowRosterList();\n\t}\n\tRoster* rosterToAdd = new Roster;\n\tcout << \"******************************\\n\";\n\tcout << \" New Roster Created \\n\";\n\tcout << \"******************************\\n\";\n\tcin >> *rosterToAdd;\n\trosterList[rListSz++] = rosterToAdd;\n}\n\nvoid RosterSystem::selectRoster(std::string courseNumber) {\n\tint location = findRoster (courseNumber);\n\tif (location == NOT_FOUND || location == EMPTY_LIST) {\n\t\treturn;\n\t}\n\tRoster* rosterToEdit = rosterList[location];\n\tdo {\n\t\tif (loginStatus == SUPERVISOR) {\n\t\t\tadminSelectOpts(*rosterToEdit);\n\t\t} else {\n\t\t\tuserSelectOpts(*rosterToEdit);\n\t\t}\n\t\tcout << \"Would you like to continue editing the same roster(Y\/N)? \";\n\t} while (getYesOrNo());\n}\n\nvoid RosterSystem::removeRoster(std::string courseCode) {\n\tint location = findRoster(courseCode);\n\tif (location == NOT_FOUND || location == EMPTY_LIST) {\n\t\treturn;\n\t}\n\tclearScreen ( );\n\t\/\/\t\tDisplays a title as:\n\t\/\/*******************************\n\t\/\/ CourseName Has Been Deleted \n\t\/\/*******************************\n\tint lengthOfName = rosterList[location]->getCourseName ( ).length ( );\n\tstring numOfAsterixs = \"**\";\n\tfor (int i = 0; i < lengthOfName; ++i) {\n\t\tnumOfAsterixs += \"*\";\n\t}\n\tcout << numOfAsterixs << \"*******************\\n\";\n\tcout << \" \" << rosterList[location]->getCourseName() << \" Has Been Deleted \\n\";\n\tcout << numOfAsterixs << \"*******************\\n\";\n\t\/\/Shifts all rosters over to the left.\n\tdelete rosterList[location];\n\tfor (; location < rListSz - 1; ++location) {\n\t\trosterList[location] = rosterList[location + 1];\n\t};\n\trosterList[rListSz - 1] = nullptr;\n\t--rListSz;\n}\n\nvoid RosterSystem::growEnrollmentList( ) {\n\tint newCap = eListCap * 2 + 1;\n\tStudent** tempList = new Student*[newCap];\n\tfor (int i = 0; i < eListSz; ++i) {\n\t\ttempList[i] = enrollmentList[i];\n\t}\n\tdelete[] enrollmentList;\n\tenrollmentList = tempList;\n}\n\nvoid RosterSystem::growRosterList( ) {\n\tint newCap = rListCap * 2 + 1;\n\tRoster** tempList = new Roster*[newCap];\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\ttempList[i] = rosterList[i];\n\t}\n\tdelete[] rosterList;\n\trListCap = newCap;\n\trosterList = tempList;\n}\n\nvoid RosterSystem::adminSelectOpts(Roster& selectedRoster) {\n\tclearScreen();\n\tcout << \"******************************\\n\";\n\tcout << \" Editing Roster \\n\";\n\tcout << \"******************************\\n\";\n\tcout << \"Course: \" << selectedRoster.getCourseName() << \"\\n\";\n\tcout << \"Code: \" << selectedRoster.getCourseCode() << \"\\n\";\n\tfor (int i = 0; i < numOfSelectOpts; ++i) {\n\t\tcout << static_cast('a' + i) << \") \" << selectOpts[i] << \"\\n\";\n\t}\n\tstring userChoice;\n\tcout << \"Please choose an option(a-d): \";\n\tgetline(cin, userChoice);\n\n\tswitch (userChoice[0]) {\n\t\tcase 'A':\n\t\tcase 'a':\n\t\t\t{\n\t\t\t\taddToEnrollmentAndRoster(selectedRoster);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'B':\n\t\tcase 'b':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.removeStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'C':\n\t\tcase 'c':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.editStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'D':\n\t\tcase 'd':\n\t\t\tselectedRoster.listAllStudents();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Invalid option selected.\\n\";\n\t}\n}\n\nvoid RosterSystem::displayRoster(std::string courseNumber) const {\n\tclearScreen ( );\n\tint location = findRoster(courseNumber);\n\tif (location == NOT_FOUND || location == EMPTY_LIST) {\n\t\treturn;\n\t}\n\tRoster* rosterToDisplay = rosterList[location];\n\trosterToDisplay->displayInfo();\n}\n\nvoid RosterSystem::displayAllRosters( ) const {\n\tclearScreen ( );\n\tif(rListSz == 0) {\n\t\tcout << \"There are no rosters in the system.\\n\";\n\t\treturn;\n\t}\n\tcout << \"******************************\\n\";\n\tcout << \" Display All Rosters \\n\";\n\tcout << \"******************************\\n\";\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\trosterList[i]->displayInfo();\n\t\tcout << \"\\n\";\n\t}\n}\n\nvoid RosterSystem::userSelectOpts(Roster& selectedRoster) {\n\tclearScreen();\n\tcout << \"******************************\\n\";\n\tcout << \" Editing Roster \\n\";\n\tcout << \"******************************\\n\";\n\tcout << \"Course: \" << selectedRoster.getCourseName() << \"\\n\";\n\tcout << \"Code: \" << selectedRoster.getCourseCode() << \"\\n\";\n\n\t\/\/Subtract 1 due to the fact that \"user\" does not have access to the last option.\n\tfor (int i = 0; i < numOfSelectOpts - 1; ++i) {\n\t\tcout << static_cast('a' + i) << \") \" << selectOpts[i] << \"\\n\";\n\t}\n\tstring userChoice;\n\tcout << \"Please choose an option(a-c): \";\n\tgetline(cin, userChoice);\n\n\tswitch (userChoice[0]) {\n\t\tcase 'A':\n\t\tcase 'a':\n\t\t\t{\n\t\t\t\taddToEnrollmentAndRoster(selectedRoster);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'B':\n\t\tcase 'b':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.removeStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'C':\n\t\tcase 'c':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.editStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Invalid option selected.\\n\";\n\t}\n}\n\nnamespace RosterSystemUtils {\n\tint getMenuOptSelection (int start, int end) {\n\t\tstring choice;\n\t\tdo {\n\t\t\tgetline (cin, choice);\n\t\t} while (choice[0] - '0' < start || choice[0] - '0' > end &&\n\t\t\t\t choice != \"q\" && choice != \"Q\");\n\t\tint selection = choice[0] - '0';\n\t\treturn selection;\n\t}\n\n\tchar getLoginOptSelection ( ) {\n\t\tstring choice;\n\t\tdo {\n\t\t\tgetline (cin, choice);\n\t\t} while (choice != \"A\" && choice != \"B\" && choice != \"C\" &&\n\t\t\t\t choice != \"a\" && choice != \"b\" && choice != \"c\");\n\t\treturn choice[0];\n\n\t}\n}Adds case C to the login menu which exports the rosters to a file\/\/ RosterSystem.cpp\n\/\/ Created by Evan Almonte\n\/\/\n#include \"RosterSystem.hpp\"\n#include \"Roster.hpp\"\n#include \"RSFileManager.hpp\"\n#include \"Student.hpp\"\n#include \"Utilities.hpp\"\n#include \n\nusing std::cout;\nusing std::cin;\nusing std::string;\n\nnamespace RosterSystemUtils {\n\tint getMenuOptSelection (int start, int end);\n\tchar getLoginOptSelection ( );\n}\nconst string RosterSystem::menuOpts[numOfMenuOpts] = {\n\t\"Create a new Roster\",\n\t\"Drop a Roster\",\n\t\"Display Roster Information\",\n\t\"Display All Rosters\",\n\t\"Select a Roster\"\n};\nconst string RosterSystem::selectOpts[numOfSelectOpts] = {\n\t\"Add a New Student\",\n\t\"Remove a Student\",\n\t\"Update a Student\",\n\t\"List All Students\"\n};\n\nRosterSystem::RosterSystem( ) : loginStatus(NOT_LOGGED), rListSz(0), rListCap(0), rosterList(nullptr),\n eListSz(0), eListCap(0), enrollmentList(nullptr) {}\n\nRosterSystem::~RosterSystem( ) {\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\tdelete rosterList[i];\n\t}\n\tdelete[] rosterList;\n\tfor (int i = 0; i < eListSz; ++i) {\n\t\tdelete enrollmentList[i];\n\t}\n\tdelete[] enrollmentList;\n}\n\nvoid RosterSystem::loginMenu( ) {\n\tclearScreen ( );\n\tloginStatus = USER;\n\tcout << \"********************************\\n\";\n\tcout << \" Welcome To SchoolManager v.1 \\n\";\n\tcout << \"********************************\\n\";\n\tcout << \"A) Supervisor Mode\\n\";\n\tcout << \"B) User Mode\\n\";\n\tcout << \"C) Exit\\n\";\n\tcout << \"Please choose an option: \";\n\tchar choice = RosterSystemUtils::getLoginOptSelection ( );\n\tswitch(choice) {\n\t\tcase 'A':\n\t\tcase 'a': {\n\t\t\tRSFileManager database (\"Database.txt\", false);\n\t\t\tloginStatus = database.attemptLogin ( );\n\t\t}\n\t\tcase 'B':\n\t\tcase 'b':\n\t\t\tmainMenu ( );\n\t\t\tloginMenu ( );\n\t\t\tbreak;\n\t\tcase 'C':\n\t\tcase 'c': {\n\t\t\tRSFileManager writeRosters (\"RosterFile.txt\", true);\n\t\t\twriteRosters.exportRosters (rosterList, rListSz);\n\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Invalid choice please try again.\\n\";\n\t\t\tcout << \"Press ENTER to continue . . .\";\n\t\t\tcin.get ( );\n\t\t\tloginMenu ( );\n\t}\n}\n\nvoid RosterSystem::mainMenu( ) {\n\tclearScreen ( );\n\tcout << \"******************************\\n\";\n\tcout << \" Main Menu \\n\";\n\tcout << \"******************************\\n\";\n\tint startOption = 1, endOption;\n\tif (loginStatus == SUPERVISOR) {\n\t\tendOption = numOfMenuOpts;\n\t\tdisplayAdminMenu();\n\t} else {\n\t\tendOption = 1;\n\t\tdisplayUserMenu();\n\t}\n\tcout << \"Please choose an option(q to Quit): \";\n\tint choice = RosterSystemUtils::getMenuOptSelection(startOption, endOption);\n\n\tif (choice == 1 && loginStatus != SUPERVISOR) {\n\t\tchoice = 5;\n\t}\n\n\tswitch (choice) {\n\t\tcase 1:\n\t\t\taddRoster();\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\t{\n\t\t\t\tstring courseNumber;\n\t\t\t\tcout << \"Please enter the rosters course number: \";\n\t\t\t\tgetline(cin, courseNumber);\n\t\t\t\tremoveRoster(courseNumber);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\t{\n\t\t\t\tcout << \"Please enter the rosters course number: \";\n\t\t\t\tstring courseNumber;\n\t\t\t\tgetline(cin, courseNumber);\n\t\t\t\tdisplayRoster(courseNumber);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tdisplayAllRosters();\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\t{\n\t\t\t\tstring courseNumber;\n\t\t\t\tcout << \"Please enter the rosters course number: \";\n\t\t\t\tgetline(cin, courseNumber);\n\t\t\t\tselectRoster(courseNumber);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Exiting to login menu.\\n\";\n\t\t\treturn;\n\t}\n\tcout << \"Press ENTER to continue . . .\";\n\tcin.get();\n\tmainMenu();\n}\n\nvoid RosterSystem::displayAdminMenu( ) {\n\tfor (int i = 0; i < numOfMenuOpts; ++i) {\n\t\tcout << i + 1 << \") \" << menuOpts[i] << \"\\n\";\n\t}\n}\n\nvoid RosterSystem::displayUserMenu( ) {\n\tint i = numOfMenuOpts - 1;\n\tcout << i + 1 << \") \" << menuOpts[numOfMenuOpts - 1] << \"\\n\";\n}\n\nvoid RosterSystem::addToEnrollmentList(Student* aStudent) {\n\tif (eListSz == eListCap) {\n\t\tgrowEnrollmentList();\n\t}\n\tenrollmentList[eListSz++] = aStudent;\n}\n\nvoid RosterSystem::addToEnrollmentAndRoster(Roster& selectedRoster) {\n\tclearScreen();\n\tif (eListSz == eListCap) {\n\t\tgrowEnrollmentList();\n\t}\n\tStudent* studentToAdd = new Student();\n\tcout << \"******************************\\n\";\n\tcout << \" New Student Added \\n\";\n\tcout << \"******************************\\n\";\n\tcin >> *studentToAdd;\n\tenrollmentList[eListSz++] = studentToAdd;\n\tselectedRoster.addStudent(studentToAdd);\n}\n\nint RosterSystem::findRoster(std::string courseCode) const {\n\tif (rListSz == 0) {\n\t\tcout << \"There are no rosters in the system.\\n\";\n\t\treturn EMPTY_LIST;\n\t}\n\tint foundIndex = NOT_FOUND;\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\tif (courseCode == rosterList[i]->getCourseCode()) {\n\t\t\tfoundIndex = i;\n\t\t}\n\t}\n\tif(foundIndex == NOT_FOUND) {\n\t\tcout << \"No roster with a course number of: \" << courseCode << \" was found.\\n\";\n\t}\n\treturn foundIndex;\n}\n\nvoid RosterSystem::addRoster( ) {\n\tclearScreen();\n\tif (rListSz == rListCap) {\n\t\tgrowRosterList();\n\t}\n\tRoster* rosterToAdd = new Roster;\n\tcout << \"******************************\\n\";\n\tcout << \" New Roster Created \\n\";\n\tcout << \"******************************\\n\";\n\tcin >> *rosterToAdd;\n\trosterList[rListSz++] = rosterToAdd;\n}\n\nvoid RosterSystem::selectRoster(std::string courseNumber) {\n\tint location = findRoster (courseNumber);\n\tif (location == NOT_FOUND || location == EMPTY_LIST) {\n\t\treturn;\n\t}\n\tRoster* rosterToEdit = rosterList[location];\n\tdo {\n\t\tif (loginStatus == SUPERVISOR) {\n\t\t\tadminSelectOpts(*rosterToEdit);\n\t\t} else {\n\t\t\tuserSelectOpts(*rosterToEdit);\n\t\t}\n\t\tcout << \"Would you like to continue editing the same roster(Y\/N)? \";\n\t} while (getYesOrNo());\n}\n\nvoid RosterSystem::removeRoster(std::string courseCode) {\n\tint location = findRoster(courseCode);\n\tif (location == NOT_FOUND || location == EMPTY_LIST) {\n\t\treturn;\n\t}\n\tclearScreen ( );\n\t\/\/\t\tDisplays a title as:\n\t\/\/*******************************\n\t\/\/ CourseName Has Been Deleted \n\t\/\/*******************************\n\tint lengthOfName = rosterList[location]->getCourseName ( ).length ( );\n\tstring numOfAsterixs = \"**\";\n\tfor (int i = 0; i < lengthOfName; ++i) {\n\t\tnumOfAsterixs += \"*\";\n\t}\n\tcout << numOfAsterixs << \"*******************\\n\";\n\tcout << \" \" << rosterList[location]->getCourseName() << \" Has Been Deleted \\n\";\n\tcout << numOfAsterixs << \"*******************\\n\";\n\t\/\/Shifts all rosters over to the left.\n\tdelete rosterList[location];\n\tfor (; location < rListSz - 1; ++location) {\n\t\trosterList[location] = rosterList[location + 1];\n\t};\n\trosterList[rListSz - 1] = nullptr;\n\t--rListSz;\n}\n\nvoid RosterSystem::growEnrollmentList( ) {\n\tint newCap = eListCap * 2 + 1;\n\tStudent** tempList = new Student*[newCap];\n\tfor (int i = 0; i < eListSz; ++i) {\n\t\ttempList[i] = enrollmentList[i];\n\t}\n\tfor (int i = eListSz; i < eListCap; i++) {\n\t\tenrollmentList[i] = nullptr;\n\t}\n\tdelete[] enrollmentList;\n\teListCap = newCap;\n\tenrollmentList = tempList;\n}\n\nvoid RosterSystem::growRosterList( ) {\n\tint newCap = rListCap * 2 + 1;\n\tRoster** tempList = new Roster*[newCap];\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\ttempList[i] = rosterList[i];\n\t}\n\tfor (int i = rListSz; i < rListCap; i++) {\n\t\trosterList[i] = nullptr;\n\t}\n\tdelete[] rosterList;\n\trListCap = newCap;\n\trosterList = tempList;\n}\n\nvoid RosterSystem::adminSelectOpts(Roster& selectedRoster) {\n\tclearScreen();\n\tcout << \"******************************\\n\";\n\tcout << \" Editing Roster \\n\";\n\tcout << \"******************************\\n\";\n\tcout << \"Course: \" << selectedRoster.getCourseName() << \"\\n\";\n\tcout << \"Code: \" << selectedRoster.getCourseCode() << \"\\n\";\n\tfor (int i = 0; i < numOfSelectOpts; ++i) {\n\t\tcout << static_cast('a' + i) << \") \" << selectOpts[i] << \"\\n\";\n\t}\n\tstring userChoice;\n\tcout << \"Please choose an option(a-d): \";\n\tgetline(cin, userChoice);\n\n\tswitch (userChoice[0]) {\n\t\tcase 'A':\n\t\tcase 'a':\n\t\t\t{\n\t\t\t\taddToEnrollmentAndRoster(selectedRoster);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'B':\n\t\tcase 'b':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.removeStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'C':\n\t\tcase 'c':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.editStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'D':\n\t\tcase 'd':\n\t\t\tselectedRoster.listAllStudents();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Invalid option selected.\\n\";\n\t}\n}\n\nvoid RosterSystem::displayRoster(std::string courseNumber) const {\n\tclearScreen ( );\n\tint location = findRoster(courseNumber);\n\tif (location == NOT_FOUND || location == EMPTY_LIST) {\n\t\treturn;\n\t}\n\tRoster* rosterToDisplay = rosterList[location];\n\trosterToDisplay->displayInfo();\n}\n\nvoid RosterSystem::displayAllRosters( ) const {\n\tclearScreen ( );\n\tif(rListSz == 0) {\n\t\tcout << \"There are no rosters in the system.\\n\";\n\t\treturn;\n\t}\n\tcout << \"******************************\\n\";\n\tcout << \" Display All Rosters \\n\";\n\tcout << \"******************************\\n\";\n\tfor (int i = 0; i < rListSz; ++i) {\n\t\trosterList[i]->displayInfo();\n\t\tcout << \"\\n\";\n\t}\n}\n\nvoid RosterSystem::userSelectOpts(Roster& selectedRoster) {\n\tclearScreen();\n\tcout << \"******************************\\n\";\n\tcout << \" Editing Roster \\n\";\n\tcout << \"******************************\\n\";\n\tcout << \"Course: \" << selectedRoster.getCourseName() << \"\\n\";\n\tcout << \"Code: \" << selectedRoster.getCourseCode() << \"\\n\";\n\n\t\/\/Subtract 1 due to the fact that \"user\" does not have access to the last option.\n\tfor (int i = 0; i < numOfSelectOpts - 1; ++i) {\n\t\tcout << static_cast('a' + i) << \") \" << selectOpts[i] << \"\\n\";\n\t}\n\tstring userChoice;\n\tcout << \"Please choose an option(a-c): \";\n\tgetline(cin, userChoice);\n\n\tswitch (userChoice[0]) {\n\t\tcase 'A':\n\t\tcase 'a':\n\t\t\t{\n\t\t\t\taddToEnrollmentAndRoster(selectedRoster);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'B':\n\t\tcase 'b':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.removeStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'C':\n\t\tcase 'c':\n\t\t\t{\n\t\t\t\tcout << \"Please enter the student's last name: \";\n\t\t\t\tstring lastName;\n\t\t\t\tgetline(cin, lastName);\n\t\t\t\tselectedRoster.editStudent(lastName);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Invalid option selected.\\n\";\n\t}\n}\n\nnamespace RosterSystemUtils {\n\tint getMenuOptSelection (int start, int end) {\n\t\tstring choice;\n\t\tdo {\n\t\t\tgetline (cin, choice);\n\t\t} while (choice[0] - '0' < start || choice[0] - '0' > end &&\n\t\t\t\t choice != \"q\" && choice != \"Q\");\n\t\tint selection = choice[0] - '0';\n\t\treturn selection;\n\t}\n\n\tchar getLoginOptSelection ( ) {\n\t\tstring choice;\n\t\tdo {\n\t\t\tgetline (cin, choice);\n\t\t} while (choice != \"A\" && choice != \"B\" && choice != \"C\" &&\n\t\t\t\t choice != \"a\" && choice != \"b\" && choice != \"c\");\n\t\treturn choice[0];\n\n\t}\n}<|endoftext|>"} {"text":"\/*************************************************************************\n> File Name: Deck.cpp\n> Project Name: Hearthstone++\n> Author: Chan-Ho Chris Ohk\n> Purpose: Deck class that stores a list of cards.\n> Created Time: 2017\/10\/13\n> Copyright (c) 2017, Chan-Ho Chris Ohk\n*************************************************************************\/\n#include \n\n#include \n#include \n\nnamespace Hearthstonepp\n{\n\tDeck::Deck() :\n\t\tm_name(\"Empty\"), m_class(CardClass::INVALID), m_numOfCards(0)\n\t{\n\n\t}\n\n\tDeck::Deck(std::string name, const CardClass playerClass) :\n\t\tm_name(std::move(name)), m_class(playerClass), m_numOfCards(0)\n\t{\n\n\t}\n\n\tstd::string Deck::GetName() const\n\t{\n\t\treturn m_name;\n\t}\n\n\tCardClass Deck::GetClass() const\n\t{\n\t\treturn m_class;\n\t}\n\n\tunsigned int Deck::GetNumOfCards() const\n\t{\n\t\treturn m_numOfCards;\n\t}\n\n\tsize_t Deck::GetUniqueNumOfCards() const\n\t{\n\t\treturn m_cards.size();\n\t}\n\n\tunsigned int Deck::GetNumCardInDeck(std::string cardID)\n\t{\n\t\tauto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(),\n\t\t\t[&cardID](const std::pair& elem) { return elem.first == cardID; });\n\n\t\tif (isCardExistInDeck != m_cards.end())\n\t\t{\n\t\t\treturn (*isCardExistInDeck).second;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tstd::vector Deck::GetPrimitiveDeck() const\n\t{\n\t\tCards* cards = Cards::GetInstance();\n\n\t\tstd::vector deck;\n\t\tfor (const auto& pair : m_cards)\n\t\t{\n\t\t\tconst Card* card = cards->FindCardByID(pair.first);\n\t\t\tfor (int i = 0; i < pair.second; ++i)\n\t\t\t{\n\t\t\t\tdeck.push_back(card);\n\t\t\t}\t\n\t\t}\n\n\t\treturn deck;\n\t}\n\n\tstd::pair Deck::GetCard(size_t idx) const\n\t{\n\t\treturn m_cards.at(idx);\n\t}\n\n\tvoid Deck::ShowCardList() const\n\t{\n\t\tint idx = 1;\n\n\t\tfor (auto& cardInfo : m_cards)\n\t\t{\n\t\t\tconst Card* card = Cards::GetInstance()->FindCardByID(cardInfo.first);\n\t\t\tif (card == nullptr)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::cout << idx << \". \";\n\t\t\tcard->ShowBriefInfo();\n\t\t\tstd::cout << \"(\" << cardInfo.second << \" card(s))\\n\";\n\t\t\t\n\t\t\tidx++;\n\t\t}\n\n\t}\n\n\tint Deck::AddCard(std::string cardID, int numCardToAdd)\n\t{\n\t\tconst Card* card = Cards::GetInstance()->FindCardByID(cardID);\n\t\tCardClass cls = card->GetCardClass();\n\t\tif (cls != GetClass() && cls != CardClass::NEUTRAL || card->GetMaxAllowedInDeck() < numCardToAdd) \n\t\t{\n\t\t\treturn -1;\n\t\t}\n\n\t\tauto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(),\n\t\t\t[&cardID](const std::pair& elem) { return elem.first == cardID; });\n\n\t\tif (isCardExistInDeck != m_cards.end()) \/\/ card is in deck\n\t\t{\n\t\t\tif (card->GetMaxAllowedInDeck() < (*isCardExistInDeck).second + numCardToAdd)\n\t\t\t\treturn -1;\n\n\t\t\t(*isCardExistInDeck).second += numCardToAdd;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_cards.emplace_back(std::make_pair(cardID, numCardToAdd));\n\t\t}\n\n\t\tm_numOfCards += numCardToAdd;\n\n\t\treturn 0;\n\t}\n\n\tint Deck::DeleteCard(std::string cardID, const int numCardToDelete)\n\t{\n\t\tauto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(),\n\t\t\t[&cardID](const std::pair& elem) { return elem.first == cardID; });\n\n\t\tif (isCardExistInDeck != m_cards.end())\n\t\t{\n\t\t\tif ((*isCardExistInDeck).second - numCardToDelete == 0)\n\t\t\t{\n\t\t\t\tm_cards.erase(isCardExistInDeck);\n\t\t\t}\n\t\t\telse if ((*isCardExistInDeck).second - numCardToDelete < 0)\n\t\t\t{\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\t(*isCardExistInDeck).second -= numCardToDelete;\n\t\t\tm_numOfCards -= numCardToDelete;\n\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn -1;\n\t}\n}Modi Deck.cpp - fix parentheses, sign-compare\/*************************************************************************\n> File Name: Deck.cpp\n> Project Name: Hearthstone++\n> Author: Chan-Ho Chris Ohk\n> Purpose: Deck class that stores a list of cards.\n> Created Time: 2017\/10\/13\n> Copyright (c) 2017, Chan-Ho Chris Ohk\n*************************************************************************\/\n#include \n\n#include \n#include \n\nnamespace Hearthstonepp\n{\n\tDeck::Deck() :\n\t\tm_name(\"Empty\"), m_class(CardClass::INVALID), m_numOfCards(0)\n\t{\n\n\t}\n\n\tDeck::Deck(std::string name, const CardClass playerClass) :\n\t\tm_name(std::move(name)), m_class(playerClass), m_numOfCards(0)\n\t{\n\n\t}\n\n\tstd::string Deck::GetName() const\n\t{\n\t\treturn m_name;\n\t}\n\n\tCardClass Deck::GetClass() const\n\t{\n\t\treturn m_class;\n\t}\n\n\tunsigned int Deck::GetNumOfCards() const\n\t{\n\t\treturn m_numOfCards;\n\t}\n\n\tsize_t Deck::GetUniqueNumOfCards() const\n\t{\n\t\treturn m_cards.size();\n\t}\n\n\tunsigned int Deck::GetNumCardInDeck(std::string cardID)\n\t{\n\t\tauto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(),\n\t\t\t[&cardID](const std::pair& elem) { return elem.first == cardID; });\n\n\t\tif (isCardExistInDeck != m_cards.end())\n\t\t{\n\t\t\treturn (*isCardExistInDeck).second;\n\t\t}\n\n\t\treturn 0;\n\t}\n\n\tstd::vector Deck::GetPrimitiveDeck() const\n\t{\n\t\tCards* cards = Cards::GetInstance();\n\n\t\tstd::vector deck;\n\t\tfor (const auto& pair : m_cards)\n\t\t{\n\t\t\tconst Card* card = cards->FindCardByID(pair.first);\n\t\t\tfor (int i = 0; i < pair.second; ++i)\n\t\t\t{\n\t\t\t\tdeck.push_back(card);\n\t\t\t}\t\n\t\t}\n\n\t\treturn deck;\n\t}\n\n\tstd::pair Deck::GetCard(size_t idx) const\n\t{\n\t\treturn m_cards.at(idx);\n\t}\n\n\tvoid Deck::ShowCardList() const\n\t{\n\t\tint idx = 1;\n\n\t\tfor (auto& cardInfo : m_cards)\n\t\t{\n\t\t\tconst Card* card = Cards::GetInstance()->FindCardByID(cardInfo.first);\n\t\t\tif (card == nullptr)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tstd::cout << idx << \". \";\n\t\t\tcard->ShowBriefInfo();\n\t\t\tstd::cout << \"(\" << cardInfo.second << \" card(s))\\n\";\n\t\t\t\n\t\t\tidx++;\n\t\t}\n\n\t}\n\n\tint Deck::AddCard(std::string cardID, int numCardToAdd)\n\t{\n\t\tconst Card* card = Cards::GetInstance()->FindCardByID(cardID);\n\t\tCardClass cls = card->GetCardClass();\n\t\tif ((cls != GetClass() && cls != +CardClass::NEUTRAL) || int(card->GetMaxAllowedInDeck()) < numCardToAdd) \n\t\t{\n\t\t\treturn -1;\n\t\t}\n\n\t\tauto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(),\n\t\t\t[&cardID](const std::pair& elem) { return elem.first == cardID; });\n\n\t\tif (isCardExistInDeck != m_cards.end()) \/\/ card is in deck\n\t\t{\n\t\t\tif (int(card->GetMaxAllowedInDeck()) < (*isCardExistInDeck).second + numCardToAdd)\n\t\t\t\treturn -1;\n\n\t\t\t(*isCardExistInDeck).second += numCardToAdd;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_cards.emplace_back(std::make_pair(cardID, numCardToAdd));\n\t\t}\n\n\t\tm_numOfCards += numCardToAdd;\n\n\t\treturn 0;\n\t}\n\n\tint Deck::DeleteCard(std::string cardID, const int numCardToDelete)\n\t{\n\t\tauto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(),\n\t\t\t[&cardID](const std::pair& elem) { return elem.first == cardID; });\n\n\t\tif (isCardExistInDeck != m_cards.end())\n\t\t{\n\t\t\tif ((*isCardExistInDeck).second - numCardToDelete == 0)\n\t\t\t{\n\t\t\t\tm_cards.erase(isCardExistInDeck);\n\t\t\t}\n\t\t\telse if ((*isCardExistInDeck).second - numCardToDelete < 0)\n\t\t\t{\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t\t(*isCardExistInDeck).second -= numCardToDelete;\n\t\t\tm_numOfCards -= numCardToDelete;\n\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn -1;\n\t}\n}<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n\n\nint main()\n{\n PXCSession *session = PXCSession::CreateInstance();\n PXCSession::ImplVersion ver = session->QueryVersion();\n TLOG(INFO) << ver.major << \".\" << ver.minor;\n session->Release();\n\n return EXIT_SUCCESS;\n}\nStarted implementing RealSense grabber#include \n\n#ifdef _MSC_VER\n #pragma warning(push)\n #pragma warning(disable: 4309) \/\/ truncation of const value\n#endif\n#include \n#ifdef _MSC_VER\n #pragma warning(pop)\n#endif\n\n#include \n\n\nint main()\n{\n \/*PXCSession *session = PXCSession::CreateInstance();\n PXCSession::ImplVersion ver = session->QueryVersion();\n TLOG(INFO) << ver.major << \".\" << ver.minor;\n session->Release();*\/\n\n PXCSenseManager *senseManager = PXCSenseManager::CreateInstance();\n senseManager->EnableStream(Intel::RealSense::StreamType::STREAM_TYPE_COLOR, 1920, 1080, 30.0f);\n senseManager->EnableStream(Intel::RealSense::StreamType::STREAM_TYPE_DEPTH, 628, 468, 30.0f);\n\n senseManager->Init();\n\n int numFrames = 0;\n\n while (senseManager->AcquireFrame(true) >= PXC_STATUS_NO_ERROR)\n {\n PXCCapture::Sample *sample = senseManager->QuerySample();\n const auto colorInfo = sample->color->QueryInfo(), depthInfo = sample->depth->QueryInfo();\n senseManager->ReleaseFrame();\n ++numFrames;\n TLOG(INFO) << \"Captured color frame #\" << numFrames << \" \" << colorInfo.format << \" \" << colorInfo.width << \" \" << colorInfo.height << \" \" << colorInfo.reserved;\n TLOG(INFO) << \"Captured depth frame #\" << numFrames << \" \" << depthInfo.format << \" \" << depthInfo.width << \" \" << depthInfo.height << \" \" << depthInfo.reserved;\n }\n\n senseManager->Release();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include \"AutowiringDebug.h\"\n#include \"Autowired.h\"\n#include \n#include \n#include \n\nusing namespace autowiring;\nusing namespace autowiring::dbg;\n\n#ifdef _MSC_VER\n\/\/ On Windows, lambda functions start with the key string \"class <\"\nbool autowiring::dbg::IsLambda(const std::type_info& ti) {\n return demangle(ti).compare(0, 7, \"class <\") == 0;\n}\n#else\n\/\/ On other platforms, try to find lambda functions by the presence of forbidden characters\nbool autowiring::dbg::IsLambda(const std::type_info& ti) {\n auto name = demangle(ti);\n for (auto cur : name)\n if (\n !('a' <= cur && cur <= 'z') &&\n !('A' <= cur && cur <= 'Z') &&\n !('0' <= cur && cur <= '9') &&\n cur != '_' &&\n cur != ':' &&\n cur != '<' &&\n cur != '>' &&\n cur != ',' &&\n cur != ' '\n )\n return true;\n return false;\n}\n#endif\n\nstatic std::string TrimPrefix(std::string name) {\n \/\/ \"class\" or \"struct\" prefixes should be eliminated\n if (name.compare(0, 6, \"class \"))\n name = name.substr(5);\n if (name.compare(0, 7, \"struct \"))\n name = name.substr(6);\n return name;\n}\n\nstatic std::string DemangleWithAutoID(const std::type_info& ti) {\n auto retVal = demangle(ti);\n\n \/\/ prefix is at the beginning of the string, skip over it\n static const char prefix [] = \"struct auto_id<\";\n if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) {\n size_t off = sizeof(prefix) - 1;\n retVal = retVal.substr(off, retVal.length() - off - 2);\n }\n return TrimPrefix(retVal);\n}\n\nstd::string autowiring::dbg::ContextName(void) {\n AutoCurrentContext ctxt;\n return autowiring::demangle(ctxt->GetSigilType());\n}\n\nAutoPacket* autowiring::dbg::CurrentPacket(void) {\n Autowired factory;\n if (!factory)\n return nullptr;\n return factory->CurrentPacket().get();\n}\n\nstatic const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector& filters) {\n for (const auto& filter : filters) {\n auto type = filter.GetType();\n if (!type)\n continue;\n\n auto curName = TrimPrefix(demangle(type));\n if (!curName.compare(name))\n return &filter;\n }\n return nullptr;\n}\n\nconst AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) {\n Autowired factory;\n if (!factory)\n return nullptr;\n\n return DescriptorByName(name, factory->GetAutoFilters());\n}\n\nstd::string autowiring::dbg::AutoFilterInfo(const char* name) {\n Autowired factory;\n if (!factory)\n return \"No factory detected in this context\";\n\n \/\/ Obtain all descriptors:\n const std::vector descs = factory->GetAutoFilters();\n\n \/\/ Need the root descriptor first\n const AutoFilterDescriptor* desc = DescriptorByName(name, descs);\n if (!desc)\n return \"Filter not found\";\n\n std::ostringstream os;\n std::function fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) {\n auto args = desc.GetAutoFilterArguments();\n\n for (size_t i = 0; i < desc.GetArity(); i++) {\n \/\/ Argument must be an input to the filter we want to know more about\n if (!args[i].is_input)\n continue;\n\n \/\/ Who provides this input?\n for (const auto& providerDesc : descs) {\n auto providerArg = providerDesc.GetArgumentType(args[i].ti);\n if (providerArg && providerArg->is_output) {\n \/\/ Need to print information about this provider:\n os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl;\n\n \/\/ The current descriptor provides an input to the parent, recurse\n fnCall(providerDesc, nLevels + 1);\n }\n }\n }\n };\n\n \/\/ Root typename print first:\n os << demangle(desc->GetType()) << std::endl;\n fnCall(*desc, 1);\n\n auto retVal = os.str();\n return retVal;\n}\n\nstd::vector autowiring::dbg::ListRootDecorations(void) {\n Autowired factory;\n if (!factory)\n return std::vector{};\n\n \/\/ Obtain all descriptors:\n const std::vector descs = factory->GetAutoFilters();\n\n \/\/ Get all baseline descriptor types, figure out what isn't satisfied:\n std::unordered_map outputs;\n std::unordered_map inputs;\n\n for (const auto& desc : descs) {\n auto args = desc.GetAutoFilterArguments();\n for (size_t i = 0; i < desc.GetArity(); i++)\n (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti;\n }\n\n \/\/ Remove all inputs that exist in the outputs set:\n for (auto& output : outputs)\n inputs.erase(*output.second);\n\n \/\/ Any remaining inputs are unsatisfied\n std::vector retVal;\n for (auto& input : inputs)\n if (input.second)\n retVal.push_back(DemangleWithAutoID(*input.second));\n return retVal;\n}\n\nvoid autowiring::dbg::DebugInit(void) {\n\n}Make TrimPrefix a noop on mac\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include \"AutowiringDebug.h\"\n#include \"Autowired.h\"\n#include \n#include \n#include \n\nusing namespace autowiring;\nusing namespace autowiring::dbg;\n\n#ifdef _MSC_VER\n\/\/ On Windows, lambda functions start with the key string \"class <\"\nbool autowiring::dbg::IsLambda(const std::type_info& ti) {\n return demangle(ti).compare(0, 7, \"class <\") == 0;\n}\n#else\n\/\/ On other platforms, try to find lambda functions by the presence of forbidden characters\nbool autowiring::dbg::IsLambda(const std::type_info& ti) {\n auto name = demangle(ti);\n for (auto cur : name)\n if (\n !('a' <= cur && cur <= 'z') &&\n !('A' <= cur && cur <= 'Z') &&\n !('0' <= cur && cur <= '9') &&\n cur != '_' &&\n cur != ':' &&\n cur != '<' &&\n cur != '>' &&\n cur != ',' &&\n cur != ' '\n )\n return true;\n return false;\n}\n#endif\n\nstatic std::string TrimPrefix(std::string name) {\n#ifdef _MSC_VER\n \/\/ \"class\" or \"struct\" prefixes should be eliminated\n if (name.compare(0, 6, \"class \"))\n name = name.substr(5);\n if (name.compare(0, 7, \"struct \"))\n name = name.substr(6);\n#endif\n\n return name;\n}\n\nstatic std::string DemangleWithAutoID(const std::type_info& ti) {\n auto retVal = demangle(ti);\n\n \/\/ prefix is at the beginning of the string, skip over it\n static const char prefix [] = \"struct auto_id<\";\n if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) {\n size_t off = sizeof(prefix) - 1;\n retVal = retVal.substr(off, retVal.length() - off - 2);\n }\n return TrimPrefix(retVal);\n}\n\nstd::string autowiring::dbg::ContextName(void) {\n AutoCurrentContext ctxt;\n return autowiring::demangle(ctxt->GetSigilType());\n}\n\nAutoPacket* autowiring::dbg::CurrentPacket(void) {\n Autowired factory;\n if (!factory)\n return nullptr;\n return factory->CurrentPacket().get();\n}\n\nstatic const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector& filters) {\n for (const auto& filter : filters) {\n auto type = filter.GetType();\n if (!type)\n continue;\n\n auto curName = TrimPrefix(demangle(type));\n if (!curName.compare(name))\n return &filter;\n }\n return nullptr;\n}\n\nconst AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) {\n Autowired factory;\n if (!factory)\n return nullptr;\n\n return DescriptorByName(name, factory->GetAutoFilters());\n}\n\nstd::string autowiring::dbg::AutoFilterInfo(const char* name) {\n Autowired factory;\n if (!factory)\n return \"No factory detected in this context\";\n\n \/\/ Obtain all descriptors:\n const std::vector descs = factory->GetAutoFilters();\n\n \/\/ Need the root descriptor first\n const AutoFilterDescriptor* desc = DescriptorByName(name, descs);\n if (!desc)\n return \"Filter not found\";\n\n std::ostringstream os;\n std::function fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) {\n auto args = desc.GetAutoFilterArguments();\n\n for (size_t i = 0; i < desc.GetArity(); i++) {\n \/\/ Argument must be an input to the filter we want to know more about\n if (!args[i].is_input)\n continue;\n\n \/\/ Who provides this input?\n for (const auto& providerDesc : descs) {\n auto providerArg = providerDesc.GetArgumentType(args[i].ti);\n if (providerArg && providerArg->is_output) {\n \/\/ Need to print information about this provider:\n os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl;\n\n \/\/ The current descriptor provides an input to the parent, recurse\n fnCall(providerDesc, nLevels + 1);\n }\n }\n }\n };\n\n \/\/ Root typename print first:\n os << demangle(desc->GetType()) << std::endl;\n fnCall(*desc, 1);\n\n auto retVal = os.str();\n return retVal;\n}\n\nstd::vector autowiring::dbg::ListRootDecorations(void) {\n Autowired factory;\n if (!factory)\n return std::vector{};\n\n \/\/ Obtain all descriptors:\n const std::vector descs = factory->GetAutoFilters();\n\n \/\/ Get all baseline descriptor types, figure out what isn't satisfied:\n std::unordered_map outputs;\n std::unordered_map inputs;\n\n for (const auto& desc : descs) {\n auto args = desc.GetAutoFilterArguments();\n for (size_t i = 0; i < desc.GetArity(); i++)\n (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti;\n }\n\n \/\/ Remove all inputs that exist in the outputs set:\n for (auto& output : outputs)\n inputs.erase(*output.second);\n\n \/\/ Any remaining inputs are unsatisfied\n std::vector retVal;\n for (auto& input : inputs)\n if (input.second)\n retVal.push_back(DemangleWithAutoID(*input.second));\n return retVal;\n}\n\nvoid autowiring::dbg::DebugInit(void) {\n\n}<|endoftext|>"} {"text":"\/*****************************************************************************\n mergeBed.cpp\n\n (c) 2009 - Aaron Quinlan\n Hall Laboratory\n Department of Biochemistry and Molecular Genetics\n University of Virginia\n aaronquinlan@gmail.com\n\n Licenced under the GNU General Public License 2.0+ license.\n******************************************************************************\/\n#include \"lineFileUtilities.h\"\n#include \"mergeBed.h\"\n\n\/\/ ===============\n\/\/ = Constructor =\n\/\/ ===============\nBedMerge::BedMerge(string &bedFile, bool &numEntries, int &maxDistance, bool &forceStrand, bool &reportNames) {\n\n\tthis->bedFile = bedFile;\n\tthis->numEntries = numEntries;\n\tthis->maxDistance = -1 * maxDistance;\n\tthis->forceStrand = forceStrand;\n\tthis->reportNames = reportNames;\n\t\n\tthis->bed = new BedFile(bedFile);\n}\n\n\n\/\/ =================\n\/\/ = Destructor =\n\/\/ =================\nBedMerge::~BedMerge(void) {\n}\n\n\n\/\/ =====================================================\n\/\/ = Merge overlapping BED entries into a single entry =\n\/\/ =====================================================\nvoid BedMerge::MergeBed() {\n\n\t\/\/ load the \"B\" bed file into a map so\n\t\/\/ that we can easily compare \"A\" to it for overlaps\n\tbed->loadBedFileIntoMapNoBin();\n\n\t\/\/ loop through each chromosome and merge their BED entries\n\tfor (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) {\n\n\t\t\/\/ bedList is already sorted by start position.\n\t\tvector bedList = m->second; \n\n\t\tint minStart = INT_MAX;\n\t\tint maxEnd = 0;\n\t\tbool OIP = false; \/\/ OIP = Overlap In Progress. Lame, I realize.\n\t\tunsigned int prev = 0;\n\t\tunsigned int curr = 0;\n\t\tint mergeCount = 1;\n\t\tvector names;\n\n\t\t\/\/ loop through the BED entries for this chromosome\n\t\t\/\/ and look for overlaps\n\t\tfor (curr = 1; curr < bedList.size(); ++curr) {\n\t\t\t\n\t\t\t\/\/ Is there an overlap between the current and previous entries?\t\t\n\t\t\tif ( overlaps(bedList[prev].start, bedList[prev].end, \n\t\t\t \t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\t\t\t\t\n\t\t\t\tOIP = true;\n\t\t\t\tmergeCount++;\n\t\t\t\tminStart = min(bedList[prev].start, min(minStart, bedList[curr].start));\n\t\t\t\tmaxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end));\n\t\t\t\t\n\t\t\t\t\/\/names.push_back(bedList[prev].name);\n\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t}\n\t\t\telse if ( overlaps(minStart, maxEnd, \n\t\t\t\t\t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\t\t\t\tmergeCount++;\n\t\t\t\tminStart = min(minStart, bedList[curr].start);\n\t\t\t\tmaxEnd = max(maxEnd, bedList[curr].end);\n\t\t\t\t\n\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t}\n\t\t\telse {\n\n\t\t\t\t\/\/ was there an overlap befor the current entry broke it?\n\t\t\t\tif (OIP) {\n\t\t\t\t\tif (this->numEntries) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this->numEntries) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ reset things for the next overlapping \"block\"\n\t\t\t\tOIP = false;\n\t\t\t\tmergeCount = 1;\t\t\t\n\t\t\t\tminStart = INT_MAX;\n\t\t\t\tmaxEnd = 0;\n\t\t\t\tnames.clear();\n\t\t\t\tnames.push_back(bedList[prev].name);\n\t\t\t}\n\t\t\tprev = curr;\n\t\t}\n\n\t\t\/\/ clean up based on the last entry for the current chromosome\n\t\tif (OIP) {\n\t\t\tif (this->numEntries) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << endl;\n\t\t\t}\n\t\t\telse if (this->reportNames) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << endl;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (this->numEntries) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << endl;\n\t\t\t}\n\t\t\telse if (this->reportNames) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << endl;\t\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\/\/ ==================================================================================\n\/\/ = Merge overlapping BED entries into a single entry, accounting for strandedness =\n\/\/ ==================================================================================\nvoid BedMerge::MergeBedStranded() {\n\n\t\/\/ load the \"B\" bed file into a map so\n\t\/\/ that we can easily compare \"A\" to it for overlaps\n\tbed->loadBedFileIntoMapNoBin();\n\n\t\/\/ loop through each chromosome and merge their BED entries\n\tfor (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) {\n\n\t\t\/\/ bedList is already sorted by start position.\n\t\tvector bedList = m->second; \n\n\t\t\/\/ make a list of the two strands to merge separately.\n\t\tvector strands(2);\n\t\tstrands[0] = \"+\";\n\t\tstrands[1] = \"-\";\n\n\t\t\/\/ do two passes, one for each strand.\n\t\tfor (unsigned int s = 0; s < strands.size(); s++) {\n\n\t\t\tint minStart = INT_MAX;\n\t\t\tint maxEnd = 0;\n\t\t\tbool OIP = false; \/\/ OIP = Overlap In Progress. Lame, I realize.\n\t\t\tint prev = -1;\n\t\t\tunsigned int curr = 0;\n\t\t\tint mergeCount = 1;\n\t\t\tint numOnStrand = 0;\n\t\t\tvector names;\t\n\t\t\t\n\t\t\t\/\/ loop through the BED entries for this chromosome\n\t\t\t\/\/ and look for overlaps\n\t\t\tfor (curr = 0; curr < bedList.size(); ++curr) {\n\n\t\t\t\t\/\/ if forcing strandedness, move on if the hit\n\t\t\t\t\/\/ is not on the current strand.\n\t\t\t\t\n\t\t\t\tif (bedList[curr].strand != strands[s]) {\n\t\t\t\t\tcontinue;\t\t\/\/ continue force the next iteration of the for loop.\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnumOnStrand++;\n\t\t\t\t}\n\n\t\t\t\t\/\/ make sure prev points to an actual element on the\n\t\t\t\t\/\/ current strand\n\t\t\t\tif (prev < 0) {\n\t\t\t\t\tif (bedList[curr].strand == strands[s]) {\n\t\t\t\t\t\tprev = curr;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\n\t\t\t\tif ( overlaps(bedList[prev].start, bedList[prev].end, \n\t\t\t\t \t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\t\t\t\t\t\n\t\t\t\t\tOIP = true;\n\t\t\t\t\tmergeCount++;\n\t\t\t\t\tminStart = min(bedList[prev].start, min(minStart, bedList[curr].start));\n\t\t\t\t\tmaxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end));\n\n\t\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t\t}\n\t\t\t\telse if ( overlaps(minStart, maxEnd, \n\t\t\t\t\t\t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\n\t\t\t\t\tmergeCount++;\n\t\t\t\t\tminStart = min(minStart, bedList[curr].start);\n\t\t\t\t\tmaxEnd = max(maxEnd, bedList[curr].end);\n\t\t\t\t\t\n\t\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t\t}\n\t\t\t\telse {\n\n\t\t\t\t\t\/\/ was there an overlap before the current entry broke it?\n\t\t\t\t\tif (OIP) {\n\t\t\t\t\t\tif (this->numEntries) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << strands[s] << endl;\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\tif ((this->numEntries) && (numOnStrand > 0)) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (numOnStrand > 0) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ reset things for the next overlapping \"block\"\n\t\t\t\t\tOIP = false;\n\t\t\t\t\tmergeCount = 1;\t\t\t\n\t\t\t\t\tminStart = INT_MAX;\n\t\t\t\t\tmaxEnd = 0;\n\t\t\t\t\tnames.clear();\n\t\t\t\t\t\n\t\t\t\t\t\/\/ add the name of the \n\t\t\t\t\tnames.push_back(bedList[prev].name);\n\t\t\t\t}\n\t\t\t\tprev = curr;\n\t\t\t}\n\n\t\t\t\/\/ clean up based on the last entry for the current chromosome\n\t\t\tif (OIP) {\n\t\t\t\tif (this->numEntries) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t\t}\n\t\t\t\t\tcout << endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ((this->numEntries) && (numOnStrand > 0)) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << endl;\n\t\t\t\t}\n\t\t\t\telse if (numOnStrand > 0) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\nFixed bug in mergeBed that caused segfault when -nms and -s used together.\/*****************************************************************************\n mergeBed.cpp\n\n (c) 2009 - Aaron Quinlan\n Hall Laboratory\n Department of Biochemistry and Molecular Genetics\n University of Virginia\n aaronquinlan@gmail.com\n\n Licenced under the GNU General Public License 2.0+ license.\n******************************************************************************\/\n#include \"lineFileUtilities.h\"\n#include \"mergeBed.h\"\n\n\/\/ ===============\n\/\/ = Constructor =\n\/\/ ===============\nBedMerge::BedMerge(string &bedFile, bool &numEntries, int &maxDistance, bool &forceStrand, bool &reportNames) {\n\n\tthis->bedFile = bedFile;\n\tthis->numEntries = numEntries;\n\tthis->maxDistance = -1 * maxDistance;\n\tthis->forceStrand = forceStrand;\n\tthis->reportNames = reportNames;\n\t\n\tthis->bed = new BedFile(bedFile);\n}\n\n\n\/\/ =================\n\/\/ = Destructor =\n\/\/ =================\nBedMerge::~BedMerge(void) {\n}\n\n\n\/\/ =====================================================\n\/\/ = Merge overlapping BED entries into a single entry =\n\/\/ =====================================================\nvoid BedMerge::MergeBed() {\n\n\t\/\/ load the \"B\" bed file into a map so\n\t\/\/ that we can easily compare \"A\" to it for overlaps\n\tbed->loadBedFileIntoMapNoBin();\n\n\t\/\/ loop through each chromosome and merge their BED entries\n\tfor (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) {\n\n\t\t\/\/ bedList is already sorted by start position.\n\t\tvector bedList = m->second; \n\n\t\tint minStart = INT_MAX;\n\t\tint maxEnd = 0;\n\t\tbool OIP = false; \/\/ OIP = Overlap In Progress. Lame, I realize.\n\t\tunsigned int prev = 0;\n\t\tunsigned int curr = 0;\n\t\tint mergeCount = 1;\n\t\tvector names;\n\n\t\t\/\/ loop through the BED entries for this chromosome\n\t\t\/\/ and look for overlaps\n\t\tfor (curr = 1; curr < bedList.size(); ++curr) {\n\t\t\t\n\t\t\t\/\/ Is there an overlap between the current and previous entries?\t\t\n\t\t\tif ( overlaps(bedList[prev].start, bedList[prev].end, \n\t\t\t \t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\t\t\t\t\n\t\t\t\tOIP = true;\n\t\t\t\tmergeCount++;\n\t\t\t\tminStart = min(bedList[prev].start, min(minStart, bedList[curr].start));\n\t\t\t\tmaxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end));\n\t\t\t\t\n\t\t\t\t\/\/names.push_back(bedList[prev].name);\n\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t}\n\t\t\telse if ( overlaps(minStart, maxEnd, \n\t\t\t\t\t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\t\t\t\tmergeCount++;\n\t\t\t\tminStart = min(minStart, bedList[curr].start);\n\t\t\t\tmaxEnd = max(maxEnd, bedList[curr].end);\n\t\t\t\t\n\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t}\n\t\t\telse {\n\n\t\t\t\t\/\/ was there an overlap befor the current entry broke it?\n\t\t\t\tif (OIP) {\n\t\t\t\t\tif (this->numEntries) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcout << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (this->numEntries) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << endl;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ reset things for the next overlapping \"block\"\n\t\t\t\tOIP = false;\n\t\t\t\tmergeCount = 1;\t\t\t\n\t\t\t\tminStart = INT_MAX;\n\t\t\t\tmaxEnd = 0;\n\t\t\t\tnames.clear();\n\t\t\t\tnames.push_back(bedList[prev].name);\n\t\t\t}\n\t\t\tprev = curr;\n\t\t}\n\n\t\t\/\/ clean up based on the last entry for the current chromosome\n\t\tif (OIP) {\n\t\t\tif (this->numEntries) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << endl;\n\t\t\t}\n\t\t\telse if (this->reportNames) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t}\n\t\t\t\tcout << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << endl;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif (this->numEntries) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << endl;\n\t\t\t}\n\t\t\telse if (this->reportNames) {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << endl;\t\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\/\/ ==================================================================================\n\/\/ = Merge overlapping BED entries into a single entry, accounting for strandedness =\n\/\/ ==================================================================================\nvoid BedMerge::MergeBedStranded() {\n\n\t\/\/ load the \"B\" bed file into a map so\n\t\/\/ that we can easily compare \"A\" to it for overlaps\n\tbed->loadBedFileIntoMapNoBin();\n\n\t\/\/ loop through each chromosome and merge their BED entries\n\tfor (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) {\n\n\t\t\/\/ bedList is already sorted by start position.\n\t\tvector bedList = m->second; \n\n\t\t\/\/ make a list of the two strands to merge separately.\n\t\tvector strands(2);\n\t\tstrands[0] = \"+\";\n\t\tstrands[1] = \"-\";\n\n\t\t\/\/ do two passes, one for each strand.\n\t\tfor (unsigned int s = 0; s < strands.size(); s++) {\n\n\t\t\tint minStart = INT_MAX;\n\t\t\tint maxEnd = 0;\n\t\t\tbool OIP = false; \/\/ OIP = Overlap In Progress. Lame, I realize.\n\t\t\tint prev = -1;\n\t\t\tunsigned int curr = 0;\n\t\t\tint mergeCount = 1;\n\t\t\tint numOnStrand = 0;\n\t\t\tvector names;\t\n\t\t\t\n\t\t\t\/\/ loop through the BED entries for this chromosome\n\t\t\t\/\/ and look for overlaps\n\t\t\tfor (curr = 0; curr < bedList.size(); ++curr) {\n\n\t\t\t\t\/\/ if forcing strandedness, move on if the hit\n\t\t\t\t\/\/ is not on the current strand.\n\t\t\t\t\n\t\t\t\tif (bedList[curr].strand != strands[s]) {\n\t\t\t\t\tcontinue;\t\t\/\/ continue force the next iteration of the for loop.\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tnumOnStrand++;\n\t\t\t\t}\n\n\t\t\t\t\/\/ make sure prev points to an actual element on the\n\t\t\t\t\/\/ current strand\n\t\t\t\tif (prev < 0) {\n\t\t\t\t\tif (bedList[curr].strand == strands[s]) {\n\t\t\t\t\t\tprev = curr;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\n\t\t\t\tif ( overlaps(bedList[prev].start, bedList[prev].end, \n\t\t\t\t \t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\t\t\t\t\t\n\t\t\t\t\tOIP = true;\n\t\t\t\t\tmergeCount++;\n\t\t\t\t\tminStart = min(bedList[prev].start, min(minStart, bedList[curr].start));\n\t\t\t\t\tmaxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end));\n\n\t\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t\t}\n\t\t\t\telse if ( overlaps(minStart, maxEnd, \n\t\t\t\t\t\t\t\tbedList[curr].start, bedList[curr].end) >= this->maxDistance) {\n\n\t\t\t\t\tmergeCount++;\n\t\t\t\t\tminStart = min(minStart, bedList[curr].start);\n\t\t\t\t\tmaxEnd = max(maxEnd, bedList[curr].end);\n\t\t\t\t\t\n\t\t\t\t\tnames.push_back(bedList[curr].name);\n\t\t\t\t}\n\t\t\t\telse {\n\n\t\t\t\t\t\/\/ was there an overlap before the current entry broke it?\n\t\t\t\t\tif (OIP) {\n\t\t\t\t\t\tif (this->numEntries) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcout << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << strands[s] << endl;\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\tif ((this->numEntries) && (numOnStrand > 0)) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (numOnStrand > 0) {\n\t\t\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << strands[s] << endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ reset things for the next overlapping \"block\"\n\t\t\t\t\tOIP = false;\n\t\t\t\t\tmergeCount = 1;\t\t\t\n\t\t\t\t\tminStart = INT_MAX;\n\t\t\t\t\tmaxEnd = 0;\n\t\t\t\t\tnames.clear();\n\t\t\t\t\t\n\t\t\t\t\t\/\/ add the name of the \n\t\t\t\t\tnames.push_back(bedList[prev].name);\n\t\t\t\t}\n\t\t\t\tprev = curr;\n\t\t\t}\n\n\t\t\t\/\/ clean up based on the last entry for the current chromosome\n\t\t\tif (OIP) {\n\t\t\t\tif (this->numEntries) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t\telse if (this->reportNames) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\";\n\t\t\t\t\tfor (unsigned int n = 0; n < names.size(); ++n) {\n\t\t\t\t\t\tif (n < (names.size() - 1)) {cout << names[n] << \";\";}\n\t\t\t\t\t\telse {cout << names[n];}\n\t\t\t\t\t}\n\t\t\t\t\tcout << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << minStart << \"\\t\" << maxEnd << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ((this->numEntries) && (numOnStrand > 0)) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << mergeCount << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t\telse if ((this->reportNames) && (numOnStrand > 0)) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << bedList[prev].name << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t\telse if (numOnStrand > 0) {\n\t\t\t\t\tcout << bedList[prev].chrom << \"\\t\" << bedList[prev].start << \"\\t\" << bedList[prev].end << \"\\t\" << strands[s] << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n * c7a\/api\/dia.hpp\n *\n * Interface for Operations, holds pointer to node and lambda from node to state\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_DIA_HEADER\n#define C7A_API_DIA_HEADER\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"dia_node.hpp\"\n#include \"function_traits.hpp\"\n#include \"lop_node.hpp\"\n#include \"zip_node.hpp\"\n#include \"read_node.hpp\"\n#include \"reduce_node.hpp\"\n#include \"context.hpp\"\n#include \"write_node.hpp\"\n\nnamespace c7a {\n\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * DIARef is the interface between the user and the c7a framework. A DIARef can\n * be imagined as an immutable array, even though the data does not need to be\n * materialized at all. A DIARef contains a pointer to a DIANode of type T,\n * which represents the state after the previous DOp or Action. Additionally, a\n * DIARef stores the local lambda function chain of type Stack, which can transform\n * elements of the DIANode to elements of this DIARef. DOps\/Actions create a\n * DIARef and a new DIANode, to which the DIARef links to. LOps only create a\n * new DIARef, which link to the previous DIANode.\n *\n * \\tparam T Type of elements in this DIARef.\n *\n * \\tparam Stack Type of the function chain.\n *\/\ntemplate >\nclass DIARef\n{\n friend class Context;\n using DIANodePtr = std::shared_ptr >;\n\npublic:\n \/*!\n * Constructor of a new DIARef with a pointer to a DIANode and a\n * function chain from the DIANode to this DIARef.\n *\n * \\param node Pointer to the last DIANode, DOps and Actions create a new\n * DIANode, LOps link to the DIANode of the previous DIARef.\n *\n * \\param stack Function stack consisting of functions between last DIANode\n * and this DIARef.\n *\/\n DIARef(DIANodePtr& node, Stack& stack)\n : node_(node),\n local_stack_(stack)\n { }\n\n \/*!\n * Constructor of a new DIARef supporting move semantics of nodes.\n *\n * \\param node Pointer to the last DIANode, DOps and Actions create a new\n * DIANode, LOps link to the DIANode of the previous DIARef.\n *\n * \\param stack Function stack consisting of functions between last DIANode\n * and this DIARef.\n *\/\n DIARef(DIANodePtr&& node, Stack& stack)\n : node_(std::move(node)),\n local_stack_(stack)\n { }\n\n \/*!\n * Copy-Constructor of a DIARef with empty function chain\n * from a DIARef with a non-empty chain.\n * The functionality of the chain is stored in a newly created LOpNode.\n * The current DIARef than points to this LOpNode.\n * This is needed to support assignment operations between DIARef's.\n *\n * \\param rhs DIA containing a non-empty function chain.\n *\/\n template \n DIARef(const DIARef& rhs) {\n \/\/ Create new LOpNode\n \/\/ Transfer stack from rhs to LOpNode\n \/\/ Build new DIARef with empty stack and LOpNode\n auto rhs_node = std::move(rhs.get_node());\n auto rhs_stack = rhs.get_stack();\n using LOpChainNode\n = LOpNode;\n\n auto shared_node\n = std::make_shared(rhs_node->get_context(),\n rhs_node,\n rhs_stack);\n node_ = std::move(shared_node);\n local_stack_ = FunctionStack<>();\n }\n\n \/*!\n * Returns a pointer to the according DIANode.\n *\/\n DIANode * get_node() const {\n return node_.get();\n }\n\n \/*!\n * Returns the number of references to the according DIANode.\n *\/\n int get_node_count() const {\n return node_.use_count();\n }\n\n \/*!\n * Returns the stored function chain.\n *\/\n Stack & get_stack() {\n return local_stack_;\n }\n\n \/*!\n * Map is a LOp, which maps this DIARef according to the map_fn given by the\n * user. The map_fn maps each element to another\n * element of a possibly different type. The DIARef returned by Map has the\n * same type T. The function chain of the returned DIARef is this DIARef's\n * local_stack_ chained with map_fn.\n *\n * \\tparam map_fn_t Type of the map function.\n *\n * \\param map_fn Map function of type map_fn_t, which maps each element to\n * an element of a possibly different type.\n *\n *\/\n template \n auto Map(const map_fn_t &map_fn) {\n using map_arg_t\n = typename FunctionTraits::template arg<0>;\n using map_result_t\n = typename FunctionTraits::result_type;\n auto conv_map_fn = [=](map_arg_t input, std::function emit_func) {\n emit_func(map_fn(input));\n };\n\n auto new_stack = local_stack_.push(conv_map_fn);\n return DIARef(node_, new_stack);\n }\n\n \/*!\n * Filter is a LOp, which filters elements from this DIARef\n * according to the filter_fn given by the\n * user. The filter_fn maps each element to a boolean.\n * The DIARef returned by Filter has the same type T.\n * The function chain of the returned DIARef is this DIARef's\n * local_stack_ chained with filter_fn.\n *\n * \\tparam filter_fn_t Type of the map function.\n *\n * \\param filter_fn Filter function of type filter_fn_t, which maps each element to\n * a boolean.\n *\n *\/\n template \n auto Filter(const filter_fn_t &filter_fn) {\n using filter_arg_t\n = typename FunctionTraits::template arg<0>;\n auto conv_filter_fn = [=](filter_arg_t input, std::function emit_func) {\n if (filter_fn(input)) emit_func(input);\n };\n\n auto new_stack = local_stack_.push(conv_filter_fn);\n return DIARef(node_, new_stack);\n }\n\n \/*!\n * FlatMap is a LOp, which maps this DIARef according to the flatmap_fn\n * given by the user. The flatmap_fn maps each element\n * to elements of a possibly different type. The flatmap_fn has an emitter\n * function as it's second parameter. This emitter is called once for each\n * element to be emitted. The DIARef returned by FlatMap has the same type\n * T. The function chain of the returned DIARef is this DIARef's\n * local_stack_ chained with flatmap_fn.\n *\n * \\tparam flatmap_fn_t Type of the map function.\n *\n * \\param flatmap_fn Map function of type map_fn_t, which maps each element\n * to elements of a possibly different type.\n *\/\n template \n auto FlatMap(const flatmap_fn_t &flatmap_fn) {\n auto new_stack = local_stack_.push(flatmap_fn);\n return DIARef(node_, new_stack);\n }\n\n \/*!\n * Reduce is a DOp, which groups elements of the DIARef with the\n * key_extractor and reduces each key-bucket to a single element using the\n * associative reduce_function. The reduce_function defines how two elements\n * can be reduced to a single element of equal type. Since Reduce is a DOp, it\n * creates a new DIANode. The DIARef returned by Reduce links to this newly\n * created DIANode. The local_stack_ of the returned DIARef consists of\n * the PostOp of Reduce, as a reduced element can\n * directly be chained to the following LOps.\n *\n * \\tparam key_extr_fn_t Type of the key_extractor function.\n * The key_extractor function is equal to a map function.\n *\n * \\param key_extractor Key extractor function, which maps each element to a\n * key of possibly different type.\n *\n *\/\n template \n auto ReduceBy(const key_extr_fn_t &key_extractor) {\n return ReduceSugar(key_extractor, node_.get(), local_stack_);\n }\n\n \/*!\n * Zip is a DOp, which Zips two DIAs in style of functional programming. The\n * zip_function is used to zip the i-th elements of both input DIAs together\n * to form the i-th element of the output DIARef. The type of the output\n * DIARef can be inferred from the zip_function.\n *\n * \\tparam zip_fn_t Type of the zip_function. This is a function with two\n * input elements, both of the local type, and one output element, which is\n * the type of the Zip node.\n *\n * \\param zip_fn Zip function, which zips two elements together\n *\n * \\param second_dia DIARef, which is zipped together with the original\n * DIARef.\n *\/\n template \n auto Zip(const zip_fn_t &zip_fn, second_dia_t second_dia) {\n using zip_result_t\n = typename FunctionTraits::result_type;\n using zip_arg_0_t\n = typename FunctionTraits::template arg<0>;\n using zip_arg_1_t\n = typename FunctionTraits::template arg<1>;\n using ZipResultNode\n = TwoZipNode;\n\n auto shared_node\n = std::make_shared(node_->get_context(),\n node_.get(),\n second_dia.get_node(),\n local_stack_,\n second_dia.get_stack(),\n zip_fn);\n\n auto zip_stack = shared_node->ProduceStack();\n return DIARef\n (std::move(shared_node), zip_stack);\n }\n\n template \n void WriteToFileSystem(std::string filepath,\n const write_fn_t &write_fn) {\n using write_result_t = typename FunctionTraits::result_type;\n\n using WriteResultNode = WriteNode;\n\n auto shared_node =\n std::make_shared(node_->get_context(),\n node_.get(),\n write_fn,\n filepath);\n\n shared_node->ProduceStack();\n }\n\n \/*!\n * Returns Chuck Norris!\n *\n * \\return Chuck Norris\n *\/\n const std::vector & evil_get_data() const {\n return (std::vector{ T() });\n }\n\n \/*!\n * Returns the string which defines the DIANode node_.\n *\n * \\return The string of node_\n *\/\n std::string NodeString() {\n return node_->ToString();\n }\n\n \/*!\n * Prints the DIANode and all it's children recursively. The printing is\n * performed tree-style.\n *\/\n void PrintNodes() {\n using BasePair = std::pair;\n std::stack dia_stack;\n dia_stack.push(std::make_pair(node_, 0));\n while (!dia_stack.empty()) {\n auto curr = dia_stack.top();\n auto node = curr.first;\n int depth = curr.second;\n dia_stack.pop();\n auto is_end = true;\n if (!dia_stack.empty()) is_end = dia_stack.top().second < depth;\n for (int i = 0; i < depth - 1; ++i) {\n std::cout << \"│ \";\n }\n if (is_end && depth > 0) std::cout << \"└── \";\n else if (depth > 0) std::cout << \"├── \";\n std::cout << node->ToString() << std::endl;\n auto children = node->get_childs();\n for (auto c : children) {\n dia_stack.push(std::make_pair(c, depth + 1));\n }\n }\n }\n\nprivate:\n \/\/! The DIANode which DIARef points to. The node represents the latest DOp\n \/\/! or Action performed previously.\n DIANodePtr node_;\n\n \/\/! The local function chain, which stores the chained lambda function from\n \/\/! the last DIANode to this DIARef.\n Stack local_stack_;\n\n \/*!\n * Syntactic sugaaah for reduce\n *\/\n template \n class ReduceSugar\n {\n public:\n ReduceSugar(const key_extr_fn_t& key_extractor, DIANode* node, Stack& local_stack)\n : key_extractor_(key_extractor), node_(node), local_stack_(local_stack) { }\n\n \/*!\n * Syntactic sugaaah\n *\n * \\tparam reduce_fn_t Type of the reduce_function. This is a function\n * reducing two elements of L's result type to a single element of equal\n * type.\n *\n * \\param reduce_function Reduce function, which defines how the key\n * buckets are reduced to a single element. This function is applied\n * associative but not necessarily commutative.\n *\n *\/\n template \n auto With(const reduce_fn_t &reduce_function) {\n using dop_result_t\n = typename FunctionTraits::result_type;\n using ReduceResultNode\n = ReduceNode;\n\n auto shared_node\n = std::make_shared(node_->get_context(),\n node_,\n local_stack_,\n key_extractor_,\n reduce_function);\n\n auto reduce_stack = shared_node->ProduceStack();\n\n return DIARef\n (std::move(shared_node), reduce_stack);\n }\n\n private:\n const key_extr_fn_t& key_extractor_;\n DIANode* node_;\n Stack& local_stack_;\n };\n};\n\n\/\/! \\}\n\ntemplate \nauto ReadFromFileSystem(Context & ctx, std::string filepath,\n const read_fn_t &read_fn) {\n using read_result_t = typename FunctionTraits::result_type;\n using ReadResultNode = ReadNode;\n\n auto shared_node =\n std::make_shared(ctx,\n read_fn,\n filepath);\n\n auto read_stack = shared_node->ProduceStack();\n\n return DIARef\n (std::move(shared_node), read_stack);\n}\n\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_API_DIA_HEADER\n\n\/******************************************************************************\/\nadded doc to WriteToFileSystem\/*******************************************************************************\n * c7a\/api\/dia.hpp\n *\n * Interface for Operations, holds pointer to node and lambda from node to state\n *\n * Part of Project c7a.\n *\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_DIA_HEADER\n#define C7A_API_DIA_HEADER\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"dia_node.hpp\"\n#include \"function_traits.hpp\"\n#include \"lop_node.hpp\"\n#include \"zip_node.hpp\"\n#include \"read_node.hpp\"\n#include \"reduce_node.hpp\"\n#include \"context.hpp\"\n#include \"write_node.hpp\"\n\nnamespace c7a {\n\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * DIARef is the interface between the user and the c7a framework. A DIARef can\n * be imagined as an immutable array, even though the data does not need to be\n * materialized at all. A DIARef contains a pointer to a DIANode of type T,\n * which represents the state after the previous DOp or Action. Additionally, a\n * DIARef stores the local lambda function chain of type Stack, which can transform\n * elements of the DIANode to elements of this DIARef. DOps\/Actions create a\n * DIARef and a new DIANode, to which the DIARef links to. LOps only create a\n * new DIARef, which link to the previous DIANode.\n *\n * \\tparam T Type of elements in this DIARef.\n *\n * \\tparam Stack Type of the function chain.\n *\/\ntemplate >\nclass DIARef\n{\n friend class Context;\n using DIANodePtr = std::shared_ptr >;\n\npublic:\n \/*!\n * Constructor of a new DIARef with a pointer to a DIANode and a\n * function chain from the DIANode to this DIARef.\n *\n * \\param node Pointer to the last DIANode, DOps and Actions create a new\n * DIANode, LOps link to the DIANode of the previous DIARef.\n *\n * \\param stack Function stack consisting of functions between last DIANode\n * and this DIARef.\n *\/\n DIARef(DIANodePtr& node, Stack& stack)\n : node_(node),\n local_stack_(stack)\n { }\n\n \/*!\n * Constructor of a new DIARef supporting move semantics of nodes.\n *\n * \\param node Pointer to the last DIANode, DOps and Actions create a new\n * DIANode, LOps link to the DIANode of the previous DIARef.\n *\n * \\param stack Function stack consisting of functions between last DIANode\n * and this DIARef.\n *\/\n DIARef(DIANodePtr&& node, Stack& stack)\n : node_(std::move(node)),\n local_stack_(stack)\n { }\n\n \/*!\n * Copy-Constructor of a DIARef with empty function chain\n * from a DIARef with a non-empty chain.\n * The functionality of the chain is stored in a newly created LOpNode.\n * The current DIARef than points to this LOpNode.\n * This is needed to support assignment operations between DIARef's.\n *\n * \\param rhs DIA containing a non-empty function chain.\n *\/\n template \n DIARef(const DIARef& rhs) {\n \/\/ Create new LOpNode\n \/\/ Transfer stack from rhs to LOpNode\n \/\/ Build new DIARef with empty stack and LOpNode\n auto rhs_node = std::move(rhs.get_node());\n auto rhs_stack = rhs.get_stack();\n using LOpChainNode\n = LOpNode;\n\n auto shared_node\n = std::make_shared(rhs_node->get_context(),\n rhs_node,\n rhs_stack);\n node_ = std::move(shared_node);\n local_stack_ = FunctionStack<>();\n }\n\n \/*!\n * Returns a pointer to the according DIANode.\n *\/\n DIANode * get_node() const {\n return node_.get();\n }\n\n \/*!\n * Returns the number of references to the according DIANode.\n *\/\n int get_node_count() const {\n return node_.use_count();\n }\n\n \/*!\n * Returns the stored function chain.\n *\/\n Stack & get_stack() {\n return local_stack_;\n }\n\n \/*!\n * Map is a LOp, which maps this DIARef according to the map_fn given by the\n * user. The map_fn maps each element to another\n * element of a possibly different type. The DIARef returned by Map has the\n * same type T. The function chain of the returned DIARef is this DIARef's\n * local_stack_ chained with map_fn.\n *\n * \\tparam map_fn_t Type of the map function.\n *\n * \\param map_fn Map function of type map_fn_t, which maps each element to\n * an element of a possibly different type.\n *\n *\/\n template \n auto Map(const map_fn_t &map_fn) {\n using map_arg_t\n = typename FunctionTraits::template arg<0>;\n using map_result_t\n = typename FunctionTraits::result_type;\n auto conv_map_fn = [=](map_arg_t input, std::function emit_func) {\n emit_func(map_fn(input));\n };\n\n auto new_stack = local_stack_.push(conv_map_fn);\n return DIARef(node_, new_stack);\n }\n\n \/*!\n * Filter is a LOp, which filters elements from this DIARef\n * according to the filter_fn given by the\n * user. The filter_fn maps each element to a boolean.\n * The DIARef returned by Filter has the same type T.\n * The function chain of the returned DIARef is this DIARef's\n * local_stack_ chained with filter_fn.\n *\n * \\tparam filter_fn_t Type of the map function.\n *\n * \\param filter_fn Filter function of type filter_fn_t, which maps each element to\n * a boolean.\n *\n *\/\n template \n auto Filter(const filter_fn_t &filter_fn) {\n using filter_arg_t\n = typename FunctionTraits::template arg<0>;\n auto conv_filter_fn = [=](filter_arg_t input, std::function emit_func) {\n if (filter_fn(input)) emit_func(input);\n };\n\n auto new_stack = local_stack_.push(conv_filter_fn);\n return DIARef(node_, new_stack);\n }\n\n \/*!\n * FlatMap is a LOp, which maps this DIARef according to the flatmap_fn\n * given by the user. The flatmap_fn maps each element\n * to elements of a possibly different type. The flatmap_fn has an emitter\n * function as it's second parameter. This emitter is called once for each\n * element to be emitted. The DIARef returned by FlatMap has the same type\n * T. The function chain of the returned DIARef is this DIARef's\n * local_stack_ chained with flatmap_fn.\n *\n * \\tparam flatmap_fn_t Type of the map function.\n *\n * \\param flatmap_fn Map function of type map_fn_t, which maps each element\n * to elements of a possibly different type.\n *\/\n template \n auto FlatMap(const flatmap_fn_t &flatmap_fn) {\n auto new_stack = local_stack_.push(flatmap_fn);\n return DIARef(node_, new_stack);\n }\n\n \/*!\n * Reduce is a DOp, which groups elements of the DIARef with the\n * key_extractor and reduces each key-bucket to a single element using the\n * associative reduce_function. The reduce_function defines how two elements\n * can be reduced to a single element of equal type. Since Reduce is a DOp, it\n * creates a new DIANode. The DIARef returned by Reduce links to this newly\n * created DIANode. The local_stack_ of the returned DIARef consists of\n * the PostOp of Reduce, as a reduced element can\n * directly be chained to the following LOps.\n *\n * \\tparam key_extr_fn_t Type of the key_extractor function.\n * The key_extractor function is equal to a map function.\n *\n * \\param key_extractor Key extractor function, which maps each element to a\n * key of possibly different type.\n *\n *\/\n template \n auto ReduceBy(const key_extr_fn_t &key_extractor) {\n return ReduceSugar(key_extractor, node_.get(), local_stack_);\n }\n\n \/*!\n * Zip is a DOp, which Zips two DIAs in style of functional programming. The\n * zip_function is used to zip the i-th elements of both input DIAs together\n * to form the i-th element of the output DIARef. The type of the output\n * DIARef can be inferred from the zip_function.\n *\n * \\tparam zip_fn_t Type of the zip_function. This is a function with two\n * input elements, both of the local type, and one output element, which is\n * the type of the Zip node.\n *\n * \\param zip_fn Zip function, which zips two elements together\n *\n * \\param second_dia DIARef, which is zipped together with the original\n * DIARef.\n *\/\n template \n auto Zip(const zip_fn_t &zip_fn, second_dia_t second_dia) {\n using zip_result_t\n = typename FunctionTraits::result_type;\n using zip_arg_0_t\n = typename FunctionTraits::template arg<0>;\n using zip_arg_1_t\n = typename FunctionTraits::template arg<1>;\n using ZipResultNode\n = TwoZipNode;\n\n auto shared_node\n = std::make_shared(node_->get_context(),\n node_.get(),\n second_dia.get_node(),\n local_stack_,\n second_dia.get_stack(),\n zip_fn);\n\n auto zip_stack = shared_node->ProduceStack();\n return DIARef\n (std::move(shared_node), zip_stack);\n }\n\n \/*!\n * WriteToFileSystem is an Action, which writes elements to an output file. A\n * provided function is used prepare the elements before written.\n *\n * \\tparam write_fn_t Type of the write_function. This is a function with one\n * input element of the local type.\n *\n * \\param write_fn Write function, which prepares an element to be written to disk.\n *\n * \\param filepath Destination of the output file.\n *\/\n template \n void WriteToFileSystem(std::string filepath,\n const write_fn_t &write_fn) {\n using write_result_t = typename FunctionTraits::result_type;\n\n using WriteResultNode = WriteNode;\n\n auto shared_node =\n std::make_shared(node_->get_context(),\n node_.get(),\n write_fn,\n filepath);\n\n shared_node->ProduceStack();\n }\n\n \/*!\n * Returns Chuck Norris!\n *\n * \\return Chuck Norris\n *\/\n const std::vector & evil_get_data() const {\n return (std::vector{ T() });\n }\n\n \/*!\n * Returns the string which defines the DIANode node_.\n *\n * \\return The string of node_\n *\/\n std::string NodeString() {\n return node_->ToString();\n }\n\n \/*!\n * Prints the DIANode and all it's children recursively. The printing is\n * performed tree-style.\n *\/\n void PrintNodes() {\n using BasePair = std::pair;\n std::stack dia_stack;\n dia_stack.push(std::make_pair(node_, 0));\n while (!dia_stack.empty()) {\n auto curr = dia_stack.top();\n auto node = curr.first;\n int depth = curr.second;\n dia_stack.pop();\n auto is_end = true;\n if (!dia_stack.empty()) is_end = dia_stack.top().second < depth;\n for (int i = 0; i < depth - 1; ++i) {\n std::cout << \"│ \";\n }\n if (is_end && depth > 0) std::cout << \"└── \";\n else if (depth > 0) std::cout << \"├── \";\n std::cout << node->ToString() << std::endl;\n auto children = node->get_childs();\n for (auto c : children) {\n dia_stack.push(std::make_pair(c, depth + 1));\n }\n }\n }\n\nprivate:\n \/\/! The DIANode which DIARef points to. The node represents the latest DOp\n \/\/! or Action performed previously.\n DIANodePtr node_;\n\n \/\/! The local function chain, which stores the chained lambda function from\n \/\/! the last DIANode to this DIARef.\n Stack local_stack_;\n\n \/*!\n * Syntactic sugaaah for reduce\n *\/\n template \n class ReduceSugar\n {\n public:\n ReduceSugar(const key_extr_fn_t& key_extractor, DIANode* node, Stack& local_stack)\n : key_extractor_(key_extractor), node_(node), local_stack_(local_stack) { }\n\n \/*!\n * Syntactic sugaaah\n *\n * \\tparam reduce_fn_t Type of the reduce_function. This is a function\n * reducing two elements of L's result type to a single element of equal\n * type.\n *\n * \\param reduce_function Reduce function, which defines how the key\n * buckets are reduced to a single element. This function is applied\n * associative but not necessarily commutative.\n *\n *\/\n template \n auto With(const reduce_fn_t &reduce_function) {\n using dop_result_t\n = typename FunctionTraits::result_type;\n using ReduceResultNode\n = ReduceNode;\n\n auto shared_node\n = std::make_shared(node_->get_context(),\n node_,\n local_stack_,\n key_extractor_,\n reduce_function);\n\n auto reduce_stack = shared_node->ProduceStack();\n\n return DIARef\n (std::move(shared_node), reduce_stack);\n }\n\n private:\n const key_extr_fn_t& key_extractor_;\n DIANode* node_;\n Stack& local_stack_;\n };\n};\n\n\/\/! \\}\n\ntemplate \nauto ReadFromFileSystem(Context & ctx, std::string filepath,\n const read_fn_t &read_fn) {\n using read_result_t = typename FunctionTraits::result_type;\n using ReadResultNode = ReadNode;\n\n auto shared_node =\n std::make_shared(ctx,\n read_fn,\n filepath);\n\n auto read_stack = shared_node->ProduceStack();\n\n return DIARef\n (std::move(shared_node), read_stack);\n}\n\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_API_DIA_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"\/****************************************************************************\n** Meta object code from reading C++ file 'LogDock.h'\n**\n** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5)\n**\n** WARNING! All changes made in this file will be lost!\n*****************************************************************************\/\n\n#include \"src\/Widgets\/LogDock.h\"\n#if !defined(Q_MOC_OUTPUT_REVISION)\n#error \"The header file 'LogDock.h' doesn't include .\"\n#elif Q_MOC_OUTPUT_REVISION != 63\n#error \"This file was generated using the moc from 4.8.5. It\"\n#error \"cannot be used with the include files from this version of Qt.\"\n#error \"(The moc has changed too much.)\"\n#endif\n\nQT_BEGIN_MOC_NAMESPACE\nstatic const uint qt_meta_data_LogDock[] = {\n\n \/\/ content:\n 6, \/\/ revision\n 0, \/\/ classname\n 0, 0, \/\/ classinfo\n 0, 0, \/\/ methods\n 0, 0, \/\/ properties\n 0, 0, \/\/ enums\/sets\n 0, 0, \/\/ constructors\n 0, \/\/ flags\n 0, \/\/ signalCount\n\n 0 \/\/ eod\n};\n\nstatic const char qt_meta_stringdata_LogDock[] = {\n \"LogDock\\0\"\n};\n\nvoid LogDock::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)\n{\n Q_UNUSED(_o);\n Q_UNUSED(_id);\n Q_UNUSED(_c);\n Q_UNUSED(_a);\n}\n\nconst QMetaObjectExtraData LogDock::staticMetaObjectExtraData = {\n 0, qt_static_metacall \n};\n\nconst QMetaObject LogDock::staticMetaObject = {\n { &QDockWidget::staticMetaObject, qt_meta_stringdata_LogDock,\n qt_meta_data_LogDock, &staticMetaObjectExtraData }\n};\n\n#ifdef Q_NO_DATA_RELOCATION\nconst QMetaObject &LogDock::getStaticMetaObject() { return staticMetaObject; }\n#endif \/\/Q_NO_DATA_RELOCATION\n\nconst QMetaObject *LogDock::metaObject() const\n{\n return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;\n}\n\nvoid *LogDock::qt_metacast(const char *_clname)\n{\n if (!_clname) return 0;\n if (!strcmp(_clname, qt_meta_stringdata_LogDock))\n return static_cast(const_cast< LogDock*>(this));\n return QDockWidget::qt_metacast(_clname);\n}\n\nint LogDock::qt_metacall(QMetaObject::Call _c, int _id, void **_a)\n{\n _id = QDockWidget::qt_metacall(_c, _id, _a);\n if (_id < 0)\n return _id;\n return _id;\n}\nQT_END_MOC_NAMESPACE\nDelete moc_LogDock.cpp<|endoftext|>"} {"text":"\/*\n * Copyright 2015-2017 Two Pore Guys, Inc.\n * All rights reserved\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted providing that the following conditions\n * 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 *\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\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"catch.hpp\"\n\n#include \n#include \"..\/src\/internal.h\"\n\n#include \n\nSCENARIO(\"RPC_NULL_OBJECT\", \"Create a NULL RPC object and perform basic operations on it\") {\n\tGIVEN(\"BOOL object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t copy;\n\t\tobject = rpc_null_create();\n\n\t\tTHEN(\"Type is NULL\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_NULL);\n\t\t}\n\n\t\tAND_THEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nSCENARIO(\"RPC_BOOL_OBJECT\", \"Create a BOOL RPC object and perform basic operations on it\") {\n\tGIVEN(\"BOOL object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tbool value = true;\n\t\tbool different_value = false;\n\t\tobject = rpc_bool_create(value);\n\t\tdifferent_object = rpc_bool_create(different_value);\n\n\t\tTHEN(\"Type is BOOL\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_BOOL);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_bool_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_b == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_UINT64_OBJECT\", \"Create a UINT64 RPC object and perform basic operations on it\") {\n\tGIVEN(\"UINT64 object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tuint64_t value = 1234;\n\t\tuint64_t different_value = 5678;\n\t\tobject = rpc_uint64_create(value);\n\t\tdifferent_object = rpc_uint64_create(different_value);\n\n\t\tTHEN(\"Type is UINT64\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_UINT64);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_uint64_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_ui == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_INT64_OBJECT\", \"Create a INT64 RPC object and perform basic operations on it\") {\n\tGIVEN(\"INT64 object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tint64_t value = 1234;\n\t\tint64_t different_value = -1234;\n\t\tobject = rpc_int64_create(value);\n\t\tdifferent_object = rpc_int64_create(different_value);\n\n\t\tTHEN(\"Type is INT64\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_INT64);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_int64_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_i == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_DOUBLE_OBJECT\", \"Create a DOUBLE RPC object and perform basic operations on it\") {\n\tGIVEN(\"DOUBLE object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tdouble value = 12.34;\n\t\tdouble different_value = -12.34;\n\t\tobject = rpc_double_create(value);\n\t\tdifferent_object = rpc_double_create(different_value);\n\n\t\tTHEN(\"Type is DOUBLE\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_DOUBLE);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_double_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_d == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_DESCRIPTION_TEST\", \"Create a tree of RPC objects and print their description\") {\n\tGIVEN(\"RPC objects tree\") {\n\t\tint data = 0xff00ff00;\n\t\tstatic const char *referene = \" {\\n\"\n\t\t \" null_val: ,\\n\"\n\t\t \" array: [\\n\"\n\t\t \" 0: ,\\n\"\n\t\t \" 1: true,\\n\"\n\t\t \" 2: 1234,\\n\"\n\t\t \" 3: -1234,\\n\"\n\t\t \" 4: 12.340000,\\n\"\n\t\t \" 5: 1970-01-01 00:00:00,\\n\"\n\t\t \" 6: \\\"test string\\\",\\n\"\n\t\t \" 7: 00ff00ff,\\n\"\n\t\t \" 8: 10,\\n\"\n\t\t \" ],\\n\"\n\t\t \" test_string2: \\\"test_test_test\\\",\\n\"\n\t\t \"}\\n\";\n\n\t\trpc_object_t null = rpc_null_create();\n\t\trpc_object_t boolean = rpc_bool_create(true);\n\t\trpc_object_t u_integer = rpc_uint64_create(1234);\n\t\trpc_object_t integer = rpc_int64_create(-1234);\n\t\trpc_object_t dbl = rpc_double_create(12.34);\n\t\trpc_object_t date = rpc_date_create(0);\n\t\trpc_object_t string = rpc_string_create(\"test string\");\n\t\trpc_object_t binary = rpc_data_create(&data, sizeof(data), false);\n\t\trpc_object_t fd = rpc_fd_create(10);\n\t\trpc_object_t dict = rpc_dictionary_create();\n\t\trpc_object_t array = rpc_array_create();\n\n\t\trpc_array_append_stolen_value(array, null);\n\t\trpc_array_append_stolen_value(array, boolean);\n\t\trpc_array_append_stolen_value(array, u_integer);\n\t\trpc_array_append_stolen_value(array, integer);\n\t\trpc_array_append_stolen_value(array, dbl);\n\t\trpc_array_append_stolen_value(array, date);\n\t\trpc_array_append_stolen_value(array, string);\n\t\trpc_array_append_stolen_value(array, binary);\n\t\trpc_array_append_stolen_value(array, fd);\n\n\t\trpc_dictionary_set_value(dict, \"null_val\", null);\n\t\trpc_dictionary_set_value(dict, \"array\", array);\n\n\t\trpc_dictionary_set_string(dict, \"test_string2\", \"test_test_test\");\n\n\t\tTHEN(\"Parent RPC object's description is equal to refrence description\") {\n\t\t\tREQUIRE(g_strcmp0(referene, rpc_copy_description(dict)) == 0);\n\t\t}\n\t}\n}\nFIXED: make sure to free memory in tests\/*\n * Copyright 2015-2017 Two Pore Guys, Inc.\n * All rights reserved\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted providing that the following conditions\n * 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 *\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\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \"catch.hpp\"\n\n#include \n#include \"..\/src\/internal.h\"\n\nSCENARIO(\"RPC_NULL_OBJECT\", \"Create a NULL RPC object and perform basic operations on it\") {\n\tGIVEN(\"BOOL object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t copy;\n\t\tobject = rpc_null_create();\n\n\t\tTHEN(\"Type is NULL\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_NULL);\n\t\t}\n\n\t\tAND_THEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nSCENARIO(\"RPC_BOOL_OBJECT\", \"Create a BOOL RPC object and perform basic operations on it\") {\n\tGIVEN(\"BOOL object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tbool value = true;\n\t\tbool different_value = false;\n\t\tobject = rpc_bool_create(value);\n\t\tdifferent_object = rpc_bool_create(different_value);\n\n\t\tTHEN(\"Type is BOOL\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_BOOL);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_bool_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_b == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_UINT64_OBJECT\", \"Create a UINT64 RPC object and perform basic operations on it\") {\n\tGIVEN(\"UINT64 object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tuint64_t value = 1234;\n\t\tuint64_t different_value = 5678;\n\t\tobject = rpc_uint64_create(value);\n\t\tdifferent_object = rpc_uint64_create(different_value);\n\n\t\tTHEN(\"Type is UINT64\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_UINT64);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_uint64_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_ui == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_INT64_OBJECT\", \"Create a INT64 RPC object and perform basic operations on it\") {\n\tGIVEN(\"INT64 object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tint64_t value = 1234;\n\t\tint64_t different_value = -1234;\n\t\tobject = rpc_int64_create(value);\n\t\tdifferent_object = rpc_int64_create(different_value);\n\n\t\tTHEN(\"Type is INT64\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_INT64);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_int64_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_i == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_DOUBLE_OBJECT\", \"Create a DOUBLE RPC object and perform basic operations on it\") {\n\tGIVEN(\"DOUBLE object\") {\n\t\trpc_object_t object;\n\t\trpc_object_t different_object;\n\t\trpc_object_t copy;\n\t\tdouble value = 12.34;\n\t\tdouble different_value = -12.34;\n\t\tobject = rpc_double_create(value);\n\t\tdifferent_object = rpc_double_create(different_value);\n\n\t\tTHEN(\"Type is DOUBLE\") {\n\t\t\tREQUIRE(rpc_get_type(object) == RPC_TYPE_DOUBLE);\n\t\t}\n\n\t\tTHEN(\"Refcount equals 1\") {\n\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t}\n\n\t\tTHEN(\"Extracted value matches\") {\n\t\t\tREQUIRE(rpc_double_get_value(object) == value);\n\t\t}\n\n\t\tAND_THEN(\"Direct value matches\") {\n\t\t\tREQUIRE(object->ro_value.rv_d == value);\n\t\t}\n\n\t\tWHEN(\"Object's copy is created\") {\n\t\t\tcopy = rpc_copy(object);\n\n\t\t\tTHEN(\"Source and copy are equal\"){\n\t\t\t\tREQUIRE(rpc_equal(object, copy));\n\t\t\t}\n\n\t\t\tAND_THEN(\"Object is different from object initialized with different value\") {\n\t\t\t\tREQUIRE(!rpc_equal(object, different_object));\n\t\t\t}\n\t\t}\n\n\t\tWHEN(\"reference count is incremented\") {\n\t\t\trpc_retain(object);\n\n\t\t\tTHEN(\"reference count equals 2\"){\n\t\t\t\tREQUIRE(object->ro_refcnt == 2);\n\t\t\t}\n\n\t\t\tAND_WHEN(\"reference count is decremented\") {\n\t\t\t\trpc_release(object);\n\n\t\t\t\tTHEN(\"reference count equals 1\") {\n\t\t\t\t\tREQUIRE(object->ro_refcnt == 1);\n\t\t\t\t}\n\n\t\t\t\tAND_WHEN(\"reference count reaches 0\") {\n\t\t\t\t\trpc_release(object);\n\n\t\t\t\t\tTHEN(\"RPC object pointer is NULL\") {\n\t\t\t\t\t\tREQUIRE(object == NULL);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trpc_release(different_object);\n\t}\n}\n\nSCENARIO(\"RPC_DESCRIPTION_TEST\", \"Create a tree of RPC objects and print their description\") {\n\tGIVEN(\"RPC objects tree\") {\n\t\tint data = 0xff00ff00;\n\t\tstatic const char *referene = \" {\\n\"\n\t\t \" null_val: ,\\n\"\n\t\t \" array: [\\n\"\n\t\t \" 0: ,\\n\"\n\t\t \" 1: true,\\n\"\n\t\t \" 2: 1234,\\n\"\n\t\t \" 3: -1234,\\n\"\n\t\t \" 4: 12.340000,\\n\"\n\t\t \" 5: 1970-01-01 00:00:00,\\n\"\n\t\t \" 6: \\\"test string\\\",\\n\"\n\t\t \" 7: 00ff00ff,\\n\"\n\t\t \" 8: 10,\\n\"\n\t\t \" ],\\n\"\n\t\t \" test_string2: \\\"test_test_test\\\",\\n\"\n\t\t \"}\\n\";\n\n\t\trpc_object_t null = rpc_null_create();\n\t\trpc_object_t boolean = rpc_bool_create(true);\n\t\trpc_object_t u_integer = rpc_uint64_create(1234);\n\t\trpc_object_t integer = rpc_int64_create(-1234);\n\t\trpc_object_t dbl = rpc_double_create(12.34);\n\t\trpc_object_t date = rpc_date_create(0);\n\t\trpc_object_t string = rpc_string_create(\"test string\");\n\t\trpc_object_t binary = rpc_data_create(&data, sizeof(data), false);\n\t\trpc_object_t fd = rpc_fd_create(10);\n\t\trpc_object_t dict = rpc_dictionary_create();\n\t\trpc_object_t array = rpc_array_create();\n\n\t\trpc_array_append_stolen_value(array, null);\n\t\trpc_array_append_stolen_value(array, boolean);\n\t\trpc_array_append_stolen_value(array, u_integer);\n\t\trpc_array_append_stolen_value(array, integer);\n\t\trpc_array_append_stolen_value(array, dbl);\n\t\trpc_array_append_stolen_value(array, date);\n\t\trpc_array_append_stolen_value(array, string);\n\t\trpc_array_append_stolen_value(array, binary);\n\t\trpc_array_append_stolen_value(array, fd);\n\n\t\trpc_dictionary_set_value(dict, \"null_val\", null);\n\t\trpc_dictionary_set_value(dict, \"array\", array);\n\n\t\trpc_dictionary_set_string(dict, \"test_string2\", \"test_test_test\");\n\n\t\tTHEN(\"Parent RPC object's description is equal to refrence description\") {\n\t\t\tREQUIRE(g_strcmp0(referene, rpc_copy_description(dict)) == 0);\n\t\t}\n\n\t\trpc_release(dict);\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastructure 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 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#include \"global_id_generator.hpp\"\n#include \"exception.hpp\"\n#include \n\n#ifndef ATOMIC_I8_SUPPORT\n#include \n#include \n#endif\n\nnamespace jubatus { namespace common {\n\nclass global_id_generator_impl {\n private:\n bool is_standalone_;\n uint64_t counter_;\n std::string path_;\n cshared_ptr ls_;\n\n#ifndef ATOMIC_I8_SUPPORT\n pfi::concurrent::mutex counter_mutex_;\n#endif\n\n public:\n global_id_generator_impl():\n is_standalone_(true),\n counter_(0)\n {}\n\n global_id_generator_impl(bool is_standalone):\n is_standalone_(is_standalone),\n counter_(0)\n {}\n\n uint64_t generate()\n {\n if(is_standalone_){\n\n#ifdef ATOMIC_I8_SUPPORT\n return __sync_fetch_and_add(&counter_, 1);\n#else\n pfi::concurrent::scoped_lock lk(counter_mutex_);\n return ++counter_;\n#endif\n\n }else{\n\n#ifdef HAVE_ZOOKEEPER_H\n uint64_t res;\n if (ls_->create_id(path_, 0, res))\n return res;\n else\n throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error(\"Failed to create id\"));\n#else\n \/\/ never reaches here\n assert(is_standalone_);\n return 0; \/\/ dummy to remove warning\n#endif\n\n }\n }\n\n void set_ls(cshared_ptr& ls,\n const std::string& path_prefix)\n {\n\n#ifdef HAVE_ZOOKEEPER_H\n if (!is_standalone_) {\n path_ = path_prefix + \"\/id_generator\";\n ls_ = ls;\n if (!ls_->create(path_))\n throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error(\"Failed to create global id generator\")\n << jubatus::exception::error_api_func(\"lock_service::create\")\n << jubatus::exception::error_message(path_));\n }\n#endif\n\n }\n};\n\nglobal_id_generator::global_id_generator():\n pimpl_(new global_id_generator_impl())\n{}\n\nglobal_id_generator::global_id_generator(bool is_standalone):\n pimpl_(new global_id_generator_impl(is_standalone))\n{}\n\nglobal_id_generator::~global_id_generator()\n{}\n\nuint64_t global_id_generator::generate()\n{\n return pimpl_->generate();\n}\n\nvoid global_id_generator::set_ls(cshared_ptr& ls,\n const std::string& path_prefix)\n{\n pimpl_->set_ls(ls, path_prefix);\n}\n\n}}\nfix initial value of global_id_generator (fix #165)\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastructure 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 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#include \"global_id_generator.hpp\"\n#include \"exception.hpp\"\n#include \n\n#ifndef ATOMIC_I8_SUPPORT\n#include \n#include \n#endif\n\nnamespace jubatus { namespace common {\n\nclass global_id_generator_impl {\n private:\n bool is_standalone_;\n uint64_t counter_;\n std::string path_;\n cshared_ptr ls_;\n\n#ifndef ATOMIC_I8_SUPPORT\n pfi::concurrent::mutex counter_mutex_;\n#endif\n\n public:\n global_id_generator_impl():\n is_standalone_(true),\n counter_(0)\n {}\n\n global_id_generator_impl(bool is_standalone):\n is_standalone_(is_standalone),\n counter_(0)\n {}\n\n uint64_t generate()\n {\n if(is_standalone_){\n\n#ifdef ATOMIC_I8_SUPPORT\n return __sync_fetch_and_add(&counter_, 1);\n#else\n pfi::concurrent::scoped_lock lk(counter_mutex_);\n return counter_++;\n#endif\n\n }else{\n\n#ifdef HAVE_ZOOKEEPER_H\n uint64_t res;\n if (ls_->create_id(path_, 0, res))\n return res;\n else\n throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error(\"Failed to create id\"));\n#else\n \/\/ never reaches here\n assert(is_standalone_);\n return 0; \/\/ dummy to remove warning\n#endif\n\n }\n }\n\n void set_ls(cshared_ptr& ls,\n const std::string& path_prefix)\n {\n\n#ifdef HAVE_ZOOKEEPER_H\n if (!is_standalone_) {\n path_ = path_prefix + \"\/id_generator\";\n ls_ = ls;\n if (!ls_->create(path_))\n throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error(\"Failed to create global id generator\")\n << jubatus::exception::error_api_func(\"lock_service::create\")\n << jubatus::exception::error_message(path_));\n }\n#endif\n\n }\n};\n\nglobal_id_generator::global_id_generator():\n pimpl_(new global_id_generator_impl())\n{}\n\nglobal_id_generator::global_id_generator(bool is_standalone):\n pimpl_(new global_id_generator_impl(is_standalone))\n{}\n\nglobal_id_generator::~global_id_generator()\n{}\n\nuint64_t global_id_generator::generate()\n{\n return pimpl_->generate();\n}\n\nvoid global_id_generator::set_ls(cshared_ptr& ls,\n const std::string& path_prefix)\n{\n pimpl_->set_ls(ls, path_prefix);\n}\n\n}}\n<|endoftext|>"} {"text":"#include \"invertebrate.h\"\n\nInvertebrate::Invertebrate()\n{\n\n}\n\nbool Invertebrate::operator <(const Invertebrate& inv) const\n{\n return name < inv.name;\n}\n\nbool Invertebrate::operator >(const Invertebrate& inv) const\n{\n return name > inv.name;\n}\n\nbool Invertebrate::operator ==(const Invertebrate& inv) const\n{\n return name == inv.name;\n}\n\nQDataStream &operator<<(QDataStream &ds, const Invertebrate &obj) {\n ds << obj.commonName\n << obj.description\n << obj.family\n << obj.flyName\n << obj.genus\n << obj.imageFileLocal\n << obj.imageFileRemote\n << obj.imageIsReady\n << obj.imageIsUpToDate\n << obj.name;\n\n return ds;\n}\n\nQDataStream &operator>>(QDataStream &ds, Invertebrate &obj) {\n ds >> obj.commonName;\n ds >> obj.description;\n ds >> obj.family;\n ds >> obj.flyName;\n ds >> obj.genus;\n ds >> obj.imageFileLocal;\n ds >> obj.imageFileRemote;\n ds >> obj.imageIsReady;\n ds >> obj.imageIsUpToDate;\n ds >> obj.name;\n\n return ds;\n}\n\nQDebug operator<<(QDebug debug, const Invertebrate &invertebrate)\n{\n QDebugStateSaver saver(debug);\n QStringList list{invertebrate.name, invertebrate.commonName, invertebrate.description, invertebrate.family, invertebrate.flyName, invertebrate.genus, invertebrate.imageFileLocal, invertebrate.imageFileRemote};\n debug.nospace() << \"(\" << list.join(\", \") << \")\";\n\n return debug;\n}\nImproved QDebug implmentation for Invertebrate#include \"invertebrate.h\"\n\nInvertebrate::Invertebrate()\n{\n\n}\n\nbool Invertebrate::operator <(const Invertebrate& inv) const\n{\n return name < inv.name;\n}\n\nbool Invertebrate::operator >(const Invertebrate& inv) const\n{\n return name > inv.name;\n}\n\nbool Invertebrate::operator ==(const Invertebrate& inv) const\n{\n return name == inv.name;\n}\n\nQDataStream &operator<<(QDataStream &ds, const Invertebrate &obj) {\n ds << obj.commonName\n << obj.description\n << obj.family\n << obj.flyName\n << obj.genus\n << obj.imageFileLocal\n << obj.imageFileRemote\n << obj.imageIsReady\n << obj.imageIsUpToDate\n << obj.name;\n\n return ds;\n}\n\nQDataStream &operator>>(QDataStream &ds, Invertebrate &obj) {\n ds >> obj.commonName;\n ds >> obj.description;\n ds >> obj.family;\n ds >> obj.flyName;\n ds >> obj.genus;\n ds >> obj.imageFileLocal;\n ds >> obj.imageFileRemote;\n ds >> obj.imageIsReady;\n ds >> obj.imageIsUpToDate;\n ds >> obj.name;\n\n return ds;\n}\n\nQDebug operator<<(QDebug debug, const Invertebrate &invertebrate)\n{\n QDebugStateSaver saver(debug);\n debug.nospace() << \"(\\n\" <<\n \" commonName: \" << invertebrate.commonName << \",\\n\" <<\n \" description: \" << invertebrate.description << \",\\n\" <<\n \" family: \" << invertebrate.family << \",\\n\" <<\n \" flyName: \" << invertebrate.flyName << \",\\n\" <<\n \" genus: \" << invertebrate.genus << \",\\n\" <<\n \" imageFileLocal: \" << invertebrate.imageFileLocal << \",\\n\" <<\n \" imageFileRemote: \" << invertebrate.imageFileRemote << \",\\n\" <<\n \" imageIsReady: \" << invertebrate.imageIsReady << \",\\n\" <<\n \" imageIsUpToDate: \" << invertebrate.imageIsUpToDate << \",\\n\" <<\n \" name: \" << invertebrate.name << \",\\n\" <<\n \" order: \" << invertebrate.order <<\n \"\\n)\";\n\n return debug;\n}\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\/\/ Single cell view widget\n\/\/==============================================================================\n\n#include \"cellmlfilemanager.h\"\n#include \"singlecellviewsimulationwidget.h\"\n#include \"singlecellviewwidget.h\"\n\n\/\/==============================================================================\n\n#include \"ui_singlecellviewwidget.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace SingleCellView {\n\n\/\/==============================================================================\n\nSingleCellViewWidget::SingleCellViewWidget(SingleCellViewPlugin *pPlugin,\n QWidget *pParent) :\n ViewWidget(pParent),\n mPlugin(pPlugin),\n mSimulationWidget(0),\n mSimulationWidgets(QMap())\n{\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::retranslateUi()\n{\n \/\/ Retranslate our simulation widgets\n\n foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets)\n simulationWidget->retranslateUi();\n}\n\n\/\/==============================================================================\n\nbool SingleCellViewWidget::contains(const QString &pFileName) const\n{\n \/\/ Return whether we know about the given file\n\n return mSimulationWidgets.contains(pFileName);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::initialize(const QString &pFileName)\n{\n \/\/ Retrieve the simulation widget associated with the given file, if any\n\n SingleCellViewSimulationWidget *oldSimulationWidget = mSimulationWidget;\n\n mSimulationWidget = mSimulationWidgets.value(pFileName);\n\n if (!mSimulationWidget) {\n \/\/ No simulation widget exists for the given file, so create one\n\n mSimulationWidget = new SingleCellViewSimulationWidget(mPlugin, this);\n\n \/\/ Keep track of our editing widget and add it to ourselves\n\n mSimulationWidgets.insert(pFileName, mSimulationWidget);\n\n layout()->addWidget(mSimulationWidget);\n }\n\n \/\/ Hide our previous simulation widget and show our new one\n\n mSimulationWidget->show();\n\n if (oldSimulationWidget && (mSimulationWidget != oldSimulationWidget))\n oldSimulationWidget->hide();\n\n \/\/ Set our focus proxy to our 'new' simulation widget and make sure that the\n \/\/ latter immediately gets the focus\n\n setFocusProxy(mSimulationWidget);\n\n mSimulationWidget->setFocus();\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::finalize(const QString &pFileName)\n{\n \/\/ Remove the simulation widget, should there be one for the given file\n\n SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);\n\n if (simulationWidget) {\n \/\/ There is a simulation widget for the given file name, so delete it\n \/\/ and remove it from our list\n\n delete simulationWidget;\n\n mSimulationWidgets.remove(pFileName);\n\n \/\/ Reset our memory of the current editor, if needed\n\n if (simulationWidget == mSimulationWidget)\n mSimulationWidget = 0;\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::filePermissionsChanged(const QString &pFileName)\n{\n \/\/ The given file has been un\/locked, so enable\/disable parts of our GUI,\n \/\/ should the given file be managed\n\n SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);\n\n if (simulationWidget)\n simulationWidget->filePermissionsChanged();\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::fileReloaded(const QString &pFileName)\n{\n \/\/ The given file has been reloaded, so reload it, should it be managed\n\n if (contains(pFileName)) {\n finalize(pFileName);\n\n if (CellMLSupport::CellmlFileManager::instance()->isCellmlFile(pFileName))\n initialize(pFileName);\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::fileRenamed(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ The given file has been renamed, so update our simulating widgets mapping\n\n SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName);\n\n if (simulationWidget) {\n mSimulationWidgets.insert(pNewFileName, simulationWidget);\n mSimulationWidgets.remove(pOldFileName);\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace SingleCellView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\nSingle Cell view: some work on making the view more file specific (#590) [ci skip].\/*******************************************************************************\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\/\/ Single cell view widget\n\/\/==============================================================================\n\n#include \"cellmlfilemanager.h\"\n#include \"singlecellviewsimulationwidget.h\"\n#include \"singlecellviewwidget.h\"\n\n\/\/==============================================================================\n\n#include \n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace SingleCellView {\n\n\/\/==============================================================================\n\nSingleCellViewWidget::SingleCellViewWidget(SingleCellViewPlugin *pPlugin,\n QWidget *pParent) :\n ViewWidget(pParent),\n mPlugin(pPlugin),\n mSimulationWidget(0),\n mSimulationWidgets(QMap())\n{\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::retranslateUi()\n{\n \/\/ Retranslate our simulation widgets\n\n foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets)\n simulationWidget->retranslateUi();\n}\n\n\/\/==============================================================================\n\nbool SingleCellViewWidget::contains(const QString &pFileName) const\n{\n \/\/ Return whether we know about the given file\n\n return mSimulationWidgets.contains(pFileName);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::initialize(const QString &pFileName)\n{\n \/\/ Retrieve the simulation widget associated with the given file, if any\n\n SingleCellViewSimulationWidget *oldSimulationWidget = mSimulationWidget;\n\n mSimulationWidget = mSimulationWidgets.value(pFileName);\n\n if (!mSimulationWidget) {\n \/\/ No simulation widget exists for the given file, so create one\n\n mSimulationWidget = new SingleCellViewSimulationWidget(mPlugin, this);\n\n \/\/ Keep track of our editing widget and add it to ourselves\n\n mSimulationWidgets.insert(pFileName, mSimulationWidget);\n\n layout()->addWidget(mSimulationWidget);\n }\n\n \/\/ Hide our previous simulation widget and show our new one\n\n mSimulationWidget->show();\n\n if (oldSimulationWidget && (mSimulationWidget != oldSimulationWidget))\n oldSimulationWidget->hide();\n\n \/\/ Set our focus proxy to our 'new' simulation widget and make sure that the\n \/\/ latter immediately gets the focus\n\n setFocusProxy(mSimulationWidget);\n\n mSimulationWidget->setFocus();\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::finalize(const QString &pFileName)\n{\n \/\/ Remove the simulation widget, should there be one for the given file\n\n SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);\n\n if (simulationWidget) {\n \/\/ There is a simulation widget for the given file name, so delete it\n \/\/ and remove it from our list\n\n delete simulationWidget;\n\n mSimulationWidgets.remove(pFileName);\n\n \/\/ Reset our memory of the current editor, if needed\n\n if (simulationWidget == mSimulationWidget)\n mSimulationWidget = 0;\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::filePermissionsChanged(const QString &pFileName)\n{\n \/\/ The given file has been un\/locked, so enable\/disable parts of our GUI,\n \/\/ should the given file be managed\n\n SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName);\n\n if (simulationWidget)\n simulationWidget->filePermissionsChanged();\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::fileReloaded(const QString &pFileName)\n{\n \/\/ The given file has been reloaded, so reload it, should it be managed\n\n if (contains(pFileName)) {\n finalize(pFileName);\n\n if (CellMLSupport::CellmlFileManager::instance()->isCellmlFile(pFileName))\n initialize(pFileName);\n }\n}\n\n\/\/==============================================================================\n\nvoid SingleCellViewWidget::fileRenamed(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ The given file has been renamed, so update our simulating widgets mapping\n\n SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName);\n\n if (simulationWidget) {\n mSimulationWidgets.insert(pNewFileName, simulationWidget);\n mSimulationWidgets.remove(pOldFileName);\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace SingleCellView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \n#include \n#include \n#if !defined(WIN32)\n#include \n#endif\n\n#include \"condor_query.h\"\n#include \"condor_attributes.h\"\n#include \"condor_collector.h\"\n#include \"condor_config.h\"\n#include \"condor_network.h\"\n#include \"condor_io.h\"\n#include \"condor_parser.h\"\n#include \"condor_adtypes.h\"\n#include \"condor_debug.h\"\n\n\n#define XDR_ASSERT(x) {if (!(x)) return Q_COMMUNICATION_ERROR;}\n\nchar *new_strdup (const char *);\n\n\/\/ The order and number of the elements of the following arrays *are*\n\/\/ important. (They follow the structure of the enumerations supplied\n\/\/ in the header file condor_query.h)\nconst char *ScheddStringKeywords [] = \n{\n\tATTR_NAME \n};\n\nconst char *ScheddIntegerKeywords [] = \n{\n\tATTR_NUM_USERS,\n\tATTR_IDLE_JOBS,\n\tATTR_RUNNING_JOBS\n};\n\nconst char *ScheddFloatKeywords [] = \n{\n\t\"\"\t\t\/\/ add null string to avoid compiler error\n};\n\nconst char *StartdStringKeywords [] = \n{\n\tATTR_NAME,\n\tATTR_MACHINE,\n\tATTR_ARCH,\n\tATTR_OPSYS\n};\n\nconst char *StartdIntegerKeywords [] = \n{\n\tATTR_MEMORY,\n\tATTR_DISK\n};\n\nconst char *StartdFloatKeywords [] =\n{\n\t\"\"\t\t\/\/ add null string to avoid compiler error\n};\n\n\/\/ normal ctor\nCondorQuery::\nCondorQuery (AdTypes qType)\n{\n\tqueryType = qType;\n\tswitch (qType)\n\t{\n\t case STARTD_AD:\n\t\tquery.setNumStringCats (STARTD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(STARTD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (STARTD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)StartdIntegerKeywords);\n\t\tquery.setStringKwList ((char **)StartdStringKeywords);\n\t\tquery.setFloatKwList ((char **)StartdFloatKeywords);\n\t\tcommand = QUERY_STARTD_ADS;\n\t\tbreak;\n\n\t case STARTD_PVT_AD:\n\t\tquery.setNumStringCats (STARTD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(STARTD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (STARTD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)StartdIntegerKeywords);\n\t\tquery.setStringKwList ((char **)StartdStringKeywords);\n\t\tquery.setFloatKwList ((char **)StartdFloatKeywords);\n\t\tcommand = QUERY_STARTD_PVT_ADS;\n\t\tbreak;\n\n\t case SCHEDD_AD:\n\t\tquery.setNumStringCats (SCHEDD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(SCHEDD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)ScheddIntegerKeywords);\n\t\tquery.setStringKwList ((char **)ScheddStringKeywords);\n\t\tquery.setFloatKwList ((char **)ScheddFloatKeywords);\n\t\tcommand = QUERY_SCHEDD_ADS;\n\t\tbreak;\n\n\t case SUBMITTOR_AD:\n\t\tquery.setNumStringCats (SCHEDD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(SCHEDD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)ScheddIntegerKeywords);\n\t\tquery.setStringKwList ((char **)ScheddStringKeywords);\n\t\tquery.setFloatKwList ((char **)ScheddFloatKeywords);\n\t\tcommand = QUERY_SUBMITTOR_ADS;\n\t\tbreak;\n\n\t case LICENSE_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_LICENSE_ADS;\n\t\tbreak;\n\n\t case MASTER_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_MASTER_ADS;\n\t\tbreak;\n\n\t case CKPT_SRVR_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_CKPT_SRVR_ADS;\n\t\tbreak;\n\n\t case COLLECTOR_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_COLLECTOR_ADS;\n\t\tbreak;\n\n\t default:\n\t\tcommand = -1;\n\t\tqueryType = (AdTypes) -1;\n\t}\n}\n\n\n\/\/ copy ctor; makes deep copy\nCondorQuery::\nCondorQuery (const CondorQuery &from)\n{\n}\n\n\n\/\/ dtor\nCondorQuery::\n~CondorQuery ()\n{\t\n}\n\n\n\/\/ clear particular string category\nQueryResult CondorQuery::\nclearStringConstraints (const int i)\n{\n\treturn (QueryResult) query.clearString (i);\n}\n\n\n\/\/ clear particular integer category\nQueryResult CondorQuery::\nclearIntegerConstraints (const int i)\n{\n\treturn (QueryResult) query.clearInteger (i);\n}\n\n\/\/ clear particular float category\nQueryResult CondorQuery::\nclearFloatConstraints (const int i)\n{\n\treturn (QueryResult) query.clearFloat (i);\n}\n\n\nvoid CondorQuery::\nclearCustomConstraints (void)\n{\n\tquery.clearCustom ();\n}\n\n\n\/\/ add a string constraint\nQueryResult CondorQuery::\naddConstraint (const int cat, const char *value)\n{\n\treturn (QueryResult) query.addString (cat, (char *) value);\n}\n\n\n\/\/ add an integer constraint\nQueryResult CondorQuery::\naddConstraint (const int cat, const int value)\n{\n\treturn (QueryResult) query.addInteger (cat, value);\n}\n\n\n\/\/ add a float constraint\nQueryResult CondorQuery::\naddConstraint (const int cat, const float value)\n{\n\treturn (QueryResult) query.addFloat (cat, value);\n}\n\n\n\/\/ add a custom constraint\nQueryResult CondorQuery::\naddConstraint (const char *value)\n{\n\treturn (QueryResult) query.addCustom ((char *) value);\n}\n\n\n\/\/ fetch all ads from the collector that satisfy the constraints\nQueryResult CondorQuery::\nfetchAds (ClassAdList &adList, const char *poolName)\n{\n char *pool;\n\tchar\t\tdefaultPool[32];\n ReliSock sock; \n\tint\t\t\tmore;\n QueryResult result;\n ClassAd queryAd, *ad;\n\n\t\/\/ use current pool's collector if not specified\n\tif (poolName == NULL || poolName[0] == '\\0')\n\t{\n\t\tif ((pool = param (\"COLLECTOR_HOST\")) == NULL) {\n\t\t\treturn Q_NO_COLLECTOR_HOST;\n\t\t}\n\t\tstrcpy (defaultPool, pool);\n\t\tfree (pool);\n\t\tpool = defaultPool;\n\t}\n\telse {\n\t\t\/\/ pool specified\n\t\tpool = (char *) poolName;\n\t}\n\n\t\/\/ make the query ad\n\tresult = (QueryResult) query.makeQuery (queryAd);\n\tif (result != Q_OK) return result;\n\n\t\/\/ fix types\n\tqueryAd.SetMyTypeName (QUERY_ADTYPE);\n\tswitch (queryType) {\n\t case STARTD_AD:\n\t case STARTD_PVT_AD:\n\t\tqueryAd.SetTargetTypeName (STARTD_ADTYPE);\n\t\tbreak;\n\n\t case SCHEDD_AD:\n\t case SUBMITTOR_AD:\n\t\tqueryAd.SetTargetTypeName (SCHEDD_ADTYPE);\n\t\tbreak;\n\n\t case LICENSE_AD:\n\t\tqueryAd.SetTargetTypeName (LICENSE_ADTYPE);\n\t\tbreak;\n\n\t case MASTER_AD:\n\t\tqueryAd.SetTargetTypeName (MASTER_ADTYPE);\n\t\tbreak;\n\n\t case CKPT_SRVR_AD:\n\t\tqueryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE);\n\t\tbreak;\n\n\t case COLLECTOR_AD:\n\t\tqueryAd.SetTargetTypeName (COLLECTOR_ADTYPE);\n\t\tbreak;\n\n\t default:\n\t\treturn Q_INVALID_QUERY;\n\t}\n\n\t\/\/ contact collector\n\tif (!sock.connect(pool, COLLECTOR_COMM_PORT)) {\n return Q_COMMUNICATION_ERROR;\n }\n\n\t\/\/ ship query\n\tsock.encode();\n\tif (!sock.code (command) || !queryAd.put (sock) || !sock.end_of_message()) {\n\t\treturn Q_COMMUNICATION_ERROR;\n\t}\n\t\n\t\/\/ get result\n\tsock.decode ();\n\tmore = 1;\n\twhile (more)\n\t{\n\t\tif (!sock.code (more)) {\n\t\t\tsock.end_of_message();\n\t\t\treturn Q_COMMUNICATION_ERROR;\n\t\t}\n\t\tif (more) {\n\t\t\tad = new ClassAd;\n\t\t\tif (!ad->get (sock)) {\n\t\t\t\tsock.end_of_message();\n\t\t\t\tdelete ad;\n\t\t\t\treturn Q_COMMUNICATION_ERROR;\n\t\t\t}\n\t\t\tadList.Insert (ad);\n\t\t}\n\t}\n\tsock.end_of_message();\n\n\t\/\/ finalize\n\tsock.close ();\n\t\n\treturn (Q_OK);\n}\n\n\nQueryResult CondorQuery::\ngetQueryAd (ClassAd &queryAd)\n{\n\tQueryResult\tresult;\n\n\tresult = (QueryResult) query.makeQuery (queryAd);\n\tif (result != Q_OK) return result;\n\n\t\/\/ fix types\n\tqueryAd.SetMyTypeName (QUERY_ADTYPE);\n\tswitch (queryType) {\n\t case STARTD_AD:\n\t case STARTD_PVT_AD:\n\t\tqueryAd.SetTargetTypeName (STARTD_ADTYPE);\n\t\tbreak;\n\n\t case SCHEDD_AD:\n\t case SUBMITTOR_AD:\n\t\tqueryAd.SetTargetTypeName (SCHEDD_ADTYPE);\n\t\tbreak;\n\n\t case LICENSE_AD:\n\t\tqueryAd.SetTargetTypeName (LICENSE_ADTYPE);\n\t\tbreak;\n\n\t case MASTER_AD:\n\t\tqueryAd.SetTargetTypeName (MASTER_ADTYPE);\n\t\tbreak;\n\n\t case CKPT_SRVR_AD:\n\t\tqueryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE);\n\t\tbreak;\n\n\t case COLLECTOR_AD:\n\t\tqueryAd.SetTargetTypeName (COLLECTOR_ADTYPE);\n\t\tbreak;\n\n\t default:\n\t\treturn Q_INVALID_QUERY;\n\t}\n\n\treturn Q_OK;\n}\n\n\t\nQueryResult CondorQuery::\nfilterAds (ClassAdList &in, ClassAdList &out)\n{\n\tClassAd queryAd, *candidate;\n\tQueryResult\tresult;\n\n\t\/\/ make the query ad\n\tresult = (QueryResult) query.makeQuery (queryAd);\n\tif (result != Q_OK) return result;\n\n\tin.Open();\n\twhile (candidate = (ClassAd *) in.Next())\n {\n \/\/ if a match occurs\n\t\tif ((*candidate) >= (queryAd)) out.Insert (candidate);\n }\n in.Close ();\n \n\treturn Q_OK;\n}\n\n\nchar *getStrQueryResult(QueryResult q)\n{\n\tswitch (q)\n\t{\n \tcase Q_OK:\t\t\t\t\treturn \"ok\";\n \tcase Q_INVALID_CATEGORY:\treturn \"invalid category\";\n \tcase Q_MEMORY_ERROR:\t\treturn \"memory error\";\n \tcase Q_PARSE_ERROR:\t\t\treturn \"parse error\";\n\t case Q_COMMUNICATION_ERROR:\treturn \"communication error\";\n\t case Q_INVALID_QUERY:\t\treturn \"invalid query\";\n\t case Q_NO_COLLECTOR_HOST:\treturn \"no COLLECTOR_HOST\";\n\t\tdefault:\n\t\t\treturn \"unknown error\";\n\t}\n}\n+ Use get_collector_addr() instead of doing things manually. + Removed some system header files we don't need.\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \"condor_query.h\"\n#include \"condor_attributes.h\"\n#include \"condor_collector.h\"\n#include \"condor_config.h\"\n#include \"condor_network.h\"\n#include \"condor_io.h\"\n#include \"condor_parser.h\"\n#include \"condor_adtypes.h\"\n#include \"condor_debug.h\"\n#include \"get_daemon_addr.h\"\n\n\n#define XDR_ASSERT(x) {if (!(x)) return Q_COMMUNICATION_ERROR;}\n\nchar *new_strdup (const char *);\n\n\/\/ The order and number of the elements of the following arrays *are*\n\/\/ important. (They follow the structure of the enumerations supplied\n\/\/ in the header file condor_query.h)\nconst char *ScheddStringKeywords [] = \n{\n\tATTR_NAME \n};\n\nconst char *ScheddIntegerKeywords [] = \n{\n\tATTR_NUM_USERS,\n\tATTR_IDLE_JOBS,\n\tATTR_RUNNING_JOBS\n};\n\nconst char *ScheddFloatKeywords [] = \n{\n\t\"\"\t\t\/\/ add null string to avoid compiler error\n};\n\nconst char *StartdStringKeywords [] = \n{\n\tATTR_NAME,\n\tATTR_MACHINE,\n\tATTR_ARCH,\n\tATTR_OPSYS\n};\n\nconst char *StartdIntegerKeywords [] = \n{\n\tATTR_MEMORY,\n\tATTR_DISK\n};\n\nconst char *StartdFloatKeywords [] =\n{\n\t\"\"\t\t\/\/ add null string to avoid compiler error\n};\n\n\/\/ normal ctor\nCondorQuery::\nCondorQuery (AdTypes qType)\n{\n\tqueryType = qType;\n\tswitch (qType)\n\t{\n\t case STARTD_AD:\n\t\tquery.setNumStringCats (STARTD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(STARTD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (STARTD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)StartdIntegerKeywords);\n\t\tquery.setStringKwList ((char **)StartdStringKeywords);\n\t\tquery.setFloatKwList ((char **)StartdFloatKeywords);\n\t\tcommand = QUERY_STARTD_ADS;\n\t\tbreak;\n\n\t case STARTD_PVT_AD:\n\t\tquery.setNumStringCats (STARTD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(STARTD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (STARTD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)StartdIntegerKeywords);\n\t\tquery.setStringKwList ((char **)StartdStringKeywords);\n\t\tquery.setFloatKwList ((char **)StartdFloatKeywords);\n\t\tcommand = QUERY_STARTD_PVT_ADS;\n\t\tbreak;\n\n\t case SCHEDD_AD:\n\t\tquery.setNumStringCats (SCHEDD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(SCHEDD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)ScheddIntegerKeywords);\n\t\tquery.setStringKwList ((char **)ScheddStringKeywords);\n\t\tquery.setFloatKwList ((char **)ScheddFloatKeywords);\n\t\tcommand = QUERY_SCHEDD_ADS;\n\t\tbreak;\n\n\t case SUBMITTOR_AD:\n\t\tquery.setNumStringCats (SCHEDD_STRING_THRESHOLD);\n\t\tquery.setNumIntegerCats(SCHEDD_INT_THRESHOLD);\n\t\tquery.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD);\n\t\tquery.setIntegerKwList ((char **)ScheddIntegerKeywords);\n\t\tquery.setStringKwList ((char **)ScheddStringKeywords);\n\t\tquery.setFloatKwList ((char **)ScheddFloatKeywords);\n\t\tcommand = QUERY_SUBMITTOR_ADS;\n\t\tbreak;\n\n\t case LICENSE_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_LICENSE_ADS;\n\t\tbreak;\n\n\t case MASTER_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_MASTER_ADS;\n\t\tbreak;\n\n\t case CKPT_SRVR_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_CKPT_SRVR_ADS;\n\t\tbreak;\n\n\t case COLLECTOR_AD:\n\t\tquery.setNumStringCats (0);\n\t\tquery.setNumIntegerCats(0);\n\t\tquery.setNumFloatCats (0);\n\t\tcommand = QUERY_COLLECTOR_ADS;\n\t\tbreak;\n\n\t default:\n\t\tcommand = -1;\n\t\tqueryType = (AdTypes) -1;\n\t}\n}\n\n\n\/\/ copy ctor; makes deep copy\nCondorQuery::\nCondorQuery (const CondorQuery &from)\n{\n}\n\n\n\/\/ dtor\nCondorQuery::\n~CondorQuery ()\n{\t\n}\n\n\n\/\/ clear particular string category\nQueryResult CondorQuery::\nclearStringConstraints (const int i)\n{\n\treturn (QueryResult) query.clearString (i);\n}\n\n\n\/\/ clear particular integer category\nQueryResult CondorQuery::\nclearIntegerConstraints (const int i)\n{\n\treturn (QueryResult) query.clearInteger (i);\n}\n\n\/\/ clear particular float category\nQueryResult CondorQuery::\nclearFloatConstraints (const int i)\n{\n\treturn (QueryResult) query.clearFloat (i);\n}\n\n\nvoid CondorQuery::\nclearCustomConstraints (void)\n{\n\tquery.clearCustom ();\n}\n\n\n\/\/ add a string constraint\nQueryResult CondorQuery::\naddConstraint (const int cat, const char *value)\n{\n\treturn (QueryResult) query.addString (cat, (char *) value);\n}\n\n\n\/\/ add an integer constraint\nQueryResult CondorQuery::\naddConstraint (const int cat, const int value)\n{\n\treturn (QueryResult) query.addInteger (cat, value);\n}\n\n\n\/\/ add a float constraint\nQueryResult CondorQuery::\naddConstraint (const int cat, const float value)\n{\n\treturn (QueryResult) query.addFloat (cat, value);\n}\n\n\n\/\/ add a custom constraint\nQueryResult CondorQuery::\naddConstraint (const char *value)\n{\n\treturn (QueryResult) query.addCustom ((char *) value);\n}\n\n\n\/\/ fetch all ads from the collector that satisfy the constraints\nQueryResult CondorQuery::\nfetchAds (ClassAdList &adList, const char *poolName)\n{\n char *pool;\n\tchar\t\tdefaultPool[32];\n ReliSock sock; \n\tint\t\t\tmore;\n QueryResult result;\n ClassAd queryAd, *ad;\n\n\t\t\/\/ This will return the correct addr for the local pool's\n\t\t\/\/ collector if poolName is NULL.\n\tpool = get_collector_addr( poolName );\n\n\t\/\/ make the query ad\n\tresult = (QueryResult) query.makeQuery (queryAd);\n\tif (result != Q_OK) return result;\n\n\t\/\/ fix types\n\tqueryAd.SetMyTypeName (QUERY_ADTYPE);\n\tswitch (queryType) {\n\t case STARTD_AD:\n\t case STARTD_PVT_AD:\n\t\tqueryAd.SetTargetTypeName (STARTD_ADTYPE);\n\t\tbreak;\n\n\t case SCHEDD_AD:\n\t case SUBMITTOR_AD:\n\t\tqueryAd.SetTargetTypeName (SCHEDD_ADTYPE);\n\t\tbreak;\n\n\t case LICENSE_AD:\n\t\tqueryAd.SetTargetTypeName (LICENSE_ADTYPE);\n\t\tbreak;\n\n\t case MASTER_AD:\n\t\tqueryAd.SetTargetTypeName (MASTER_ADTYPE);\n\t\tbreak;\n\n\t case CKPT_SRVR_AD:\n\t\tqueryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE);\n\t\tbreak;\n\n\t case COLLECTOR_AD:\n\t\tqueryAd.SetTargetTypeName (COLLECTOR_ADTYPE);\n\t\tbreak;\n\n\t default:\n\t\treturn Q_INVALID_QUERY;\n\t}\n\n\t\/\/ contact collector\n\tif (!sock.connect(pool, COLLECTOR_COMM_PORT)) {\n return Q_COMMUNICATION_ERROR;\n }\n\n\t\/\/ ship query\n\tsock.encode();\n\tif (!sock.code (command) || !queryAd.put (sock) || !sock.end_of_message()) {\n\t\treturn Q_COMMUNICATION_ERROR;\n\t}\n\t\n\t\/\/ get result\n\tsock.decode ();\n\tmore = 1;\n\twhile (more)\n\t{\n\t\tif (!sock.code (more)) {\n\t\t\tsock.end_of_message();\n\t\t\treturn Q_COMMUNICATION_ERROR;\n\t\t}\n\t\tif (more) {\n\t\t\tad = new ClassAd;\n\t\t\tif (!ad->get (sock)) {\n\t\t\t\tsock.end_of_message();\n\t\t\t\tdelete ad;\n\t\t\t\treturn Q_COMMUNICATION_ERROR;\n\t\t\t}\n\t\t\tadList.Insert (ad);\n\t\t}\n\t}\n\tsock.end_of_message();\n\n\t\/\/ finalize\n\tsock.close ();\n\t\n\treturn (Q_OK);\n}\n\n\nQueryResult CondorQuery::\ngetQueryAd (ClassAd &queryAd)\n{\n\tQueryResult\tresult;\n\n\tresult = (QueryResult) query.makeQuery (queryAd);\n\tif (result != Q_OK) return result;\n\n\t\/\/ fix types\n\tqueryAd.SetMyTypeName (QUERY_ADTYPE);\n\tswitch (queryType) {\n\t case STARTD_AD:\n\t case STARTD_PVT_AD:\n\t\tqueryAd.SetTargetTypeName (STARTD_ADTYPE);\n\t\tbreak;\n\n\t case SCHEDD_AD:\n\t case SUBMITTOR_AD:\n\t\tqueryAd.SetTargetTypeName (SCHEDD_ADTYPE);\n\t\tbreak;\n\n\t case LICENSE_AD:\n\t\tqueryAd.SetTargetTypeName (LICENSE_ADTYPE);\n\t\tbreak;\n\n\t case MASTER_AD:\n\t\tqueryAd.SetTargetTypeName (MASTER_ADTYPE);\n\t\tbreak;\n\n\t case CKPT_SRVR_AD:\n\t\tqueryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE);\n\t\tbreak;\n\n\t case COLLECTOR_AD:\n\t\tqueryAd.SetTargetTypeName (COLLECTOR_ADTYPE);\n\t\tbreak;\n\n\t default:\n\t\treturn Q_INVALID_QUERY;\n\t}\n\n\treturn Q_OK;\n}\n\n\t\nQueryResult CondorQuery::\nfilterAds (ClassAdList &in, ClassAdList &out)\n{\n\tClassAd queryAd, *candidate;\n\tQueryResult\tresult;\n\n\t\/\/ make the query ad\n\tresult = (QueryResult) query.makeQuery (queryAd);\n\tif (result != Q_OK) return result;\n\n\tin.Open();\n\twhile (candidate = (ClassAd *) in.Next())\n {\n \/\/ if a match occurs\n\t\tif ((*candidate) >= (queryAd)) out.Insert (candidate);\n }\n in.Close ();\n \n\treturn Q_OK;\n}\n\n\nchar *getStrQueryResult(QueryResult q)\n{\n\tswitch (q)\n\t{\n \tcase Q_OK:\t\t\t\t\treturn \"ok\";\n \tcase Q_INVALID_CATEGORY:\treturn \"invalid category\";\n \tcase Q_MEMORY_ERROR:\t\treturn \"memory error\";\n \tcase Q_PARSE_ERROR:\t\t\treturn \"parse error\";\n\t case Q_COMMUNICATION_ERROR:\treturn \"communication error\";\n\t case Q_INVALID_QUERY:\t\treturn \"invalid query\";\n\t case Q_NO_COLLECTOR_HOST:\treturn \"no COLLECTOR_HOST\";\n\t\tdefault:\n\t\t\treturn \"unknown error\";\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n**==============================================================================\n**\n** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer\n** Copyright (c) 2008, Michael E. Brasher\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 FROM,\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n** SOFTWARE.\n**\n**==============================================================================\n*\/\n\n#include \"MOF_Data_Type.h\"\n#include \"MOF_Error.h\"\n#include \"MOF_String.h\"\n#include \"MOF_Yacc.h\"\n\nconst char* MOF_Data_Type::to_string(int data_type)\n{\n switch (data_type)\n {\n case TOK_UINT8: \n return \"uint8\";\n\n case TOK_SINT8: \n return \"sint8\";\n\n case TOK_UINT16: \n return \"uint16\";\n\n case TOK_SINT16: \n return \"sint16\";\n\n case TOK_UINT32: \n return \"uint32\";\n\n case TOK_SINT32: \n return \"sint32\";\n\n case TOK_UINT64: \n return \"uint64\";\n\n case TOK_SINT64: \n return \"sint64\";\n\n case TOK_REAL32: \n return \"real32\";\n\n case TOK_REAL64: \n return \"real64\";\n\n case TOK_CHAR16: \n return \"char16\";\n\n case TOK_STRING: \n return \"string\";\n\n case TOK_BOOLEAN: \n return \"boolean\";\n\n case TOK_DATETIME: \n return \"datetime\";\n\n default:\n MOF_ASSERT(false);\n return 0;\n }\n\n \/* Unreachable *\/\n return 0;\n}\nFix instance to string conversion\/*\n**==============================================================================\n**\n** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer\n** Copyright (c) 2008, Michael E. Brasher\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 FROM,\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n** SOFTWARE.\n**\n**==============================================================================\n*\/\n\n#include \"MOF_Data_Type.h\"\n#include \"MOF_Error.h\"\n#include \"MOF_String.h\"\n#include \"MOF_Yacc.h\"\n\nconst char* MOF_Data_Type::to_string(int data_type)\n{\n switch (data_type)\n {\n case TOK_UINT8: \n return \"uint8\";\n\n case TOK_SINT8: \n return \"sint8\";\n\n case TOK_UINT16: \n return \"uint16\";\n\n case TOK_SINT16: \n return \"sint16\";\n\n case TOK_UINT32: \n return \"uint32\";\n\n case TOK_SINT32: \n return \"sint32\";\n\n case TOK_UINT64: \n return \"uint64\";\n\n case TOK_SINT64: \n return \"sint64\";\n\n case TOK_REAL32: \n return \"real32\";\n\n case TOK_REAL64: \n return \"real64\";\n\n case TOK_CHAR16: \n return \"char16\";\n\n case TOK_STRING: \n return \"string\";\n\n case TOK_BOOLEAN: \n return \"boolean\";\n\n case TOK_DATETIME: \n return \"datetime\";\n\n case TOK_INSTANCE:\n return \"instance\";\n\n default:\n MOF_ASSERT(false);\n return 0;\n }\n\n \/* Unreachable *\/\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\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\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 \"GafferScene\/GlobalsProcessor.h\"\n\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nGAFFER_GRAPHCOMPONENT_DEFINE_TYPE( GlobalsProcessor );\n\nGlobalsProcessor::GlobalsProcessor( const std::string &name )\n\t:\tSceneProcessor( name )\n{\n\t\/\/ Fast pass-throughs for everything except the globals\n\toutPlug()->boundPlug()->setInput( inPlug()->boundPlug() );\n\toutPlug()->transformPlug()->setInput( inPlug()->transformPlug() );\n\toutPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );\n\toutPlug()->objectPlug()->setInput( inPlug()->objectPlug() );\n\toutPlug()->childNamesPlug()->setInput( inPlug()->childNamesPlug() );\n\toutPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );\n\toutPlug()->setPlug()->setInput( inPlug()->setPlug() );\n}\n\nGlobalsProcessor::~GlobalsProcessor()\n{\n}\n\nvoid GlobalsProcessor::affects( const Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tSceneProcessor::affects( input, outputs );\n\n\tif( input == inPlug()->globalsPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->globalsPlug() );\n\t}\n}\n\nvoid GlobalsProcessor::hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tSceneProcessor::hashGlobals( context, parent, h );\n\tinPlug()->globalsPlug()->hash( h );\n\thashProcessedGlobals( context, h );\n}\n\nIECore::ConstCompoundObjectPtr GlobalsProcessor::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tIECore::ConstCompoundObjectPtr globals = inPlug()->globalsPlug()->getValue();\n\treturn computeProcessedGlobals( context, globals );\n}\nGlobalsProcessor : Add pass-through for `childBoundsPlug()`\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\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\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 \"GafferScene\/GlobalsProcessor.h\"\n\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nGAFFER_GRAPHCOMPONENT_DEFINE_TYPE( GlobalsProcessor );\n\nGlobalsProcessor::GlobalsProcessor( const std::string &name )\n\t:\tSceneProcessor( name )\n{\n\t\/\/ Fast pass-throughs for everything except the globals\n\toutPlug()->boundPlug()->setInput( inPlug()->boundPlug() );\n\toutPlug()->transformPlug()->setInput( inPlug()->transformPlug() );\n\toutPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );\n\toutPlug()->objectPlug()->setInput( inPlug()->objectPlug() );\n\toutPlug()->childNamesPlug()->setInput( inPlug()->childNamesPlug() );\n\toutPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );\n\toutPlug()->setPlug()->setInput( inPlug()->setPlug() );\n\toutPlug()->childBoundsPlug()->setInput( inPlug()->childBoundsPlug() );\n}\n\nGlobalsProcessor::~GlobalsProcessor()\n{\n}\n\nvoid GlobalsProcessor::affects( const Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tSceneProcessor::affects( input, outputs );\n\n\tif( input == inPlug()->globalsPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->globalsPlug() );\n\t}\n}\n\nvoid GlobalsProcessor::hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const\n{\n\tSceneProcessor::hashGlobals( context, parent, h );\n\tinPlug()->globalsPlug()->hash( h );\n\thashProcessedGlobals( context, h );\n}\n\nIECore::ConstCompoundObjectPtr GlobalsProcessor::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const\n{\n\tIECore::ConstCompoundObjectPtr globals = inPlug()->globalsPlug()->getValue();\n\treturn computeProcessedGlobals( context, globals );\n}\n<|endoftext|>"} {"text":"some fixes<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n#include \"mitkIOUtil.h\"\n#include \n\n#include \n\nclass mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite );\n\n MITK_TEST(ImageDescription_PhantomTest_3D);\n MITK_TEST(ImageDescription_PhantomTest_2D);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n mitk::Image::Pointer m_IBSI_Phantom_Image_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Image_Large;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;\n\npublic:\n\n void setUp(void) override\n {\n m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Small.nrrd\"));\n m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Large.nrrd\"));\n m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Small.nrrd\"));\n m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Large.nrrd\"));\n }\n\n void ImageDescription_PhantomTest_3D()\n {\n mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();\n\n featureCalculator->SetUseBinsize(true);\n featureCalculator->SetBinsize(1.0);\n featureCalculator->SetUseMinimumIntensity(true);\n featureCalculator->SetUseMaximumIntensity(true);\n featureCalculator->SetMinimumIntensity(0.5);\n featureCalculator->SetMaximumIntensity(6.5);\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);\n\n std::map results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 18 features.\", std::size_t(18), featureList.size());\n\n \/\/ These values are obtained with IBSI\n \/\/ Standard accuracy is 0.01\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image\", 0.255, results[\"Grey Level Size Zone::Small Zone Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image\", 550, results[\"Grey Level Size Zone::Large Zone Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.253, results[\"Grey Level Size Zone::Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image\", 15.6, results[\"Grey Level Size Zone::High Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.0256, results[\"Grey Level Size Zone::Small Zone Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 2.76, results[\"Grey Level Size Zone::Small Zone High Grey Level Emphasis\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 503, results[\"Grey Level Size Zone::Large Zone Low Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 1495, results[\"Grey Level Size Zone::Large Zone High Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image\", 1.4, results[\"Grey Level Size Zone::Grey Level Non-Uniformity\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.28, results[\"Grey Level Size Zone::Grey Level Non-Uniformity Normalized\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image\", 1, results[\"Grey Level Size Zone::Zone Size Non-Uniformity\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.2, results[\"Grey Level Size Zone::Zone Size Non-Uniformity Normalized\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image\", 0.0676, results[\"Grey Level Size Zone::Zone Percentage\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image\", 2.64, results[\"Grey Level Size Zone::Grey Level Variance\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image\", 331, results[\"Grey Level Size Zone::Zone Size Variance\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image\", 2.32, results[\"Grey Level Size Zone::Zone Size Entropy\"], 0.01);\n \/\/CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone:: with Large IBSI Phantom Image\", 0.045, results[\"Grey Level Size Zone::\"], 0.001);\n\n \/\/ These values are obtained by manually running the tool\n \/\/ Values might be wrong.\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image\", 3.6, results[\"Grey Level Size Zone::Grey Level Mean\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image\", 14.8, results[\"Grey Level Size Zone::Zone Size Mean\"], 0.001);\n }\n\n void ImageDescription_PhantomTest_2D()\n {\n mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();\n\n featureCalculator->SetUseBinsize(true);\n featureCalculator->SetBinsize(1.0);\n featureCalculator->SetUseMinimumIntensity(true);\n featureCalculator->SetUseMaximumIntensity(true);\n featureCalculator->SetMinimumIntensity(0.5);\n featureCalculator->SetMaximumIntensity(6.5);\n\n auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2);\n\n std::map results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 108 features.\", std::size_t(108), featureList.size());\n\n \/\/ These values are obtained with IBSI\n \/\/ Standard accuracy is 0.01\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image\", 0.363, results[\"SliceWise Mean Grey Level Size Zone::Small Zone Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image\", 43.9, results[\"SliceWise Mean Grey Level Size Zone::Large Zone Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.371, results[\"SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image\", 16.4, results[\"SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.0259, results[\"SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 10.3, results[\"SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 40.4, results[\"SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 113, results[\"SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image\", 1.41, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.323, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image\", 1.49, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.333, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image\", 0.24, results[\"SliceWise Mean Grey Level Size Zone::Zone Percentage\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image\", 3.97, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Variance\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image\", 21, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Variance\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image\", 1.93, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Entropy\"], 0.01);\n \/\/CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone:: with Large IBSI Phantom Image\", 0.045, results[\"SliceWise Mean Grey Level Size Zone::\"], 0.001);\n\n \/\/ These values are obtained by manually running the tool\n \/\/ Values might be wrong.\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image\", 3.6, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Mean\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image\", 14.8, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Mean\"], 0.001);\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )Updated test tolerances\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n#include \"mitkIOUtil.h\"\n#include \n\n#include \n\nclass mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite );\n\n MITK_TEST(ImageDescription_PhantomTest_3D);\n MITK_TEST(ImageDescription_PhantomTest_2D);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n mitk::Image::Pointer m_IBSI_Phantom_Image_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Image_Large;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Small;\n mitk::Image::Pointer m_IBSI_Phantom_Mask_Large;\n\npublic:\n\n void setUp(void) override\n {\n m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Small.nrrd\"));\n m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Image_Large.nrrd\"));\n m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Small.nrrd\"));\n m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath(\"Radiomics\/IBSI_Phantom_Mask_Large.nrrd\"));\n }\n\n void ImageDescription_PhantomTest_3D()\n {\n mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();\n\n featureCalculator->SetUseBinsize(true);\n featureCalculator->SetBinsize(1.0);\n featureCalculator->SetUseMinimumIntensity(true);\n featureCalculator->SetUseMaximumIntensity(true);\n featureCalculator->SetMinimumIntensity(0.5);\n featureCalculator->SetMaximumIntensity(6.5);\n\n auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large);\n\n std::map results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 18 features.\", std::size_t(18), featureList.size());\n\n \/\/ These values are obtained with IBSI\n \/\/ Standard accuracy is 0.01\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image\", 0.255, results[\"Grey Level Size Zone::Small Zone Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image\", 550, results[\"Grey Level Size Zone::Large Zone Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.253, results[\"Grey Level Size Zone::Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image\", 15.6, results[\"Grey Level Size Zone::High Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.0256, results[\"Grey Level Size Zone::Small Zone Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 2.76, results[\"Grey Level Size Zone::Small Zone High Grey Level Emphasis\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 503, results[\"Grey Level Size Zone::Large Zone Low Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 1495, results[\"Grey Level Size Zone::Large Zone High Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image\", 1.4, results[\"Grey Level Size Zone::Grey Level Non-Uniformity\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.28, results[\"Grey Level Size Zone::Grey Level Non-Uniformity Normalized\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image\", 1, results[\"Grey Level Size Zone::Zone Size Non-Uniformity\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.2, results[\"Grey Level Size Zone::Zone Size Non-Uniformity Normalized\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image\", 0.0676, results[\"Grey Level Size Zone::Zone Percentage\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image\", 2.64, results[\"Grey Level Size Zone::Grey Level Variance\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image\", 331, results[\"Grey Level Size Zone::Zone Size Variance\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image\", 2.32, results[\"Grey Level Size Zone::Zone Size Entropy\"], 0.01);\n \/\/CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone:: with Large IBSI Phantom Image\", 0.045, results[\"Grey Level Size Zone::\"], 0.001);\n\n \/\/ These values are obtained by manually running the tool\n \/\/ Values might be wrong.\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image\", 3.6, results[\"Grey Level Size Zone::Grey Level Mean\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image\", 14.8, results[\"Grey Level Size Zone::Zone Size Mean\"], 0.001);\n }\n\n void ImageDescription_PhantomTest_2D()\n {\n mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New();\n\n featureCalculator->SetUseBinsize(true);\n featureCalculator->SetBinsize(1.0);\n featureCalculator->SetUseMinimumIntensity(true);\n featureCalculator->SetUseMaximumIntensity(true);\n featureCalculator->SetMinimumIntensity(0.5);\n featureCalculator->SetMaximumIntensity(6.5);\n\n auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2);\n\n std::map results;\n for (auto valuePair : featureList)\n {\n MITK_INFO << valuePair.first << \" : \" << valuePair.second;\n results[valuePair.first] = valuePair.second;\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Image Diagnostics should calculate 108 features.\", std::size_t(108), featureList.size());\n\n \/\/ These values are obtained with IBSI\n \/\/ Standard accuracy is 0.01\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image\", 0.363, results[\"SliceWise Mean Grey Level Size Zone::Small Zone Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image\", 43.9, results[\"SliceWise Mean Grey Level Size Zone::Large Zone Emphasis\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.371, results[\"SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image\", 16.4, results[\"SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 0.0259, results[\"SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 10.3, results[\"SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image\", 40.4, results[\"SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image\", 113, results[\"SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis\"], 1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image\", 1.41, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.323, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image\", 1.49, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image\", 0.333, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image\", 0.24, results[\"SliceWise Mean Grey Level Size Zone::Zone Percentage\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image\", 3.97, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Variance\"], 0.01);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image\", 21, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Variance\"], 0.1);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image\", 1.93, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Entropy\"], 0.01);\n \/\/CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone:: with Large IBSI Phantom Image\", 0.045, results[\"SliceWise Mean Grey Level Size Zone::\"], 0.001);\n\n \/\/ These values are obtained by manually running the tool\n \/\/ Values might be wrong.\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image\", 3.526, results[\"SliceWise Mean Grey Level Size Zone::Grey Level Mean\"], 0.001);\n CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE(\"SliceWise Mean Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image\", 4.59524, results[\"SliceWise Mean Grey Level Size Zone::Zone Size Mean\"], 0.001);\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )<|endoftext|>"} {"text":"#include \"sampler.hpp\"\n#include \"context.hpp\"\n#include \"texture.hpp\"\n\n#include \"internal\/wrapper.hpp\"\n\n#include \"internal\/modules.hpp\"\n#include \"internal\/tools.hpp\"\n#include \"internal\/glsl.hpp\"\n\n\/* MGLContext.sampler(texture)\n *\/\nPyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {\n if (nargs != 1) {\n \/\/ TODO: error\n return 0;\n }\n\n PyObject * texture = args[0];\n\n MGLSampler * sampler = MGLContext_new_object(self, Sampler);\n\n const GLMethods & gl = self->gl;\n gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj);\n\n if (!sampler->sampler_obj) {\n PyErr_Format(moderngl_error, \"cannot create sampler\");\n Py_DECREF(sampler);\n return 0;\n }\n\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\n SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture;\n return NEW_REF(sampler->wrapper);\n}\n\n\/* MGLSampler.use(location)\n *\/\nPyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) {\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n\n int location = PyLong_AsLong(arg);\n self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj);\n Py_RETURN_NONE;\n}\n\nint MGLSampler_set_filter(MGLSampler * self, PyObject * value) {\n return 0;\n}\n\nenum MGLSamplerWrapModes {\n MGL_CLAMP_TO_EDGE = 0x01,\n MGL_REPEAT = 0x02,\n MGL_MIRRORED_REPEAT = 0x04,\n MGL_MIRROR_CLAMP_TO_EDGE = 0x08,\n MGL_CLAMP_TO_BORDER = 0x10,\n};\n\nint MGLSampler_set_wrap(MGLSampler * self, PyObject * value) {\n int wrap = PyLong_AsLong(value);\n SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap);\n switch (((unsigned char *)&wrap)[0]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n switch (((unsigned char *)&wrap)[1]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n if (texture->texture_target == GL_TEXTURE_3D) {\n switch (((unsigned char *)&wrap)[2]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n } else if (((unsigned char *)&wrap)[2]) {\n return -1;\n }\n return 0;\n}\n\nint MGLSampler_set_border_color(MGLSampler * self, PyObject * value) {\n PyObject * border_color = PySequence_Fast(value, \"not iterable\");\n if (!border_color) {\n return -1;\n }\n float color[4] = {};\n switch (PySequence_Fast_GET_SIZE(border_color)) {\n case 4:\n color[3] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 3));\n case 3:\n color[2] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 2));\n case 2:\n color[1] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 1));\n case 1:\n color[0] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 0));\n default:\n \/\/ TODO: error\n return -1;\n }\n\n\tself->context->gl.SamplerParameterfv(self->sampler_obj, GL_TEXTURE_BORDER_COLOR, color);\n return 0;\n}\n\nint MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) {\n\tfloat anisotropy = (float)PyFloat_AsDouble(value);\n if (anisotropy < 1.0) {\n anisotropy = 1.0;\n }\n \/\/ if (anisotropy > max_anisotropy) {\n \/\/ anisotropy = max_anisotropy;\n \/\/ }\n \/\/ SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy);\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_ANISOTROPY, anisotropy);\n return 0;\n}\n\nint MGLSampler_set_lod_range(MGLSampler * self, PyObject * value) {\n PyObject * lod_range = PySequence_Fast(value, \"not iterable\");\n if (!lod_range) {\n return -1;\n }\n\n int min_lod;\n int max_lod;\n float lod_bias = 0.0f;\n switch (PySequence_Fast_GET_SIZE(lod_range)) {\n case 3:\n lod_bias = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(lod_range, 2));\n case 2:\n min_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 0));\n max_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 1));\n default:\n \/\/ TODO: error\n return -1;\n }\n\n \/\/ SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy);\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod);\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, max_lod);\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_LOD_BIAS, lod_bias);\n return 0;\n}\n\n#if PY_VERSION_HEX >= 0x03070000\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#else\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#endif\n\nPyGetSetDef MGLSampler_getset[] = {\n {\"filter\", 0, (setter)MGLSampler_set_filter, 0, 0},\n {\"wrap\", 0, (setter)MGLSampler_set_wrap, 0, 0},\n {\"anisotropy\", 0, (setter)MGLSampler_set_anisotropy, 0, 0},\n {\"border_color\", 0, (setter)MGLSampler_set_border_color, 0, 0},\n {\"lod_range\", 0, (setter)MGLSampler_set_lod_range, 0, 0},\n {0},\n};\n\nPyType_Slot MGLSampler_slots[] = {\n {Py_tp_methods, MGLSampler_methods},\n {Py_tp_getset, MGLSampler_getset},\n {0},\n};\n\nPyType_Spec MGLSampler_spec = {\n mgl_ext \".Sampler\",\n sizeof(MGLSampler),\n 0,\n Py_TPFLAGS_DEFAULT,\n MGLSampler_slots,\n};\nsampler properties#include \"sampler.hpp\"\n#include \"context.hpp\"\n#include \"texture.hpp\"\n\n#include \"internal\/wrapper.hpp\"\n\n#include \"internal\/modules.hpp\"\n#include \"internal\/tools.hpp\"\n#include \"internal\/glsl.hpp\"\n\n\/* MGLContext.sampler(texture)\n *\/\nPyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {\n if (nargs != 1) {\n \/\/ TODO: error\n return 0;\n }\n\n PyObject * texture = args[0];\n\n MGLSampler * sampler = MGLContext_new_object(self, Sampler);\n\n const GLMethods & gl = self->gl;\n gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj);\n\n if (!sampler->sampler_obj) {\n PyErr_Format(moderngl_error, \"cannot create sampler\");\n Py_DECREF(sampler);\n return 0;\n }\n\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\n SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture;\n return NEW_REF(sampler->wrapper);\n}\n\n\/* MGLSampler.use(location)\n *\/\nPyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) {\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n\n int location = PyLong_AsLong(arg);\n self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj);\n Py_RETURN_NONE;\n}\n\nint MGLSampler_set_filter(MGLSampler * self, PyObject * value) {\n return 0;\n}\n\nenum MGLSamplerWrapModes {\n MGL_CLAMP_TO_EDGE = 0x01,\n MGL_REPEAT = 0x02,\n MGL_MIRRORED_REPEAT = 0x04,\n MGL_MIRROR_CLAMP_TO_EDGE = 0x08,\n MGL_CLAMP_TO_BORDER = 0x10,\n};\n\nint MGLSampler_set_wrap(MGLSampler * self, PyObject * value) {\n int wrap = PyLong_AsLong(value);\n SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap);\n switch (((unsigned char *)&wrap)[0]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n switch (((unsigned char *)&wrap)[1]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n if (texture->texture_target == GL_TEXTURE_3D) {\n switch (((unsigned char *)&wrap)[2]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n } else if (((unsigned char *)&wrap)[2]) {\n return -1;\n }\n return 0;\n}\n\nint MGLSampler_set_border(MGLSampler * self, PyObject * value) {\n PyObject * border = PySequence_Fast(value, \"not iterable\");\n if (!border) {\n return -1;\n }\n\n float color[4] = {};\n\n switch (PySequence_Fast_GET_SIZE(border)) {\n case 4:\n color[3] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 3));\n case 3:\n color[2] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 2));\n case 2:\n color[1] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 1));\n case 1:\n color[0] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 0));\n default:\n Py_DECREF(border);\n \/\/ TODO: error\n return -1;\n }\n\n Py_DECREF(border);\n\n\tself->context->gl.SamplerParameterfv(self->sampler_obj, GL_TEXTURE_BORDER_COLOR, color);\n Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_border), float_tuple(color[0], color[1], color[2], color[3]));\n return 0;\n}\n\nint MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) {\n\tfloat anisotropy = (float)PyFloat_AsDouble(value);\n if (anisotropy < 1.0) {\n anisotropy = 1.0;\n }\n \/\/ TODO: clamp with max value\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_ANISOTROPY, anisotropy);\n Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_anisotropy), PyFloat_FromDouble(anisotropy));\n return 0;\n}\n\nint MGLSampler_set_lod_range(MGLSampler * self, PyObject * value) {\n PyObject * lod_range = PySequence_Fast(value, \"not iterable\");\n if (!lod_range) {\n return -1;\n }\n\n if (PySequence_Fast_GET_SIZE(lod_range) != 2) {\n Py_DECREF(lod_range);\n \/\/ TODO: error\n return -1;\n }\n\n int min_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 0));\n int max_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 1));\n Py_DECREF(lod_range);\n\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod);\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, max_lod);\n Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_lod_range), int_tuple(min_lod, max_lod));\n return 0;\n}\n\nint MGLSampler_set_lod_bias(MGLSampler * self, PyObject * value) {\n\tfloat lod_bias = (float)PyFloat_AsDouble(value);\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_LOD_BIAS, lod_bias);\n Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_lod_bias), PyFloat_FromDouble(lod_bias));\n return 0;\n}\n\n#if PY_VERSION_HEX >= 0x03070000\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#else\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#endif\n\nPyGetSetDef MGLSampler_getset[] = {\n {\"filter\", 0, (setter)MGLSampler_set_filter, 0, 0},\n {\"wrap\", 0, (setter)MGLSampler_set_wrap, 0, 0},\n {\"anisotropy\", 0, (setter)MGLSampler_set_anisotropy, 0, 0},\n {\"border\", 0, (setter)MGLSampler_set_border, 0, 0},\n {\"lod_range\", 0, (setter)MGLSampler_set_lod_range, 0, 0},\n {\"lod_bias\", 0, (setter)MGLSampler_set_lod_bias, 0, 0},\n {0},\n};\n\nPyType_Slot MGLSampler_slots[] = {\n {Py_tp_methods, MGLSampler_methods},\n {Py_tp_getset, MGLSampler_getset},\n {0},\n};\n\nPyType_Spec MGLSampler_spec = {\n mgl_ext \".Sampler\",\n sizeof(MGLSampler),\n 0,\n Py_TPFLAGS_DEFAULT,\n MGLSampler_slots,\n};\n<|endoftext|>"} {"text":"\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n#include \"mitkContourModelLiveWireInteractor.h\"\n\n#include \"mitkInteractionPositionEvent.h\"\n#include \"mitkToolManager.h\"\n\n#include \"mitkBaseRenderer.h\"\n#include \"mitkRenderingManager.h\"\n\n#include \n\n#include \"mitkIOUtil.h\"\n\nmitk::ContourModelLiveWireInteractor::ContourModelLiveWireInteractor() : ContourModelInteractor()\n{\n m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New();\n m_LiveWireFilter->SetUseCostFunction(true);\n m_NextActiveVertexDown.Fill(0);\n m_NextActiveVertexUp.Fill(0);\n}\n\nmitk::ContourModelLiveWireInteractor::~ContourModelLiveWireInteractor()\n{\n}\n\nvoid mitk::ContourModelLiveWireInteractor::ConnectActionsAndFunctions()\n{\n CONNECT_CONDITION(\"checkisOverPoint\", OnCheckPointClick);\n CONNECT_CONDITION(\"mouseMove\", IsHovering);\n\n CONNECT_FUNCTION(\"movePoint\", OnMovePoint);\n CONNECT_FUNCTION(\"deletePoint\", OnDeletePoint);\n CONNECT_FUNCTION(\"addPoint\", OnAddPoint)\n CONNECT_FUNCTION(\"finish\", OnFinishEditing);\n}\n\nbool mitk::ContourModelLiveWireInteractor::OnCheckPointClick(const InteractionEvent *interactionEvent)\n{\n auto isVertexSelected = Superclass::OnCheckPointClick(interactionEvent);\n\n if (isVertexSelected)\n {\n auto* contour = dynamic_cast(this->GetDataNode()->GetData());\n const auto* positionEvent =\n dynamic_cast(interactionEvent);\n mitk::Point3D click = positionEvent->GetPositionInWorld();\n const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData());\n\n auto controlVertices = contour->GetControlVertices(timeStep);\n const mitk::ContourModel::VertexType* nextPoint = contour->GetNextControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep);\n const mitk::ContourModel::VertexType* previousPoint = contour->GetPreviousControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep);\n this->SplitContourFromSelectedVertex(contour, nextPoint, previousPoint, timeStep);\n m_NextActiveVertexUp = nextPoint->Coordinates;\n m_NextActiveVertexDown = previousPoint->Coordinates;\n\n \/\/ clear previous void positions\n this->m_LiveWireFilter->ClearRepulsivePoints();\n\n \/\/ all points in lower and upper part should be marked as repulsive points to not be changed\n this->SetRepulsivePoints(previousPoint, m_ContourLeft, timeStep);\n this->SetRepulsivePoints(nextPoint, m_ContourRight, timeStep);\n\n \/\/ clear container with void points between neighboring control points\n m_ContourBeingModified.clear();\n }\n return isVertexSelected;\n}\n\nvoid mitk::ContourModelLiveWireInteractor::SetWorkingImage(mitk::Image *_arg)\n{\n if (this->m_WorkingSlice != _arg)\n {\n this->m_WorkingSlice = _arg;\n this->m_LiveWireFilter->SetInput(this->m_WorkingSlice);\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnAddPoint(StateMachineAction* sm, InteractionEvent* interactionEvent)\n{\n Superclass::OnAddPoint(sm, interactionEvent);\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnDeletePoint(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData());\n\n auto *contour = dynamic_cast(this->GetDataNode()->GetData());\n if (contour == nullptr)\n {\n MITK_ERROR << \"Invalid Contour!\";\n return;\n }\n\n if (contour->GetSelectedVertex())\n {\n mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();\n newContour->Expand(contour->GetTimeSteps());\n newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone());\n\n newContour->Concatenate(m_ContourLeft, timeStep);\n\n \/\/ recompute contour between neighbored two active control points\n this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown);\n this->m_LiveWireFilter->SetEndPoint(this->m_NextActiveVertexUp);\n this->m_LiveWireFilter->Update();\n\n mitk::ContourModel *liveWireContour = this->m_LiveWireFilter->GetOutput();\n assert(liveWireContour);\n\n if (liveWireContour->IsEmpty(timeStep))\n return;\n\n liveWireContour->RemoveVertexAt(0, timeStep);\n liveWireContour->RemoveVertexAt(liveWireContour->GetNumberOfVertices(timeStep) - 1, timeStep);\n\n \/\/ insert new live wire computed points\n newContour->Concatenate(liveWireContour, timeStep);\n\n \/\/ insert right side of original contour\n newContour->Concatenate(this->m_ContourRight, timeStep);\n\n newContour->SetClosed(contour->IsClosed(timeStep), timeStep);\n\n \/\/ instead of leaving a single point, delete all points\n if (newContour->GetNumberOfVertices(timeStep) <= 2)\n {\n newContour->Clear(timeStep);\n }\n\n this->GetDataNode()->SetData(newContour);\n\n mitk::RenderingManager::GetInstance()->RequestUpdate(interactionEvent->GetSender()->GetRenderWindow());\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnMovePoint(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n const auto *positionEvent = dynamic_cast(interactionEvent);\n if (!positionEvent)\n return;\n\n const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData());\n mitk::Point3D currentPosition = positionEvent->GetPositionInWorld();\n\n auto *contour = dynamic_cast(this->GetDataNode()->GetData());\n if (contour == nullptr)\n {\n MITK_ERROR << \"invalid contour\";\n return;\n }\n\n std::cout << currentPosition << std::endl;\n\n mitk::ContourModel::Pointer editingContour = mitk::ContourModel::New();\n editingContour->Expand(contour->GetTimeSteps());\n editingContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone());\n\n \/\/ recompute left live wire, i.e. the contour between previous active vertex and selected vertex\n this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown);\n this->m_LiveWireFilter->SetEndPoint(currentPosition);\n\n \/\/ remove void positions between previous active vertex and next active vertex.\n if (!m_ContourBeingModified.empty())\n {\n std::vector>::const_iterator iter = m_ContourBeingModified.begin();\n for (; iter != m_ContourBeingModified.end(); iter++)\n {\n this->m_LiveWireFilter->RemoveRepulsivePoint((*iter));\n }\n }\n\n \/\/ update to get the left livewire. Remember that the points in the rest of the contour are already\n \/\/ set as void positions in the filter\n this->m_LiveWireFilter->Update();\n\n mitk::ContourModel::Pointer leftLiveWire = this->m_LiveWireFilter->GetOutput();\n assert(leftLiveWire);\n\n if (!leftLiveWire->IsEmpty(timeStep))\n leftLiveWire->RemoveVertexAt(0, timeStep);\n\n editingContour->Concatenate(leftLiveWire, timeStep);\n\n \/\/ the new index of the selected vertex\n unsigned int selectedVertexIndex =\n this->m_ContourLeft->GetNumberOfVertices(timeStep) + leftLiveWire->GetNumberOfVertices(timeStep) - 1;\n\n \/\/ at this point the container has to be empty\n m_ContourBeingModified.clear();\n\n \/\/ add points from left live wire contour\n auto iter = leftLiveWire->IteratorBegin(timeStep);\n for (; iter != leftLiveWire->IteratorEnd(timeStep); iter++)\n {\n itk::Index<2> idx;\n this->m_WorkingSlice->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx);\n this->m_LiveWireFilter->AddRepulsivePoint(idx);\n\n \/\/ add indices\n m_ContourBeingModified.push_back(idx);\n }\n\n \/\/ recompute right live wire, i.e. the contour between selected vertex and next active vertex\n this->m_LiveWireFilter->SetStartPoint(currentPosition);\n this->m_LiveWireFilter->SetEndPoint(m_NextActiveVertexUp);\n\n \/\/ update filter with all contour points set as void but the right live wire portion to be calculated now\n this->m_LiveWireFilter->Update();\n\n mitk::ContourModel::Pointer rightLiveWire = this->m_LiveWireFilter->GetOutput();\n assert(rightLiveWire);\n\n if (!leftLiveWire->IsEmpty(timeStep))\n leftLiveWire->SetControlVertexAt(leftLiveWire->GetNumberOfVertices() - 1, timeStep);\n\n if (!rightLiveWire->IsEmpty(timeStep))\n rightLiveWire->RemoveVertexAt(0, timeStep);\n\n editingContour->Concatenate(rightLiveWire, timeStep);\n\n mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();\n newContour->Expand(contour->GetTimeSteps());\n newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone());\n\n \/\/ concatenate left original contour\n newContour->Concatenate(this->m_ContourLeft, timeStep);\n\n newContour->Concatenate(editingContour, timeStep, true);\n\n \/\/ set last inserted vertex as selected\n newContour->SelectVertexAt(selectedVertexIndex, timeStep);\n\n \/\/ set as control point\n newContour->SetSelectedVertexAsControlPoint(true);\n\n \/\/ concatenate right original contour\n newContour->Concatenate(this->m_ContourRight, timeStep);\n\n newContour->SetClosed(contour->IsClosed(timeStep), timeStep);\n this->GetDataNode()->SetData(newContour);\n\n mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());\n}\n\n\nvoid mitk::ContourModelLiveWireInteractor::SplitContourFromSelectedVertex(mitk::ContourModel *srcContour,\n const mitk::ContourModel::VertexType *nextPoint,\n const mitk::ContourModel::VertexType *previousPoint,\n int timeStep)\n{\n m_ContourLeft = mitk::ContourModel::New();\n m_ContourRight = mitk::ContourModel::New();\n\n auto it = srcContour->IteratorBegin();\n \/\/ part between nextPoint and end of Countour\n bool upperPart = false;\n \/\/ part between start of countour and previousPoint\n bool lowerPart = true;\n\n \/\/ edge cases when point right before first control vertex is selected or first control vertex is selected\n if (nextPoint == (*it) || srcContour->GetSelectedVertex() == (*it))\n {\n upperPart = true;\n lowerPart = false;\n m_ContourLeft->AddVertex(previousPoint->Coordinates, previousPoint->IsControlPoint, timeStep);\n }\n \/\/ if first control vertex is selected, move to next point before adding vertices to m_ContourRight\n \/\/ otherwise, second line appears when moving the vertex\n if (srcContour->GetSelectedVertex() == (*it))\n {\n while (*it != nextPoint)\n {\n it++;\n }\n }\n\n for (; it != srcContour->IteratorEnd(timeStep); it++)\n {\n \/\/ everything in lower part should be added to m_CountoutLeft\n if (lowerPart)\n {\n m_ContourLeft->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep);\n }\n \/\/ start of \"restricted area\" where no vertex should be added to m_CountoutLeft or m_CountoutRight\n if (*it == previousPoint)\n {\n lowerPart = false;\n upperPart = false;\n }\n \/\/ start of upperPart\n if (*it == nextPoint)\n {\n upperPart = true;\n }\n \/\/ everything in upper part should be added to m_CountoutRight\n if (upperPart)\n {\n m_ContourRight->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep);\n }\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::SetRepulsivePoints(const mitk::ContourModel::VertexType *pointToExclude,\n mitk::ContourModel *contour,\n int timeStep)\n{\n auto it = contour->IteratorBegin();\n for (; it != contour->IteratorEnd(timeStep); it++)\n {\n if (*it != pointToExclude)\n {\n itk::Index<2> idx;\n this->m_WorkingSlice->GetGeometry()->WorldToIndex((*it)->Coordinates, idx);\n this->m_LiveWireFilter->AddRepulsivePoint(idx);\n }\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnFinishEditing(StateMachineAction *, InteractionEvent *)\n{\n\n}\nRemove output from changing livewire points\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n#include \"mitkContourModelLiveWireInteractor.h\"\n\n#include \"mitkInteractionPositionEvent.h\"\n#include \"mitkToolManager.h\"\n\n#include \"mitkBaseRenderer.h\"\n#include \"mitkRenderingManager.h\"\n\n#include \n\n#include \"mitkIOUtil.h\"\n\nmitk::ContourModelLiveWireInteractor::ContourModelLiveWireInteractor() : ContourModelInteractor()\n{\n m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New();\n m_LiveWireFilter->SetUseCostFunction(true);\n m_NextActiveVertexDown.Fill(0);\n m_NextActiveVertexUp.Fill(0);\n}\n\nmitk::ContourModelLiveWireInteractor::~ContourModelLiveWireInteractor()\n{\n}\n\nvoid mitk::ContourModelLiveWireInteractor::ConnectActionsAndFunctions()\n{\n CONNECT_CONDITION(\"checkisOverPoint\", OnCheckPointClick);\n CONNECT_CONDITION(\"mouseMove\", IsHovering);\n\n CONNECT_FUNCTION(\"movePoint\", OnMovePoint);\n CONNECT_FUNCTION(\"deletePoint\", OnDeletePoint);\n CONNECT_FUNCTION(\"addPoint\", OnAddPoint)\n CONNECT_FUNCTION(\"finish\", OnFinishEditing);\n}\n\nbool mitk::ContourModelLiveWireInteractor::OnCheckPointClick(const InteractionEvent *interactionEvent)\n{\n auto isVertexSelected = Superclass::OnCheckPointClick(interactionEvent);\n\n if (isVertexSelected)\n {\n auto* contour = dynamic_cast(this->GetDataNode()->GetData());\n const auto* positionEvent =\n dynamic_cast(interactionEvent);\n mitk::Point3D click = positionEvent->GetPositionInWorld();\n const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData());\n\n auto controlVertices = contour->GetControlVertices(timeStep);\n const mitk::ContourModel::VertexType* nextPoint = contour->GetNextControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep);\n const mitk::ContourModel::VertexType* previousPoint = contour->GetPreviousControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep);\n this->SplitContourFromSelectedVertex(contour, nextPoint, previousPoint, timeStep);\n m_NextActiveVertexUp = nextPoint->Coordinates;\n m_NextActiveVertexDown = previousPoint->Coordinates;\n\n \/\/ clear previous void positions\n this->m_LiveWireFilter->ClearRepulsivePoints();\n\n \/\/ all points in lower and upper part should be marked as repulsive points to not be changed\n this->SetRepulsivePoints(previousPoint, m_ContourLeft, timeStep);\n this->SetRepulsivePoints(nextPoint, m_ContourRight, timeStep);\n\n \/\/ clear container with void points between neighboring control points\n m_ContourBeingModified.clear();\n }\n return isVertexSelected;\n}\n\nvoid mitk::ContourModelLiveWireInteractor::SetWorkingImage(mitk::Image *_arg)\n{\n if (this->m_WorkingSlice != _arg)\n {\n this->m_WorkingSlice = _arg;\n this->m_LiveWireFilter->SetInput(this->m_WorkingSlice);\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnAddPoint(StateMachineAction* sm, InteractionEvent* interactionEvent)\n{\n Superclass::OnAddPoint(sm, interactionEvent);\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnDeletePoint(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData());\n\n auto *contour = dynamic_cast(this->GetDataNode()->GetData());\n if (contour == nullptr)\n {\n MITK_ERROR << \"Invalid Contour!\";\n return;\n }\n\n if (contour->GetSelectedVertex())\n {\n mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();\n newContour->Expand(contour->GetTimeSteps());\n newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone());\n\n newContour->Concatenate(m_ContourLeft, timeStep);\n\n \/\/ recompute contour between neighbored two active control points\n this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown);\n this->m_LiveWireFilter->SetEndPoint(this->m_NextActiveVertexUp);\n this->m_LiveWireFilter->Update();\n\n mitk::ContourModel *liveWireContour = this->m_LiveWireFilter->GetOutput();\n assert(liveWireContour);\n\n if (liveWireContour->IsEmpty(timeStep))\n return;\n\n liveWireContour->RemoveVertexAt(0, timeStep);\n liveWireContour->RemoveVertexAt(liveWireContour->GetNumberOfVertices(timeStep) - 1, timeStep);\n\n \/\/ insert new live wire computed points\n newContour->Concatenate(liveWireContour, timeStep);\n\n \/\/ insert right side of original contour\n newContour->Concatenate(this->m_ContourRight, timeStep);\n\n newContour->SetClosed(contour->IsClosed(timeStep), timeStep);\n\n \/\/ instead of leaving a single point, delete all points\n if (newContour->GetNumberOfVertices(timeStep) <= 2)\n {\n newContour->Clear(timeStep);\n }\n\n this->GetDataNode()->SetData(newContour);\n\n mitk::RenderingManager::GetInstance()->RequestUpdate(interactionEvent->GetSender()->GetRenderWindow());\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnMovePoint(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n const auto *positionEvent = dynamic_cast(interactionEvent);\n if (!positionEvent)\n return;\n\n const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData());\n mitk::Point3D currentPosition = positionEvent->GetPositionInWorld();\n\n auto *contour = dynamic_cast(this->GetDataNode()->GetData());\n if (contour == nullptr)\n {\n MITK_ERROR << \"invalid contour\";\n return;\n }\n\n mitk::ContourModel::Pointer editingContour = mitk::ContourModel::New();\n editingContour->Expand(contour->GetTimeSteps());\n editingContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone());\n\n \/\/ recompute left live wire, i.e. the contour between previous active vertex and selected vertex\n this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown);\n this->m_LiveWireFilter->SetEndPoint(currentPosition);\n\n \/\/ remove void positions between previous active vertex and next active vertex.\n if (!m_ContourBeingModified.empty())\n {\n std::vector>::const_iterator iter = m_ContourBeingModified.begin();\n for (; iter != m_ContourBeingModified.end(); iter++)\n {\n this->m_LiveWireFilter->RemoveRepulsivePoint((*iter));\n }\n }\n\n \/\/ update to get the left livewire. Remember that the points in the rest of the contour are already\n \/\/ set as void positions in the filter\n this->m_LiveWireFilter->Update();\n\n mitk::ContourModel::Pointer leftLiveWire = this->m_LiveWireFilter->GetOutput();\n assert(leftLiveWire);\n\n if (!leftLiveWire->IsEmpty(timeStep))\n leftLiveWire->RemoveVertexAt(0, timeStep);\n\n editingContour->Concatenate(leftLiveWire, timeStep);\n\n \/\/ the new index of the selected vertex\n unsigned int selectedVertexIndex =\n this->m_ContourLeft->GetNumberOfVertices(timeStep) + leftLiveWire->GetNumberOfVertices(timeStep) - 1;\n\n \/\/ at this point the container has to be empty\n m_ContourBeingModified.clear();\n\n \/\/ add points from left live wire contour\n auto iter = leftLiveWire->IteratorBegin(timeStep);\n for (; iter != leftLiveWire->IteratorEnd(timeStep); iter++)\n {\n itk::Index<2> idx;\n this->m_WorkingSlice->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx);\n this->m_LiveWireFilter->AddRepulsivePoint(idx);\n\n \/\/ add indices\n m_ContourBeingModified.push_back(idx);\n }\n\n \/\/ recompute right live wire, i.e. the contour between selected vertex and next active vertex\n this->m_LiveWireFilter->SetStartPoint(currentPosition);\n this->m_LiveWireFilter->SetEndPoint(m_NextActiveVertexUp);\n\n \/\/ update filter with all contour points set as void but the right live wire portion to be calculated now\n this->m_LiveWireFilter->Update();\n\n mitk::ContourModel::Pointer rightLiveWire = this->m_LiveWireFilter->GetOutput();\n assert(rightLiveWire);\n\n if (!leftLiveWire->IsEmpty(timeStep))\n leftLiveWire->SetControlVertexAt(leftLiveWire->GetNumberOfVertices() - 1, timeStep);\n\n if (!rightLiveWire->IsEmpty(timeStep))\n rightLiveWire->RemoveVertexAt(0, timeStep);\n\n editingContour->Concatenate(rightLiveWire, timeStep);\n\n mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();\n newContour->Expand(contour->GetTimeSteps());\n newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone());\n\n \/\/ concatenate left original contour\n newContour->Concatenate(this->m_ContourLeft, timeStep);\n\n newContour->Concatenate(editingContour, timeStep, true);\n\n \/\/ set last inserted vertex as selected\n newContour->SelectVertexAt(selectedVertexIndex, timeStep);\n\n \/\/ set as control point\n newContour->SetSelectedVertexAsControlPoint(true);\n\n \/\/ concatenate right original contour\n newContour->Concatenate(this->m_ContourRight, timeStep);\n\n newContour->SetClosed(contour->IsClosed(timeStep), timeStep);\n this->GetDataNode()->SetData(newContour);\n\n mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());\n}\n\n\nvoid mitk::ContourModelLiveWireInteractor::SplitContourFromSelectedVertex(mitk::ContourModel *srcContour,\n const mitk::ContourModel::VertexType *nextPoint,\n const mitk::ContourModel::VertexType *previousPoint,\n int timeStep)\n{\n m_ContourLeft = mitk::ContourModel::New();\n m_ContourRight = mitk::ContourModel::New();\n\n auto it = srcContour->IteratorBegin();\n \/\/ part between nextPoint and end of Countour\n bool upperPart = false;\n \/\/ part between start of countour and previousPoint\n bool lowerPart = true;\n\n \/\/ edge cases when point right before first control vertex is selected or first control vertex is selected\n if (nextPoint == (*it) || srcContour->GetSelectedVertex() == (*it))\n {\n upperPart = true;\n lowerPart = false;\n m_ContourLeft->AddVertex(previousPoint->Coordinates, previousPoint->IsControlPoint, timeStep);\n }\n \/\/ if first control vertex is selected, move to next point before adding vertices to m_ContourRight\n \/\/ otherwise, second line appears when moving the vertex\n if (srcContour->GetSelectedVertex() == (*it))\n {\n while (*it != nextPoint)\n {\n it++;\n }\n }\n\n for (; it != srcContour->IteratorEnd(timeStep); it++)\n {\n \/\/ everything in lower part should be added to m_CountoutLeft\n if (lowerPart)\n {\n m_ContourLeft->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep);\n }\n \/\/ start of \"restricted area\" where no vertex should be added to m_CountoutLeft or m_CountoutRight\n if (*it == previousPoint)\n {\n lowerPart = false;\n upperPart = false;\n }\n \/\/ start of upperPart\n if (*it == nextPoint)\n {\n upperPart = true;\n }\n \/\/ everything in upper part should be added to m_CountoutRight\n if (upperPart)\n {\n m_ContourRight->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep);\n }\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::SetRepulsivePoints(const mitk::ContourModel::VertexType *pointToExclude,\n mitk::ContourModel *contour,\n int timeStep)\n{\n auto it = contour->IteratorBegin();\n for (; it != contour->IteratorEnd(timeStep); it++)\n {\n if (*it != pointToExclude)\n {\n itk::Index<2> idx;\n this->m_WorkingSlice->GetGeometry()->WorldToIndex((*it)->Coordinates, idx);\n this->m_LiveWireFilter->AddRepulsivePoint(idx);\n }\n }\n}\n\nvoid mitk::ContourModelLiveWireInteractor::OnFinishEditing(StateMachineAction *, InteractionEvent *)\n{\n\n}\n<|endoftext|>"} {"text":"\/*\n * enlargeshrinkplugin.cpp\n *\n * Copyright (C) 2012 Igalia, S.L.\n * Author: Antia Puentes \n *\n * This file is part of the Gallery Enlarge\/Shrink Plugin.\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 * as published by the Free Software Foundation; version 2.1 of\n * the License, or (at your option) any later version.\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, see http:\/\/www.gnu.org\/licenses\/ *\n *\/\n\n#include \"enlargeshrink.h\"\n\n#include \n\n#define FILTER_NAME_ENLARGESHRINK \"com.igalia.enlargeshrink\"\n#define FORCE_OPTION \"force\"\n#define FORCE_FACTOR 3.2\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846264338327950288\n#endif\n\n\/\/ Maximum \"width\" of a pixel, measured diagonally\n#ifndef M_SQRT2\n#define M_SQRT2 1.41421356237309504880168872420969808\n#endif\n\n#define FIXEDPOINT_FRACTIONBITS 8\n#define FIXEDPOINT_MULTIPLIER (1 << FIXEDPOINT_FRACTIONBITS)\n\n\nstatic double fraction(double n)\n{\n return n - floor(n);\n}\n\nstatic int fixedfraction(double n)\n{\n return (int) (fraction(n) * FIXEDPOINT_MULTIPLIER);\n}\n\nstatic QRgb weighpixel(QRgb rgb, int percentage)\n{\n return qRgb((qRed(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2),\n (qGreen(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2),\n (qBlue(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2));\n}\n\n\/*\n * Gets a pixel at a floating-point coordinate, thus causing it to take into\n * accountance neighbour pixels if one of the coordinates have a fractional part\n *\n * The function will calculate the pixel value by calculating all areas the\n * pixel occupies in each neighbouring pixel.\n *\/\nstatic QRgb getPixel(const QImage &img, double x, double y)\n{\n int fx = fixedfraction(x);\n int fy = fixedfraction(y);\n\n int px = (int) x;\n int py = (int) y;\n\n int right = 1;\n if (px >= img.width() - 1) {\n right = 0;\n }\n\n int below = 1;\n if (py >= img.height() - 1) {\n below = 0;\n }\n\n QRgb p1 = weighpixel(img.pixel(px, py), (FIXEDPOINT_MULTIPLIER - fx) * (FIXEDPOINT_MULTIPLIER - fy));\n QRgb p2 = weighpixel(img.pixel(px + right, py), fx * (FIXEDPOINT_MULTIPLIER - fy));\n QRgb p3 = weighpixel(img.pixel(px, py + below), (FIXEDPOINT_MULTIPLIER - fx) * fy);\n QRgb p4 = weighpixel(img.pixel(px + right, py + below), fx * fy);\n\n return qRgb((qRed(p1) + qRed(p2) + qRed(p3) + qRed(p4)),\n (qGreen(p1) + qGreen(p2) + qGreen(p3) + qGreen(p4)),\n (qBlue(p1) + qBlue(p2) + qBlue(p3) + qBlue(p4)));\n\n}\n\n\/**\n * Returns the enlarge\/shrink effect for a given \"n\".\n * The function should be continous and should return 0 for x=0 and return 1 for\n * x = 1 if not, abrupt changes might appear in the image. The function only\n * needs to be valid for the interval [0..1].\n * \\a amplitude should be in the interval [-0.3125, 0.3125], if it is outside\n * this interval the function might return negative values (which might give\n * interesting effects but not an enlarge\/shrink effect)\n * A positive \\a amplitude will give a \"punch\", negative a \"pinch\"\n *\n * Keeping the function linear (return x;) will in theory not change the image,\n * but due to rounding errors one might expect minor distortion.\n *\/\nstatic double distort(double n, double amplitude)\n{\n return n - sin(M_PI * n) * amplitude;\n}\n\nEnlargeShrink::EnlargeShrink() :\n m_Radius(0), m_Center(-1, -1), m_Force(0)\n{\n}\n\nEnlargeShrink::~EnlargeShrink()\n{\n}\n\nconst QString EnlargeShrink::name() const\n{\n return FILTER_NAME_ENLARGESHRINK;\n}\n\nconst QStringList EnlargeShrink::supportedOptions() const\n{\n QStringList supportedOptions;\n supportedOptions << QuillImageFilter::Radius\n << QuillImageFilter::Center\n << FORCE_OPTION;\n return supportedOptions;\n}\n\nbool EnlargeShrink::setOption(const QString &option, const QVariant &value)\n{\n bool ok = false;\n\n if (option == QuillImageFilter::Radius) {\n double radius = value.toDouble(&ok);\n if (ok) {\n m_Radius = radius;\n }\n\n } else if (option == QuillImageFilter::Center) {\n QPoint center = value.toPoint();\n if (!center.isNull()) {\n m_Center = center;\n ok = true;\n }\n\n } else if (option == FORCE_OPTION) {\n double force = value.toDouble(&ok);\n ok = ok && force <= 1.0 && force >= -1.0;\n if (ok) {\n \/\/ Divide by the FORCE_FACTOR to get appropiated values for\n \/\/ the Amplitude used by the \"distort\" function\n m_Force = force\/FORCE_FACTOR;\n }\n }\n\n return ok;\n}\n\nQVariant EnlargeShrink::option(const QString &option) const\n{\n QVariant value;\n\n if (option == QuillImageFilter::Radius) {\n value = m_Radius;\n } else if (option == QuillImageFilter::Center) {\n value = m_Center;\n } else if (option == FORCE_OPTION) {\n value = m_Force * FORCE_FACTOR;\n }\n\n return value;\n}\n\nQuillImage EnlargeShrink::apply(const QuillImage& image) const\n{\n if (image.fullImageSize().isEmpty()) {\n return QImage();\n }\n\n QuillImage out;\n enlargeShrink(image, &out);\n return out;\n}\n\ndouble EnlargeShrink::getRadius(const QuillImage &img) const\n{\n double radius = m_Radius;\n if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) {\n if (img.fullImageSize().width() < img.fullImageSize().height()) {\n radius = radius * img.width() \/ img.fullImageSize().width();\n } else {\n radius = radius * img.height() \/ img.fullImageSize().height();\n }\n }\n return radius;\n}\n\nQPoint EnlargeShrink::getCenter(const QuillImage &img) const\n{\n QPoint center = m_Center;\n if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) {\n center.setX(center.x() * img.width() \/ img.fullImageSize().width());\n center.setY(center.y() * img.height() \/ img.fullImageSize().height());\n }\n return center;\n}\n\nbool EnlargeShrink::enlargeShrink(const QuillImage &img,\n QuillImage *outputImg) const\n{\n *outputImg = img;\n\n double radius = getRadius(img);\n QPoint center = getCenter(img);\n\n for (int y = 0; y < img.height(); y++) {\n for (int x = 0; x < img.width(); x++) {\n int dx = x - center.x();\n int dy = y - center.y();\n double distance = sqrt(dx * dx + dy * dy);\n if (distance <= radius + M_SQRT2) {\n \/\/ Evaluate the area inside the radius + this M_SQRT2\n \/\/ (to reduce aliasing effects)\n double n = distance \/ radius;\n if (n > 0.0 && n < 1.0) {\n n = distort(n, m_Force);\n }\n \/\/ Normalize the distance vector< and find the length after\n \/\/ distortion\n if (dx != 0 || dy != 0) {\n double mag = n * radius\/distance;\n dx = dx * mag;\n dy = dy * mag;\n }\n double tx = center.x() + dx;\n double ty = center.y() + dy;\n \/\/ Crop off overflows\n if (tx > img.width() || tx < 0) tx = x;\n if (ty > img.height() || ty < 0) ty = y;\n\n outputImg->setPixel(x, y, getPixel(img, tx, ty));\n }\n }\n }\n\n return true;\n}\nFixed an overflow\/*\n * enlargeshrinkplugin.cpp\n *\n * Copyright (C) 2012 Igalia, S.L.\n * Author: Antia Puentes \n *\n * This file is part of the Gallery Enlarge\/Shrink Plugin.\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 * as published by the Free Software Foundation; version 2.1 of\n * the License, or (at your option) any later version.\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, see http:\/\/www.gnu.org\/licenses\/ *\n *\/\n\n#include \"enlargeshrink.h\"\n\n#include \n\n#define FILTER_NAME_ENLARGESHRINK \"com.igalia.enlargeshrink\"\n#define FORCE_OPTION \"force\"\n#define FORCE_FACTOR 3.2\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846264338327950288\n#endif\n\n\/\/ Maximum \"width\" of a pixel, measured diagonally\n#ifndef M_SQRT2\n#define M_SQRT2 1.41421356237309504880168872420969808\n#endif\n\n#define FIXEDPOINT_FRACTIONBITS 8\n#define FIXEDPOINT_MULTIPLIER (1 << FIXEDPOINT_FRACTIONBITS)\n\n\nstatic double fraction(double n)\n{\n return n - floor(n);\n}\n\nstatic int fixedfraction(double n)\n{\n return (int) (fraction(n) * FIXEDPOINT_MULTIPLIER);\n}\n\nstatic QRgb weighpixel(QRgb rgb, int percentage)\n{\n return qRgb((qRed(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2),\n (qGreen(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2),\n (qBlue(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2));\n}\n\n\/*\n * Gets a pixel at a floating-point coordinate, thus causing it to take into\n * accountance neighbour pixels if one of the coordinates have a fractional part\n *\n * The function will calculate the pixel value by calculating all areas the\n * pixel occupies in each neighbouring pixel.\n *\/\nstatic QRgb getPixel(const QImage &img, double x, double y)\n{\n int fx = fixedfraction(x);\n int fy = fixedfraction(y);\n\n int px = (int) x;\n int py = (int) y;\n\n int right = 1;\n if (px >= img.width() - 1) {\n right = 0;\n }\n\n int below = 1;\n if (py >= img.height() - 1) {\n below = 0;\n }\n\n QRgb p1 = weighpixel(img.pixel(px, py), (FIXEDPOINT_MULTIPLIER - fx) * (FIXEDPOINT_MULTIPLIER - fy));\n QRgb p2 = weighpixel(img.pixel(px + right, py), fx * (FIXEDPOINT_MULTIPLIER - fy));\n QRgb p3 = weighpixel(img.pixel(px, py + below), (FIXEDPOINT_MULTIPLIER - fx) * fy);\n QRgb p4 = weighpixel(img.pixel(px + right, py + below), fx * fy);\n\n return qRgb((qRed(p1) + qRed(p2) + qRed(p3) + qRed(p4)),\n (qGreen(p1) + qGreen(p2) + qGreen(p3) + qGreen(p4)),\n (qBlue(p1) + qBlue(p2) + qBlue(p3) + qBlue(p4)));\n\n}\n\n\/**\n * Returns the enlarge\/shrink effect for a given \"n\".\n * The function should be continous and should return 0 for x=0 and return 1 for\n * x = 1 if not, abrupt changes might appear in the image. The function only\n * needs to be valid for the interval [0..1].\n * \\a amplitude should be in the interval [-0.3125, 0.3125], if it is outside\n * this interval the function might return negative values (which might give\n * interesting effects but not an enlarge\/shrink effect)\n * A positive \\a amplitude will give a \"punch\", negative a \"pinch\"\n *\n * Keeping the function linear (return x;) will in theory not change the image,\n * but due to rounding errors one might expect minor distortion.\n *\/\nstatic double distort(double n, double amplitude)\n{\n return n - sin(M_PI * n) * amplitude;\n}\n\nEnlargeShrink::EnlargeShrink() :\n m_Radius(0), m_Center(-1, -1), m_Force(0)\n{\n}\n\nEnlargeShrink::~EnlargeShrink()\n{\n}\n\nconst QString EnlargeShrink::name() const\n{\n return FILTER_NAME_ENLARGESHRINK;\n}\n\nconst QStringList EnlargeShrink::supportedOptions() const\n{\n QStringList supportedOptions;\n supportedOptions << QuillImageFilter::Radius\n << QuillImageFilter::Center\n << FORCE_OPTION;\n return supportedOptions;\n}\n\nbool EnlargeShrink::setOption(const QString &option, const QVariant &value)\n{\n bool ok = false;\n\n if (option == QuillImageFilter::Radius) {\n double radius = value.toDouble(&ok);\n if (ok) {\n m_Radius = radius;\n }\n\n } else if (option == QuillImageFilter::Center) {\n QPoint center = value.toPoint();\n if (!center.isNull()) {\n m_Center = center;\n ok = true;\n }\n\n } else if (option == FORCE_OPTION) {\n double force = value.toDouble(&ok);\n ok = ok && force <= 1.0 && force >= -1.0;\n if (ok) {\n \/\/ Divide by the FORCE_FACTOR to get appropiated values for\n \/\/ the Amplitude used by the \"distort\" function\n m_Force = force\/FORCE_FACTOR;\n }\n }\n\n return ok;\n}\n\nQVariant EnlargeShrink::option(const QString &option) const\n{\n QVariant value;\n\n if (option == QuillImageFilter::Radius) {\n value = m_Radius;\n } else if (option == QuillImageFilter::Center) {\n value = m_Center;\n } else if (option == FORCE_OPTION) {\n value = m_Force * FORCE_FACTOR;\n }\n\n return value;\n}\n\nQuillImage EnlargeShrink::apply(const QuillImage& image) const\n{\n if (image.fullImageSize().isEmpty()) {\n return QImage();\n }\n\n QuillImage out;\n enlargeShrink(image, &out);\n return out;\n}\n\ndouble EnlargeShrink::getRadius(const QuillImage &img) const\n{\n double radius = m_Radius;\n if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) {\n if (img.fullImageSize().width() < img.fullImageSize().height()) {\n radius = radius * img.width() \/ img.fullImageSize().width();\n } else {\n radius = radius * img.height() \/ img.fullImageSize().height();\n }\n }\n return radius;\n}\n\nQPoint EnlargeShrink::getCenter(const QuillImage &img) const\n{\n QPoint center = m_Center;\n if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) {\n center.setX(center.x() * img.width() \/ img.fullImageSize().width());\n center.setY(center.y() * img.height() \/ img.fullImageSize().height());\n }\n return center;\n}\n\nbool EnlargeShrink::enlargeShrink(const QuillImage &img,\n QuillImage *outputImg) const\n{\n *outputImg = img;\n\n double radius = getRadius(img);\n QPoint center = getCenter(img);\n\n for (int y = 0; y < img.height(); y++) {\n for (int x = 0; x < img.width(); x++) {\n int dx = x - center.x();\n int dy = y - center.y();\n double distance = sqrt(dx * dx + dy * dy);\n if (distance <= radius + M_SQRT2) {\n \/\/ Evaluate the area inside the radius + this M_SQRT2\n \/\/ (to reduce aliasing effects)\n double n = distance \/ radius;\n if (n > 0.0 && n < 1.0) {\n n = distort(n, m_Force);\n }\n \/\/ Normalize the distance vector< and find the length after\n \/\/ distortion\n if (dx != 0 || dy != 0) {\n double mag = n * radius\/distance;\n dx = dx * mag;\n dy = dy * mag;\n }\n double tx = center.x() + dx;\n double ty = center.y() + dy;\n \/\/ Crop off overflows\n if (tx >= img.width() || tx < 0) tx = x;\n if (ty >= img.height() || ty < 0) ty = y;\n\n outputImg->setPixel(x, y, getPixel(img, tx, ty));\n }\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/*\n$Log$\nRevision 1.1.4.1 2000\/05\/08 15:13:59 cblume\nIntroduce boundary checking\n\nRevision 1.1 2000\/02\/28 18:59:19 cblume\nAdd new TRD classes\n\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Base class of a general container for data of a TRD detector segment. \/\/\n\/\/ Adapted from AliDigits (origin: M.Ivanov). \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TClass.h\"\n#include \"TError.h\"\n#include \"AliTRDsegmentID.h\"\n#include \"AliTRDarrayI.h\"\n#include \"AliTRDdataArray.h\"\n\nClassImp(AliTRDdataArray)\n\n\/\/_____________________________________________________________________________\nAliTRDdataArray::AliTRDdataArray()\n{\n \/\/\n \/\/ Default constructor\n \/\/\n\n fIndex = 0;\n\n fNdim1 = -1;\n fNdim2 = -1;\n fNelems = -1; \n\n fBufType = -1;\n\n fNrow = 0;\n fNcol = 0;\n fNtime = 0;\n\n}\n\n\/\/_____________________________________________________________________________\nAliTRDdataArray::AliTRDdataArray(Int_t nrow, Int_t ncol, Int_t ntime)\n{\n \/\/\n \/\/ Creates a AliTRDdataArray with the dimensions , , and .\n \/\/ The row- and column dimensions are compressible.\n \/\/\n\n Allocate(nrow,ncol,ntime);\n\n}\n\n\/\/_____________________________________________________________________________\nAliTRDdataArray::~AliTRDdataArray()\n{\n \/\/\n \/\/ Destructor\n \/\/\n\n if (fIndex) fIndex->Delete();\n \n}\n\n\/\/_____________________________________________________________________________\nvoid AliTRDdataArray::Allocate(Int_t nrow, Int_t ncol,Int_t ntime)\n{\n \/\/\n \/\/ Allocates memory for a AliTRDdataArray with the dimensions \n \/\/ , , and .\n \/\/ The row- and column dimensions are compressible.\n \/\/\n\n if (nrow <= 0) {\n Error(\"AliTRDdataArray::Allocate\",\"The number of rows has to be positive\");\n exit(1);\n }\n if (ncol <= 0) {\n Error(\"AliTRDdataArray::Allocate\",\"The number of columns has to be positive\");\n exit(1);\n }\n if (ntime <= 0) {\n Error(\"AliTRDdataArray::Allocate\",\"The number of timebins has to be positive\");\n exit(1);\n }\n\n \/\/ The two-dimensional array row\/column gets mapped into the first \n \/\/ dimension of the array. The second array dimension, which is not compressible,\n \/\/ corresponds to the time direction\n fNdim1 = nrow * ncol;\n fNdim2 = ntime;\n fNelems = fNdim1 * fNdim2;\n\n fNrow = nrow;\n fNcol = ncol;\n fNtime = ntime;\n\n if (fIndex) delete fIndex;\n fIndex = new AliTRDarrayI;\n fIndex->Set(fNdim2);\n for (Int_t i = 0, k = 0; i < fNdim2; i++, k += fNdim1) { \n (*fIndex)[i] = k;\n }\n\n fBufType = 0;\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliTRDdataArray::Reset() \n{ \n \/\/\n \/\/ Reset the array (old content gets deleted)\n \/\/\n\n if (fIndex) delete fIndex;\n fIndex = new AliTRDarrayI;\n fIndex->Set(0); \n\n fNdim1 = -1;\n fNdim2 = -1;\n fNelems = -1; \n\n fBufType = -1;\n\n fNrow = 0;\n fNcol = 0;\n fNtime = 0;\n\n}\n\n \nAdded #include \/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/*\n$Log$\nRevision 1.2 2000\/05\/08 16:17:27 cblume\nMerge TRD-develop\n\nRevision 1.1.4.1 2000\/05\/08 15:13:59 cblume\nIntroduce boundary checking\n\nRevision 1.1 2000\/02\/28 18:59:19 cblume\nAdd new TRD classes\n\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Base class of a general container for data of a TRD detector segment. \/\/\n\/\/ Adapted from AliDigits (origin: M.Ivanov). \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"TClass.h\"\n#include \"TError.h\"\n#include \"AliTRDsegmentID.h\"\n#include \"AliTRDarrayI.h\"\n#include \"AliTRDdataArray.h\"\n\nClassImp(AliTRDdataArray)\n\n\/\/_____________________________________________________________________________\nAliTRDdataArray::AliTRDdataArray()\n{\n \/\/\n \/\/ Default constructor\n \/\/\n\n fIndex = 0;\n\n fNdim1 = -1;\n fNdim2 = -1;\n fNelems = -1; \n\n fBufType = -1;\n\n fNrow = 0;\n fNcol = 0;\n fNtime = 0;\n\n}\n\n\/\/_____________________________________________________________________________\nAliTRDdataArray::AliTRDdataArray(Int_t nrow, Int_t ncol, Int_t ntime)\n{\n \/\/\n \/\/ Creates a AliTRDdataArray with the dimensions , , and .\n \/\/ The row- and column dimensions are compressible.\n \/\/\n\n Allocate(nrow,ncol,ntime);\n\n}\n\n\/\/_____________________________________________________________________________\nAliTRDdataArray::~AliTRDdataArray()\n{\n \/\/\n \/\/ Destructor\n \/\/\n\n if (fIndex) fIndex->Delete();\n \n}\n\n\/\/_____________________________________________________________________________\nvoid AliTRDdataArray::Allocate(Int_t nrow, Int_t ncol,Int_t ntime)\n{\n \/\/\n \/\/ Allocates memory for a AliTRDdataArray with the dimensions \n \/\/ , , and .\n \/\/ The row- and column dimensions are compressible.\n \/\/\n\n if (nrow <= 0) {\n Error(\"AliTRDdataArray::Allocate\",\"The number of rows has to be positive\");\n exit(1);\n }\n if (ncol <= 0) {\n Error(\"AliTRDdataArray::Allocate\",\"The number of columns has to be positive\");\n exit(1);\n }\n if (ntime <= 0) {\n Error(\"AliTRDdataArray::Allocate\",\"The number of timebins has to be positive\");\n exit(1);\n }\n\n \/\/ The two-dimensional array row\/column gets mapped into the first \n \/\/ dimension of the array. The second array dimension, which is not compressible,\n \/\/ corresponds to the time direction\n fNdim1 = nrow * ncol;\n fNdim2 = ntime;\n fNelems = fNdim1 * fNdim2;\n\n fNrow = nrow;\n fNcol = ncol;\n fNtime = ntime;\n\n if (fIndex) delete fIndex;\n fIndex = new AliTRDarrayI;\n fIndex->Set(fNdim2);\n for (Int_t i = 0, k = 0; i < fNdim2; i++, k += fNdim1) { \n (*fIndex)[i] = k;\n }\n\n fBufType = 0;\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliTRDdataArray::Reset() \n{ \n \/\/\n \/\/ Reset the array (old content gets deleted)\n \/\/\n\n if (fIndex) delete fIndex;\n fIndex = new AliTRDarrayI;\n fIndex->Set(0); \n\n fNdim1 = -1;\n fNdim2 = -1;\n fNelems = -1; \n\n fBufType = -1;\n\n fNrow = 0;\n fNcol = 0;\n fNtime = 0;\n\n}\n\n \n<|endoftext|>"} {"text":"#include \"StdAfx.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"jrOSGHighlightVisitor.h\"\r\n\r\n\r\njrOSGHighlightVisitor::jrOSGHighlightVisitor(void) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {\r\n}\r\n\r\n\r\njrOSGHighlightVisitor::~jrOSGHighlightVisitor(void) {\r\n}\r\n\r\nvoid jrOSGHighlightVisitor::apply(osg::Node &node) {\r\n\tif (node.getName().find(\"ForeArm.Flat\") != std::string::npos) {\r\n\t\t\/\/std::cout << \"highlighting: \" << node.getName() << std::endl;\r\n\t\t\/\/osgFX::Scribe* scribe = new osgFX::Scribe();\r\n\t\t\/\/osg::Group* parent = node.getParent(0);\r\n\t\t\/\/\r\n\t\t\/\/scribe->setName(\"highlighted\");\r\n\t\t\/\/scribe->setWireframeColor(osg::Vec4(0,1,0,0.5));\r\n\t\t\/\/scribe->addChild(&node);\r\n\t\t\/\/\r\n\t\t\/\/parent->replaceChild(&node, scribe);\r\n\r\n\t\tosg::Group* parent = node.getParent(0);\r\n\r\n\t\tosg::MatrixTransform* transform = new osg::MatrixTransform;\r\n\r\n\t\tconst double angle = 0.1;\r\n\t\tconst osg::Vec3d axis(0, 0, 1);\r\n\t\ttransform->setMatrix(osg::Matrix::rotate(angle, axis));\r\n\t\ttransform->setName(\"trans\");\r\n\t\ttransform->addChild(&node);\r\n\t\tparent->replaceChild(&node, transform);\r\n\r\n\t} \t\r\n\telse if (node.getName().find(\"highlighted\") != std::string::npos) {\r\n\t\tstd::cout << \"removing highlight on: \" << node.getName() << std::endl;\r\n\t\tosg::Group* parent = node.getParent(0);\r\n\t\tosgFX::Scribe* scribe = dynamic_cast(&node);\r\n\t\tparent->replaceChild(&node, scribe->getChild(0));\r\n\t\treturn;\r\n\t}\r\n\r\n\ttraverse(node);\r\n}\r\nMore work on the highlight visitor.#include \"StdAfx.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"jrOSGHighlightVisitor.h\"\r\n\r\n\r\njrOSGHighlightVisitor::jrOSGHighlightVisitor(void) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {\r\n}\r\n\r\n\r\njrOSGHighlightVisitor::~jrOSGHighlightVisitor(void) {\r\n}\r\n\r\nvoid jrOSGHighlightVisitor::apply(osg::Node &node) {\r\n\tif (node.getName().find(\"ForeArm.Flat\") != std::string::npos) {\r\n\t\tstd::cout << \"highlighting: \" << node.getName() << std::endl;\r\n\t\tosgFX::Scribe* scribe = new osgFX::Scribe();\r\n\t\tosg::Group* parent = node.getParent(0);\r\n\t\t\r\n\t\tscribe->setName(\"highlighted\");\r\n\t\tscribe->setWireframeColor(osg::Vec4(0,1,0,0.5));\r\n\t\tscribe->addChild(&node);\r\n\t\t\r\n\t\tparent->replaceChild(&node, scribe);\r\n\r\n\t\tparent = node.getParent(0);\r\n\t\t\r\n\t\tosg::MatrixTransform* transform = new osg::MatrixTransform;\r\n\t\t\r\n\t\tconst double angle = 0.1;\r\n\t\tconst osg::Vec3d axis(0, 0, 1);\r\n\t\ttransform->setMatrix(osg::Matrix::rotate(angle, axis));\r\n\t\ttransform->setName(\"trans\");\r\n\t\ttransform->addChild(&node);\r\n\t\tparent->replaceChild(&node, transform);\r\n\r\n\t} \t\r\n\telse if (node.getName().find(\"highlighted\") != std::string::npos) {\r\n\t\tstd::cout << \"removing highlight on: \" << node.getName() << std::endl;\r\n\t\tosg::Group* parent = node.getParent(0);\r\n\t\tosgFX::Scribe* scribe = dynamic_cast(&node);\r\n\t\tparent->replaceChild(&node, scribe->getChild(0));\r\n\t\treturn;\r\n\t}\r\n\r\n\r\n\r\n\r\n\ttraverse(node);\r\n}\r\n<|endoftext|>"} {"text":"\/************************************************************************************\n** \n* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.\n*\n*************************************************************************************\/\n\/**\n* @GFile g_file.cpp\n* @version \n* @brief \n* @author duye\n* @date\t 2013-06-20\n* @note\n*\n* 1. 2013-06-20 duye Created this GFile\n* \n*\/\n#include \n#include \n#include \n#include \n#include \n\nnamespace gsys {\n\n\/\/ default create GFile permissions\nstatic const GUint32 G_FILE_MASK = 0x775;\n\nGResult FileUtil::createFile(const GInt8* filePath)\n{\n return createFile(filePath, 0);\n}\n\nGResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)\n{\n GInt32 fd = ::creat(filePath, G_FILE_MASK);\n if (fd == -1)\n {\n \treturn G_NO;\n }\n\n if (ftruncate(fd, initSize) == -1)\n {\n \t::close(fd);\n \treturn G_NO;\n }\n\n ::close(fd);\n\n return G_YES;\n}\n\nbool FileUtil::isExist(const GInt8* filePath)\n{\n if (filePath == nullptr)\n {\n \treturn false;\n }\n \n if (access(filePath, 0) < 0)\n {\n \treturn false;\n }\n\n return true;\n}\n\nGResult FileUtil::removeFile(const GInt8* filePath)\n{\n if (filePath == nullptr)\n {\n \treturn G_NO;\n }\n\t\n GInt8 cmd[128] = {0};\n sprintf(cmd, \"rm %s -f\", filePath);\n return System::shell(cmd);\n}\n\nFile::File() : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n m_error[0] = 0;\n m_path[0] = 0;\n}\n\nFile::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n GUint32 len = strlen(filePath);\n if (len < G_PATH_MAX)\n {\n \tmemcpy(m_path, filePath, len);\n \tm_path[len] = 0;\n \tm_pathLen = len;\n }\n \n m_error[0] = 0;\n}\n\nFile::~File() \n{\n close();\n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags)\n{\n return open(fileOpenFlags, G_FILE_MASK); \n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)\n{\n GInt32 openFlags = 0;\n if (fileOpenFlags | G_OPEN_READ)\n {\n \topenFlags = O_RDONLY;\n }\n else if (fileOpenFlags | G_OPEN_WRITE)\n {\n openFlags = O_WRONLY | O_CREAT;\n }\n else if (fileOpenFlags | G_OPEN_RDWR)\n {\n \topenFlags = O_RDWR | O_CREAT; \n }\n else if (fileOpenFlags | G_OPEN_APPEND)\n {\n \tif (openFlags == 0)\n \t{\n return G_NO;\n \t}\n openFlags |= O_APPEND;\n }\n\n if (openFlags == 0)\n {\n \tsetError(\"input open mode error\");\n \treturn G_NO;\n }\n\n return orgOpen(openFlags, mode); \n}\n\nGResult File::close()\n{\n if (m_fd < 0)\n {\n setError(\"file don't open\");\n return G_NO;\n }\n\n GResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);\n\n m_fd = -1;\n m_path[0] = 0;\n m_flags = 0;\n\n return ret;\n}\n\nGInt64 File::getSize()\n{\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n } \n\n struct stat\tfileStat;\n fstat(m_fd, &fileStat); \n\n return (GInt64)(fileStat.st_size);\n}\n\nGInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)\n{\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n } \n\n GInt32 sysFlags = -1;\n\n switch(flags)\n {\n\tcase G_SEEK_BEG:\n sysFlags = SEEK_SET;\n break;\n\tcase G_SEEK_CUR:\n sysFlags = SEEK_CUR;\n break;\n\tcase G_SEEK_END:\n sysFlags = SEEK_END;\n break;\n\tdefault:\n\t return G_NO;\n\t break;\n }\n\n return ::lseek(m_fd, offset, sysFlags);\n}\n\nGInt64 File::tell()\n{\n return seek(0, G_SEEK_CUR);\n}\n\nGInt64 File::read(GInt8* buffer, const GUint64 size)\n{\n if (buffer == NULL || size <= 0)\n {\n \tsetError(\"input parameter is error\");\n \treturn G_NO; \n }\n\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n }\n\n return ::read(m_fd, buffer, size);\n}\n\nGInt64 File::write(const GInt8* data, const GUint64 length)\n{\n if (data == NULL || length <= 0)\n {\n \tsetError(\"input parameter is error\");\n \treturn G_NO; \n }\n\n if (m_fd <= 0)\n {\n setError(\"file don't open\");\n return G_NO;\n }\n\n return ::write(m_fd, data, length);\n}\n\nGInt8* File::getError()\n{\n return m_error;\n}\n\nGResult File::orgOpen(const GInt32 flags, const GUint32 mode)\n{ \n if (m_fd > 0)\n {\n \tsetError(\"file had opened\");\n \treturn G_NO;\n }\n\n if (m_pathLen == 0)\n {\n \tsetError(\"hasn't set file path\");\n \treturn G_NO; \n }\n\n m_fd = ::open(m_path, flags, mode);\n if (m_fd > 0)\n {\n \tm_flags = flags;\n }\n else\n {\n \tsetError(\"open file failed, check whether exist this file path\");\n }\n\n return (m_fd != -1 ? true : false);\n}\n\nvoid File::setError(const GInt8* args, ...)\n{\n System::pformat(m_error, G_ERROR_BUF_SIZE, args);\n}\nUpdate g_file.cpp\/************************************************************************************\n** \n* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.\n*\n*************************************************************************************\/\n\/**\n* @GFile g_file.cpp\n* @version \n* @brief \n* @author duye\n* @date\t 2013-06-20\n* @note\n*\n* 1. 2013-06-20 duye Created this GFile\n* \n*\/\n#include \n#include \n#include \n#include \n#include \n\nnamespace gsys {\n\n\/\/ default create GFile permissions\nstatic const GUint32 G_FILE_MASK = 0x775;\n\nGResult FileUtil::createFile(const GInt8* filePath)\n{\n return createFile(filePath, 0);\n}\n\nGResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)\n{\n GInt32 fd = ::creat(filePath, G_FILE_MASK);\n if (fd == -1)\n {\n \treturn G_NO;\n }\n\n if (ftruncate(fd, initSize) == -1)\n {\n \t::close(fd);\n \treturn G_NO;\n }\n\n ::close(fd);\n\n return G_YES;\n}\n\nbool FileUtil::isExist(const GInt8* filePath)\n{\n if (filePath == nullptr)\n {\n \treturn false;\n }\n \n if (access(filePath, 0) < 0)\n {\n \treturn false;\n }\n\n return true;\n}\n\nGResult FileUtil::removeFile(const GInt8* filePath)\n{\n if (filePath == nullptr)\n {\n \treturn G_NO;\n }\n\t\n GInt8 cmd[128] = {0};\n sprintf(cmd, \"rm %s -f\", filePath);\n return System::shell(cmd);\n}\n\nFile::File() : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n m_error[0] = 0;\n m_path[0] = 0;\n}\n\nFile::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n GUint32 len = strlen(filePath);\n if (len < G_PATH_MAX)\n {\n \tmemcpy(m_path, filePath, len);\n \tm_path[len] = 0;\n \tm_pathLen = len;\n }\n \n m_error[0] = 0;\n}\n\nFile::~File() \n{\n close();\n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags)\n{\n return open(fileOpenFlags, G_FILE_MASK); \n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)\n{\n GInt32 openFlags = 0;\n if (fileOpenFlags | G_OPEN_READ)\n {\n \topenFlags = O_RDONLY;\n }\n else if (fileOpenFlags | G_OPEN_WRITE)\n {\n openFlags = O_WRONLY | O_CREAT;\n }\n else if (fileOpenFlags | G_OPEN_RDWR)\n {\n \topenFlags = O_RDWR | O_CREAT; \n }\n else if (fileOpenFlags | G_OPEN_APPEND)\n {\n \tif (openFlags == 0)\n \t{\n return G_NO;\n \t}\n openFlags |= O_APPEND;\n }\n\n if (openFlags == 0)\n {\n \tsetError(\"input open mode error\");\n \treturn G_NO;\n }\n\n return orgOpen(openFlags, mode); \n}\n\nGResult File::close()\n{\n if (m_fd < 0)\n {\n setError(\"file don't open\");\n return G_NO;\n }\n\n GResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);\n\n m_fd = -1;\n m_path[0] = 0;\n m_flags = 0;\n\n return ret;\n}\n\nGInt64 File::getSize()\n{\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n } \n\n struct stat\tfileStat;\n fstat(m_fd, &fileStat); \n\n return (GInt64)(fileStat.st_size);\n}\n\nGInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)\n{\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n } \n\n GInt32 sysFlags = -1;\n\n switch(flags)\n {\n\tcase G_SEEK_BEG:\n sysFlags = SEEK_SET;\n break;\n\tcase G_SEEK_CUR:\n sysFlags = SEEK_CUR;\n break;\n\tcase G_SEEK_END:\n sysFlags = SEEK_END;\n break;\n\tdefault:\n\t return G_NO;\n\t break;\n }\n\n return ::lseek(m_fd, offset, sysFlags);\n}\n\nGInt64 File::tell()\n{\n return seek(0, G_SEEK_CUR);\n}\n\nGInt64 File::read(GInt8* buffer, const GUint64 size)\n{\n if (buffer == NULL || size <= 0)\n {\n \tsetError(\"input parameter is error\");\n \treturn G_NO; \n }\n\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n }\n\n return ::read(m_fd, buffer, size);\n}\n\nGInt64 File::write(const GInt8* data, const GUint64 length)\n{\n if (data == NULL || length <= 0)\n {\n \tsetError(\"input parameter is error\");\n \treturn G_NO; \n }\n\n if (m_fd <= 0)\n {\n setError(\"file don't open\");\n return G_NO;\n }\n\n return ::write(m_fd, data, length);\n}\n\nGInt8* File::getError()\n{\n return m_error;\n}\n\nGResult File::orgOpen(const GInt32 flags, const GUint32 mode)\n{ \n if (m_fd > 0)\n {\n \tsetError(\"file had opened\");\n \treturn G_NO;\n }\n\n if (m_pathLen == 0)\n {\n \tsetError(\"hasn't set file path\");\n \treturn G_NO; \n }\n\n m_fd = ::open(m_path, flags, mode);\n if (m_fd > 0)\n {\n \tm_flags = flags;\n }\n else\n {\n \tsetError(\"open file failed, check whether exist this file path\");\n }\n\n return (m_fd != -1 ? true : false);\n}\n\nvoid File::setError(const GInt8* args, ...)\n{\n System::pformat(m_error, G_ERROR_BUF_SIZE, args);\n}\n}\n<|endoftext|>"} {"text":"#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include \"TError.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\n#include \"qaRec\/AliTRDrecoTask.h\"\n\n#endif\n\n#include \"run.h\"\n\nChar_t *libs[] = {\"libProofPlayer.so\", \"libANALYSIS.so\", \"libTRDqaRec.so\", \"libPyROOT\"};\n\nvoid makeResults(Char_t *tasks = \"ALL\", Char_t* dir=0x0)\n{\n\t\/\/ Load Libraries in interactive mode\n Int_t nlibs = static_cast(sizeof(libs)\/sizeof(Char_t *));\n for(Int_t ilib=0; ilibLoad(libs[ilib]) >= 0) continue;\n printf(\"Failed to load %s.\\n\", libs[ilib]);\n return;\n }\n\n\n gStyle->SetOptStat(0);\n Bool_t mc = kTRUE;\n Bool_t friends = kTRUE;\n\n \/\/ select tasks to process; we should move it to an \n \/\/ individual function and move the task identifiers \n \/\/ outside the const space\n TObjArray *tasksArray = TString(tasks).Tokenize(\" \");\n Int_t fSteerTask = 0;\n for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){\n TString s = (dynamic_cast(tasksArray->UncheckedAt(isel)))->String();\n if(s.CompareTo(\"ALL\") == 0){\n for(Int_t itask = 1; itask < fknTasks; itask++) SETBIT(fSteerTask, itask);\n continue;\n } else if(s.CompareTo(\"NOFR\") == 0){ \n friends = kFALSE;\n } else if(s.CompareTo(\"NOMC\") == 0){ \n mc = kFALSE;\n } else { \n Bool_t foundOpt = kFALSE; \n for(Int_t itask = 1; itask < fknTasks; itask++){\n if(s.CompareTo(fTaskOpt[itask]) != 0) continue;\n SETBIT(fSteerTask, itask);\n foundOpt = kTRUE;\n break;\n }\n if(!foundOpt) Info(\"makeResults.C\", Form(\"Task %s not implemented (yet).\", s.Data()));\n }\n }\n\n\n \/\/ catch the list of files using the ROOT Python Interface\n TPython *pyshell = new TPython();\n pyshell->Exec(\"import commands\");\n\n \/\/ file merger object\n TFileMerger *fFM = new TFileMerger();\n TClass *ctask = 0x0;\n TObject *o = 0x0;\n TObjArray *fContainer = 0x0;\n AliTRDrecoTask *task = 0x0;\n\n if(gSystem->AccessPathName(Form(\"%s\/merge\", gSystem->ExpandPathName(\"$PWD\")))) gSystem->Exec(Form(\"mkdir -v %s\/merge\", gSystem->ExpandPathName(\"$PWD\")));\n\n printf(\"\\n\\tPROCESSING DATA FOR TASKS [%b]:\\n\", fSteerTask);\n for(Int_t itask = 1; itask New();\n task->SetDebugLevel(0);\n task->SetMCdata(mc);\n task->SetFriends(friends);\n printf(\"\\t%s [%s]\\n\", task->GetTitle(), task->GetName());\n\n \/\/ setup filelist\n TString pathname = gSystem->ExpandPathName( dir ? dir : \"$PWD\");\n TString filestring((const Char_t*) pyshell->Eval(Form(\"commands.getstatusoutput(\\\"find %s | grep TRD.Task%s.root\\\")[1]\", pathname.Data(), task->GetName())));\n TObjArray *filenames = filestring.Tokenize(\"\\n\");\n Int_t nFiles = filenames->GetEntriesFast();\n if(!nFiles){\n printf(\"No Files found for Task %s\\n\", task->GetName());\n delete task;\n delete ctask;\n continue;\n }\n\n if(nFiles>1){\n fFM = new(fFM) TFileMerger(kTRUE);\n fFM->OutputFile(Form(\"%s\/merge\/TRD.Task%s.root\", gSystem->ExpandPathName(\"$PWD\"), task->GetName()));\n for(Int_t ifile = 0; ifile < nFiles; ifile++){\n TString filename = (dynamic_cast(filenames->UncheckedAt(ifile)))->String();\n if(filename.Contains(\"merge\")) continue;\n \/\/printf(\"\\tProcessing %s ...\\n\", filename.Data());\n fFM->AddFile(filename.Data());\n }\n fFM->Merge();\n fFM->~TFileMerger();\n task->Load(Form(\"%s\/merge\/TRD.Task%s.root\", gSystem->ExpandPathName(\"$PWD\"), task->GetName()));\n } else task->Load((dynamic_cast(filenames->UncheckedAt(0)))->String().Data());\n\n if(!(fContainer = task->Container())) {\n delete task;\n delete ctask;\n continue;\n } \n \n task->PostProcess();\n for(Int_t ipic=0; ipicGetNRefFigures(); ipic++){\n TCanvas *c = new TCanvas(\"c\", \"\", 500, 500);\n Int_t ifirst, ilast; Option_t *opt;\n TH1 *h = 0x0; TGraph *g = 0x0;\n task->GetRefFigure(ipic, ifirst, ilast, opt);\n if(!(o = fContainer->At(ifirst))) continue;\n \n if(o->InheritsFrom(\"TH1\")){ \n h = dynamic_cast(o);\n h->Draw(opt);\n } else if(o->InheritsFrom(\"TGraph\")){ \n g = dynamic_cast(o);\n g->Draw(opt);\n } else{\n printf(\"No idea how to plot object of type %s.\\n\", o->IsA()->GetName());\n printf(\"Please teach me.\\n\");\n continue;\n }\n\n for(Int_t ig=ifirst+1; igAt(ig))) continue;\n if(o->InheritsFrom(\"TH1\")){\n h = dynamic_cast(o);\n h->Draw(Form(\"%ssame\", opt));\n } else if(o->InheritsFrom(\"TGraph\")){\n g = dynamic_cast(o);\n g->Draw(opt);\n }\n }\n c->SaveAs(Form(\"%s_fig%d.gif\", task->GetName(), ipic));\n delete c;\n }\n delete task;\n delete ctask;\n }\n delete pyshell;\n}\n\nsmall fix for drawing superimposed graphs#if ! defined (__CINT__) || defined (__MAKECINT__)\n#include \"TError.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\n#include \"qaRec\/AliTRDrecoTask.h\"\n\n#endif\n\n#include \"run.h\"\n\nChar_t *libs[] = {\"libProofPlayer.so\", \"libANALYSIS.so\", \"libTRDqaRec.so\", \"libPyROOT\"};\n\nvoid makeResults(Char_t *tasks = \"ALL\", Char_t* dir=0x0)\n{\n\t\/\/ Load Libraries in interactive mode\n Int_t nlibs = static_cast(sizeof(libs)\/sizeof(Char_t *));\n for(Int_t ilib=0; ilibLoad(libs[ilib]) >= 0) continue;\n printf(\"Failed to load %s.\\n\", libs[ilib]);\n return;\n }\n\n\n gStyle->SetOptStat(0);\n Bool_t mc = kTRUE;\n Bool_t friends = kTRUE;\n\n \/\/ select tasks to process; we should move it to an \n \/\/ individual function and move the task identifiers \n \/\/ outside the const space\n TObjArray *tasksArray = TString(tasks).Tokenize(\" \");\n Int_t fSteerTask = 0;\n for(Int_t isel = 0; isel < tasksArray->GetEntriesFast(); isel++){\n TString s = (dynamic_cast(tasksArray->UncheckedAt(isel)))->String();\n if(s.CompareTo(\"ALL\") == 0){\n for(Int_t itask = 1; itask < fknTasks; itask++) SETBIT(fSteerTask, itask);\n continue;\n } else if(s.CompareTo(\"NOFR\") == 0){ \n friends = kFALSE;\n } else if(s.CompareTo(\"NOMC\") == 0){ \n mc = kFALSE;\n } else { \n Bool_t foundOpt = kFALSE; \n for(Int_t itask = 1; itask < fknTasks; itask++){\n if(s.CompareTo(fTaskOpt[itask]) != 0) continue;\n SETBIT(fSteerTask, itask);\n foundOpt = kTRUE;\n break;\n }\n if(!foundOpt) Info(\"makeResults.C\", Form(\"Task %s not implemented (yet).\", s.Data()));\n }\n }\n\n\n \/\/ catch the list of files using the ROOT Python Interface\n TPython *pyshell = new TPython();\n pyshell->Exec(\"import commands\");\n\n \/\/ file merger object\n TFileMerger *fFM = new TFileMerger();\n TClass *ctask = 0x0;\n TObject *o = 0x0;\n TObjArray *fContainer = 0x0;\n AliTRDrecoTask *task = 0x0;\n\n if(gSystem->AccessPathName(Form(\"%s\/merge\", gSystem->ExpandPathName(\"$PWD\")))) gSystem->Exec(Form(\"mkdir -v %s\/merge\", gSystem->ExpandPathName(\"$PWD\")));\n\n printf(\"\\n\\tPROCESSING DATA FOR TASKS [%b]:\\n\", fSteerTask);\n for(Int_t itask = 1; itask New();\n task->SetDebugLevel(0);\n task->SetMCdata(mc);\n task->SetFriends(friends);\n printf(\"\\t%s [%s]\\n\", task->GetTitle(), task->GetName());\n\n \/\/ setup filelist\n TString pathname = gSystem->ExpandPathName( dir ? dir : \"$PWD\");\n TString filestring((const Char_t*) pyshell->Eval(Form(\"commands.getstatusoutput(\\\"find %s | grep TRD.Task%s.root\\\")[1]\", pathname.Data(), task->GetName())));\n TObjArray *filenames = filestring.Tokenize(\"\\n\");\n Int_t nFiles = filenames->GetEntriesFast();\n if(!nFiles){\n printf(\"No Files found for Task %s\\n\", task->GetName());\n delete task;\n delete ctask;\n continue;\n }\n\n if(nFiles>1){\n fFM = new(fFM) TFileMerger(kTRUE);\n fFM->OutputFile(Form(\"%s\/merge\/TRD.Task%s.root\", gSystem->ExpandPathName(\"$PWD\"), task->GetName()));\n for(Int_t ifile = 0; ifile < nFiles; ifile++){\n TString filename = (dynamic_cast(filenames->UncheckedAt(ifile)))->String();\n if(filename.Contains(\"merge\")) continue;\n \/\/printf(\"\\tProcessing %s ...\\n\", filename.Data());\n fFM->AddFile(filename.Data());\n }\n fFM->Merge();\n fFM->~TFileMerger();\n task->Load(Form(\"%s\/merge\/TRD.Task%s.root\", gSystem->ExpandPathName(\"$PWD\"), task->GetName()));\n } else task->Load((dynamic_cast(filenames->UncheckedAt(0)))->String().Data());\n\n if(!(fContainer = task->Container())) {\n delete task;\n delete ctask;\n continue;\n } \n \n task->PostProcess();\n for(Int_t ipic=0; ipicGetNRefFigures(); ipic++){\n TCanvas *c = new TCanvas(\"c\", \"\", 500, 500);\n Int_t ifirst, ilast; Option_t *opt;\n TH1 *h = 0x0; TGraph *g = 0x0;\n task->GetRefFigure(ipic, ifirst, ilast, opt);\n if(!(o = fContainer->At(ifirst))) continue;\n \n if(o->InheritsFrom(\"TH1\")){ \n h = dynamic_cast(o);\n h->Draw(opt);\n } else if(o->InheritsFrom(\"TGraph\")){ \n g = dynamic_cast(o);\n g->Draw(Form(\"a%s\", opt));\n } else{\n printf(\"No idea how to plot object of type %s.\\n\", o->IsA()->GetName());\n printf(\"Please teach me.\\n\");\n continue;\n }\n\n for(Int_t ig=ifirst+1; igAt(ig))) continue;\n if(o->InheritsFrom(\"TH1\")){\n h = dynamic_cast(o);\n h->Draw(Form(\"%ssame\", opt));\n } else if(o->InheritsFrom(\"TGraph\")){\n g = dynamic_cast(o);\n g->Draw(opt);\n }\n }\n c->SaveAs(Form(\"%s_fig%d.gif\", task->GetName(), ipic));\n delete c;\n }\n delete task;\n delete ctask;\n }\n delete pyshell;\n}\n\n<|endoftext|>"} {"text":"\/**\n * Copyright © 2012, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All rights reserved.\n * \n * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed\n * 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\/\n\n\/**\n * @file tgHillyGround.cpp\n * @brief Contains the implementation of class tgHillyGround\n * @author Steven Lessard\n * $Id$\n *\/\n\n\/\/This Module\n#include \"tgHillyGround.h\"\n\n\/\/Bullet Physics\n#include \"BulletCollision\/CollisionShapes\/btBoxShape.h\"\n#include \"BulletCollision\/CollisionShapes\/btTriangleIndexVertexArray.h\"\n#include \"BulletCollision\/CollisionShapes\/btBvhTriangleMeshShape.h\"\n#include \"BulletDynamics\/Dynamics\/btRigidBody.h\"\n#include \"LinearMath\/btDefaultMotionState.h\"\n#include \"LinearMath\/btTransform.h\"\n\n\/\/ The C++ Standard Library\n#include \n#include \/\/For debugging\n\ntgHillyGround::Config::Config(btVector3 eulerAngles,\n btScalar friction,\n btScalar restitution,\n btVector3 size,\n btVector3 origin,\n size_t nx,\n size_t ny,\n double margin,\n double triangleSize,\n double waveHeight,\n double offset) :\n m_eulerAngles(eulerAngles),\n m_friction(friction),\n m_restitution(restitution),\n m_size(size),\n m_origin(origin),\n m_nx(nx),\n m_ny(ny),\n m_margin(margin),\n m_triangleSize(triangleSize),\n m_waveHeight(waveHeight),\n m_offset(offset)\n{\n assert((m_friction >= 0.0) && (m_friction <= 1.0));\n assert((m_restitution >= 0.0) && (m_restitution <= 1.0));\n assert((m_size[0] >= 0.0) && (m_size[1] >= 0.0) && (m_size[2] >= 0.0));\n assert(m_nx > 0);\n assert(m_ny > 0);\n assert(m_margin >= 0.0);\n assert(m_triangleSize >= 0.0);\n assert(m_waveHeight >= 0.0);\n assert(m_offset >= 0.0);\n}\n\ntgHillyGround::tgHillyGround() :\n m_config(Config())\n{\n \/\/ @todo make constructor aux to avoid repeated code\n pGroundShape = hillyCollisionShape();\n}\n\ntgHillyGround::tgHillyGround(const tgHillyGround::Config& config) :\n m_config(config)\n{\n pGroundShape = hillyCollisionShape();\n}\n\nbtRigidBody* tgHillyGround::getGroundRigidBody() const\n{\n const btScalar mass = 0.0;\n\n btTransform groundTransform;\n groundTransform.setIdentity();\n groundTransform.setOrigin(m_config.m_origin);\n\n btQuaternion orientation;\n orientation.setEuler(m_config.m_eulerAngles[0], \/\/ Yaw\n m_config.m_eulerAngles[1], \/\/ Pitch\n m_config.m_eulerAngles[2]); \/\/ Roll\n groundTransform.setRotation(orientation);\n\n \/\/ Using motionstate is recommended\n \/\/ It provides interpolation capabilities, and only synchronizes 'active' objects\n btDefaultMotionState* const pMotionState =\n new btDefaultMotionState(groundTransform);\n\n const btVector3 localInertia(0, 0, 0);\n\n btRigidBody::btRigidBodyConstructionInfo const rbInfo(mass, pMotionState, pGroundShape, localInertia);\n\n btRigidBody* const pGroundBody = new btRigidBody(rbInfo);\n\n assert(pGroundBody);\n return pGroundBody;\n} \n\nbtCollisionShape* tgHillyGround::hillyCollisionShape() {\n btCollisionShape * pShape = 0;\n \/\/ The number of vertices in the mesh\n \/\/ Hill Paramenters: Subject to Change\n const size_t vertexCount = m_config.m_nx * m_config.m_ny;\n std::cout << \"vertexCount: \" << vertexCount << std::endl;\n\n std::cout << \"In hillyCollisionShape()\" << std::endl;\n if (vertexCount > 0) {\n \/\/ The number of triangles in the mesh\n const size_t triangleCount = 2 * (m_config.m_nx - 1) * (m_config.m_ny - 1);\n std::cout << \"triangleCount: \" << triangleCount << std::endl;\n\n \/\/ A flattened array of all vertices in the mesh\n btVector3 * const vertices = new btVector3[vertexCount];\n\n \/\/ Supplied by the derived class\n setVertices(vertices);\n \/\/ A flattened array of indices for each corner of each triangle\n int *indices = new int[triangleCount * 3];\n\n \/\/ Supplied by the derived class\n setIndices(indices);\n\n \/\/ Create the mesh object\n btTriangleIndexVertexArray* const pMesh =\n createMesh(triangleCount, indices, vertexCount, vertices);\n\n \/\/ Create the shape object\n pShape = createShape(pMesh);\n\n \/\/ Set the margin\n pShape->setMargin(m_config.m_margin);\n \/\/ DO NOT deallocate vertices, indices or pMesh! The shape owns them.\n }\n\n assert(pShape);\n return pShape; \n}\n\nbtTriangleIndexVertexArray *tgHillyGround::createMesh(size_t triangleCount, int indices[], size_t vertexCount, btVector3 vertices[]) {\n const int vertexStride = sizeof(btVector3);\n const int indexStride = 3 * sizeof(int);\n\n btTriangleIndexVertexArray* const pMesh = \n new btTriangleIndexVertexArray(triangleCount,\n indices,\n indexStride,\n vertexCount,\n (btScalar*) &vertices[0].x(),\n vertexStride);\n return pMesh;\n}\n\nbtCollisionShape *tgHillyGround::createShape(btTriangleIndexVertexArray *pMesh) {\n const bool useQuantizedAabbCompression = true;\n btCollisionShape *const pShape = \n new btBvhTriangleMeshShape(pMesh, useQuantizedAabbCompression);\n return pShape;\n}\n\nvoid tgHillyGround::setVertices(btVector3 vertices[]) {\n for (size_t i = 0; i < m_config.m_nx; i++)\n {\n for (size_t j = 0; j < m_config.m_ny; j++)\n {\n const btScalar x = (i - (m_config.m_nx * 0.5)) * m_config.m_triangleSize;\n const btScalar y = (m_config.m_waveHeight * sinf((float)i) * cosf((float)j) +\n m_config.m_offset);\n const btScalar z = (j - (m_config.m_ny * 0.5)) * m_config.m_triangleSize;\n vertices[i + (j * m_config.m_nx)].setValue(x, y, z);\n }\n }\n}\n\nvoid tgHillyGround::setIndices(int indices[]) {\n int index = 0;\n for (int i = 0; i < m_config.m_nx - 1; i++)\n {\n for (int j = 0; j < m_config.m_ny - 1; j++)\n {\n indices[index++] = (j * m_config.m_nx) + i;\n indices[index++] = (j * m_config.m_nx) + i + 1;\n indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;\n\n indices[index++] = (j * m_config.m_nx) + i;\n indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;\n indices[index++] = ((j + 1) * m_config.m_nx) + i;\n }\n }\n}\n\nRemoved debugging print statements\/**\n * Copyright © 2012, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All rights reserved.\n * \n * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is licensed\n * 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,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n * either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\/\n\n\/**\n * @file tgHillyGround.cpp\n * @brief Contains the implementation of class tgHillyGround\n * @author Steven Lessard\n * $Id$\n *\/\n\n\/\/This Module\n#include \"tgHillyGround.h\"\n\n\/\/Bullet Physics\n#include \"BulletCollision\/CollisionShapes\/btBoxShape.h\"\n#include \"BulletCollision\/CollisionShapes\/btTriangleIndexVertexArray.h\"\n#include \"BulletCollision\/CollisionShapes\/btBvhTriangleMeshShape.h\"\n#include \"BulletDynamics\/Dynamics\/btRigidBody.h\"\n#include \"LinearMath\/btDefaultMotionState.h\"\n#include \"LinearMath\/btTransform.h\"\n\n\/\/ The C++ Standard Library\n#include \n\ntgHillyGround::Config::Config(btVector3 eulerAngles,\n btScalar friction,\n btScalar restitution,\n btVector3 size,\n btVector3 origin,\n size_t nx,\n size_t ny,\n double margin,\n double triangleSize,\n double waveHeight,\n double offset) :\n m_eulerAngles(eulerAngles),\n m_friction(friction),\n m_restitution(restitution),\n m_size(size),\n m_origin(origin),\n m_nx(nx),\n m_ny(ny),\n m_margin(margin),\n m_triangleSize(triangleSize),\n m_waveHeight(waveHeight),\n m_offset(offset)\n{\n assert((m_friction >= 0.0) && (m_friction <= 1.0));\n assert((m_restitution >= 0.0) && (m_restitution <= 1.0));\n assert((m_size[0] >= 0.0) && (m_size[1] >= 0.0) && (m_size[2] >= 0.0));\n assert(m_nx > 0);\n assert(m_ny > 0);\n assert(m_margin >= 0.0);\n assert(m_triangleSize >= 0.0);\n assert(m_waveHeight >= 0.0);\n assert(m_offset >= 0.0);\n}\n\ntgHillyGround::tgHillyGround() :\n m_config(Config())\n{\n \/\/ @todo make constructor aux to avoid repeated code\n pGroundShape = hillyCollisionShape();\n}\n\ntgHillyGround::tgHillyGround(const tgHillyGround::Config& config) :\n m_config(config)\n{\n pGroundShape = hillyCollisionShape();\n}\n\nbtRigidBody* tgHillyGround::getGroundRigidBody() const\n{\n const btScalar mass = 0.0;\n\n btTransform groundTransform;\n groundTransform.setIdentity();\n groundTransform.setOrigin(m_config.m_origin);\n\n btQuaternion orientation;\n orientation.setEuler(m_config.m_eulerAngles[0], \/\/ Yaw\n m_config.m_eulerAngles[1], \/\/ Pitch\n m_config.m_eulerAngles[2]); \/\/ Roll\n groundTransform.setRotation(orientation);\n\n \/\/ Using motionstate is recommended\n \/\/ It provides interpolation capabilities, and only synchronizes 'active' objects\n btDefaultMotionState* const pMotionState =\n new btDefaultMotionState(groundTransform);\n\n const btVector3 localInertia(0, 0, 0);\n\n btRigidBody::btRigidBodyConstructionInfo const rbInfo(mass, pMotionState, pGroundShape, localInertia);\n\n btRigidBody* const pGroundBody = new btRigidBody(rbInfo);\n\n assert(pGroundBody);\n return pGroundBody;\n} \n\nbtCollisionShape* tgHillyGround::hillyCollisionShape() {\n btCollisionShape * pShape = 0;\n \/\/ The number of vertices in the mesh\n \/\/ Hill Paramenters: Subject to Change\n const size_t vertexCount = m_config.m_nx * m_config.m_ny;\n\n if (vertexCount > 0) {\n \/\/ The number of triangles in the mesh\n const size_t triangleCount = 2 * (m_config.m_nx - 1) * (m_config.m_ny - 1);\n\n \/\/ A flattened array of all vertices in the mesh\n btVector3 * const vertices = new btVector3[vertexCount];\n\n \/\/ Supplied by the derived class\n setVertices(vertices);\n \/\/ A flattened array of indices for each corner of each triangle\n int *indices = new int[triangleCount * 3];\n\n \/\/ Supplied by the derived class\n setIndices(indices);\n\n \/\/ Create the mesh object\n btTriangleIndexVertexArray* const pMesh =\n createMesh(triangleCount, indices, vertexCount, vertices);\n\n \/\/ Create the shape object\n pShape = createShape(pMesh);\n\n \/\/ Set the margin\n pShape->setMargin(m_config.m_margin);\n \/\/ DO NOT deallocate vertices, indices or pMesh! The shape owns them.\n }\n\n assert(pShape);\n return pShape; \n}\n\nbtTriangleIndexVertexArray *tgHillyGround::createMesh(size_t triangleCount, int indices[], size_t vertexCount, btVector3 vertices[]) {\n const int vertexStride = sizeof(btVector3);\n const int indexStride = 3 * sizeof(int);\n\n btTriangleIndexVertexArray* const pMesh = \n new btTriangleIndexVertexArray(triangleCount,\n indices,\n indexStride,\n vertexCount,\n (btScalar*) &vertices[0].x(),\n vertexStride);\n return pMesh;\n}\n\nbtCollisionShape *tgHillyGround::createShape(btTriangleIndexVertexArray *pMesh) {\n const bool useQuantizedAabbCompression = true;\n btCollisionShape *const pShape = \n new btBvhTriangleMeshShape(pMesh, useQuantizedAabbCompression);\n return pShape;\n}\n\nvoid tgHillyGround::setVertices(btVector3 vertices[]) {\n for (size_t i = 0; i < m_config.m_nx; i++)\n {\n for (size_t j = 0; j < m_config.m_ny; j++)\n {\n const btScalar x = (i - (m_config.m_nx * 0.5)) * m_config.m_triangleSize;\n const btScalar y = (m_config.m_waveHeight * sinf((float)i) * cosf((float)j) +\n m_config.m_offset);\n const btScalar z = (j - (m_config.m_ny * 0.5)) * m_config.m_triangleSize;\n vertices[i + (j * m_config.m_nx)].setValue(x, y, z);\n }\n }\n}\n\nvoid tgHillyGround::setIndices(int indices[]) {\n int index = 0;\n for (int i = 0; i < m_config.m_nx - 1; i++)\n {\n for (int j = 0; j < m_config.m_ny - 1; j++)\n {\n indices[index++] = (j * m_config.m_nx) + i;\n indices[index++] = (j * m_config.m_nx) + i + 1;\n indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;\n\n indices[index++] = (j * m_config.m_nx) + i;\n indices[index++] = ((j + 1) * m_config.m_nx) + i + 1;\n indices[index++] = ((j + 1) * m_config.m_nx) + i;\n }\n }\n}\n\n<|endoftext|>"} {"text":"these 9 scripts are in icu >= 4.8, but not in 4.6.1<|endoftext|>"} {"text":"\/\/\n\/\/ Electron.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 03\/01\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Electron.hpp\"\n\n#include \n\nusing namespace Electron;\n\nMachine::Machine()\n{\n\tsetup6502();\n}\n\nMachine::~Machine()\n{\n}\n\nunsigned int Machine::perform_bus_operation(CPU6502::BusOperation operation, uint16_t address, uint8_t *value)\n{\n\tprintf(\"%04x\\n\", address);\n\n\tif(address < 32768)\n\t{\n\t\tif(isReadOperation(operation))\n\t\t{\n\t\t\t*value = ram[address];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tram[address] = *value;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(address > 49152)\n\t\t{\n\t\t\tif(isReadOperation(operation)) *value = os[address - 49152];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(isReadOperation(operation)) *value = basic[address - 32768];\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nvoid Machine::set_rom(ROMSlot slot, size_t length, const uint8_t *data)\n{\n\tuint8_t *target = nullptr;\n\tswitch(slot)\n\t{\n\t\tcase ROMTypeBASIC:\ttarget = basic;\tbreak;\n\t\tcase ROMTypeOS:\t\ttarget = os;\tbreak;\n\t}\n\n\tmemcpy(target, data, std::min((size_t)16384, length));\n}\nThis is the bare minimum to prove that the ROM is trying properly to boot.\/\/\n\/\/ Electron.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 03\/01\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Electron.hpp\"\n\n#include \n\nusing namespace Electron;\n\nMachine::Machine()\n{\n\tsetup6502();\n}\n\nMachine::~Machine()\n{\n}\n\nunsigned int Machine::perform_bus_operation(CPU6502::BusOperation operation, uint16_t address, uint8_t *value)\n{\n\tif(address < 32768)\n\t{\n\t\tif(isReadOperation(operation))\n\t\t{\n\t\t\t*value = ram[address];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tram[address] = *value;\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(address > 49152)\n\t\t{\n\t\t\tif((address & 0xff00) == 0xfe00)\n\t\t\t{\n\t\t\t\tprintf(\"%c: %02x: \", isReadOperation(operation) ? 'r' : 'w', *value);\n\n\t\t\t\tswitch(address&0xf)\n\t\t\t\t{\n\t\t\t\t\tcase 0x0:\n\t\t\t\t\t\tprintf(\"Interrupt status or control\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x1:\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x2:\n\t\t\t\t\tcase 0x3:\n\t\t\t\t\t\tprintf(\"Screen start address\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x4:\n\t\t\t\t\t\tprintf(\"Cassette\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x5:\n\t\t\t\t\t\tprintf(\"Interrupt clear and paging\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x6:\n\t\t\t\t\t\tprintf(\"Counter\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0x7:\n\t\t\t\t\t\tprintf(\"Misc. control\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tprintf(\"Palette\\n\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(isReadOperation(operation))\n\t\t\t\t\t*value = os[address - 49152];\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(isReadOperation(operation)) *value = basic[address - 32768];\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nvoid Machine::set_rom(ROMSlot slot, size_t length, const uint8_t *data)\n{\n\tuint8_t *target = nullptr;\n\tswitch(slot)\n\t{\n\t\tcase ROMTypeBASIC:\ttarget = basic;\tbreak;\n\t\tcase ROMTypeOS:\t\ttarget = os;\tbreak;\n\t}\n\n\tmemcpy(target, data, std::min((size_t)16384, length));\n}\n<|endoftext|>"} {"text":"\/********************************************************************\n * Copyright © 2016 Computational Molecular Biology Group, * \n * Freie Universität Berlin (GER) *\n * *\n * This file is part of ReaDDy. *\n * *\n * ReaDDy is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Lesser General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General *\n * Public License along with this program. If not, see *\n * . *\n ********************************************************************\/\n\n\n\/**\n * << detailed description >>\n *\n * @file ParticleTypeRegistry.cpp\n * @brief << brief description >>\n * @author clonker\n * @date 29.03.17\n * @copyright GNU Lesser General Public License v3.0\n *\/\n\n#include \n#include \n\nnamespace readdy {\nnamespace model {\n\n\nParticleTypeInfo::ParticleTypeInfo(const std::string &name, const scalar diffusionConstant,\n const particle_flavor flavor, const Particle::type_type typeId)\n : name(name), diffusionConstant(diffusionConstant), flavor(flavor), typeId(typeId) {}\n\n\nvoid ParticleTypeRegistry::add(const std::string &name, const scalar diffusionConst, const particle_flavor flavor) {\n util::validateTypeName(name);\n {\n if(diffusionConst < 0) {\n throw std::invalid_argument(\"The diffusion constant must not be negative\");\n }\n \/\/ check if name already exists\n for(const auto &e : particle_info_) {\n if(e.second.name == name) {\n throw std::invalid_argument(fmt::format(\"A particle type with name {} already exists.\", name));\n }\n }\n }\n particle_type_type t_id = type_counter_++;\n type_mapping_.emplace(name, t_id);\n particle_info_.emplace(std::make_pair(t_id, ParticleTypeInfo{name, diffusionConst, flavor, t_id}));\n n_types_++;\n}\n\nstd::string ParticleTypeRegistry::describe() const {\n namespace rus = readdy::util::str;\n std::string description;\n description += fmt::format(\" - particle types:{}\", rus::newline);\n auto flavorName = [](auto flavor) -> std::string {\n switch (flavor) {\n case particleflavor::NORMAL: {\n return \"\";\n }\n case particleflavor::TOPOLOGY: {\n return \"Topology\";\n }\n case particleflavor::MEMBRANE: {\n return \"Membrane\";\n }\n default: {\n throw std::logic_error(\"encountered a particle flavor that was neither of NORMAL, TOPOLOGY, MEMBRANE.\");\n }\n }\n };\n for (const auto &entry : particle_info_) {\n description += fmt::format(\" * {} particle type \\\"{}\\\" with D={}{}\", entry.second.name,\n flavorName(entry.second.flavor), entry.second.diffusionConstant, rus::newline);\n }\n return description;\n}\n\n}\n}\nprettified particle type registry output\/********************************************************************\n * Copyright © 2016 Computational Molecular Biology Group, * \n * Freie Universität Berlin (GER) *\n * *\n * This file is part of ReaDDy. *\n * *\n * ReaDDy is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Lesser General Public License as *\n * published by the Free Software Foundation, either version 3 of *\n * the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General *\n * Public License along with this program. If not, see *\n * . *\n ********************************************************************\/\n\n\n\/**\n * << detailed description >>\n *\n * @file ParticleTypeRegistry.cpp\n * @brief << brief description >>\n * @author clonker\n * @date 29.03.17\n * @copyright GNU Lesser General Public License v3.0\n *\/\n\n#include \n#include \n\nnamespace readdy {\nnamespace model {\n\n\nParticleTypeInfo::ParticleTypeInfo(const std::string &name, const scalar diffusionConstant,\n const particle_flavor flavor, const Particle::type_type typeId)\n : name(name), diffusionConstant(diffusionConstant), flavor(flavor), typeId(typeId) {}\n\n\nvoid ParticleTypeRegistry::add(const std::string &name, const scalar diffusionConst, const particle_flavor flavor) {\n util::validateTypeName(name);\n {\n if(diffusionConst < 0) {\n throw std::invalid_argument(\"The diffusion constant must not be negative\");\n }\n \/\/ check if name already exists\n for(const auto &e : particle_info_) {\n if(e.second.name == name) {\n throw std::invalid_argument(fmt::format(\"A particle type with name {} already exists.\", name));\n }\n }\n }\n particle_type_type t_id = type_counter_++;\n type_mapping_.emplace(name, t_id);\n particle_info_.emplace(std::make_pair(t_id, ParticleTypeInfo{name, diffusionConst, flavor, t_id}));\n n_types_++;\n}\n\nstd::string ParticleTypeRegistry::describe() const {\n namespace rus = readdy::util::str;\n std::string description;\n description += fmt::format(\" - particle types:{}\", rus::newline);\n auto flavorName = [](auto flavor) -> std::string {\n switch (flavor) {\n case particleflavor::NORMAL: {\n return \"\";\n }\n case particleflavor::TOPOLOGY: {\n return \"Topology\";\n }\n case particleflavor::MEMBRANE: {\n return \"Membrane\";\n }\n default: {\n throw std::logic_error(\"encountered a particle flavor that was neither of NORMAL, TOPOLOGY, MEMBRANE.\");\n }\n }\n };\n for (const auto &entry : particle_info_) {\n description += fmt::format(\" * {} particle type \\\"{}\\\" with D={}{}\", flavorName(entry.second.flavor),\n entry.second.name, entry.second.diffusionConstant, rus::newline);\n }\n return description;\n}\n\n}\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"initializer_list\"\n\nstatic const uint16_t WATCHDOG_PERIOD = 16;\n\nstatic const uint32_t SEND_PERIOD_SECS = 60;\nstatic const uint32_t CAM_REPLY_TIMEOUT_SECS = 2;\n\nstatic const size_t CAM_RX_BUFFER_MAX = 64;\nstatic const size_t CAM_TX_BUFFER_MAX = 16;\n\nstatic const size_t CAM_RECV_BUFFER_SIZE = 16;\nstatic const size_t CAM_PICT_BUFFER_SIZE = 32;\n\nstatic const Board::DigitalPin CAM_TX_PIN = Board::D2;\nstatic const Board::InterruptPin CAM_RX_PIN = Board::PCI3;\n\nstatic uint8_t HI(uint16_t in)\n{\n\treturn (in >> 8);\n}\n\nstatic uint8_t LO(uint16_t in)\n{\n\treturn (in & 0xFF);\n}\n\nstatic uint16_t SWAP(uint16_t in)\n{\n\treturn (LO(in) << 8) | HI(in);\n}\n\nclass Camera\n{\npublic:\n\tenum class Resolution\n\t{\n\t\tRES_640x480,\n\t\tRES_320x240,\n\t\tRES_160x120,\n\t};\n\t\n\tenum class BaudRate\n\t{\n\t\tBAUD_9600,\n\t\tBAUD_19200,\n\t\tBAUD_38400,\n\t\tBAUD_57600,\n\t\tBAUD_115200\n\t};\n\t\n\tCamera(IOStream& cam, uint32_t timeout)\n\t\t:_timeout(timeout * 1000), _cam(cam)\n\t{\n\t\tdelay(3000);\n\t\t_trace(true);\n\t}\n\t\n\tvoid reset()\n\t{\n\/\/\t\ttrace << \"reset\" << endl;\n\t\t_send({0x56, 0x00, 0x26, 0x00});\n\t\t_receive({0x76, 0x00, 0x26, 0x00, 0x00});\n\t\t\/\/FIXME reset generates the power on init string: we should wait until it is received then!\n\t\tdelay(3000);\n\/\/\t\t_trace(true);\n\t}\n\t\n\t\/\/TODO method to take picture and notify callback for content\n\ttemplate\n\tvoid take_picture(CB& callback)\n\t{\n\t\ttake_picture();\n\t\tint32_t size = picture_size();\n\t\tuint16_t address = 0;\n\t\twhile (size > 0)\n\t\t{\n\t\t\t\/\/TODO buffer should be an argument to the function (more customizable)\n\t\t\tuint8_t buffer[CAM_PICT_BUFFER_SIZE];\n\t\t\tpicture_content(address, CAM_PICT_BUFFER_SIZE, buffer);\n\t\t\taddress += CAM_PICT_BUFFER_SIZE;\n\t\t\tsize -= CAM_PICT_BUFFER_SIZE;\n\t\t\tcallback(buffer, CAM_PICT_BUFFER_SIZE, (size > 0));\n\t\t}\n\t\tstop_picture();\n\t}\n\t\n\tvoid take_picture()\n\t{\n\/\/\t\ttrace << \"take_picture\" << endl;\n\t\t_send({0x56, 0x00, 0x36, 0x01, 0x00});\n\t\t_receive({0x76, 0x00, 0x36, 0x00, 0x00});\n\t}\n\t\n\tvoid stop_picture()\n\t{\n\/\/\t\ttrace << \"stop_picture\" << endl;\n\t\t_send({0x56, 0x00, 0x36, 0x01, 0x03});\n\t\t_receive({0x76, 0x00, 0x36, 0x00, 0x00});\n\t}\n\t\n\tuint16_t picture_size()\n\t{\n\/\/\t\ttrace << \"get picture_size\" << endl;\n\t\t_send({0x56, 0x00, 0x34, 0x01, 0x00});\n\t\tuint16_t size;\n\t\tif (\t_receive({0x76, 0x00, 0x34, 0x00, 0x04, 0x00, 0x00})\n\t\t\t&&\t_receive((uint8_t*)(&size), sizeof(size)))\n\t\t\treturn SWAP(size);\n\t\treturn 0;\n\t}\n\t\n\tvoid picture_content(uint16_t address, uint16_t size, uint8_t* buffer)\n\t{\n\t\t_send({\n\t\t\t0x56, 0x00, 0x32, 0x0C, 0x00, 0x0A, \n\t\t\t0x00, 0x00, HI(address), LO(address), \n\t\t\t0x00, 0x00, HI(size), LO(size), \n\t\t\t0x00, 0x0A});\n\t\t_receive({0x76, 0x00, 0x32, 0x00, 0x00}) &&\n\t\t_receive(buffer, size) &&\n\t\t_receive({0x76, 0x00, 0x32, 0x00, 0x00});\n\t}\n\t\n\tvoid compression(uint8_t ratio)\n\t{\n\t\t_send({0x56, 0x00, 0x31, 0x05, 0x01, 0x01, 0x12, 0x04, ratio});\n\t\t_receive({0x76, 0x00, 0x31, 0x00, 0x00});\n\t}\n\t\n\tvoid picture_resolution(Resolution resolution)\n\t{\n\t\tuint8_t code;\n\t\tswitch (resolution)\n\t\t{\n\t\t\tcase Resolution::RES_160x120: code = 0x22; break;\n\t\t\tcase Resolution::RES_320x240: code = 0x11; break;\n\t\t\tcase Resolution::RES_640x480: code = 0x00; break;\n\t\t}\n\t\t_send({0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, code});\n\t\t_receive({0x76, 0x00, 0x31, 0x00, 0x00});\n\t}\n\t\n\tvoid enter_power_save()\n\t{\n\/\/\t\ttrace << \"enter_power_save\" << endl;\n\t\t_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x01});\n\t\t_receive({0x76, 0x00, 0x3E, 0x00, 0x00});\n\t}\n\t\n\tvoid exit_power_save()\n\t{\n\/\/\t\ttrace << \"exit_power_save\" << endl;\n\t\t_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x00});\n\t\t_receive({0x76, 0x00, 0x3E, 0x00, 0x00});\n\t}\n\t\n\tvoid baud_rate(BaudRate baud)\n\t{\n\t\tuint16_t code;\n\t\tswitch (baud)\n\t\t{\n\t\t\tcase BaudRate::BAUD_9600: code = 0xAEC8; break;\n\t\t\tcase BaudRate::BAUD_19200: code = 0x56E4; break;\n\t\t\tcase BaudRate::BAUD_38400: code = 0x2AF2; break;\n\t\t\tcase BaudRate::BAUD_57600: code = 0x1C4C; break;\n\t\t\tcase BaudRate::BAUD_115200: code = 0x0DA6; break;\n\t\t}\n\t\t_send({\n\t\t\t0x56, 0x00, 0x24, 0x03, 0x01, \n\t\t\tHI(code), LO(code)});\n\t\t_receive({0x76, 0x00, 0x24, 0x00, 0x00});\n\t}\n\t\nprivate:\n\tvoid _send(std::initializer_list content)\n\t{\n\t\tfor (auto i : content)\n\t\t\t_cam.device()->putchar(i);\n\t\t_cam.device()->flush();\n\t}\n\t\n\tbool _receive(std::initializer_list expected)\n\t{\n\t\tuint8_t content[CAM_RECV_BUFFER_SIZE];\n\t\tif (_receive(content, expected.size()))\n\t\t{\n\t\t\tuint8_t* compare = content;\n\t\t\tfor (auto i : expected)\n\t\t\t{\n\t\t\t\tif (*compare != i)\n\t\t\t\t{\n\t\t\t\t\ttrace << \"expected \" << hex << i << \", actual \" << *compare << endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t++compare;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool _receive(uint8_t* content, uint8_t size)\n\t{\n\t\t\/\/ Wait until timeout or expected received\n\t\tuint32_t now = RTT::millis();\n\t\tuint8_t count = 0;\n\t\tdo\n\t\t{\n\t\t\twhile (_cam.device()->available())\n\t\t\t{\n\t\t\t\t*content++ = _cam.device()->getchar();\n\t\t\t\tif (++count == size)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\tdelay(1);\n\t\t}\n\t\twhile (RTT::since(now) < _timeout);\n\t\ttrace << \"receive timeout. Expected size \" << size << \", actual \" << count << endl;\n\t\treturn false;\n\t}\n\n\tvoid _trace(bool ascii_response = false)\n\t{\n\t\ttrace << \"<< \";\n\t\twhile (_cam.device()->available()) \n\t\t{\n\t\t\tint c = _cam.device()->getchar();\n\t\t\tif (ascii_response)\n\t\t\t\ttrace << (char) c;\n\t\t\telse\n\t\t\t\ttrace << hex << c << ' ';\n\t\t}\n\t\ttrace << endl;\n\t}\n\n\tconst uint32_t _timeout;\n\tIOStream& _cam;\n};\n\n\nclass CamHandler: public Alarm\n{\npublic:\n\tCamHandler(Camera& cam, ::Clock* clock, uint32_t period)\n\t\t:Alarm(clock, period), _cam(cam), _led(Board::LED, 0)\n\t{\n\t\tcam.reset();\n\t\tcam.compression(0x36);\n\t\tcam.picture_resolution(Camera::Resolution::RES_640x480);\n\t\tcam.reset();\n\t}\n\t\n\tvirtual void run()\n\t{\n\t\t_led.toggle();\n\t\t_cam.exit_power_save();\n\t\t_cam.take_picture();\n\t\tint32_t size = _cam.picture_size();\n\t\ttrace << \"picture size = \" << size << endl;\n\t\tuint16_t address = 0;\n\t\twhile (size > 0)\n\t\t{\n\t\t\tuint8_t buffer[CAM_PICT_BUFFER_SIZE];\n\t\t\t_cam.picture_content(address, CAM_PICT_BUFFER_SIZE, buffer);\n\t\t\taddress += CAM_PICT_BUFFER_SIZE;\n\t\t\tsize -= CAM_PICT_BUFFER_SIZE;\n\t\t}\n\t\t_cam.stop_picture();\n\t\t_cam.enter_power_save();\n\t\t\/\/ This delay seems necessary to avoid garbage sent to trace... (1ms is not long enough)\n\t\tdelay(5);\n\t}\n\t\nprivate:\n\tCamera& _cam;\n\tOutputPin _led;\n};\n\nint main()\n{\n\t\/\/ Disable analog comparator\n\tACSR = _BV(ACD);\n\t\/\/ Disable all modules but ADC (required for bandgap reading)\n\tPower::all_disable();\n\tPower::adc_enable();\n\t\/\/ Allow interrupts from here\n\tsei();\n\t\n\t\/\/ Start watchdog and alarms\n\tWatchdog::begin(WATCHDOG_PERIOD);\n\/\/\tPower::set(SLEEP_MODE_PWR_DOWN);\t\t\/\/ 5uA\n\t\n\t\/\/ Start using RTT\n\tRTT::begin();\n\t\n\tuart.begin(115200);\n\ttrace.begin(&uart, PSTR(\"CamCheck: started\"));\n\t\n\tIOBuffer ibuf;\n\n\tSoft::UART uartCam{CAM_TX_PIN, CAM_RX_PIN, &ibuf};\n\tuartCam.begin(38400);\n\tIOStream streamCam{&uartCam};\n\tCamera camera{streamCam, CAM_REPLY_TIMEOUT_SECS};\n\t\n\t\/\/TODO improve baud rate here\n\/\/\tcamera.baud_rate(Camera::BaudRate::BAUD_115200);\n\/\/\tuartCam.end();\n\/\/\tuartCam.begin(115200);\n\t\n\t\/\/ Needed for Alarms to work properly\n\tWatchdog::Clock clock;\n\tCamHandler handler(camera, &clock, SEND_PERIOD_SECS);\n\t\n\t\/\/ Stop using RTT and restore Watchdog\n\tRTT::end();\n\t::delay = Watchdog::delay;\n\n\thandler.start();\n\t\n\twhile (true)\n\t{\n\t\tWatchdog::await();\n\n\t\t\/\/ If there is at least one event to be dispatched, then change sleep mode, start RTT and NRF\n\t\tif (Event::queue.available())\n\t\t{\n\t\t\t\/\/ Only this mode works when using serial output and full-time RTC\n\t\t\tPower::set(SLEEP_MODE_IDLE);\t\t\t\/\/ 15mA\n\t\t\t\/\/ Start using RTT\n\t\t\tRTT::begin();\n\t\t\t\n\t\t\tEvent event;\n\t\t\twhile (Event::queue.dequeue(&event))\n\t\t\t\tevent.dispatch();\n\t\t\t\n\t\t\t\/\/ Stop using RTT and restore Watchdog\n\t\t\tRTT::end();\n\t\t\t::delay = Watchdog::delay;\n\t\t\t\/\/ Lowest consumption mode\n\t\t\tPower::set(SLEEP_MODE_PWR_DOWN);\t\t\/\/ 5uA\n\t\t}\n\t}\n}\nImprove project prototype for LinkSprite Camera.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"initializer_list\"\n\nstatic const uint16_t WATCHDOG_PERIOD = 16;\n\nstatic const uint32_t SEND_PERIOD_SECS = 60;\nstatic const uint32_t CAM_REPLY_TIMEOUT_SECS = 2;\n\nstatic const size_t CAM_RX_BUFFER_MAX = 64;\nstatic const size_t CAM_TX_BUFFER_MAX = 16;\n\nstatic const size_t CAM_RECV_BUFFER_SIZE = 16;\nstatic const size_t CAM_PICT_BUFFER_SIZE = 64;\n\/\/static const size_t CAM_PICT_BUFFER_SIZE = 32;\n\nstatic const Board::DigitalPin CAM_TX_PIN = Board::D2;\nstatic const Board::InterruptPin CAM_RX_PIN = Board::PCI3;\n\nstatic uint8_t HI(uint16_t in)\n{\n\treturn (in >> 8);\n}\n\nstatic uint8_t LO(uint16_t in)\n{\n\treturn (in & 0xFF);\n}\n\nstatic uint16_t SWAP(uint16_t in)\n{\n\treturn (LO(in) << 8) | HI(in);\n}\n\nclass Camera\n{\npublic:\n\tenum class Resolution\n\t{\n\t\tRES_640x480,\n\t\tRES_320x240,\n\t\tRES_160x120\n\t};\n\t\n\tenum class BaudRate\n\t{\n\t\tBAUD_9600,\n\t\tBAUD_19200,\n\t\tBAUD_38400,\n\t\tBAUD_57600,\n\t\tBAUD_115200\n\t};\n\t\n\tCamera(IOStream& cam, uint32_t timeout)\n\t\t:_timeout(timeout * 1000), _cam(cam)\n\t{\n\t\treset();\n\t}\n\t\n\tvoid reset()\n\t{\n\t\ttrace << \"reset\" << endl;\n\t\t_send({0x56, 0x00, 0x26, 0x00});\n\t\t_receive({0x76, 0x00, 0x26, 0x00, 0x00});\n\t\t\/\/ Reset generates the power on init string: wait until it is received\n\/\/\t\t_wait_init();\n\t\tdelay(3000);\n\t\t_cam.device()->empty();\n\/\/\t\t_trace(true);\n\t}\n\t\n\t\/\/TODO method to take picture and notify callback for content\n\ttemplate\n\tvoid take_picture(CB& callback)\n\t{\n\t\ttake_picture();\n\t\tint32_t size = picture_size();\n\t\tuint16_t address = 0;\n\t\twhile (size > 0)\n\t\t{\n\t\t\t\/\/TODO buffer should be an argument to the function (more customizable)\n\t\t\tuint8_t buffer[CAM_PICT_BUFFER_SIZE];\n\t\t\tpicture_content(address, CAM_PICT_BUFFER_SIZE, buffer);\n\t\t\taddress += CAM_PICT_BUFFER_SIZE;\n\t\t\tsize -= CAM_PICT_BUFFER_SIZE;\n\t\t\tcallback(buffer, CAM_PICT_BUFFER_SIZE, (size > 0));\n\t\t}\n\t\tstop_picture();\n\t}\n\t\n\tvoid take_picture()\n\t{\n\/\/\t\ttrace << \"take_picture\" << endl;\n\t\t_send({0x56, 0x00, 0x36, 0x01, 0x00});\n\t\t_receive({0x76, 0x00, 0x36, 0x00, 0x00});\n\t}\n\t\n\tvoid stop_picture()\n\t{\n\/\/\t\ttrace << \"stop_picture\" << endl;\n\t\t_send({0x56, 0x00, 0x36, 0x01, 0x03});\n\t\t_receive({0x76, 0x00, 0x36, 0x00, 0x00});\n\t}\n\t\n\tuint16_t picture_size()\n\t{\n\/\/\t\ttrace << \"get picture_size\" << endl;\n\t\t_send({0x56, 0x00, 0x34, 0x01, 0x00});\n\t\tuint16_t size;\n\t\tif (\t_receive({0x76, 0x00, 0x34, 0x00, 0x04, 0x00, 0x00})\n\t\t\t&&\t_receive((uint8_t*)(&size), sizeof(size)))\n\t\t\treturn SWAP(size);\n\t\treturn 0;\n\t}\n\t\n\tvoid picture_content(uint16_t address, uint16_t size, uint8_t* buffer)\n\t{\n\t\t_send({\n\t\t\t0x56, 0x00, 0x32, 0x0C, 0x00, 0x0A, \n\t\t\t0x00, 0x00, HI(address), LO(address), \n\t\t\t0x00, 0x00, HI(size), LO(size), \n\t\t\t0x00, 0x0A});\n\t\t_receive({0x76, 0x00, 0x32, 0x00, 0x00}) &&\n\t\t_receive(buffer, size) &&\n\t\t_receive({0x76, 0x00, 0x32, 0x00, 0x00});\n\t}\n\t\n\tvoid compression(uint8_t ratio)\n\t{\n\/\/\t\ttrace << \"compression\" << endl;\n\t\t_send({0x56, 0x00, 0x31, 0x05, 0x01, 0x01, 0x12, 0x04, ratio});\n\t\t_receive({0x76, 0x00, 0x31, 0x00, 0x00});\n\t}\n\t\n\tvoid picture_resolution(Resolution resolution)\n\t{\n\/\/\t\ttrace << \"picture_resolution\" << endl;\n\t\tuint8_t code;\n\t\tswitch (resolution)\n\t\t{\n\t\t\tcase Resolution::RES_160x120: code = 0x22; break;\n\t\t\tcase Resolution::RES_320x240: code = 0x11; break;\n\t\t\tcase Resolution::RES_640x480: code = 0x00; break;\n\t\t}\n\t\t_send({0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, code});\n\t\t_receive({0x76, 0x00, 0x31, 0x00, 0x00});\n\t}\n\t\n\tvoid enter_power_save()\n\t{\n\/\/\t\ttrace << \"enter_power_save\" << endl;\n\t\t_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x01});\n\t\t_receive({0x76, 0x00, 0x3E, 0x00, 0x00});\n\t}\n\t\n\tvoid exit_power_save()\n\t{\n\/\/\t\ttrace << \"exit_power_save\" << endl;\n\t\t_send({0x56, 0x00, 0x3E, 0x03, 0x00, 0x01, 0x00});\n\t\t_receive({0x76, 0x00, 0x3E, 0x00, 0x00});\n\t}\n\t\n\tvoid baud_rate(BaudRate baud)\n\t{\n\/\/\t\ttrace << \"baud_rate\" << endl;\n\t\tuint16_t code;\n\t\tswitch (baud)\n\t\t{\n\t\t\tcase BaudRate::BAUD_9600: code = 0xAEC8; break;\n\t\t\tcase BaudRate::BAUD_19200: code = 0x56E4; break;\n\t\t\tcase BaudRate::BAUD_38400: code = 0x2AF2; break;\n\t\t\tcase BaudRate::BAUD_57600: code = 0x1C4C; break;\n\t\t\tcase BaudRate::BAUD_115200: code = 0x0DA6; break;\n\t\t}\n\t\t_send({\n\t\t\t0x56, 0x00, 0x24, 0x03, 0x01, \n\t\t\tHI(code), LO(code)});\n\t\t_receive({0x76, 0x00, 0x24, 0x00, 0x00});\n\t}\n\t\nprivate:\n\tbool _wait_init()\n\t{\n\t\t\/\/ Wait until timeout or expected received\n\t\tuint32_t now = RTT::millis();\n\t\tdo\n\t\t{\n\t\t\tchar buffer[80];\n\t\t\tif (\t_cam.readline(buffer, sizeof(buffer), false)\n\t\t\t\t&&\tstrstr(buffer, \"Init end\"))\n\t\t\t{\n\t\t\t\t_cam.device()->empty();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tdelay(1);\n\t\t}\n\t\twhile (RTT::since(now) < 3000);\n\t\ttrace << \"wait init timeout.\" << endl;\n\t\t_cam.device()->empty();\n\t\treturn false;\n\t}\n\t\n\tvoid _send(std::initializer_list content)\n\t{\n\t\tfor (auto i : content)\n\t\t\t_cam.device()->putchar(i);\n\t\t_cam.device()->flush();\n\t}\n\t\n\tbool _receive(std::initializer_list expected)\n\t{\n\t\tuint8_t content[CAM_RECV_BUFFER_SIZE];\n\t\tif (_receive(content, expected.size()))\n\t\t{\n\t\t\tuint8_t* compare = content;\n\t\t\tfor (auto i : expected)\n\t\t\t{\n\t\t\t\tif (*compare != i)\n\t\t\t\t{\n\t\t\t\t\ttrace << \"expected \" << hex << i << \", actual \" << hex << *compare << endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t++compare;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool _receive(uint8_t* content, uint8_t size)\n\t{\n\t\t\/\/ Wait until timeout or expected received\n\t\tuint32_t now = RTT::millis();\n\t\tuint8_t count = 0;\n\t\tdo\n\t\t{\n\t\t\twhile (_cam.device()->available())\n\t\t\t{\n\t\t\t\t*content++ = _cam.device()->getchar();\n\t\t\t\tif (++count == size)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\tdelay(1);\n\t\t}\n\t\twhile (RTT::since(now) < _timeout);\n\t\ttrace << \"receive timeout. Expected size \" << size << \", actual \" << count << endl;\n\t\treturn false;\n\t}\n\n\tvoid _trace(bool ascii_response = false)\n\t{\n\t\ttrace << \"<< \";\n\t\twhile (_cam.device()->available()) \n\t\t{\n\t\t\tint c = _cam.device()->getchar();\n\t\t\tif (ascii_response)\n\t\t\t\ttrace << (char) c;\n\t\t\telse\n\t\t\t\ttrace << hex << c << ' ';\n\t\t}\n\t\ttrace << endl;\n\t}\n\n\tconst uint32_t _timeout;\n\tIOStream& _cam;\n};\n\n\nclass CamHandler: public Alarm\n{\npublic:\n\tCamHandler(Camera& cam, ::Clock* clock, uint32_t period)\n\t\t:Alarm(clock, period), _cam(cam), _led(Board::LED, 0)\n\t{\n\t\tcam.compression(0x36);\n\t\tcam.picture_resolution(Camera::Resolution::RES_640x480);\n\t\tcam.reset();\n\t}\n\t\n\tvirtual void run()\n\t{\n\t\t_led.toggle();\n\t\t_cam.exit_power_save();\n\t\t_cam.take_picture();\n\t\tint32_t size = _cam.picture_size();\n\/\/\t\ttrace << \"picture size = \" << size << endl;\n\t\tuint16_t address = 0;\n\t\twhile (size > 0)\n\t\t{\n\t\t\tuint8_t buffer[CAM_PICT_BUFFER_SIZE];\n\t\t\t_cam.picture_content(address, CAM_PICT_BUFFER_SIZE, buffer);\n\t\t\taddress += CAM_PICT_BUFFER_SIZE;\n\t\t\tsize -= CAM_PICT_BUFFER_SIZE;\n\t\t\ttrace.device()->write(buffer, CAM_PICT_BUFFER_SIZE);\n\t\t}\n\t\t_cam.stop_picture();\n\t\t_cam.enter_power_save();\n\t\t\/\/ This delay seems necessary to avoid garbage sent to trace... (1ms is not long enough)\n\t\tdelay(5);\n\t}\n\t\nprivate:\n\tCamera& _cam;\n\tOutputPin _led;\n};\n\nint main()\n{\n\t\/\/ Disable analog comparator\n\tACSR = _BV(ACD);\n\t\/\/ Disable all modules but ADC (required for bandgap reading)\n\tPower::all_disable();\n\tPower::adc_enable();\n\t\/\/ Allow interrupts from here\n\tsei();\n\t\n\t\/\/ Start watchdog and alarms\n\tWatchdog::begin(WATCHDOG_PERIOD);\n\/\/\tPower::set(SLEEP_MODE_PWR_DOWN);\t\t\/\/ 5uA\n\t\n\t\/\/ Start using RTT\n\tRTT::begin();\n\t\n\tuart.begin(115200);\n\ttrace.begin(&uart, PSTR(\"CamCheck: started\"));\n\t\n\tIOBuffer ibuf;\n\n\tSoft::UART uartCam{CAM_TX_PIN, CAM_RX_PIN, &ibuf};\n\tuartCam.begin(38400);\n\tIOStream streamCam{&uartCam};\n\tCamera camera{streamCam, CAM_REPLY_TIMEOUT_SECS};\n\t\n\t\/\/TODO improve baud rate here\n\/\/\tcamera.baud_rate(Camera::BaudRate::BAUD_115200);\n\/\/\tuartCam.end();\n\/\/\tuartCam.begin(115200);\n\t\n\t\/\/ Needed for Alarms to work properly\n\tWatchdog::Clock clock;\n\tCamHandler handler(camera, &clock, SEND_PERIOD_SECS);\n\t\n\t\/\/ Stop using RTT and restore Watchdog\n\tRTT::end();\n\t::delay = Watchdog::delay;\n\n\thandler.start();\n\t\n\twhile (true)\n\t{\n\t\tWatchdog::await();\n\n\t\t\/\/ If there is at least one event to be dispatched, then change sleep mode, start RTT and NRF\n\t\tif (Event::queue.available())\n\t\t{\n\t\t\t\/\/ Only this mode works when using serial output and full-time RTC\n\t\t\tPower::set(SLEEP_MODE_IDLE);\t\t\t\/\/ 15mA\n\t\t\t\/\/ Start using RTT\n\t\t\tRTT::begin();\n\t\t\t\n\t\t\tEvent event;\n\t\t\twhile (Event::queue.dequeue(&event))\n\t\t\t\tevent.dispatch();\n\t\t\t\n\t\t\t\/\/ Stop using RTT and restore Watchdog\n\t\t\tRTT::end();\n\t\t\t::delay = Watchdog::delay;\n\t\t\t\/\/ Lowest consumption mode\n\t\t\tPower::set(SLEEP_MODE_PWR_DOWN);\t\t\/\/ 5uA\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * The main source of the Beng proxy server.\n *\n * author: Max Kellermann \n *\/\n\n#include \"direct.hxx\"\n#include \"lb_instance.hxx\"\n#include \"lb_check.hxx\"\n#include \"lb_setup.hxx\"\n#include \"lb_connection.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"tcp_balancer.hxx\"\n#include \"stock\/MapStock.hxx\"\n#include \"failure.hxx\"\n#include \"bulldog.hxx\"\n#include \"balancer.hxx\"\n#include \"pipe_stock.hxx\"\n#include \"log_glue.hxx\"\n#include \"lb_config.hxx\"\n#include \"ssl\/ssl_init.hxx\"\n#include \"pool.hxx\"\n#include \"thread_pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"capabilities.hxx\"\n#include \"system\/Isolate.hxx\"\n#include \"system\/SetupProcess.hxx\"\n#include \"util\/PrintException.hxx\"\n#include \"util\/Macros.hxx\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __linux\n#include \n\n#ifndef PR_SET_NO_NEW_PRIVS\n#define PR_SET_NO_NEW_PRIVS 38\n#endif\n#endif\n\nstatic constexpr cap_value_t cap_keep_list[1] = {\n \/* keep the NET_RAW capability to be able to to use the socket\n option IP_TRANSPARENT *\/\n CAP_NET_RAW,\n};\n\nvoid\nLbInstance::ShutdownCallback()\n{\n if (should_exit)\n return;\n\n should_exit = true;\n deinit_signals(this);\n thread_pool_stop();\n\n avahi_client.Close();\n\n compress_event.Cancel();\n\n deinit_all_controls(this);\n\n DisconnectCertCaches();\n\n while (!connections.empty())\n lb_connection_close(&connections.front());\n assert(n_tcp_connections == 0);\n\n deinit_all_listeners(this);\n\n thread_pool_join();\n\n monitors.Clear();\n\n pool_commit();\n\n if (tcp_balancer != nullptr)\n tcp_balancer_free(tcp_balancer);\n\n delete tcp_stock;\n\n if (balancer != nullptr)\n balancer_free(balancer);\n\n if (pipe_stock != nullptr)\n pipe_stock_free(pipe_stock);\n\n pool_commit();\n}\n\nvoid\nLbInstance::ReloadEventCallback(int)\n{\n unsigned n_ssl_sessions = FlushSSLSessionCache(LONG_MAX);\n daemon_log(3, \"flushed %u SSL sessions\\n\", n_ssl_sessions);\n\n Compress();\n}\n\nvoid\ninit_signals(LbInstance *instance)\n{\n instance->shutdown_listener.Enable();\n instance->sighup_event.Enable();\n}\n\nvoid\ndeinit_signals(LbInstance *instance)\n{\n instance->shutdown_listener.Disable();\n instance->sighup_event.Disable();\n}\n\nint main(int argc, char **argv)\n{\n const ScopeFbPoolInit fb_pool_init;\n LbInstance instance;\n\n \/* configuration *\/\n\n LbConfig config;\n ParseCommandLine(instance.cmdline, config, argc, argv);\n\n try {\n LoadConfigFile(config,\n instance.cmdline.config_path);\n } catch (const std::exception &e) {\n PrintException(e);\n return EXIT_FAILURE;\n }\n\n instance.config = &config;\n\n if (instance.cmdline.check) {\n int status = EXIT_SUCCESS;\n\n const ScopeSslGlobalInit ssl_init;\n\n try {\n lb_check(instance.event_loop, *instance.config);\n } catch (const std::exception &e) {\n PrintException(e);\n status = EXIT_FAILURE;\n }\n\n return status;\n }\n\n \/* initialize *\/\n\n SetupProcess();\n\n const ScopeSslGlobalInit ssl_init;\n\n \/* prevent libpq from initializing libssl & libcrypto again *\/\n PQinitOpenSSL(0, 0);\n\n direct_global_init();\n\n init_signals(&instance);\n\n try {\n init_all_controls(&instance);\n init_all_listeners(instance);\n } catch (const std::exception &e) {\n fprintf(stderr, \"%s\\n\", e.what());\n return EXIT_FAILURE;\n }\n\n instance.balancer = balancer_new(instance.event_loop);\n instance.tcp_stock = tcp_stock_new(instance.event_loop,\n instance.cmdline.tcp_stock_limit);\n instance.tcp_balancer = tcp_balancer_new(*instance.tcp_stock,\n *instance.balancer);\n\n instance.pipe_stock = pipe_stock_new(instance.event_loop);\n\n failure_init();\n bulldog_init(instance.cmdline.bulldog_path);\n\n \/* launch the access logger *\/\n\n log_global_init(config.access_logger.c_str(),\n &instance.cmdline.logger_user);\n\n \/* daemonize II *\/\n\n if (!instance.cmdline.user.IsEmpty())\n capabilities_pre_setuid();\n\n instance.cmdline.user.Apply();\n\n for (const auto &path : config.lua_files)\n instance.RunLuaFile(path.c_str());\n\n \/* can't change to new (empty) rootfs if we may need to reconnect\n to PostgreSQL eventually *\/\n \/\/ TODO: bind-mount the PostgreSQL socket into the new rootfs\n if (!instance.config->HasCertDatabase())\n isolate_from_filesystem(instance.config->HasZeroConf());\n\n if (!instance.cmdline.user.IsEmpty())\n capabilities_post_setuid(cap_keep_list, ARRAY_SIZE(cap_keep_list));\n\n#ifdef __linux\n prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);\n#endif\n\n \/* main loop *\/\n\n instance.InitWorker();\n\n \/* tell systemd we're ready *\/\n sd_notify(0, \"READY=1\");\n\n instance.event_loop.Dispatch();\n\n \/* cleanup *\/\n\n log_global_deinit();\n\n bulldog_deinit();\n failure_deinit();\n\n deinit_all_listeners(&instance);\n deinit_all_controls(&instance);\n\n thread_pool_deinit();\n}\nlb_main: global exception handler\/*\n * The main source of the Beng proxy server.\n *\n * author: Max Kellermann \n *\/\n\n#include \"direct.hxx\"\n#include \"lb_instance.hxx\"\n#include \"lb_check.hxx\"\n#include \"lb_setup.hxx\"\n#include \"lb_connection.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"tcp_balancer.hxx\"\n#include \"stock\/MapStock.hxx\"\n#include \"failure.hxx\"\n#include \"bulldog.hxx\"\n#include \"balancer.hxx\"\n#include \"pipe_stock.hxx\"\n#include \"log_glue.hxx\"\n#include \"lb_config.hxx\"\n#include \"ssl\/ssl_init.hxx\"\n#include \"pool.hxx\"\n#include \"thread_pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"capabilities.hxx\"\n#include \"system\/Isolate.hxx\"\n#include \"system\/SetupProcess.hxx\"\n#include \"util\/PrintException.hxx\"\n#include \"util\/Macros.hxx\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __linux\n#include \n\n#ifndef PR_SET_NO_NEW_PRIVS\n#define PR_SET_NO_NEW_PRIVS 38\n#endif\n#endif\n\nstatic constexpr cap_value_t cap_keep_list[1] = {\n \/* keep the NET_RAW capability to be able to to use the socket\n option IP_TRANSPARENT *\/\n CAP_NET_RAW,\n};\n\nvoid\nLbInstance::ShutdownCallback()\n{\n if (should_exit)\n return;\n\n should_exit = true;\n deinit_signals(this);\n thread_pool_stop();\n\n avahi_client.Close();\n\n compress_event.Cancel();\n\n deinit_all_controls(this);\n\n DisconnectCertCaches();\n\n while (!connections.empty())\n lb_connection_close(&connections.front());\n assert(n_tcp_connections == 0);\n\n deinit_all_listeners(this);\n\n thread_pool_join();\n\n monitors.Clear();\n\n pool_commit();\n\n if (tcp_balancer != nullptr)\n tcp_balancer_free(tcp_balancer);\n\n delete tcp_stock;\n\n if (balancer != nullptr)\n balancer_free(balancer);\n\n if (pipe_stock != nullptr)\n pipe_stock_free(pipe_stock);\n\n pool_commit();\n}\n\nvoid\nLbInstance::ReloadEventCallback(int)\n{\n unsigned n_ssl_sessions = FlushSSLSessionCache(LONG_MAX);\n daemon_log(3, \"flushed %u SSL sessions\\n\", n_ssl_sessions);\n\n Compress();\n}\n\nvoid\ninit_signals(LbInstance *instance)\n{\n instance->shutdown_listener.Enable();\n instance->sighup_event.Enable();\n}\n\nvoid\ndeinit_signals(LbInstance *instance)\n{\n instance->shutdown_listener.Disable();\n instance->sighup_event.Disable();\n}\n\nint main(int argc, char **argv)\ntry {\n const ScopeFbPoolInit fb_pool_init;\n LbInstance instance;\n\n \/* configuration *\/\n\n LbConfig config;\n ParseCommandLine(instance.cmdline, config, argc, argv);\n\n LoadConfigFile(config, instance.cmdline.config_path);\n\n instance.config = &config;\n\n if (instance.cmdline.check) {\n const ScopeSslGlobalInit ssl_init;\n lb_check(instance.event_loop, *instance.config);\n return EXIT_SUCCESS;\n }\n\n \/* initialize *\/\n\n SetupProcess();\n\n const ScopeSslGlobalInit ssl_init;\n\n \/* prevent libpq from initializing libssl & libcrypto again *\/\n PQinitOpenSSL(0, 0);\n\n direct_global_init();\n\n init_signals(&instance);\n\n init_all_controls(&instance);\n init_all_listeners(instance);\n\n instance.balancer = balancer_new(instance.event_loop);\n instance.tcp_stock = tcp_stock_new(instance.event_loop,\n instance.cmdline.tcp_stock_limit);\n instance.tcp_balancer = tcp_balancer_new(*instance.tcp_stock,\n *instance.balancer);\n\n instance.pipe_stock = pipe_stock_new(instance.event_loop);\n\n failure_init();\n bulldog_init(instance.cmdline.bulldog_path);\n\n \/* launch the access logger *\/\n\n log_global_init(config.access_logger.c_str(),\n &instance.cmdline.logger_user);\n\n \/* daemonize II *\/\n\n if (!instance.cmdline.user.IsEmpty())\n capabilities_pre_setuid();\n\n instance.cmdline.user.Apply();\n\n for (const auto &path : config.lua_files)\n instance.RunLuaFile(path.c_str());\n\n \/* can't change to new (empty) rootfs if we may need to reconnect\n to PostgreSQL eventually *\/\n \/\/ TODO: bind-mount the PostgreSQL socket into the new rootfs\n if (!instance.config->HasCertDatabase())\n isolate_from_filesystem(instance.config->HasZeroConf());\n\n if (!instance.cmdline.user.IsEmpty())\n capabilities_post_setuid(cap_keep_list, ARRAY_SIZE(cap_keep_list));\n\n#ifdef __linux\n prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);\n#endif\n\n \/* main loop *\/\n\n instance.InitWorker();\n\n \/* tell systemd we're ready *\/\n sd_notify(0, \"READY=1\");\n\n instance.event_loop.Dispatch();\n\n \/* cleanup *\/\n\n log_global_deinit();\n\n bulldog_deinit();\n failure_deinit();\n\n deinit_all_listeners(&instance);\n deinit_all_controls(&instance);\n\n thread_pool_deinit();\n} catch (const std::exception &e) {\n PrintException(e);\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"#include \"modinclude.h\"\n#include \"bot_admin.h\"\n\nclass DieCommand : public AdminHook {\n\tpublic:\n\t\tint botAPIversion();\n\t\tbool onLoadComplete();\n\t\tvoid onRehash();\n\t\tstd::string getDesc();\n\t\tstd::vector supports();\n\t\tstd::vector > adminCommands();\n\t\tvoid onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master);\n};\n\nint DieCommand::botAPIversion() {\n\treturn 1002;\n}\n\nbool DieCommand::onLoadComplete() {\n\tstd::multimap modAbilities = getModAbilities();\n\tstd::multimap::iterator botAdminAbility = modAbilities.find(\"BOT_ADMIN\");\n\tif (botAdminAbility == modAbilities.end()) { \/\/ BOT_ADMIN not provided but required for this module\n\t\tstd::cout << \"A module providing BOT_ADMIN is required for \" << moduleName << \". Unloading.\" << std::endl;\n\t\tunloadModule(moduleName);\n\t\treturn false;\n\t}\n\tif (config[\"masteronly\"] != \"\") {\n\t\tif (config[\"masteronly\"][0] == 'n')\n\t\t\tconfig[\"masteronly\"] = \"no\";\n\t\telse\n\t\t\tconfig[\"masteronly\"] = \"yes\";\n\t} else\n\t\tconfig[\"masteronly\"] = \"yes\";\n\treturn true;\n}\n\nvoid DieCommand::onRehash() {\n\tstd::multimap modAbilities = getModAbilities();\n\tstd::multimap::iterator botAdminAbility = modAbilities.find(\"BOT_ADMIN\");\n\tif (botAdminAbility == modAbilities.end()) { \/\/ BOT_ADMIN not provided but required for this module\n\t\tstd::cout << \"A module providing BOT_ADMIN is required for \" << moduleName << \". Unloading.\" << std::endl;\n\t\tunloadModule(moduleName);\n\t}\n\tif (config[\"masteronly\"] != \"\") {\n\t\tif (config[\"masteronly\"][0] == 'n')\n\t\t\tconfig[\"masteronly\"] = \"no\";\n\t\telse\n\t\t\tconfig[\"masteronly\"] = \"yes\";\n\t} else\n\t\tconfig[\"masteronly\"] = \"yes\";\n}\n\nstd::string DieCommand::getDesc() {\n\treturn \"Allows the bot master to shut the bot down from IRC.\";\n}\n\nstd::vector DieCommand::supports() {\n\tstd::vector supporting;\n\tsupporting.push_back(\"BOT_ADMIN\");\n\treturn supporting;\n}\n\nstd::vector > DieCommand::adminCommands() {\n\tstd::vector > theCommands;\n\tstd::vector dieCommand;\n\tdieCommand.push_back(\"die\");\n\tdieCommand.push_back(\"Makes the bot shut down.\");\n\tdieCommand.push_back(\"Syntax: die [reason]\");\n\tdieCommand.push_back(\"This command causes the bot to shut down. If a reason is given, it will be used as the quit reason on all servers.\");\n\tif (config[\"masteronly\"] == \"yes\")\n\t\tdieCommand.push_back(\"This command is available only to bot admins.\");\n\ttheCommands.push_back(dieCommand);\n\treturn theCommands;\n}\n\nvoid DieCommand::onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master) {\n\tif (config[\"masteronly\"] == \"yes\" && !master) {\n\t\tif (dccMod == NULL)\n\t\t\tsendPrivMsg(server, nick, \"The die command is available only to bot masters.\");\n\t\telse\n\t\t\tdccMod->dccSend(server + \"\/\" + nick, \"The die command is available only to bot masters.\");\n\t\treturn;\n\t}\n\tstd::list connectedServers = getServers();\n\tfor (std::list::iterator servIter = connectedServers.begin(); servIter != connectedServers.end(); ++servIter)\n\t\tquitServer(*servIter, message);\n\tif (dccMod != NULL) {\n\t\tstd::vector connectedDCC = dccMod->getConnections();\n\t\tfor (unsigned int i = 0; i < connectedDCC.size(); i++)\n\t\t\tdccMod->closeDCCConnection(connectedDCC[i]);\n\t}\n\tstd::cout << \"Shutting down by admin command: die\" << std::endl;\n\tstd::exit(0);\n}\n\nextern \"C\" Module* spawn() {\n\treturn new DieCommand;\n}Add some sleep to m_admin_die so the bot doesn't exist before the send queues can flush.#include \"modinclude.h\"\n#include \"bot_admin.h\"\n\nclass DieCommand : public AdminHook {\n\tpublic:\n\t\tint botAPIversion();\n\t\tbool onLoadComplete();\n\t\tvoid onRehash();\n\t\tstd::string getDesc();\n\t\tstd::vector supports();\n\t\tstd::vector > adminCommands();\n\t\tvoid onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master);\n};\n\nint DieCommand::botAPIversion() {\n\treturn 1002;\n}\n\nbool DieCommand::onLoadComplete() {\n\tstd::multimap modAbilities = getModAbilities();\n\tstd::multimap::iterator botAdminAbility = modAbilities.find(\"BOT_ADMIN\");\n\tif (botAdminAbility == modAbilities.end()) { \/\/ BOT_ADMIN not provided but required for this module\n\t\tstd::cout << \"A module providing BOT_ADMIN is required for \" << moduleName << \". Unloading.\" << std::endl;\n\t\tunloadModule(moduleName);\n\t\treturn false;\n\t}\n\tif (config[\"masteronly\"] != \"\") {\n\t\tif (config[\"masteronly\"][0] == 'n')\n\t\t\tconfig[\"masteronly\"] = \"no\";\n\t\telse\n\t\t\tconfig[\"masteronly\"] = \"yes\";\n\t} else\n\t\tconfig[\"masteronly\"] = \"yes\";\n\treturn true;\n}\n\nvoid DieCommand::onRehash() {\n\tstd::multimap modAbilities = getModAbilities();\n\tstd::multimap::iterator botAdminAbility = modAbilities.find(\"BOT_ADMIN\");\n\tif (botAdminAbility == modAbilities.end()) { \/\/ BOT_ADMIN not provided but required for this module\n\t\tstd::cout << \"A module providing BOT_ADMIN is required for \" << moduleName << \". Unloading.\" << std::endl;\n\t\tunloadModule(moduleName);\n\t}\n\tif (config[\"masteronly\"] != \"\") {\n\t\tif (config[\"masteronly\"][0] == 'n')\n\t\t\tconfig[\"masteronly\"] = \"no\";\n\t\telse\n\t\t\tconfig[\"masteronly\"] = \"yes\";\n\t} else\n\t\tconfig[\"masteronly\"] = \"yes\";\n}\n\nstd::string DieCommand::getDesc() {\n\treturn \"Allows the bot master to shut the bot down from IRC.\";\n}\n\nstd::vector DieCommand::supports() {\n\tstd::vector supporting;\n\tsupporting.push_back(\"BOT_ADMIN\");\n\treturn supporting;\n}\n\nstd::vector > DieCommand::adminCommands() {\n\tstd::vector > theCommands;\n\tstd::vector dieCommand;\n\tdieCommand.push_back(\"die\");\n\tdieCommand.push_back(\"Makes the bot shut down.\");\n\tdieCommand.push_back(\"Syntax: die [reason]\");\n\tdieCommand.push_back(\"This command causes the bot to shut down. If a reason is given, it will be used as the quit reason on all servers.\");\n\tif (config[\"masteronly\"] == \"yes\")\n\t\tdieCommand.push_back(\"This command is available only to bot admins.\");\n\ttheCommands.push_back(dieCommand);\n\treturn theCommands;\n}\n\nvoid DieCommand::onAdminCommand(std::string server, std::string nick, std::string command, std::string message, dccSender* dccMod, bool master) {\n\tif (config[\"masteronly\"] == \"yes\" && !master) {\n\t\tif (dccMod == NULL)\n\t\t\tsendPrivMsg(server, nick, \"The die command is available only to bot masters.\");\n\t\telse\n\t\t\tdccMod->dccSend(server + \"\/\" + nick, \"The die command is available only to bot masters.\");\n\t\treturn;\n\t}\n\tstd::list connectedServers = getServers();\n\tfor (std::list::iterator servIter = connectedServers.begin(); servIter != connectedServers.end(); ++servIter)\n\t\tquitServer(*servIter, message);\n\tif (dccMod != NULL) {\n\t\tstd::vector connectedDCC = dccMod->getConnections();\n\t\tfor (unsigned int i = 0; i < connectedDCC.size(); i++)\n\t\t\tdccMod->closeDCCConnection(connectedDCC[i]);\n\t}\n\tstd::cout << \"Shutting down by admin command: die\" << std::endl;\n\tsleep(1);\n\tstd::exit(0);\n}\n\nextern \"C\" Module* spawn() {\n\treturn new DieCommand;\n}<|endoftext|>"} {"text":"\/***************************************************************************\r\n * Copyright (c) 2005 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include \r\n#endif\r\n\r\n#include \"Workbench.h\"\r\n#include \r\n#include \r\n\r\nusing namespace PartGui;\r\n\r\n#if 0 \/\/ needed for Qt's lupdate utility\r\n qApp->translate(\"Workbench\", \"&Part\");\r\n qApp->translate(\"Workbench\", \"&Simple\");\r\n qApp->translate(\"Workbench\", \"&Parametric\");\r\n qApp->translate(\"Workbench\", \"Solids\");\r\n qApp->translate(\"Workbench\", \"Part tools\");\r\n qApp->translate(\"Workbench\", \"Boolean\");\r\n#endif\r\n\r\n\/\/\/ @namespace PartGui @class Workbench\r\nTYPESYSTEM_SOURCE(PartGui::Workbench, Gui::StdWorkbench)\r\n\r\nWorkbench::Workbench()\r\n{\r\n}\r\n\r\nWorkbench::~Workbench()\r\n{\r\n}\r\n\r\nGui::MenuItem* Workbench::setupMenuBar() const\r\n{\r\n Gui::MenuItem* root = StdWorkbench::setupMenuBar();\r\n Gui::MenuItem* item = root->findItem(\"&Windows\");\r\n\r\n Gui::MenuItem* prim = new Gui::MenuItem;\r\n prim->setCommand(\"Primitives\");\r\n *prim << \"Part_Box\" << \"Part_Cylinder\" << \"Part_Sphere\"\r\n << \"Part_Cone\" << \"Part_Torus\";\r\n\r\n Gui::MenuItem* bop = new Gui::MenuItem;\r\n bop->setCommand(\"Boolean\");\r\n *bop << \"Part_Boolean\" << \"Part_Cut\" << \"Part_Fuse\" << \"Part_Common\";\r\n\r\n Gui::MenuItem* join = new Gui::MenuItem;\r\n join->setCommand(\"Join\");\r\n *join << \"Part_JoinConnect\" << \"Part_JoinEmbed\" << \"Part_JoinCutout\";\r\n\r\n Gui::MenuItem* split = new Gui::MenuItem;\r\n split->setCommand(\"Split\");\r\n *split << \"Part_BooleanFragments\" << \"Part_Slice\" << \"Part_XOR\";\r\n\r\n Gui::MenuItem* compound = new Gui::MenuItem;\r\n compound->setCommand(\"Compound\");\r\n *compound << \"Part_Compound\" << \"Part_CompoundFilter\";\r\n\r\n Gui::MenuItem* part = new Gui::MenuItem;\r\n root->insertItem(item, part);\r\n part->setCommand(\"&Part\");\r\n *part << \"Part_Import\" << \"Part_Export\" << \"Separator\";\r\n *part << prim << \"Part_Primitives\" << \"Part_Builder\" << \"Separator\"\r\n << \"Part_ShapeFromMesh\" << \"Part_MakeSolid\" << \"Part_ReverseShape\"\r\n << \"Part_SimpleCopy\" << \"Part_RefineShape\" << \"Part_CheckGeometry\"\r\n << \"Separator\" << bop << join << split << compound << \"Separator\"\r\n << \"Part_CrossSections\" << \"Part_MakeFace\" << \"Part_Extrude\"\r\n << \"Part_Revolve\" << \"Part_Mirror\" << \"Part_Fillet\" << \"Part_Chamfer\"\r\n << \"Part_RuledSurface\" << \"Part_Loft\" << \"Part_Sweep\"\r\n << \"Part_Offset\" << \"Part_Offset2D\" << \"Part_Thickness\" << \"Separator\" << \"Part_EditAttachment\";\r\n\r\n Gui::MenuItem* measure = new Gui::MenuItem;\r\n root->insertItem(item,measure);\r\n measure->setCommand(\"Measure\");\r\n *measure << \"Part_Measure_Linear\" << \"Part_Measure_Angular\" << \"Separator\" << \"Part_Measure_Clear_All\" << \"Part_Measure_Toggle_All\" <<\r\n \"Part_Measure_Toggle_3d\" << \"Part_Measure_Toggle_Delta\";\r\n\r\n \/\/ leave this for 0.14 until #0000477 is fixed\r\n#if 0\r\n Gui::MenuItem* view = root->findItem(\"&View\");\r\n if (view) {\r\n Gui::MenuItem* appr = view->findItem(\"Std_RandomColor\");\r\n appr = view->afterItem(appr);\r\n Gui::MenuItem* face = new Gui::MenuItem();\r\n face->setCommand(\"Part_ColorPerFace\");\r\n view->insertItem(appr, face);\r\n }\r\n#endif\r\n\r\n return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupToolBars() const\r\n{\r\n Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\r\n\r\n Gui::ToolBarItem* solids = new Gui::ToolBarItem(root);\r\n solids->setCommand(\"Solids\");\r\n *solids << \"Part_Box\" << \"Part_Cylinder\" << \"Part_Sphere\" << \"Part_Cone\"\r\n << \"Part_Torus\" << \"Part_Primitives\" << \"Part_Builder\";\r\n\r\n Gui::ToolBarItem* tool = new Gui::ToolBarItem(root);\r\n tool->setCommand(\"Part tools\");\r\n *tool << \"Part_Extrude\" << \"Part_Revolve\" << \"Part_Mirror\" << \"Part_Fillet\"\r\n << \"Part_Chamfer\" << \"Part_RuledSurface\" << \"Part_Loft\" << \"Part_Sweep\"\r\n << \"Part_CompOffset\" << \"Part_Thickness\";\r\n\r\n Gui::ToolBarItem* boolop = new Gui::ToolBarItem(root);\r\n boolop->setCommand(\"Boolean\");\r\n *boolop << \"Part_Boolean\" << \"Part_Cut\" << \"Part_Fuse\" << \"Part_Common\"\r\n << \"Part_CompJoinFeatures\" << \"Part_CompSplitFeatures\" << \"Part_CheckGeometry\" << \"Part_Section\"\r\n << \"Part_CrossSections\";\r\n\r\n Gui::ToolBarItem* measure = new Gui::ToolBarItem(root);\r\n measure->setCommand(\"Measure\");\r\n *measure << \"Part_Measure_Linear\" << \"Part_Measure_Angular\" << \"Separator\" << \"Part_Measure_Clear_All\" << \"Part_Measure_Toggle_All\"\r\n << \"Part_Measure_Toggle_3d\" << \"Part_Measure_Toggle_Delta\";\r\n\r\n return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupCommandBars() const\r\n{\r\n \/\/ Part tools\r\n Gui::ToolBarItem* root = new Gui::ToolBarItem;\r\n return root;\r\n}\r\nfixes #0001955: Part Section not available in the Part menu\/***************************************************************************\r\n * Copyright (c) 2005 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n\r\n#ifndef _PreComp_\r\n# include \r\n#endif\r\n\r\n#include \"Workbench.h\"\r\n#include \r\n#include \r\n\r\nusing namespace PartGui;\r\n\r\n#if 0 \/\/ needed for Qt's lupdate utility\r\n qApp->translate(\"Workbench\", \"&Part\");\r\n qApp->translate(\"Workbench\", \"&Simple\");\r\n qApp->translate(\"Workbench\", \"&Parametric\");\r\n qApp->translate(\"Workbench\", \"Solids\");\r\n qApp->translate(\"Workbench\", \"Part tools\");\r\n qApp->translate(\"Workbench\", \"Boolean\");\r\n#endif\r\n\r\n\/\/\/ @namespace PartGui @class Workbench\r\nTYPESYSTEM_SOURCE(PartGui::Workbench, Gui::StdWorkbench)\r\n\r\nWorkbench::Workbench()\r\n{\r\n}\r\n\r\nWorkbench::~Workbench()\r\n{\r\n}\r\n\r\nGui::MenuItem* Workbench::setupMenuBar() const\r\n{\r\n Gui::MenuItem* root = StdWorkbench::setupMenuBar();\r\n Gui::MenuItem* item = root->findItem(\"&Windows\");\r\n\r\n Gui::MenuItem* prim = new Gui::MenuItem;\r\n prim->setCommand(\"Primitives\");\r\n *prim << \"Part_Box\"\r\n << \"Part_Cylinder\"\r\n << \"Part_Sphere\"\r\n << \"Part_Cone\"\r\n << \"Part_Torus\";\r\n\r\n Gui::MenuItem* bop = new Gui::MenuItem;\r\n bop->setCommand(\"Boolean\");\r\n *bop << \"Part_Boolean\"\r\n << \"Part_Cut\"\r\n << \"Part_Fuse\"\r\n << \"Part_Common\";\r\n\r\n Gui::MenuItem* join = new Gui::MenuItem;\r\n join->setCommand(\"Join\");\r\n *join << \"Part_JoinConnect\"\r\n << \"Part_JoinEmbed\"\r\n << \"Part_JoinCutout\";\r\n\r\n Gui::MenuItem* split = new Gui::MenuItem;\r\n split->setCommand(\"Split\");\r\n *split << \"Part_BooleanFragments\"\r\n << \"Part_Slice\"\r\n << \"Part_XOR\";\r\n\r\n Gui::MenuItem* compound = new Gui::MenuItem;\r\n compound->setCommand(\"Compound\");\r\n *compound << \"Part_Compound\"\r\n << \"Part_CompoundFilter\";\r\n\r\n Gui::MenuItem* part = new Gui::MenuItem;\r\n root->insertItem(item, part);\r\n part->setCommand(\"&Part\");\r\n *part << \"Part_Import\"\r\n << \"Part_Export\"\r\n << \"Separator\";\r\n *part << prim\r\n << \"Part_Primitives\"\r\n << \"Part_Builder\"\r\n << \"Separator\"\r\n << \"Part_ShapeFromMesh\"\r\n << \"Part_MakeSolid\"\r\n << \"Part_ReverseShape\"\r\n << \"Part_SimpleCopy\"\r\n << \"Part_RefineShape\"\r\n << \"Part_CheckGeometry\"\r\n << \"Separator\"\r\n << bop << join << split << compound\r\n << \"Separator\"\r\n << \"Part_Section\"\r\n << \"Part_CrossSections\"\r\n << \"Part_MakeFace\"\r\n << \"Part_Extrude\"\r\n << \"Part_Revolve\"\r\n << \"Part_Mirror\"\r\n << \"Part_Fillet\"\r\n << \"Part_Chamfer\"\r\n << \"Part_RuledSurface\"\r\n << \"Part_Loft\"\r\n << \"Part_Sweep\"\r\n << \"Part_Offset\"\r\n << \"Part_Offset2D\"\r\n << \"Part_Thickness\"\r\n << \"Separator\"\r\n << \"Part_EditAttachment\";\r\n\r\n Gui::MenuItem* measure = new Gui::MenuItem;\r\n root->insertItem(item,measure);\r\n measure->setCommand(\"Measure\");\r\n *measure << \"Part_Measure_Linear\"\r\n << \"Part_Measure_Angular\"\r\n << \"Separator\"\r\n << \"Part_Measure_Clear_All\"\r\n << \"Part_Measure_Toggle_All\"\r\n << \"Part_Measure_Toggle_3d\"\r\n << \"Part_Measure_Toggle_Delta\";\r\n\r\n \/\/ leave this for 0.14 until #0000477 is fixed\r\n#if 0\r\n Gui::MenuItem* view = root->findItem(\"&View\");\r\n if (view) {\r\n Gui::MenuItem* appr = view->findItem(\"Std_RandomColor\");\r\n appr = view->afterItem(appr);\r\n Gui::MenuItem* face = new Gui::MenuItem();\r\n face->setCommand(\"Part_ColorPerFace\");\r\n view->insertItem(appr, face);\r\n }\r\n#endif\r\n\r\n return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupToolBars() const\r\n{\r\n Gui::ToolBarItem* root = StdWorkbench::setupToolBars();\r\n\r\n Gui::ToolBarItem* solids = new Gui::ToolBarItem(root);\r\n solids->setCommand(\"Solids\");\r\n *solids << \"Part_Box\"\r\n << \"Part_Cylinder\"\r\n << \"Part_Sphere\"\r\n << \"Part_Cone\"\r\n << \"Part_Torus\"\r\n << \"Part_Primitives\"\r\n << \"Part_Builder\";\r\n\r\n Gui::ToolBarItem* tool = new Gui::ToolBarItem(root);\r\n tool->setCommand(\"Part tools\");\r\n *tool << \"Part_Extrude\"\r\n << \"Part_Revolve\"\r\n << \"Part_Mirror\"\r\n << \"Part_Fillet\"\r\n << \"Part_Chamfer\"\r\n << \"Part_RuledSurface\"\r\n << \"Part_Loft\"\r\n << \"Part_Sweep\"\r\n << \"Part_CompOffset\"\r\n << \"Part_Thickness\";\r\n\r\n Gui::ToolBarItem* boolop = new Gui::ToolBarItem(root);\r\n boolop->setCommand(\"Boolean\");\r\n *boolop << \"Part_Boolean\"\r\n << \"Part_Cut\"\r\n << \"Part_Fuse\"\r\n << \"Part_Common\"\r\n << \"Part_CompJoinFeatures\"\r\n << \"Part_CompSplitFeatures\"\r\n << \"Part_CheckGeometry\"\r\n << \"Part_Section\"\r\n << \"Part_CrossSections\";\r\n\r\n Gui::ToolBarItem* measure = new Gui::ToolBarItem(root);\r\n measure->setCommand(\"Measure\");\r\n *measure << \"Part_Measure_Linear\"\r\n << \"Part_Measure_Angular\"\r\n << \"Separator\"\r\n << \"Part_Measure_Clear_All\"\r\n << \"Part_Measure_Toggle_All\"\r\n << \"Part_Measure_Toggle_3d\"\r\n << \"Part_Measure_Toggle_Delta\";\r\n\r\n return root;\r\n}\r\n\r\nGui::ToolBarItem* Workbench::setupCommandBars() const\r\n{\r\n \/\/ Part tools\r\n Gui::ToolBarItem* root = new Gui::ToolBarItem;\r\n return root;\r\n}\r\n<|endoftext|>"} {"text":"\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2016 Razer 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 \"FindDriver.h\"\n\n\/\/ Library\/third-party includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Standard includes\n#include \n#include \n#include \n\n#if _MSC_VER >= 1800\n#include \n#else\n#include \n#endif\n\n#if defined(OSVR_WINDOWS)\n#include \n#endif\n\n#undef VIVELOADER_VERBOSE\n\nusing osvr::util::finally;\n\nnamespace osvr {\nnamespace vive {\n#if defined(OSVR_WINDOWS)\n static const auto PLATFORM_DIRNAME_BASE = \"win\";\n static const auto DRIVER_EXTENSION = \".dll\";\n static const auto TOOL_EXTENSION = \".exe\";\n static const auto PATH_SEP = \"\\\\\";\n#elif defined(OSVR_MACOSX)\n \/\/\/ @todo Note that there are no 64-bit steamvr runtimes or drivers on OS X\n static const auto PLATFORM_DIRNAME_BASE = \"osx\";\n static const auto DRIVER_EXTENSION = \".dylib\";\n static const auto TOOL_EXTENSION = \"\";\n static const auto PATH_SEP = \"\/\";\n#elif defined(OSVR_LINUX)\n static const auto PLATFORM_DIRNAME_BASE = \"linux\";\n static const auto DRIVER_EXTENSION = \".so\";\n static const auto TOOL_EXTENSION = \"\";\n static const auto PATH_SEP = \"\/\";\n#else\n#error \"Sorry, Valve does not produce a SteamVR runtime for your platform.\"\n#endif\n\n#if defined(OSVR_USING_FILESYSTEM_TR2)\n using std::tr2::sys::path;\n using std::tr2::sys::wpath;\n using std::tr2::sys::exists;\n#elif defined(OSVR_USING_BOOST_FILESYSTEM)\n using boost::filesystem::path;\n using boost::filesystem::exists;\n#endif\n\n inline std::string getPlatformDirname() {\n return PLATFORM_DIRNAME_BASE +\n std::to_string(sizeof(void *) * CHAR_BIT);\n\n inline void parsePathConfigFile(std::istream &is, Json::Value &ret) {\n Json::Reader reader;\n if (!reader.parse(is, ret)) {\n std::cerr << \"Error parsing file containing path configuration - \"\n \"have you run SteamVR yet?\"\n << std::endl;\n std::cerr << reader.getFormattedErrorMessages() << std::endl;\n }\n }\n#if defined(OSVR_WINDOWS)\n\n inline Json::Value getPathConfig() {\n PWSTR outString = nullptr;\n Json::Value ret;\n \/\/ It's OK to use Vista+ stuff here, since openvr_api.dll uses Vista+\n \/\/ stuff too.\n auto hr =\n SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &outString);\n if (!SUCCEEDED(hr)) {\n std::cerr << \"Could not get local app data directory!\" << std::endl;\n return ret;\n }\n \/\/ Free the string returned when we're all done.\n auto freeString = [&] { CoTaskMemFree(outString); };\n \/\/ Build the path to the file.\n auto vrPaths =\n wpath(outString) \/ wpath(L\"openvr\") \/ wpath(L\"openvrpaths.vrpath\");\n std::ifstream is(vrPaths.string());\n if (!is) {\n std::wcerr << L\"Could not open file containing path configuration \"\n L\"- have you run SteamVR yet? \"\n << vrPaths << L\"\\n\";\n return ret;\n }\n parsePathConfigFile(is, ret);\n return ret;\n }\n#elif defined(OSVR_MACOSX)\n inline Json::Value getPathConfig() {\n#error \"implementation not complete\"\n }\n#elif defined(OSVR_LINUX)\n\n inline Json::Value getPathConfig() {\n#error \"implementation not complete\"\n }\n#endif\n\n#if 0\n#if defined(OSVR_WINDOWS)\n inline std::vector getSteamVRRoots() {\n \/\/\/ @todo make this better - there's Windows API for that.\n return std::vector{\n std::string{\"C:\\\\Program Files\\\\Steam\\\\steamapps\\\\common\\\\SteamVR\"},\n std::string{\n \"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\common\\\\SteamVR\"}};\n }\n#elif defined(OSVR_MACOSX)\n inline std::vector getSteamVRRoots() {\n#error \"implementation not complete\"\n }\n#elif defined(OSVR_LINUX)\n\n inline std::vector getSteamVRRoots() {\n#error \"implementation not complete\"\n }\n#endif\n#endif\n\n inline std::vector getSteamVRRoots(Json::Value const &json) {\n std::vector ret;\n auto &runtimes = json[\"runtime\"];\n if (!runtimes.isArray()) {\n return ret;\n }\n for (auto &runtime : runtimes) {\n ret.emplace_back(runtime.asString());\n }\n return ret;\n }\n inline std::vector getSteamVRRoots() {\n return getSteamVRRoots(getPathConfig());\n }\n\n inline void computeDriverRootAndFilePath(DriverLocationInfo &info,\n std::string const &driver) {\n auto p = path{info.steamVrRoot};\n p \/= \"drivers\";\n p \/= driver;\n p \/= \"bin\";\n p \/= getPlatformDirname();\n info.driverRoot = p.string();\n p \/= (\"driver_\" + driver + DRIVER_EXTENSION);\n info.driverFile = p.string();\n }\n\n DriverLocationInfo findDriver(std::string const &driver) {\n\n DriverLocationInfo info;\n\n for (auto &root : getSteamVRRoots()) {\n info.steamVrRoot = root;\n info.driverName = driver;\n\n computeDriverRootAndFilePath(info, driver);\n#ifdef VIVELOADER_VERBOSE\n std::cout << \"Will try to load driver from:\\n\"\n << info.driverFile << std::endl;\n if (exists(path{info.driverRoot})) {\n std::cout << \"Driver root exists\" << std::endl;\n }\n if (exists(path{info.driverFile})) {\n std::cout << \"Driver file exists\" << std::endl;\n }\n#endif\n if (exists(path{info.driverRoot}) &&\n exists(path{info.driverFile})) {\n info.found = true;\n return info;\n }\n }\n info = DriverLocationInfo{};\n return info;\n }\n\n std::string getToolLocation(std::string const &toolName,\n std::string const &steamVrRoot) {\n std::vector searchPath;\n if (!steamVrRoot.empty()) {\n searchPath = {steamVrRoot};\n } else {\n searchPath = getSteamVRRoots();\n }\n\n for (auto &root : searchPath) {\n auto p = path{root};\n p \/= \"bin\";\n p \/= getPlatformDirname();\n p \/= (toolName + TOOL_EXTENSION);\n if (exists(p)) {\n return p.string();\n }\n }\n return std::string{};\n }\n ConfigDirs findConfigDirs(std::string const & \/*steamVrRoot*\/,\n std::string const &driver) {\n ConfigDirs ret;\n auto json = getPathConfig();\n auto const &configLocations = json[\"config\"];\n if (!configLocations.isArray()) {\n return ret;\n }\n for (auto &configDir : configLocations) {\n auto configPath = path{configDir.asString()};\n if (!exists(configPath)) {\n continue;\n }\n ret.rootConfigDir = configPath.string();\n ret.driverConfigDir = (configPath \/ path{driver}).string();\n ret.valid = true;\n return ret;\n }\n ret = ConfigDirs{};\n return ret;\n }\n#if 0\n ConfigDirs findConfigDirs(std::string const &steamVrRoot,\n std::string const &driver) {\n static const auto LINE_PREFIX = \"Config path = \";\n ConfigDirs ret;\n bool foundLine = false;\n auto vrpathregFile =\n osvr::vive::getToolLocation(\"vrpathreg\", steamVrRoot);\n if (vrpathregFile.empty()) {\n return ret;\n }\n std::string pathLine;\n {\n using namespace boost::process;\n using namespace boost::process::initializers;\n using namespace boost::iostreams;\n auto p = create_pipe();\n file_descriptor_sink sink(p.sink, close_handle);\n auto c = execute(run_exe(vrpathregFile),\n#ifdef _WIN32\n\n show_window(SW_HIDE),\n#endif\n bind_stdout(sink), bind_stderr(sink));\n\n file_descriptor_source source(p.source, close_handle);\n stream is(source);\n\n for (int i = 0; i < 4; ++i) {\n std::getline(is, pathLine);\n if (pathLine.find(LINE_PREFIX) != std::string::npos) {\n foundLine = true;\n break;\n }\n }\n wait_for_exit(c);\n }\n if (!foundLine) {\n return ret;\n }\n while (!pathLine.empty() &&\n (pathLine.back() == '\\r' || pathLine.back() == '\\n')) {\n pathLine.pop_back();\n }\n\n#ifdef VIVELOADER_VERBOSE\n std::cout << \"Path line is: \" << pathLine << std::endl;\n#endif\n auto prefixLoc = pathLine.find(LINE_PREFIX);\n auto sub = pathLine.substr(std::string(LINE_PREFIX).size() + prefixLoc);\n#ifdef VIVELOADER_VERBOSE\n std::cout << \"substring is: \" << sub << std::endl;\n#endif\n ret.rootConfigDir = sub;\n ret.driverConfigDir = sub + PATH_SEP + driver;\n\n if (exists(path{ret.rootConfigDir})) {\n#ifdef VIVELOADER_VERBOSE\n std::cout << \"root config dir exists\" << std::endl;\n#endif\n ret.valid = true;\n }\n\n return ret;\n }\n#endif\n\n} \/\/ namespace vive\n} \/\/ namespace osvr\nRemove boost::process-using code from FindDriver\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2016 Razer 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 \"FindDriver.h\"\n\n\/\/ Library\/third-party includes\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Standard includes\n#include \n#include \n#include \n\n#if _MSC_VER >= 1800\n#include \n#else\n#include \n#endif\n\n#if defined(OSVR_WINDOWS)\n#include \n#endif\n\n#undef VIVELOADER_VERBOSE\n\nusing osvr::util::finally;\n\nnamespace osvr {\nnamespace vive {\n#if defined(OSVR_WINDOWS)\n static const auto PLATFORM_DIRNAME_BASE = \"win\";\n static const auto DRIVER_EXTENSION = \".dll\";\n static const auto TOOL_EXTENSION = \".exe\";\n static const auto PATH_SEP = \"\\\\\";\n#elif defined(OSVR_MACOSX)\n \/\/\/ @todo Note that there are no 64-bit steamvr runtimes or drivers on OS X\n static const auto PLATFORM_DIRNAME_BASE = \"osx\";\n static const auto DRIVER_EXTENSION = \".dylib\";\n static const auto TOOL_EXTENSION = \"\";\n static const auto PATH_SEP = \"\/\";\n#elif defined(OSVR_LINUX)\n static const auto PLATFORM_DIRNAME_BASE = \"linux\";\n static const auto DRIVER_EXTENSION = \".so\";\n static const auto TOOL_EXTENSION = \"\";\n static const auto PATH_SEP = \"\/\";\n#else\n#error \"Sorry, Valve does not produce a SteamVR runtime for your platform.\"\n#endif\n\n#if defined(OSVR_USING_FILESYSTEM_TR2)\n using std::tr2::sys::path;\n using std::tr2::sys::wpath;\n using std::tr2::sys::exists;\n#elif defined(OSVR_USING_BOOST_FILESYSTEM)\n using boost::filesystem::path;\n using boost::filesystem::exists;\n#endif\n\n#ifdef OSVR_MACOSX\n inline std::string getPlatformBitSuffix() {\n \/\/ they use universal binaries but stick them in \"32\"\n return \"32\";\n }\n#else\n inline std::string getPlatformBitSuffix() {\n return std::to_string(sizeof(void *) * CHAR_BIT);\n }\n#endif\n\n inline std::string getPlatformDirname() {\n return PLATFORM_DIRNAME_BASE + getPlatformBitSuffix();\n }\n\n inline void parsePathConfigFile(std::istream &is, Json::Value &ret) {\n Json::Reader reader;\n if (!reader.parse(is, ret)) {\n std::cerr << \"Error parsing file containing path configuration - \"\n \"have you run SteamVR yet?\"\n << std::endl;\n std::cerr << reader.getFormattedErrorMessages() << std::endl;\n }\n }\n#if defined(OSVR_WINDOWS)\n\n inline Json::Value getPathConfig() {\n PWSTR outString = nullptr;\n Json::Value ret;\n \/\/ It's OK to use Vista+ stuff here, since openvr_api.dll uses Vista+\n \/\/ stuff too.\n auto hr =\n SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &outString);\n if (!SUCCEEDED(hr)) {\n std::cerr << \"Could not get local app data directory!\" << std::endl;\n return ret;\n }\n \/\/ Free the string returned when we're all done.\n auto freeString = [&] { CoTaskMemFree(outString); };\n \/\/ Build the path to the file.\n auto vrPaths =\n wpath(outString) \/ wpath(L\"openvr\") \/ wpath(L\"openvrpaths.vrpath\");\n std::ifstream is(vrPaths.string());\n if (!is) {\n std::wcerr << L\"Could not open file containing path configuration \"\n L\"- have you run SteamVR yet? \"\n << vrPaths << L\"\\n\";\n return ret;\n }\n parsePathConfigFile(is, ret);\n return ret;\n }\n#elif defined(OSVR_MACOSX)\n inline Json::Value getPathConfig() {\n#error \"implementation not complete\"\n }\n#elif defined(OSVR_LINUX)\n\n inline Json::Value getPathConfig() {\n#error \"implementation not complete\"\n }\n#endif\n\n#if 0\n#if defined(OSVR_WINDOWS)\n inline std::vector getSteamVRRoots() {\n \/\/\/ @todo make this better - there's Windows API for that.\n return std::vector{\n std::string{\"C:\\\\Program Files\\\\Steam\\\\steamapps\\\\common\\\\SteamVR\"},\n std::string{\n \"C:\\\\Program Files (x86)\\\\Steam\\\\steamapps\\\\common\\\\SteamVR\"}};\n }\n#elif defined(OSVR_MACOSX)\n inline std::vector getSteamVRRoots() {\n#error \"implementation not complete\"\n }\n#elif defined(OSVR_LINUX)\n\n inline std::vector getSteamVRRoots() {\n#error \"implementation not complete\"\n }\n#endif\n#endif\n\n inline std::vector getSteamVRRoots(Json::Value const &json) {\n std::vector ret;\n auto &runtimes = json[\"runtime\"];\n if (!runtimes.isArray()) {\n return ret;\n }\n for (auto &runtime : runtimes) {\n ret.emplace_back(runtime.asString());\n }\n return ret;\n }\n inline std::vector getSteamVRRoots() {\n return getSteamVRRoots(getPathConfig());\n }\n\n inline void computeDriverRootAndFilePath(DriverLocationInfo &info,\n std::string const &driver) {\n auto p = path{info.steamVrRoot};\n p \/= \"drivers\";\n p \/= driver;\n p \/= \"bin\";\n p \/= getPlatformDirname();\n info.driverRoot = p.string();\n p \/= (\"driver_\" + driver + DRIVER_EXTENSION);\n info.driverFile = p.string();\n }\n\n DriverLocationInfo findDriver(std::string const &driver) {\n\n DriverLocationInfo info;\n\n for (auto &root : getSteamVRRoots()) {\n info.steamVrRoot = root;\n info.driverName = driver;\n\n computeDriverRootAndFilePath(info, driver);\n#ifdef VIVELOADER_VERBOSE\n std::cout << \"Will try to load driver from:\\n\"\n << info.driverFile << std::endl;\n if (exists(path{info.driverRoot})) {\n std::cout << \"Driver root exists\" << std::endl;\n }\n if (exists(path{info.driverFile})) {\n std::cout << \"Driver file exists\" << std::endl;\n }\n#endif\n if (exists(path{info.driverRoot}) &&\n exists(path{info.driverFile})) {\n info.found = true;\n return info;\n }\n }\n info = DriverLocationInfo{};\n return info;\n }\n\n std::string getToolLocation(std::string const &toolName,\n std::string const &steamVrRoot) {\n std::vector searchPath;\n if (!steamVrRoot.empty()) {\n searchPath = {steamVrRoot};\n } else {\n searchPath = getSteamVRRoots();\n }\n\n for (auto &root : searchPath) {\n auto p = path{root};\n p \/= \"bin\";\n p \/= getPlatformDirname();\n p \/= (toolName + TOOL_EXTENSION);\n if (exists(p)) {\n return p.string();\n }\n }\n return std::string{};\n }\n\n ConfigDirs findConfigDirs(std::string const & \/*steamVrRoot*\/,\n std::string const &driver) {\n ConfigDirs ret;\n auto json = getPathConfig();\n auto const &configLocations = json[\"config\"];\n if (!configLocations.isArray()) {\n return ret;\n }\n for (auto &configDir : configLocations) {\n auto configPath = path{configDir.asString()};\n if (!exists(configPath)) {\n continue;\n }\n ret.rootConfigDir = configPath.string();\n ret.driverConfigDir = (configPath \/ path{driver}).string();\n ret.valid = true;\n return ret;\n }\n ret = ConfigDirs{};\n return ret;\n }\n\n} \/\/ namespace vive\n} \/\/ namespace osvr\n<|endoftext|>"} {"text":"\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\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 *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* 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., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \n#include \n\n#include \n\nnamespace sofa {\n\n\nclass ImagePNG_test : public ::testing::Test\n{\nprotected:\n ImagePNG_test() {}\n\n void SetUp()\n {\n sofa::helper::system::DataRepository.addFirstPath(FRAMEWORK_TEST_RESOURCES_DIR);\n }\n void TearDown()\n {\n sofa::helper::system::DataRepository.removePath(FRAMEWORK_TEST_RESOURCES_DIR);\n }\n\n struct ImagePNGTestData\n {\n std::string filename;\n unsigned int width;\n unsigned int height;\n const unsigned char* data;\n\n ImagePNGTestData(const std::string& filename, unsigned int width, unsigned int height\n , unsigned int bpp, const unsigned char* data)\n : filename(filename), width(width), height(height), data(data)\n {\n \n }\n\n void testBench()\n {\n sofa::helper::io::ImagePNG img;\n\n EXPECT_TRUE(img.load(filename));\n EXPECT_EQ(width, img.getWidth());\n EXPECT_EQ(height, img.getHeight());\n EXPECT_EQ(width*height, img.getPixelCount());\n\n const unsigned char* testdata = img.getPixels();\n\n EXPECT_TRUE(0 == std::memcmp(data, testdata, sizeof(data)));\n }\n };\n \n};\n\nTEST_F(ImagePNG_test, ImagePNG_NoFile)\n{\n sofa::helper::io::ImagePNG imgNoFile;\n EXPECT_FALSE(imgNoFile.load(\"image\/randomnamewhichdoesnotexist.png\"));\n}\n\nTEST_F(ImagePNG_test, ImagePNG_NoImg)\n{\n sofa::helper::io::ImagePNG imgNoImage;\n EXPECT_FALSE(imgNoImage.load(\"image\/imagetest_noimage.png\"));\n}\n\nTEST_F(ImagePNG_test, ImagePNG_BlackWhite)\n{\n unsigned int width = 800;\n unsigned int height = 600;\n unsigned int bpp = 3;\n unsigned int totalsize = width*height*bpp;\n\n unsigned char* imgdata = new unsigned char[totalsize];\n \/\/half image (800x300) is black the other one is white\n std::fill(imgdata, imgdata + (800*300*3), 0);\n std::fill(imgdata + (800 * 300 * 3), imgdata + (800 * 600 * 3), 255);\n\n ImagePNGTestData imgBW(\"image\/imagetest_blackwhite.png\", width, height, bpp, imgdata);\n imgBW.testBench();\n}\n\n}\/\/ namespace sofa\n[SofaKernel] Framework_test: fixing ImagePNG_test\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\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 *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* 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., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \n#include \n#include \n\n#include \n\nnamespace sofa {\n\n\nclass ImagePNG_test : public ::testing::Test\n{\nprotected:\n ImagePNG_test() {}\n\n void SetUp()\n {\n sofa::helper::system::DataRepository.addFirstPath(FRAMEWORK_TEST_RESOURCES_DIR);\n }\n void TearDown()\n {\n sofa::helper::system::DataRepository.removePath(FRAMEWORK_TEST_RESOURCES_DIR);\n }\n\n struct ImagePNGTestData\n {\n std::string filename;\n unsigned int width;\n unsigned int height;\n unsigned int bpp;\n const unsigned char* data;\n\n ImagePNGTestData(const std::string& filename, unsigned int width, unsigned int height\n , unsigned int bpp, const unsigned char* data)\n : filename(filename), width(width), height(height), bpp(bpp), data(data)\n {\n \n }\n\n void testBench()\n {\n sofa::helper::io::ImagePNG img;\n\n EXPECT_TRUE(img.load(filename));\n EXPECT_EQ(width, img.getWidth());\n EXPECT_EQ(height, img.getHeight());\n EXPECT_EQ(width*height, img.getPixelCount());\n EXPECT_EQ(bpp, img.getBytesPerPixel());\n\n const unsigned char* testdata = img.getPixels();\n\n EXPECT_TRUE(0 == std::memcmp(data, testdata, width*height*bpp));\n }\n };\n \n};\n\nTEST_F(ImagePNG_test, ImagePNG_NoFile)\n{\n sofa::helper::io::ImagePNG imgNoFile;\n EXPECT_FALSE(imgNoFile.load(\"image\/randomnamewhichdoesnotexist.png\"));\n}\n\nTEST_F(ImagePNG_test, ImagePNG_NoImg)\n{\n sofa::helper::io::ImagePNG imgNoImage;\n EXPECT_FALSE(imgNoImage.load(\"image\/imagetest_noimage.png\"));\n}\n\nTEST_F(ImagePNG_test, ImagePNG_BlackWhite)\n{\n unsigned int width = 800;\n unsigned int height = 600;\n unsigned int bpp = 3;\n unsigned int totalsize = width*height*bpp;\n\n unsigned char* imgdata = new unsigned char[totalsize];\n \/\/half image (800x300) is black the other one is white\n std::fill(imgdata, imgdata + (800*300*3), 0);\n std::fill(imgdata + (800 * 300 * 3), imgdata + (800 * 600 * 3), 255);\n\n ImagePNGTestData imgBW(\"image\/imagetest_blackwhite.png\", width, height, bpp, imgdata);\n imgBW.testBench();\n}\n\n}\/\/ namespace sofa\n<|endoftext|>"} {"text":"\/*****************************************************************************\/\n\/**\n * @file NormalizedDeviceCoordinate.cpp\n * @author Naohisa Sakamoto\n *\/\n\/*----------------------------------------------------------------------------\n *\n * Copyright (c) Visualization Laboratory, Kyoto University.\n * All rights reserved.\n * See http:\/\/www.viz.media.kyoto-u.ac.jp\/kvs\/copyright\/ for details.\n *\n * $Id$\n *\/\n\/*****************************************************************************\/\n#include \"NormalizedDeviceCoordinate.h\"\n#include \"WindowCoordinate.h\"\n#include \"CameraCoordinate.h\"\n#include \n\n\nnamespace kvs\n{\n\n\/*===========================================================================*\/\n\/**\n * @brief Constructs a new NormalizedDeviceCoordinate class.\n * @param position [in] position in normalized device coordinates\n *\/\n\/*===========================================================================*\/\nNormalizedDeviceCoordinate::NormalizedDeviceCoordinate( const kvs::Vec3& position ):\n m_position( position )\n{\n}\n\n\/*===========================================================================*\/\n\/**\n * @brief Transforms normalized device coordinates to world coordinates.\n * @param x [in] x coordinate value of left corner of the viewport\n * @param y [in] y coordinate value of left corner of the viewport\n * @param width [in] width of the viewport\n * @param height [in] height of the viewport\n * @return world coordinates\n *\/\n\/*===========================================================================*\/\nconst WindowCoordinate NormalizedDeviceCoordinate::toWindowCoordinate(\n const int x,\n const int y,\n const size_t width,\n const size_t height ) const\n{\n const float px = ( m_position[0] + 1.0f ) * width * 0.5f + x;\n const float py = ( m_position[1] + 1.0f ) * height * 0.5f + y;\n const float pz = WindowCoordinate::CalculateDepth( ( m_position[2] + 1.0f ) \/ 2.0f );\n const kvs::Vec3 position( px, py, pz );\n return WindowCoordinate( position, x, y, width, height );\n}\n\n\/*===========================================================================*\/\n\/**\n * @brief Transforms normalized device coordinates to camera coordinates.\n * @param camera [in] pointer to a camera defines camera coordinates\n * @return camera coordinates\n *\/\n\/*===========================================================================*\/\nconst CameraCoordinate NormalizedDeviceCoordinate::toCameraCoordinate( const kvs::Camera* camera ) const\n{\n const kvs::Xform xform( camera->projectionMatrix() * camera->viewingMatrix() );\n const kvs::Vec3 position = xform.inverse().project( m_position );\n return CameraCoordinate( position, camera );\n}\n\n} \/\/ end of namespace kvs\nFixed a problem.\/*****************************************************************************\/\n\/**\n * @file NormalizedDeviceCoordinate.cpp\n * @author Naohisa Sakamoto\n *\/\n\/*----------------------------------------------------------------------------\n *\n * Copyright (c) Visualization Laboratory, Kyoto University.\n * All rights reserved.\n * See http:\/\/www.viz.media.kyoto-u.ac.jp\/kvs\/copyright\/ for details.\n *\n * $Id$\n *\/\n\/*****************************************************************************\/\n#include \"NormalizedDeviceCoordinate.h\"\n#include \"WindowCoordinate.h\"\n#include \"CameraCoordinate.h\"\n#include \n\n\nnamespace kvs\n{\n\n\/*===========================================================================*\/\n\/**\n * @brief Constructs a new NormalizedDeviceCoordinate class.\n * @param position [in] position in normalized device coordinates\n *\/\n\/*===========================================================================*\/\nNormalizedDeviceCoordinate::NormalizedDeviceCoordinate( const kvs::Vec3& position ):\n m_position( position )\n{\n}\n\n\/*===========================================================================*\/\n\/**\n * @brief Transforms normalized device coordinates to world coordinates.\n * @param x [in] x coordinate value of left corner of the viewport\n * @param y [in] y coordinate value of left corner of the viewport\n * @param width [in] width of the viewport\n * @param height [in] height of the viewport\n * @return world coordinates\n *\/\n\/*===========================================================================*\/\nconst WindowCoordinate NormalizedDeviceCoordinate::toWindowCoordinate(\n const int x,\n const int y,\n const size_t width,\n const size_t height ) const\n{\n const float px = ( m_position[0] + 1.0f ) * width * 0.5f + x;\n const float py = ( m_position[1] + 1.0f ) * height * 0.5f + y;\n const float pz = WindowCoordinate::CalculateDepth( ( m_position[2] + 1.0f ) \/ 2.0f );\n const kvs::Vec3 position( px, py, pz );\n return WindowCoordinate( position, x, y, width, height );\n}\n\n\/*===========================================================================*\/\n\/**\n * @brief Transforms normalized device coordinates to camera coordinates.\n * @param camera [in] pointer to a camera defines camera coordinates\n * @return camera coordinates\n *\/\n\/*===========================================================================*\/\nconst CameraCoordinate NormalizedDeviceCoordinate::toCameraCoordinate( const kvs::Camera* camera ) const\n{\n const kvs::Xform xform( camera->projectionMatrix() );\n const kvs::Vec3 position = xform.inverse().project( m_position );\n return CameraCoordinate( position, camera );\n}\n\n} \/\/ end of namespace kvs\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\ntemplate \nstruct NumericTest {\n\tstatic\n\tvoid test(lua_State* state) {\n\t\tconst I max_value = std::numeric_limits::max();\n\t\tconst I min_value = std::numeric_limits::lowest();\n\t\tconst I avg_value = (max_value + min_value) \/ 2;\n\n\t\t\/\/ Largest value\n\t\tCHECK(luwra::push(state, max_value) == 1);\n\t\tCHECK(luwra::read(state, -1) == max_value);\n\n\t\t\/\/ Lowest value\n\t\tCHECK(luwra::push(state, min_value) == 1);\n\t\tCHECK(luwra::read(state, -1) == min_value);\n\n\t\t\/\/ Average value\n\t\tCHECK(luwra::push(state, avg_value) == 1);\n\t\tCHECK(luwra::read(state, -1) == avg_value);\n\t}\n};\n\nstruct TautologyTest {\n\tstatic\n\tvoid test(lua_State*) {}\n};\n\ntemplate \nusing SelectNumericTest =\n\ttypename std::conditional<\n\t\tluwra::internal::NumericContainedValueBase::qualifies,\n\t\tNumericTest,\n\t\tTautologyTest\n\t>::type;\n\nTEST_CASE(\"types_numeric\") {\n\tlua_State* state = luaL_newstate();\n\n\t\/\/ Integer-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\t\/\/ Number-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"types_string\") {\n\tlua_State* state = luaL_newstate();\n\n\tconst char* test_cstr = \"Luwra Test String\";\n\tstd::string test_str(test_cstr);\n\n\t\/\/ Safety first\n\tREQUIRE(test_str == test_cstr);\n\n\t\/\/ Push both strings\n\tREQUIRE(luwra::push(state, test_cstr) == 1);\n\tREQUIRE(luwra::push(state, test_str) == 1);\n\n\t\/\/ They must be equal to Lua\n\tREQUIRE(luwra::equal(state, -1, -2));\n\n\t\/\/ Extraction as C string must not change the string's value\n\tconst char* l_cstr1 = luwra::read(state, -1);\n\tconst char* l_cstr2 = luwra::read(state, -2);\n\n\tREQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);\n\tREQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);\n\n\t\/\/ Extraction as C++ string must not change the string's value\n\tstd::string l_str1 = luwra::read(state, -1);\n\tstd::string l_str2 = luwra::read(state, -2);\n\n\tREQUIRE(l_str1 == test_cstr);\n\tREQUIRE(l_str2 == test_cstr);\n\tREQUIRE(test_str == l_str1);\n\tREQUIRE(test_str == l_str2);\n\tREQUIRE(l_str1 == l_str2);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"types_tuple\") {\n\tlua_State* state = luaL_newstate();\n\n\tint a = 13;\n\tstd::string b(\"Hello\");\n\tfloat c = 0.37;\n\n\t\/\/ Push normal tuple\n\tauto tuple = std::make_tuple(a, b, c);\n\tREQUIRE(luwra::push(state, tuple) == 3);\n\n\t\/\/ Push nested tuple\n\tauto tuple_nested = std::make_tuple(a, b, c, tuple);\n\tREQUIRE(luwra::push(state, tuple_nested) == 6);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"types_bool\") {\n\tlua_State* state = luaL_newstate();\n\n\tbool value = true;\n\n\tREQUIRE(luwra::push(state, value) == 1);\n\tREQUIRE(luwra::read(state, -1) == value);\n\n\tlua_close(state);\n}\nWhat are parentheses?#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\ntemplate \nstruct NumericTest {\n\tstatic\n\tvoid test(lua_State* state) {\n\t\tconst I max_value = std::numeric_limits::max();\n\t\tconst I min_value = std::numeric_limits::lowest();\n\t\tconst I avg_value = (max_value + min_value) \/ 2;\n\n\t\t\/\/ Largest value\n\t\tCHECK((luwra::push(state, max_value) == 1));\n\t\tCHECK((luwra::read(state, -1) == max_value));\n\n\t\t\/\/ Lowest value\n\t\tCHECK((luwra::push(state, min_value) == 1));\n\t\tCHECK((luwra::read(state, -1) == min_value));\n\n\t\t\/\/ Average value\n\t\tCHECK((luwra::push(state, avg_value) == 1));\n\t\tCHECK((luwra::read(state, -1) == avg_value));\n\t}\n};\n\nstruct TautologyTest {\n\tstatic\n\tvoid test(lua_State*) {}\n};\n\ntemplate \nusing SelectNumericTest =\n\ttypename std::conditional<\n\t\tluwra::internal::NumericContainedValueBase::qualifies,\n\t\tNumericTest,\n\t\tTautologyTest\n\t>::type;\n\nTEST_CASE(\"types_numeric\") {\n\tlua_State* state = luaL_newstate();\n\n\t\/\/ Integer-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\t\/\/ Number-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"types_string\") {\n\tlua_State* state = luaL_newstate();\n\n\tconst char* test_cstr = \"Luwra Test String\";\n\tstd::string test_str(test_cstr);\n\n\t\/\/ Safety first\n\tREQUIRE(test_str == test_cstr);\n\n\t\/\/ Push both strings\n\tREQUIRE(luwra::push(state, test_cstr) == 1);\n\tREQUIRE(luwra::push(state, test_str) == 1);\n\n\t\/\/ They must be equal to Lua\n\tREQUIRE(luwra::equal(state, -1, -2));\n\n\t\/\/ Extraction as C string must not change the string's value\n\tconst char* l_cstr1 = luwra::read(state, -1);\n\tconst char* l_cstr2 = luwra::read(state, -2);\n\n\tREQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);\n\tREQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);\n\n\t\/\/ Extraction as C++ string must not change the string's value\n\tstd::string l_str1 = luwra::read(state, -1);\n\tstd::string l_str2 = luwra::read(state, -2);\n\n\tREQUIRE(l_str1 == test_cstr);\n\tREQUIRE(l_str2 == test_cstr);\n\tREQUIRE(test_str == l_str1);\n\tREQUIRE(test_str == l_str2);\n\tREQUIRE(l_str1 == l_str2);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"types_tuple\") {\n\tlua_State* state = luaL_newstate();\n\n\tint a = 13;\n\tstd::string b(\"Hello\");\n\tfloat c = 0.37;\n\n\t\/\/ Push normal tuple\n\tauto tuple = std::make_tuple(a, b, c);\n\tREQUIRE(luwra::push(state, tuple) == 3);\n\n\t\/\/ Push nested tuple\n\tauto tuple_nested = std::make_tuple(a, b, c, tuple);\n\tREQUIRE(luwra::push(state, tuple_nested) == 6);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"types_bool\") {\n\tlua_State* state = luaL_newstate();\n\n\tbool value = true;\n\n\tREQUIRE(luwra::push(state, value) == 1);\n\tREQUIRE(luwra::read(state, -1) == value);\n\n\tlua_close(state);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 Mohammad Mehdi Saboorian\n *\n * This is part of moor, a wrapper for libarchive\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR 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#include \"archive_writer.hpp\"\n#include \"memory_writer_callback.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace moor;\n\nnamespace\n{\n class ScopedReadDisk\n {\n private:\n archive* m_archive;\n\n public:\n ScopedReadDisk()\n : m_archive(archive_read_disk_new())\n {\n if (!m_archive)\n {\n throw std::bad_alloc();\n }\n }\n\n ~ScopedReadDisk()\n {\n archive_read_close(m_archive);\n archive_read_free(m_archive);\n }\n\n operator archive*()\n {\n return m_archive;\n }\n\n operator const archive*() const\n {\n return m_archive;\n }\n };\n}\n\n\nvoid ArchiveWriter::checkError(const int err_code,\n const bool close_before_throw)\n{\n int archiveErrno = 0;\n const char* errStr = nullptr;\n if (err_code == ARCHIVE_FATAL)\n {\n archiveErrno = archive_errno(m_archive);\n errStr = archive_error_string(m_archive);\n if (close_before_throw)\n {\n close();\n }\n }\n\n if (err_code != ARCHIVE_OK && err_code != ARCHIVE_WARN)\n {\n throw std::system_error(archiveErrno,\n std::generic_category(),\n errStr ? errStr : \"\");\n }\n}\n\nArchiveWriter::ArchiveWriter(const std::string& archive_file_name_,\n const Format& format_,\n const Filter& filter_)\n : Archive(archive_write_new(), archive_file_name_),\n m_entry(archive_entry_new()),\n m_format(format_),\n m_filter(filter_),\n m_open(true)\n{\n \/\/ Set archive format\n checkError(archive_write_set_format(m_archive, (int) m_format), true);\n\n \/\/ Set archive compression\n checkError(archive_write_add_filter(m_archive, (int) m_filter), true);\n checkError(archive_write_open_filename(m_archive, cfilename()), true);\n}\n\nArchiveWriter::ArchiveWriter(std::vector& out_buffer_,\n const Format& format_,\n const Filter& filter_)\n : Archive(archive_write_new()),\n m_entry(archive_entry_new()),\n m_format(format_),\n m_filter(filter_),\n m_open(true)\n{\n \/\/ Set archive format\n checkError(archive_write_set_format(m_archive, static_cast(m_format)), true);\n\n \/\/ Set archive filter\n checkError(archive_write_add_filter(m_archive, static_cast(m_filter)), true);\n checkError(write_open_memory(m_archive, &out_buffer_), true);\n}\n\nArchiveWriter::ArchiveWriter(unsigned char* out_buffer_,\n size_t* size_,\n const Format& format_,\n const Filter& filter_)\n : Archive(archive_write_new()),\n m_entry(archive_entry_new()),\n m_format(format_),\n m_filter(filter_),\n m_open(true)\n{\n \/\/ Set archive format\n checkError(archive_write_set_format(m_archive, static_cast(m_format)), true);\n\n \/\/ Set archive filter\n checkError(archive_write_add_filter(m_archive, static_cast(m_filter)), true);\n checkError(archive_write_open_memory(m_archive, out_buffer_, *size_, size_), true);\n}\n\nArchiveWriter::~ArchiveWriter()\n{\n close();\n}\n\nvoid ArchiveWriter::addHeader(const std::string& entry_name_,\n const FileType entry_type_,\n const long long size_,\n const int permission_)\n{\n m_entry = archive_entry_clear(m_entry);\n archive_entry_set_pathname(m_entry, entry_name_.c_str());\n archive_entry_set_perm(m_entry, permission_);\n archive_entry_set_filetype(m_entry, static_cast(entry_type_));\n archive_entry_set_size(m_entry, size_);\n checkError(archive_write_header(m_archive, m_entry));\n}\n\nvoid ArchiveWriter::addHeader(const std::string& filePath, const struct stat* statBuf)\n{\n ScopedReadDisk a;\n\n m_entry = archive_entry_clear(m_entry);\n archive_entry_set_pathname(m_entry, filePath.c_str());\n checkError(archive_read_disk_entry_from_file(a, m_entry, -1, statBuf));\n checkError(archive_write_header(m_archive, m_entry));\n}\n\nvoid ArchiveWriter::addContent(const char b)\n{\n archive_write_data(m_archive, &b, 1);\n}\n\nvoid ArchiveWriter::addContent(const void* data, const unsigned long long size)\n{\n archive_write_data(m_archive, data, size);\n}\n\nvoid ArchiveWriter::addFinish()\n{\n archive_write_finish_entry(m_archive);\n}\n\nvoid ArchiveWriter::addFile(const std::string& file_path)\n{\n struct stat file_stat;\n if (stat(file_path.c_str(), &file_stat) < 0)\n {\n throw std::system_error(std::error_code(errno, std::generic_category()));\n }\n\n addHeader(file_path, &file_stat);\n\n if (!S_ISREG(file_stat.st_mode))\n {\n throw std::system_error(std::make_error_code(std::errc::not_supported));\n }\n\n std::fstream entry_file(file_path, std::ios::in);\n char buf[8192];\n while (entry_file.good())\n {\n entry_file.read(buf, sizeof(buf));\n archive_write_data(m_archive, buf, static_cast(entry_file.gcount()));\n }\n entry_file.close();\n\n addFinish();\n}\n\nvoid ArchiveWriter::addFile(const std::string& entry_name,\n const void* data,\n unsigned long long size)\n{\n addHeader(entry_name, FileType::Regular, size);\n addContent(data, size);\n addFinish();\n}\n\nvoid ArchiveWriter::addDirectory(const std::string& directory_name)\n{\n addHeader(directory_name, FileType::Directory, 0777);\n addFinish();\n}\n\nvoid ArchiveWriter::close()\n{\n if (m_open)\n {\n m_open = false;\n\n if (m_archive)\n {\n archive_write_close(m_archive);\n archive_write_free(m_archive);\n }\n\n if (m_entry)\n {\n archive_entry_free(m_entry);\n }\n }\n}\nLess C-style casts\/*\n * Copyright (c) 2013 Mohammad Mehdi Saboorian\n *\n * This is part of moor, a wrapper for libarchive\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR 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#include \"archive_writer.hpp\"\n#include \"memory_writer_callback.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace moor;\n\nnamespace\n{\n class ScopedReadDisk\n {\n private:\n archive* m_archive;\n\n public:\n ScopedReadDisk()\n : m_archive(archive_read_disk_new())\n {\n if (!m_archive)\n {\n throw std::bad_alloc();\n }\n }\n\n ~ScopedReadDisk()\n {\n archive_read_close(m_archive);\n archive_read_free(m_archive);\n }\n\n operator archive*()\n {\n return m_archive;\n }\n\n operator const archive*() const\n {\n return m_archive;\n }\n };\n}\n\n\nvoid ArchiveWriter::checkError(const int err_code,\n const bool close_before_throw)\n{\n int archiveErrno = 0;\n const char* errStr = nullptr;\n if (err_code == ARCHIVE_FATAL)\n {\n archiveErrno = archive_errno(m_archive);\n errStr = archive_error_string(m_archive);\n if (close_before_throw)\n {\n close();\n }\n }\n\n if (err_code != ARCHIVE_OK && err_code != ARCHIVE_WARN)\n {\n throw std::system_error(archiveErrno,\n std::generic_category(),\n errStr ? errStr : \"\");\n }\n}\n\nArchiveWriter::ArchiveWriter(const std::string& archive_file_name_,\n const Format& format_,\n const Filter& filter_)\n : Archive(archive_write_new(), archive_file_name_),\n m_entry(archive_entry_new()),\n m_format(format_),\n m_filter(filter_),\n m_open(true)\n{\n \/\/ Set archive format\n checkError(archive_write_set_format(m_archive, static_cast(m_format)), true);\n\n \/\/ Set archive compression\n checkError(archive_write_add_filter(m_archive, static_cast(m_filter)), true);\n checkError(archive_write_open_filename(m_archive, cfilename()), true);\n}\n\nArchiveWriter::ArchiveWriter(std::vector& out_buffer_,\n const Format& format_,\n const Filter& filter_)\n : Archive(archive_write_new()),\n m_entry(archive_entry_new()),\n m_format(format_),\n m_filter(filter_),\n m_open(true)\n{\n \/\/ Set archive format\n checkError(archive_write_set_format(m_archive, static_cast(m_format)), true);\n\n \/\/ Set archive filter\n checkError(archive_write_add_filter(m_archive, static_cast(m_filter)), true);\n checkError(write_open_memory(m_archive, &out_buffer_), true);\n}\n\nArchiveWriter::ArchiveWriter(unsigned char* out_buffer_,\n size_t* size_,\n const Format& format_,\n const Filter& filter_)\n : Archive(archive_write_new()),\n m_entry(archive_entry_new()),\n m_format(format_),\n m_filter(filter_),\n m_open(true)\n{\n \/\/ Set archive format\n checkError(archive_write_set_format(m_archive, static_cast(m_format)), true);\n\n \/\/ Set archive filter\n checkError(archive_write_add_filter(m_archive, static_cast(m_filter)), true);\n checkError(archive_write_open_memory(m_archive, out_buffer_, *size_, size_), true);\n}\n\nArchiveWriter::~ArchiveWriter()\n{\n close();\n}\n\nvoid ArchiveWriter::addHeader(const std::string& entry_name_,\n const FileType entry_type_,\n const long long size_,\n const int permission_)\n{\n m_entry = archive_entry_clear(m_entry);\n archive_entry_set_pathname(m_entry, entry_name_.c_str());\n archive_entry_set_perm(m_entry, permission_);\n archive_entry_set_filetype(m_entry, static_cast(entry_type_));\n archive_entry_set_size(m_entry, size_);\n checkError(archive_write_header(m_archive, m_entry));\n}\n\nvoid ArchiveWriter::addHeader(const std::string& filePath, const struct stat* statBuf)\n{\n ScopedReadDisk a;\n\n m_entry = archive_entry_clear(m_entry);\n archive_entry_set_pathname(m_entry, filePath.c_str());\n checkError(archive_read_disk_entry_from_file(a, m_entry, -1, statBuf));\n checkError(archive_write_header(m_archive, m_entry));\n}\n\nvoid ArchiveWriter::addContent(const char b)\n{\n archive_write_data(m_archive, &b, 1);\n}\n\nvoid ArchiveWriter::addContent(const void* data, const unsigned long long size)\n{\n archive_write_data(m_archive, data, size);\n}\n\nvoid ArchiveWriter::addFinish()\n{\n archive_write_finish_entry(m_archive);\n}\n\nvoid ArchiveWriter::addFile(const std::string& file_path)\n{\n struct stat file_stat;\n if (stat(file_path.c_str(), &file_stat) < 0)\n {\n throw std::system_error(std::error_code(errno, std::generic_category()));\n }\n\n addHeader(file_path, &file_stat);\n\n if (!S_ISREG(file_stat.st_mode))\n {\n throw std::system_error(std::make_error_code(std::errc::not_supported));\n }\n\n std::fstream entry_file(file_path, std::ios::in);\n char buf[8192];\n while (entry_file.good())\n {\n entry_file.read(buf, sizeof(buf));\n archive_write_data(m_archive, buf, static_cast(entry_file.gcount()));\n }\n entry_file.close();\n\n addFinish();\n}\n\nvoid ArchiveWriter::addFile(const std::string& entry_name,\n const void* data,\n unsigned long long size)\n{\n addHeader(entry_name, FileType::Regular, size);\n addContent(data, size);\n addFinish();\n}\n\nvoid ArchiveWriter::addDirectory(const std::string& directory_name)\n{\n addHeader(directory_name, FileType::Directory, 0777);\n addFinish();\n}\n\nvoid ArchiveWriter::close()\n{\n if (m_open)\n {\n m_open = false;\n\n if (m_archive)\n {\n archive_write_close(m_archive);\n archive_write_free(m_archive);\n }\n\n if (m_entry)\n {\n archive_entry_free(m_entry);\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"catch.hpp\"\n\n#include \n#include \n\n\n#include \n#include \n#include \n#include \n\ntemplate \nstruct NumericTest {\n\tstatic\n\tvoid test(lua_State* state) {\n\t\tconst I max_value = std::numeric_limits::max();\n\t\tconst I min_value = std::numeric_limits::lowest();\n\t\tconst I avg_value = (max_value + min_value) \/ 2;\n\n\t\t\/\/ Largest value\n\t\tREQUIRE(luwra::Value::push(state, max_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == max_value);\n\t\tlua_pop(state, 1);\n\n\t\t\/\/ Lowest value\n\t\tREQUIRE(luwra::Value::push(state, min_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == min_value);\n\t\tlua_pop(state, 1);\n\n\t\t\/\/ Average value\n\t\tREQUIRE(luwra::Value::push(state, avg_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == avg_value);\n\t\tlua_pop(state, 1);\n\t}\n};\n\nstruct TautologyTest {\n\tstatic\n\tvoid test(lua_State*) {}\n};\n\ntemplate \nusing SelectNumericTest =\n\ttypename std::conditional<\n\t\tluwra::internal::NumericContainedValueBase::qualifies,\n\t\tNumericTest,\n\t\tTautologyTest\n\t>::type;\n\nTEST_CASE(\"Test Value specialization for numeric C types\", \"types_numeric\") {\n\tlua_State* state = luaL_newstate();\n\n\t\/\/ Integer-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\t\/\/ Number-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for string types\", \"types_string\") {\n\tlua_State* state = luaL_newstate();\n\n\tconst char* test_cstr = \"Luwra Test String\";\n\tstd::string test_str(test_cstr);\n\n\t\/\/ Safety first\n\tREQUIRE(test_str == test_cstr);\n\n\t\/\/ Push both strings\n\tREQUIRE(luwra::Value::push(state, test_cstr) == 1);\n\tREQUIRE(luwra::Value::push(state, test_str) == 1);\n\n\t\/\/ They must be equal to Lua\n\tREQUIRE(lua_compare(state, -1, -2, LUA_OPEQ));\n\n\t\/\/ Extraction as C string must not change the string's value\n\tconst char* l_cstr1 = luwra::Value::read(state, -1);\n\tconst char* l_cstr2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);\n\tREQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);\n\n\t\/\/ Extraction as C++ string must not change the string's value\n\tstd::string l_str1 = luwra::Value::read(state, -1);\n\tstd::string l_str2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(l_str1 == test_cstr);\n\tREQUIRE(l_str2 == test_cstr);\n\tREQUIRE(test_str == l_str1);\n\tREQUIRE(test_str == l_str2);\n\tREQUIRE(l_str1 == l_str2);\n\n\tlua_pop(state, 2);\n\tlua_close(state);\n}\nAdd tuple test#include \"catch.hpp\"\n\n#include \n#include \n\n\n#include \n#include \n#include \n#include \n\ntemplate \nstruct NumericTest {\n\tstatic\n\tvoid test(lua_State* state) {\n\t\tconst I max_value = std::numeric_limits::max();\n\t\tconst I min_value = std::numeric_limits::lowest();\n\t\tconst I avg_value = (max_value + min_value) \/ 2;\n\n\t\t\/\/ Largest value\n\t\tREQUIRE(luwra::Value::push(state, max_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == max_value);\n\n\t\t\/\/ Lowest value\n\t\tREQUIRE(luwra::Value::push(state, min_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == min_value);\n\n\t\t\/\/ Average value\n\t\tREQUIRE(luwra::Value::push(state, avg_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == avg_value);\n\t}\n};\n\nstruct TautologyTest {\n\tstatic\n\tvoid test(lua_State*) {}\n};\n\ntemplate \nusing SelectNumericTest =\n\ttypename std::conditional<\n\t\tluwra::internal::NumericContainedValueBase::qualifies,\n\t\tNumericTest,\n\t\tTautologyTest\n\t>::type;\n\nTEST_CASE(\"Test Value specialization for numeric C types\", \"types_numeric\") {\n\tlua_State* state = luaL_newstate();\n\n\t\/\/ Integer-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\t\/\/ Number-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for string types\", \"types_string\") {\n\tlua_State* state = luaL_newstate();\n\n\tconst char* test_cstr = \"Luwra Test String\";\n\tstd::string test_str(test_cstr);\n\n\t\/\/ Safety first\n\tREQUIRE(test_str == test_cstr);\n\n\t\/\/ Push both strings\n\tREQUIRE(luwra::Value::push(state, test_cstr) == 1);\n\tREQUIRE(luwra::Value::push(state, test_str) == 1);\n\n\t\/\/ They must be equal to Lua\n\tREQUIRE(lua_compare(state, -1, -2, LUA_OPEQ));\n\n\t\/\/ Extraction as C string must not change the string's value\n\tconst char* l_cstr1 = luwra::Value::read(state, -1);\n\tconst char* l_cstr2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);\n\tREQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);\n\n\t\/\/ Extraction as C++ string must not change the string's value\n\tstd::string l_str1 = luwra::Value::read(state, -1);\n\tstd::string l_str2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(l_str1 == test_cstr);\n\tREQUIRE(l_str2 == test_cstr);\n\tREQUIRE(test_str == l_str1);\n\tREQUIRE(test_str == l_str2);\n\tREQUIRE(l_str1 == l_str2);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for tuples\", \"types_tuple\") {\n\tlua_State* state = luaL_newstate();\n\n\tint a = 13;\n\tstd::string b(\"Hello\");\n\tfloat c = 0.37;\n\n\t\/\/ Push normal tuple\n\tauto tuple = std::make_tuple(a, b, c);\n\tREQUIRE(luwra::Value::push(state, tuple) == 3);\n\n\t\/\/ Push nested tuple\n\tauto tuple_nested = std::make_tuple(a, b, c, tuple);\n\tREQUIRE(luwra::Value::push(state, tuple_nested) == 6);\n\n\tlua_close(state);\n}\n<|endoftext|>"} {"text":"#ifndef ALPINOCORPUS_EITHER_HH\n#define ALPINOCORPUS_EITHER_HH\n\nnamespace alpinocorpus {\n\n\/**\n * Either is an option type that resembles the Either type in Haskell.\n * It's used to indicate that computation results in two possible type:\n * the left type or the right type (which could have the same type).\n *\n * Unfortunately, we do not have algebraic data types in C++, so both\n * posibilities are encoded in the same type. The isLeft() and isRight()\n * methods can be used to probe whether we have a left or right value.\n *\n * In error handling the convention is that Left L<\/tt> is an error,\n * and information about the error is encoded using the type L<\/tt>.\n * Right R<\/tt> is a succesful computation with a result of the type\n * R<\/tt>.\n *\/\ntemplate \nclass Either {\npublic:\n\tstatic Either left(L left);\n\tstatic Either right(R right);\n\n\tbool isLeft();\n\tbool isRight();\n\tL left();\n\tR right();\nprivate:\n\tenum Result { LEFT, RIGHT };\n\n\tEither(Result result, L left, R right) :\n\t\td_result(result), d_left(left), d_right(right) {}\n\n\tResult d_result;\n\tL d_left;\n\tR d_right;\n};\n\ntemplate \ninline Either Either::left(L left)\n{\n\treturn Either(LEFT, left, R());\n}\n\ntemplate \ninline Either Either::right(R right)\n{\n\treturn Either(RIGHT, L(), right);\n}\n\ntemplate \ninline bool Either::isLeft()\n{\n\treturn d_result == LEFT;\n}\n\ntemplate \ninline bool Either::isRight()\n{\n\treturn d_result == RIGHT;\n}\n\ntemplate \ninline L Either::left()\n{\n\treturn d_left;\n}\n\ntemplate \ninline R Either::right()\n{\n\treturn d_right;\n}\n\nstruct Empty {};\n\n}\n\n#endif \/\/ ALPINOCORPUS_EITHER_HH\nEither: Add a note about boost::variant.#ifndef ALPINOCORPUS_EITHER_HH\n#define ALPINOCORPUS_EITHER_HH\n\nnamespace alpinocorpus {\n\n\/**\n * Either is an option type that resembles the Either type in Haskell.\n * It's used to indicate that computation results in two possible type:\n * the left type or the right type (which could have the same type).\n *\n * Unfortunately, we do not have algebraic data types in C++, so both\n * posibilities are encoded in the same type. The isLeft() and isRight()\n * methods can be used to probe whether we have a left or right value.\n *\n * In error handling the convention is that Left L<\/tt> is an error,\n * and information about the error is encoded using the type L<\/tt>.\n * Right R<\/tt> is a succesful computation with a result of the type\n * R<\/tt>.\n *\n * Note: we could have used boost::variant, but I think it is kinda\n * heavyweight. It does more, but also has a more complex API.\n *\/\ntemplate \nclass Either {\npublic:\n\tstatic Either left(L left);\n\tstatic Either right(R right);\n\n\tbool isLeft();\n\tbool isRight();\n\tL left();\n\tR right();\nprivate:\n\tenum Result { LEFT, RIGHT };\n\n\tEither(Result result, L left, R right) :\n\t\td_result(result), d_left(left), d_right(right) {}\n\n\tResult d_result;\n\tL d_left;\n\tR d_right;\n};\n\ntemplate \ninline Either Either::left(L left)\n{\n\treturn Either(LEFT, left, R());\n}\n\ntemplate \ninline Either Either::right(R right)\n{\n\treturn Either(RIGHT, L(), right);\n}\n\ntemplate \ninline bool Either::isLeft()\n{\n\treturn d_result == LEFT;\n}\n\ntemplate \ninline bool Either::isRight()\n{\n\treturn d_result == RIGHT;\n}\n\ntemplate \ninline L Either::left()\n{\n\treturn d_left;\n}\n\ntemplate \ninline R Either::right()\n{\n\treturn d_right;\n}\n\nstruct Empty {};\n\n}\n\n#endif \/\/ ALPINOCORPUS_EITHER_HH\n<|endoftext|>"} {"text":"#ifndef ALEPH_GEOMETRY_COVER_TREE_HH__\n#define ALEPH_GEOMETRY_COVER_TREE_HH__\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ FIXME: remove after debugging\n#include \n\n#include \n#include \n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\n\/**\n @class CoverTree\n @brief Generic cover tree data structure\n\n This class models a cover tree data structure, as described in the\n paper \"Cover trees for nearest neighbor\" by Beygelzimer et al.; an\n implementation is given at:\n\n http:\/\/hunch.net\/~jl\/projects\/cover_tree\/cover_tree.html\n\n This implementation attempts to be as generic as possible. It uses\n the simplified description of the cover tree, as given by Izbicki,\n Shelton in \"Faster Cover Trees\".\n*\/\n\ntemplate class CoverTree\n{\npublic:\n\n \/**\n Covering constant of the cover tree. It might make sense to change\n this later on in order to improve performance. Some papers set the\n constant to `1.3`.\n *\/\n\n constexpr static const double coveringConstant = 2.0;\n\n class Node\n {\n public:\n\n \/** Creates a new node that stores a point *\/\n Node( const Point& point, long level )\n : _point( point )\n , _level( level )\n {\n }\n\n \/** Calculates current covering distance of the node *\/\n double coveringDistance() const noexcept\n {\n return std::pow( coveringConstant, static_cast( _level ) );\n }\n\n \/** @returns true if the node is a leaf node *\/\n bool isLeaf() const noexcept\n {\n return _children.empty();\n }\n\n void insert( const Point& p )\n {\n auto d = Metric()( _point, p );\n\n std::cerr << __PRETTY_FUNCTION__ << \": Covering distance = \" << this->coveringDistance() << \"\\n\";\n std::cerr << __PRETTY_FUNCTION__ << \": Distance from point to root = \" << d << \"\\n\";\n\n if( d > this->coveringDistance() )\n {\n while( d > 2 * this->coveringDistance() )\n {\n std::cerr << __PRETTY_FUNCTION__ << \": Distance is bigger than covering distance; need to raise level of tree\\n\";\n\n \/\/ -----------------------------------------------------------\n \/\/\n \/\/ Find a leaf node that can become the new root node with\n \/\/ a raised level.\n\n std::stack nodes;\n nodes.push( this );\n\n Node* leaf = nullptr;\n Node* parent = nullptr;\n\n while( !nodes.empty() )\n {\n auto&& node = nodes.top();\n for( auto&& child : parent->_children )\n {\n if( child->isLeaf() )\n {\n leaf = child.get();\n parent = node;\n break;\n }\n }\n\n nodes.pop();\n }\n\n \/\/ There is no leaf, so there is nothing to do and we just\n \/\/ skip to the bottom where we add the current node as the\n \/\/ new root of the tree.\n if( !leaf )\n break;\n\n assert( leaf );\n assert( parent );\n\n \/\/ Remove leaf from subtree ----------------------------------\n \/\/\n \/\/ The previous tree does not contain the leaf node any more,\n \/\/ and it can be added as the new root node.\n\n std::unique_ptr leaf_ptr( nullptr );\n\n parent->_children.erase(\n std::remove_if(\n parent->_children.begin(), parent->_children.end(),\n [&leaf, &leaf_ptr] ( std::unique_ptr& child )\n {\n if( child.get() == leaf )\n {\n leaf_ptr = std::move( child );\n return true;\n }\n\n return false;\n }\n ),\n parent->_children.end()\n );\n\n \/\/ Make leaf node the new root node --------------------------\n \/\/\n \/\/ Notice that this does increase the level of the current\n \/\/ root. This has to be adjusted for.\n\n auto oldRoot\n = std::unique_ptr( new Node( this->_point, this->_level ) );\n\n for( auto&& child : _children )\n oldRoot->_children.push_back( std::move( child ) );\n\n _point = leaf->_point;\n _level = _level + 1;\n\n _children.clear();\n _children.push_back( std::move( oldRoot ) );\n }\n\n \/\/ Make current point the new root -----------------------------\n\n auto oldRoot\n = std::unique_ptr( new Node( this->_point, this->_level ) );\n\n for( auto&& child : _children )\n oldRoot->_children.push_back( std::move( child ) );\n\n _point = p;\n _level = _level + 1;\n\n _children.clear();\n _children.push_back( std::move( oldRoot ) );\n\n return;\n }\n\n return insert_( p );\n }\n\n \/**\n Auxiliary function for performing the recursive insertion of a new\n node into the tree.\n *\/\n\n void insert_( const Point& p )\n {\n for( auto&& child : _children )\n {\n auto d = Metric()( child->_point, p );\n if( d <= child->coveringDistance() )\n {\n std::cerr << __PRETTY_FUNCTION__ << \": Recursive enumeration of the tree\\n\";\n\n \/\/ We found a node in which the new point can be inserted\n \/\/ *without* violating the covering invariant.\n child->insert_( p );\n return;\n }\n }\n\n \/\/ Add the new point as a child of the current root node. Note the\n \/\/ level adjustment.\n _children.push_back( std::unique_ptr( new Node( p, _level - 1 ) ) );\n }\n\n Point _point; \/\/< The point stored in the node\n long _level; \/\/< The level of the node\n\n \/**\n All children of the node. Their order depends on the insertion\n order into the data set.\n *\/\n\n std::vector< std::unique_ptr > _children;\n };\n\n \/**\n Inserts a new point into the cover tree. If the tree is empty,\n the new point will become the root of the tree. Else, it shall\n be inserted according to the covering invariant.\n *\/\n\n void insert( const Point& p )\n {\n if( !_root )\n _root = std::unique_ptr( new Node(p,1) );\n else\n _root->insert( p );\n }\n\n \/\/ Pretty-printing function for the tree; this is only meant for\n \/\/ debugging purposes and could conceivably be implemented using\n \/\/ `std::ostream`.\n void print( std::ostream& o )\n {\n std::queue nodes;\n nodes.push( _root.get() );\n\n while( !nodes.empty() )\n {\n {\n auto n = nodes.size();\n\n for( decltype(n) i = 0; i < n; i++ )\n {\n auto&& node = nodes.front();\n\n if( i == 0 )\n o << node->_level << \": \";\n else\n o << \" \";\n\n o << node->_point;\n\n for( auto&& child : node->_children )\n nodes.push( child.get() );\n\n nodes.pop();\n }\n\n o << \"\\n\";\n }\n }\n }\n\nprivate:\n\n \/** Root pointer of the tree *\/\n std::unique_ptr _root;\n};\n\n} \/\/ namespace geometry\n\n} \/\/ namespace aleph\n\n#endif\nDocumented tree creation#ifndef ALEPH_GEOMETRY_COVER_TREE_HH__\n#define ALEPH_GEOMETRY_COVER_TREE_HH__\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ FIXME: remove after debugging\n#include \n\n#include \n#include \n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\n\/**\n @class CoverTree\n @brief Generic cover tree data structure\n\n This class models a cover tree data structure, as described in the\n paper \"Cover trees for nearest neighbor\" by Beygelzimer et al.; an\n implementation is given at:\n\n http:\/\/hunch.net\/~jl\/projects\/cover_tree\/cover_tree.html\n\n This implementation attempts to be as generic as possible. It uses\n the simplified description of the cover tree, as given by Izbicki,\n Shelton in \"Faster Cover Trees\".\n*\/\n\ntemplate class CoverTree\n{\npublic:\n\n \/**\n Covering constant of the cover tree. It might make sense to change\n this later on in order to improve performance. Some papers set the\n constant to `1.3`.\n *\/\n\n constexpr static const double coveringConstant = 2.0;\n\n class Node\n {\n public:\n\n \/** Creates a new node that stores a point *\/\n Node( const Point& point, long level )\n : _point( point )\n , _level( level )\n {\n }\n\n \/** Calculates current covering distance of the node *\/\n double coveringDistance() const noexcept\n {\n return std::pow( coveringConstant, static_cast( _level ) );\n }\n\n \/** @returns true if the node is a leaf node *\/\n bool isLeaf() const noexcept\n {\n return _children.empty();\n }\n\n void insert( const Point& p )\n {\n auto d = Metric()( _point, p );\n\n std::cerr << __PRETTY_FUNCTION__ << \": Covering distance = \" << this->coveringDistance() << \"\\n\";\n std::cerr << __PRETTY_FUNCTION__ << \": Distance from point to root = \" << d << \"\\n\";\n\n if( d > this->coveringDistance() )\n {\n while( d > 2 * this->coveringDistance() )\n {\n std::cerr << __PRETTY_FUNCTION__ << \": Distance is bigger than covering distance; need to raise level of tree\\n\";\n\n \/\/ -----------------------------------------------------------\n \/\/\n \/\/ Find a leaf node that can become the new root node with\n \/\/ a raised level.\n\n std::stack nodes;\n nodes.push( this );\n\n Node* leaf = nullptr;\n Node* parent = nullptr;\n\n while( !nodes.empty() )\n {\n auto&& node = nodes.top();\n for( auto&& child : parent->_children )\n {\n if( child->isLeaf() )\n {\n leaf = child.get();\n parent = node;\n break;\n }\n }\n\n nodes.pop();\n }\n\n \/\/ There is no leaf, so there is nothing to do and we just\n \/\/ skip to the bottom where we add the current node as the\n \/\/ new root of the tree.\n if( !leaf )\n break;\n\n assert( leaf );\n assert( parent );\n\n \/\/ Remove leaf from subtree ----------------------------------\n \/\/\n \/\/ The previous tree does not contain the leaf node any more,\n \/\/ and it can be added as the new root node.\n\n std::unique_ptr leaf_ptr( nullptr );\n\n parent->_children.erase(\n std::remove_if(\n parent->_children.begin(), parent->_children.end(),\n [&leaf, &leaf_ptr] ( std::unique_ptr& child )\n {\n if( child.get() == leaf )\n {\n leaf_ptr = std::move( child );\n return true;\n }\n\n return false;\n }\n ),\n parent->_children.end()\n );\n\n \/\/ Make leaf node the new root node --------------------------\n \/\/\n \/\/ Notice that this does increase the level of the current\n \/\/ root. This has to be adjusted for.\n\n auto oldRoot\n = std::unique_ptr( new Node( this->_point, this->_level ) );\n\n for( auto&& child : _children )\n oldRoot->_children.push_back( std::move( child ) );\n\n _point = leaf->_point;\n _level = _level + 1;\n\n _children.clear();\n _children.push_back( std::move( oldRoot ) );\n }\n\n \/\/ Make current point the new root -----------------------------\n \/\/\n \/\/ So far, the new point has not yet been inserted into the\n \/\/ tree. This needs to be done now while the cover is valid\n \/\/ again.\n\n auto oldRoot\n = std::unique_ptr( new Node( this->_point, this->_level ) );\n\n for( auto&& child : _children )\n oldRoot->_children.push_back( std::move( child ) );\n\n _point = p;\n _level = _level + 1;\n\n _children.clear();\n _children.push_back( std::move( oldRoot ) );\n\n return;\n }\n\n return insert_( p );\n }\n\n \/**\n Auxiliary function for performing the recursive insertion of a new\n node into the tree.\n *\/\n\n void insert_( const Point& p )\n {\n for( auto&& child : _children )\n {\n auto d = Metric()( child->_point, p );\n if( d <= child->coveringDistance() )\n {\n std::cerr << __PRETTY_FUNCTION__ << \": Recursive enumeration of the tree\\n\";\n\n \/\/ We found a node in which the new point can be inserted\n \/\/ *without* violating the covering invariant.\n child->insert_( p );\n return;\n }\n }\n\n \/\/ Add the new point as a child of the current root node. Note the\n \/\/ level adjustment.\n _children.push_back( std::unique_ptr( new Node( p, _level - 1 ) ) );\n }\n\n Point _point; \/\/< The point stored in the node\n long _level; \/\/< The level of the node\n\n \/**\n All children of the node. Their order depends on the insertion\n order into the data set.\n *\/\n\n std::vector< std::unique_ptr > _children;\n };\n\n \/**\n Inserts a new point into the cover tree. If the tree is empty,\n the new point will become the root of the tree. Else, it shall\n be inserted according to the covering invariant.\n *\/\n\n void insert( const Point& p )\n {\n if( !_root )\n _root = std::unique_ptr( new Node(p,1) );\n else\n _root->insert( p );\n }\n\n \/\/ Pretty-printing function for the tree; this is only meant for\n \/\/ debugging purposes and could conceivably be implemented using\n \/\/ `std::ostream`.\n void print( std::ostream& o )\n {\n std::queue nodes;\n nodes.push( _root.get() );\n\n while( !nodes.empty() )\n {\n {\n auto n = nodes.size();\n\n for( decltype(n) i = 0; i < n; i++ )\n {\n auto&& node = nodes.front();\n\n if( i == 0 )\n o << node->_level << \": \";\n else\n o << \" \";\n\n o << node->_point;\n\n for( auto&& child : node->_children )\n nodes.push( child.get() );\n\n nodes.pop();\n }\n\n o << \"\\n\";\n }\n }\n }\n\nprivate:\n\n \/** Root pointer of the tree *\/\n std::unique_ptr _root;\n};\n\n} \/\/ namespace geometry\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \n#include \/\/ dgemv, dgesvd\n#include \/\/ DenseMatrix\n#include \/\/ make_unique\n#include \/\/ SVD\n\nnamespace AnyODE {\n\n template , typename Decomp_t=SVD>\n struct OdeSysIterativeBase : public OdeSysBase {\n int m_njacvec_dot=0, m_nprec_setup=0, m_nprec_solve=0;\n std::unique_ptr m_jac_cache {nullptr};\n std::unique_ptr m_prec_cache {nullptr};\n bool m_update_prec_cache = false;\n Real_t m_old_gamma;\n\n virtual Status jac_times_vec(const Real_t * const __restrict__ vec,\n Real_t * const __restrict__ out,\n Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy\n ) override\n {\n \/\/ See \"Jacobian information (matrix-vector product)\"\n \/\/ (4.6.8 in cvs_guide.pdf for sundials 2.7.0)\n auto status = AnyODE::Status::success;\n const int ny = this->get_ny();\n if (m_jac_cache == nullptr){\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n }\n m_jac_cache->dot_vec(vec, out);\n m_njacvec_dot++;\n return status;\n }\n\n virtual Status prec_setup(Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n bool jac_ok,\n bool& jac_recomputed,\n Real_t gamma) override\n {\n const int ny = this->get_ny();\n auto status = AnyODE::Status::success;\n ignore(gamma);\n \/\/ See \"Preconditioning (Jacobian data)\" in cvs_guide.pdf (4.6.10 for 2.7.0)\n if (m_jac_cache == nullptr)\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n\n if (jac_ok){\n jac_recomputed = false;\n } else {\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n m_update_prec_cache = true;\n jac_recomputed = true;\n }\n m_nprec_setup++;\n return status;\n }\n\n virtual Status prec_solve_left(const Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n const Real_t * const __restrict__ r,\n Real_t * const __restrict__ z,\n Real_t gamma,\n Real_t delta,\n const Real_t * const __restrict__ ewt\n ) override\n {\n \/\/ See 4.6.9 on page 75 in cvs_guide.pdf (Sundials 2.6.2)\n \/\/ Solves P*z = r, where P ~= I - gamma*J\n ignore(delta);\n const int ny = this->get_ny();\n if (ewt)\n throw std::runtime_error(\"Not implemented.\");\n m_nprec_solve++;\n\n ignore(t); ignore(fy); ignore(y);\n bool recompute = false;\n if (m_prec_cache == nullptr){\n m_prec_cache = make_unique(nullptr, ny, ny, ny, true);\n recompute = true;\n } else {\n if (m_update_prec_cache or (m_old_gamma != gamma))\n recompute = true;\n }\n if (recompute){\n m_old_gamma = gamma;\n m_prec_cache->set_to_eye_plus_scaled_mtx(-gamma, *m_jac_cache);\n }\n int info;\n auto decomp = Decomp_t((JacMat_t*)(m_prec_cache.get()));\n info = decomp.solve(r, z);\n if (info == 0)\n return AnyODE::Status::success;\n return AnyODE::Status::recoverable_error;\n }\n\n\n };\n}\nRecompute jacobian for CVSpilsJacTimesVecFn#pragma once\n\n#include \n\n#include \n#include \/\/ dgemv, dgesvd\n#include \/\/ DenseMatrix\n#include \/\/ make_unique\n#include \/\/ SVD\n\nnamespace AnyODE {\n\n template , typename Decomp_t=SVD>\n struct OdeSysIterativeBase : public OdeSysBase {\n int m_njacvec_dot=0, m_nprec_setup=0, m_nprec_solve=0;\n std::unique_ptr m_jac_cache {nullptr};\n std::unique_ptr m_prec_cache {nullptr};\n bool m_update_prec_cache = false;\n Real_t m_old_gamma;\n\n virtual Status jac_times_vec(const Real_t * const __restrict__ vec,\n Real_t * const __restrict__ out,\n Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy\n ) override\n {\n \/\/ See \"Jacobian information (matrix-vector product)\"\n \/\/ (4.6.8 in cvs_guide.pdf for sundials 2.7.0)\n auto status = AnyODE::Status::success;\n const int ny = this->get_ny();\n if (m_jac_cache == nullptr){\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n }\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n m_jac_cache->dot_vec(vec, out);\n m_njacvec_dot++;\n return status;\n }\n\n virtual Status prec_setup(Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n bool jac_ok,\n bool& jac_recomputed,\n Real_t gamma) override\n {\n const int ny = this->get_ny();\n auto status = AnyODE::Status::success;\n ignore(gamma);\n \/\/ See \"Preconditioning (Jacobian data)\" in cvs_guide.pdf (4.6.10 for 2.7.0)\n if (m_jac_cache == nullptr)\n m_jac_cache = make_unique(nullptr, ny, ny, ny, true);\n\n if (jac_ok){\n jac_recomputed = false;\n } else {\n status = this->dense_jac_cmaj(t, y, fy, m_jac_cache->m_data, m_jac_cache->m_ld);\n m_update_prec_cache = true;\n jac_recomputed = true;\n }\n m_nprec_setup++;\n return status;\n }\n\n virtual Status prec_solve_left(const Real_t t,\n const Real_t * const __restrict__ y,\n const Real_t * const __restrict__ fy,\n const Real_t * const __restrict__ r,\n Real_t * const __restrict__ z,\n Real_t gamma,\n Real_t delta,\n const Real_t * const __restrict__ ewt\n ) override\n {\n \/\/ See 4.6.9 on page 75 in cvs_guide.pdf (Sundials 2.6.2)\n \/\/ Solves P*z = r, where P ~= I - gamma*J\n ignore(delta);\n const int ny = this->get_ny();\n if (ewt)\n throw std::runtime_error(\"Not implemented.\");\n m_nprec_solve++;\n\n ignore(t); ignore(fy); ignore(y);\n bool recompute = false;\n if (m_prec_cache == nullptr){\n m_prec_cache = make_unique(nullptr, ny, ny, ny, true);\n recompute = true;\n } else {\n if (m_update_prec_cache or (m_old_gamma != gamma))\n recompute = true;\n }\n if (recompute){\n m_old_gamma = gamma;\n m_prec_cache->set_to_eye_plus_scaled_mtx(-gamma, *m_jac_cache);\n }\n int info;\n auto decomp = Decomp_t((JacMat_t*)(m_prec_cache.get()));\n info = decomp.solve(r, z);\n if (info == 0)\n return AnyODE::Status::success;\n return AnyODE::Status::recoverable_error;\n }\n\n\n };\n}\n<|endoftext|>"} {"text":"namespace gen {\n\n\/** \\brief The Population template.\n *\n * Requires a `Candidate` class derived from ICandidate and implementing a\n * default constructor. *\/\ntemplate\nclass Population : private std::vector {\n bool sorted = false;\n std::mutex mtx{};\n\n static_assert(std::is_default_constructible::value,\n \"The Candidate type needs to provide a default constructor.\");\n\n typedef decltype(internal::detectFT(nullptr)) _FitnessType;\n\n static_assert(internal::hasFT(nullptr) &&\n std::is_base_of, Candidate>::value,\n \"The Candidate type needs to be derived from ICandidate.\");\n\n public:\n \/** \\brief Creates an empty population. *\/\n Population() = default;\n\n \/** \\brief Creates an empty population but preallocate space for count\n * candidates. *\/\n Population(size_t count) {\n this->reserve(count);\n }\n\n \/** \\brief Creates a population of size `count` whose candidates are results\n * of calls to the source function `src`.\n *\n * For discussion about the latter parameter see add(size_t, Source).\n *\n * \\see add(size_t, Source) *\/\n template\n Population(size_t count, Source src) {\n add(count, src);\n }\n\n \/* The Big Four: trivial but we need them because the mutex can't be \n * default copied or moved *\/\n\n \/** \\brief The copy constructor. *\/\n Population(const Population& _p): std::vector(_p), sorted(_p.sorted) { }\n\n \/** \\brief The move constructor. *\/\n Population(Population&& _p): std::vector(std::move(_p)), sorted(_p.sorted) { }\n\n \/** \\brief Copy assignment operator. *\/\n Population& operator=(const Population& _p) {\n std::lock_guard lock(mtx);\n std::vector::operator=(_p);\n sorted = _p.sorted;\n return *this;\n }\n\n \/** \\brief Move assignment operator. *\/\n Population& operator=(Population&& _p) {\n std::lock_guard lock(mtx);\n std::vector::operator=(std::move(_p));\n sorted = _p.sorted;\n return *this;\n }\n\n \/** \\brief Adds a new candidate. *\/\n void add(const Candidate& c) {\n std::lock_guard lock(mtx);\n this->push_back(c);\n sorted = false;\n }\n\n \/** \\brief Pushes back a new candidate using the move semantics. *\/\n void add(Candidate&& c) {\n std::lock_guard lock(mtx);\n this->push_back(std::forward(c));\n sorted = false;\n }\n\n \/** \\brief Draws `count` candidates from a source function `src`.\n *\n * Source can be:\n * - `std::function<(const) Candidate>`: returning by copy,\n * - `std::function<(const) Candidate&>`: returning by reference,\n * - a pointer to function returning `Candidate` or `Candidate&`,\n * - a lambda function returning either.\n *\n * The template allows for optimizations (inlining) in the latter case. *\/\n template\n void NOINLINE add(size_t count, Source src) {\n std::lock_guard lock(mtx);\n this->reserve(size() + count);\n for(size_t j = 0; j < count; j++)\n this->push_back(src());\n sorted = false;\n }\n\n \/** \\brief Copies all candidates from a vector of `Candidate`s. *\/\n void NOINLINE add(const std::vector& vec) {\n add(vec.begin(), vec.end());\n }\n\n \/** \\brief Copies an iterator range from a container of `Candidate`s. *\/\n template\n void add(InputIt first, InputIt last) {\n std::lock_guard lock(mtx);\n this->reserve(size() + std::distance(first, last));\n this->insert(end(), first, last);\n sorted = false;\n }\n\n \/** \\brief Moves all candidates from a vector of `Candidate`s. *\/\n void NOINLINE add(std::vector&& vec) {\n std::lock_guard lock(mtx);\n this->reserve(size() + vec.size());\n this->insert(end(), std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end()));\n vec.clear();\n sorted = false;\n }\n\n \/** \\brief Copies all candidates from another Population. *\/\n void add(const Population& pop) {\n return merge(static_cast&>(pop));\n }\n\n \/** \\brief Moves all candidates from another Population. *\/\n void add(Population&& pop) {\n return add(static_cast&&>(pop));\n }\n\n using std::vector::begin;\n using std::vector::end;\n using std::vector::size;\n using std::vector::clear;\n using std::vector::operator[];\n\n \/** \\brief Retrieves a candidate randomly chosen by rank-based selection.\n *\n * This method accepts as a template parameter a name of a function\n * `double(double)` that will receive arguments linearly spaced between\n * `1\/size * bias` and `bias` for candidates ranked `1` through `size` and\n * its return value will be interpreted as inverse probability, and as such,\n * is expected to be positive and strictly increasing in its argument. This\n * function will be built in at compile time, eliminating a function pointer\n * lookup. The default value is `std::exp`, for which an equivalent fast\n * replacement algorithm is provided.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied.\n *\n * \\param bias > 0 determines how much low-fitness solutions are preferred.\n * Zero would mean no account on fitness in the selection process\n * whatsoever. The bigger the value the more candidates with low fitness are\n * likely to be selected.\n * \\param rng the random number generator, or gen::rng by default.\n * \n * \\returns a constant reference to a randomly chosen `Candidate`. *\/\n template\n const Candidate& NOINLINE rankSelect(float bias, Rng& rng = rng) {\n if(internal::is_exp::value)\n return rankSelect_exp(bias, rng);\n else\n return rankSelect<\n static_cast(&internal::eval_in_product)\n > (bias);\n }\n\n \/** \\brief Retrieves a candidate randomly chosen by rank-based selection.\n *\n * This method accepts as a template parameter a name of a function\n * `double(double, double)` that will receive its first argument linearly\n * spaced between `1\/size` and `1` for candidates ranked `1` through `size`\n * and second argument equal to `bias` and its return value will be\n * interpreted as inverse probability. As such, is expected to be positive\n * and strictly increasing in its argument. This function will be built in\n * at compile time, eliminating a function pointer lookup. A usual choice\n * for `fun` is `std::pow`.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied.\n *\n * \\param bias > 0 determines how much low-fitness solutions are preferred.\n * Zero would mean no account on fitness in the selection process\n * whatsoever. The bigger the value the more candidates with low fitness are\n * likely to be selected.\n * \\param rng the random number generator, or gen::rng by default.\n * \n * \\returns a constant reference to a randomly chosen `Candidate`. *\/\n template\n const Candidate& NOINLINE rankSelect(double bias, Rng& rng = rng) {\n static thread_local std::discrete_distribution iDist{};\n static thread_local size_t last_sz = 0;\n static thread_local std::vector probs{};\n size_t sz = size();\n if(sz != last_sz) {\n probs.clear();\n probs.reserve(sz);\n for(size_t i = 0; i < sz; i++)\n probs.push_back(1 \/ fun((double)(i+1) \/ sz, bias));\n iDist = std::discrete_distribution(probs.begin(), probs.end());\n last_sz = sz;\n }\n ensureSorted();\n return (*this)[iDist(rng)];\n }\n\n private:\n template\n const Candidate& rankSelect_exp(double bias, Rng& rng = rng) {\n static thread_local std::uniform_real_distribution rDist(0, 1);\n ensureSorted();\n double x = rDist(rng);\n if(x == 1)\n return this->back();\n else\n return (*this)[(int)(-log(1 - x + x*exp(-bias))\/bias*size())];\n }\n\n public:\n\n \/** \\brief Returns the best candidate of population.\n *\n * If more candidates have equal best fitness the returned reference may be\n * any of them.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied. *\/\n const Candidate& best() {\n ensureSorted();\n return this->front();\n }\n\n \/** \\brief Reduces the population to a maximum size given by the argument,\n * dropping the worst part of the sample.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied. *\/\n Population& trim(size_t newSize) {\n ensureSorted();\n std::lock_guard lock(mtx);\n if(size() > newSize)\n this->resize(newSize);\n return *this;\n }\n\n\n \/** \\brief The return type of stat(). *\/\n struct Stat {\n double mean; \/\/\/< The mean fitness of the Population.\n double stdev; \/\/\/< The standard deviation of fitness in the Population.\n };\n\n \/** \\brief Returns the mean fitness of the population and the standard\n * deviation.\n *\n * Applicable only to candidate classes whose fitness is a simple floating\n * point type or allows an implicit convertion to one. This method\n * generates an error at compile time in specializations for which this\n * condition is not satisfied. *\/\n Stat stat() {\n static_assert(std::is_convertible<_FitnessType, double>::value,\n \"This method requires the fitness type to be convertible to double.\");\n double f, sf = 0, sf2 = 0;\n for(Candidate &c : *this) {\n f = c.fitness();\n sf += f;\n sf2 += f*f;\n }\n size_t sz = size();\n double dev2 = sf2\/sz - sf\/sz*sf\/sz;\n return Stat{sf\/sz, dev2 >= 0 ? sqrt(dev2) : 0};\n }\n\n private:\n void ensureSorted() {\n static_assert(internal::comparable<_FitnessType>(0),\n \"This method requires the fitness type to implement an operator<.\");\n std::lock_guard lock(mtx);\n if(!sorted) {\n std::sort(begin(), end());\n sorted = true;\n }\n }\n}; \/\/ class Population\n\n} \/\/ namespace gen\nFix old call to merge()namespace gen {\n\n\/** \\brief The Population template.\n *\n * Requires a `Candidate` class derived from ICandidate and implementing a\n * default constructor. *\/\ntemplate\nclass Population : private std::vector {\n bool sorted = false;\n std::mutex mtx{};\n\n static_assert(std::is_default_constructible::value,\n \"The Candidate type needs to provide a default constructor.\");\n\n typedef decltype(internal::detectFT(nullptr)) _FitnessType;\n\n static_assert(internal::hasFT(nullptr) &&\n std::is_base_of, Candidate>::value,\n \"The Candidate type needs to be derived from ICandidate.\");\n\n public:\n \/** \\brief Creates an empty population. *\/\n Population() = default;\n\n \/** \\brief Creates an empty population but preallocate space for count\n * candidates. *\/\n Population(size_t count) {\n this->reserve(count);\n }\n\n \/** \\brief Creates a population of size `count` whose candidates are results\n * of calls to the source function `src`.\n *\n * For discussion about the latter parameter see add(size_t, Source).\n *\n * \\see add(size_t, Source) *\/\n template\n Population(size_t count, Source src) {\n add(count, src);\n }\n\n \/* The Big Four: trivial but we need them because the mutex can't be \n * default copied or moved *\/\n\n \/** \\brief The copy constructor. *\/\n Population(const Population& _p): std::vector(_p), sorted(_p.sorted) { }\n\n \/** \\brief The move constructor. *\/\n Population(Population&& _p): std::vector(std::move(_p)), sorted(_p.sorted) { }\n\n \/** \\brief Copy assignment operator. *\/\n Population& operator=(const Population& _p) {\n std::lock_guard lock(mtx);\n std::vector::operator=(_p);\n sorted = _p.sorted;\n return *this;\n }\n\n \/** \\brief Move assignment operator. *\/\n Population& operator=(Population&& _p) {\n std::lock_guard lock(mtx);\n std::vector::operator=(std::move(_p));\n sorted = _p.sorted;\n return *this;\n }\n\n \/** \\brief Adds a new candidate. *\/\n void add(const Candidate& c) {\n std::lock_guard lock(mtx);\n this->push_back(c);\n sorted = false;\n }\n\n \/** \\brief Pushes back a new candidate using the move semantics. *\/\n void add(Candidate&& c) {\n std::lock_guard lock(mtx);\n this->push_back(std::forward(c));\n sorted = false;\n }\n\n \/** \\brief Draws `count` candidates from a source function `src`.\n *\n * Source can be:\n * - `std::function<(const) Candidate>`: returning by copy,\n * - `std::function<(const) Candidate&>`: returning by reference,\n * - a pointer to function returning `Candidate` or `Candidate&`,\n * - a lambda function returning either.\n *\n * The template allows for optimizations (inlining) in the latter case. *\/\n template\n void NOINLINE add(size_t count, Source src) {\n std::lock_guard lock(mtx);\n this->reserve(size() + count);\n for(size_t j = 0; j < count; j++)\n this->push_back(src());\n sorted = false;\n }\n\n \/** \\brief Copies all candidates from a vector of `Candidate`s. *\/\n void NOINLINE add(const std::vector& vec) {\n add(vec.begin(), vec.end());\n }\n\n \/** \\brief Copies an iterator range from a container of `Candidate`s. *\/\n template\n void add(InputIt first, InputIt last) {\n std::lock_guard lock(mtx);\n this->reserve(size() + std::distance(first, last));\n this->insert(end(), first, last);\n sorted = false;\n }\n\n \/** \\brief Moves all candidates from a vector of `Candidate`s. *\/\n void NOINLINE add(std::vector&& vec) {\n std::lock_guard lock(mtx);\n this->reserve(size() + vec.size());\n this->insert(end(), std::make_move_iterator(vec.begin()), std::make_move_iterator(vec.end()));\n vec.clear();\n sorted = false;\n }\n\n \/** \\brief Copies all candidates from another Population. *\/\n void add(const Population& pop) {\n return add(static_cast&>(pop));\n }\n\n \/** \\brief Moves all candidates from another Population. *\/\n void add(Population&& pop) {\n return add(static_cast&&>(pop));\n }\n\n using std::vector::begin;\n using std::vector::end;\n using std::vector::size;\n using std::vector::clear;\n using std::vector::operator[];\n\n \/** \\brief Retrieves a candidate randomly chosen by rank-based selection.\n *\n * This method accepts as a template parameter a name of a function\n * `double(double)` that will receive arguments linearly spaced between\n * `1\/size * bias` and `bias` for candidates ranked `1` through `size` and\n * its return value will be interpreted as inverse probability, and as such,\n * is expected to be positive and strictly increasing in its argument. This\n * function will be built in at compile time, eliminating a function pointer\n * lookup. The default value is `std::exp`, for which an equivalent fast\n * replacement algorithm is provided.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied.\n *\n * \\param bias > 0 determines how much low-fitness solutions are preferred.\n * Zero would mean no account on fitness in the selection process\n * whatsoever. The bigger the value the more candidates with low fitness are\n * likely to be selected.\n * \\param rng the random number generator, or gen::rng by default.\n * \n * \\returns a constant reference to a randomly chosen `Candidate`. *\/\n template\n const Candidate& NOINLINE rankSelect(float bias, Rng& rng = rng) {\n if(internal::is_exp::value)\n return rankSelect_exp(bias, rng);\n else\n return rankSelect<\n static_cast(&internal::eval_in_product)\n > (bias);\n }\n\n \/** \\brief Retrieves a candidate randomly chosen by rank-based selection.\n *\n * This method accepts as a template parameter a name of a function\n * `double(double, double)` that will receive its first argument linearly\n * spaced between `1\/size` and `1` for candidates ranked `1` through `size`\n * and second argument equal to `bias` and its return value will be\n * interpreted as inverse probability. As such, is expected to be positive\n * and strictly increasing in its argument. This function will be built in\n * at compile time, eliminating a function pointer lookup. A usual choice\n * for `fun` is `std::pow`.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied.\n *\n * \\param bias > 0 determines how much low-fitness solutions are preferred.\n * Zero would mean no account on fitness in the selection process\n * whatsoever. The bigger the value the more candidates with low fitness are\n * likely to be selected.\n * \\param rng the random number generator, or gen::rng by default.\n * \n * \\returns a constant reference to a randomly chosen `Candidate`. *\/\n template\n const Candidate& NOINLINE rankSelect(double bias, Rng& rng = rng) {\n static thread_local std::discrete_distribution iDist{};\n static thread_local size_t last_sz = 0;\n static thread_local std::vector probs{};\n size_t sz = size();\n if(sz != last_sz) {\n probs.clear();\n probs.reserve(sz);\n for(size_t i = 0; i < sz; i++)\n probs.push_back(1 \/ fun((double)(i+1) \/ sz, bias));\n iDist = std::discrete_distribution(probs.begin(), probs.end());\n last_sz = sz;\n }\n ensureSorted();\n return (*this)[iDist(rng)];\n }\n\n private:\n template\n const Candidate& rankSelect_exp(double bias, Rng& rng = rng) {\n static thread_local std::uniform_real_distribution rDist(0, 1);\n ensureSorted();\n double x = rDist(rng);\n if(x == 1)\n return this->back();\n else\n return (*this)[(int)(-log(1 - x + x*exp(-bias))\/bias*size())];\n }\n\n public:\n\n \/** \\brief Returns the best candidate of population.\n *\n * If more candidates have equal best fitness the returned reference may be\n * any of them.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied. *\/\n const Candidate& best() {\n ensureSorted();\n return this->front();\n }\n\n \/** \\brief Reduces the population to a maximum size given by the argument,\n * dropping the worst part of the sample.\n *\n * Applicable only if the fitness type of `Candidate` allows total ordering\n * using `operator<`. This method generates an error at compile time in\n * specializations for which this condition is not satisfied. *\/\n Population& trim(size_t newSize) {\n ensureSorted();\n std::lock_guard lock(mtx);\n if(size() > newSize)\n this->resize(newSize);\n return *this;\n }\n\n\n \/** \\brief The return type of stat(). *\/\n struct Stat {\n double mean; \/\/\/< The mean fitness of the Population.\n double stdev; \/\/\/< The standard deviation of fitness in the Population.\n };\n\n \/** \\brief Returns the mean fitness of the population and the standard\n * deviation.\n *\n * Applicable only to candidate classes whose fitness is a simple floating\n * point type or allows an implicit convertion to one. This method\n * generates an error at compile time in specializations for which this\n * condition is not satisfied. *\/\n Stat stat() {\n static_assert(std::is_convertible<_FitnessType, double>::value,\n \"This method requires the fitness type to be convertible to double.\");\n double f, sf = 0, sf2 = 0;\n for(Candidate &c : *this) {\n f = c.fitness();\n sf += f;\n sf2 += f*f;\n }\n size_t sz = size();\n double dev2 = sf2\/sz - sf\/sz*sf\/sz;\n return Stat{sf\/sz, dev2 >= 0 ? sqrt(dev2) : 0};\n }\n\n private:\n void ensureSorted() {\n static_assert(internal::comparable<_FitnessType>(0),\n \"This method requires the fitness type to implement an operator<.\");\n std::lock_guard lock(mtx);\n if(!sorted) {\n std::sort(begin(), end());\n sorted = true;\n }\n }\n}; \/\/ class Population\n\n} \/\/ namespace gen\n<|endoftext|>"} {"text":"\/*\n * StoichiometryView.hpp\n *\n * Copyright (C) 2012 Marc Kirchner\n *\n *\/\n#ifndef __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__\n#define __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__\n\nnamespace ipaca {\n\ntemplate\nstruct StoichiometryTraits\n{\n typedef typename T::iterator iterator_type;\n typedef typename T::const_iterator const_iterator_type;\n typedef typename T::value_type value_type;\n};\n\ntemplate\nstruct StoichiometryValueTraits\n{\n \/\/ must be specified by the user\n};\n\n\/** A generic view on stoichiometries.\n * This class declares the interface that \\c libipaca expects from a\n * stoichiometry. The client is required to specify stoichiometry\n * propertie (iterator types, value types and accessor functors in the\n * respective trait classes \\c StoichiometryTraits and\n * \\c StoichiometryValueTraits.\n *\/\ntemplate\nclass StoichiometryView\n{\npublic:\n typedef typename StoichiometryTraits::iterator_type iterator;\n typedef typename StoichiometryTraits::const_iterator_type\n const_iterator;\n\n StoichiometryView(T&);\n StoichiometryView(const StoichiometryView& rhs);\n\n const_iterator begin() const;\n const_iterator end() const;\n\n \/\/ TODO: figure out if we REALLY need the non-const iterator. Eliminate if possible.\n iterator begin();\n iterator end();\n\n const T& ref() const;\n bool isNonNegative() const;\n\nprivate:\n T& stoi_;\n};\n\n}\n\n\/\/\n\/\/ template implementation\n\/\/\n\ntemplate\nipaca::StoichiometryView::StoichiometryView(T& stoi) :\n stoi_(stoi)\n{\n}\n\ntemplate\nipaca::StoichiometryView::StoichiometryView(const StoichiometryView& rhs) :\n stoi_(rhs.stoi_)\n{\n}\n\ntemplate\ntypename ipaca::StoichiometryView::const_iterator ipaca::StoichiometryView<\n T>::begin() const\n{\n return stoi_.begin();\n}\n\ntemplate\ntypename ipaca::StoichiometryView::const_iterator ipaca::StoichiometryView<\n T>::end() const\n{\n return stoi_.end();\n}\n\ntemplate\ntypename ipaca::StoichiometryView::iterator ipaca::StoichiometryView::begin()\n{\n return stoi_.begin();\n}\n\ntemplate\ntypename ipaca::StoichiometryView::iterator ipaca::StoichiometryView::end()\n{\n return stoi_.end();\n}\n\ntemplate\nconst T& ipaca::StoichiometryView::ref() const\n{\n return stoi_;\n}\n\n#endif \/* __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__ *\/\nadding typeinfo for the viewed type\/*\n * StoichiometryView.hpp\n *\n * Copyright (C) 2012 Marc Kirchner\n *\n *\/\n#ifndef __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__\n#define __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__\n\nnamespace ipaca {\n\ntemplate\nstruct StoichiometryTraits\n{\n typedef typename T::iterator iterator_type;\n typedef typename T::const_iterator const_iterator_type;\n typedef typename T::value_type value_type;\n};\n\ntemplate\nstruct StoichiometryValueTraits\n{\n \/\/ must be specified by the user\n};\n\n\/** A generic view on stoichiometries.\n * This class declares the interface that \\c libipaca expects from a\n * stoichiometry. The client is required to specify stoichiometry\n * propertie (iterator types, value types and accessor functors in the\n * respective trait classes \\c StoichiometryTraits and\n * \\c StoichiometryValueTraits.\n *\/\ntemplate\nclass StoichiometryView\n{\npublic:\n typedef T viewed_type;\n typedef typename StoichiometryTraits::iterator_type iterator;\n typedef typename StoichiometryTraits::const_iterator_type\n const_iterator;\n\n StoichiometryView(T&);\n StoichiometryView(const StoichiometryView& rhs);\n\n const_iterator begin() const;\n const_iterator end() const;\n\n \/\/ TODO: figure out if we REALLY need the non-const iterator. Eliminate if possible.\n iterator begin();\n iterator end();\n\n const T& ref() const;\n bool isNonNegative() const;\n\nprivate:\n T& stoi_;\n};\n\n}\n\n\/\/\n\/\/ template implementation\n\/\/\n\ntemplate\nipaca::StoichiometryView::StoichiometryView(T& stoi) :\n stoi_(stoi)\n{\n}\n\ntemplate\nipaca::StoichiometryView::StoichiometryView(const StoichiometryView& rhs) :\n stoi_(rhs.stoi_)\n{\n}\n\ntemplate\ntypename ipaca::StoichiometryView::const_iterator ipaca::StoichiometryView<\n T>::begin() const\n{\n return stoi_.begin();\n}\n\ntemplate\ntypename ipaca::StoichiometryView::const_iterator ipaca::StoichiometryView<\n T>::end() const\n{\n return stoi_.end();\n}\n\ntemplate\ntypename ipaca::StoichiometryView::iterator ipaca::StoichiometryView::begin()\n{\n return stoi_.begin();\n}\n\ntemplate\ntypename ipaca::StoichiometryView::iterator ipaca::StoichiometryView::end()\n{\n return stoi_.end();\n}\n\ntemplate\nconst T& ipaca::StoichiometryView::ref() const\n{\n return stoi_;\n}\n\n#endif \/* __LIBIPACA_INCLUDE_IPACA_STOICHIOMETRYVIEW_HPP__ *\/\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/**\r\n\tParser and executer of my primitive (not Turing complete) assembly-like language\r\n\r\n\tExample:\r\n\r\n\tcreate function_name(param1, param2,...) {\r\n\t\tcreate x\r\n\t\tcreate y\r\n\t\tsetval x 5\r\n\t\tsetval y 10\r\n\t\tadd y y\r\n\t\tmul x y\r\n\t\tsub y x\r\n\t\tdiv x y\r\n\t\tsetvar param1 x\r\n\t\tsetvar param2 y\r\n\t\tprint x\r\n\t}\r\n*\/\r\n\r\n#define BIND_VALUE(member_method, bind_point) phoenix::bind(&member_method, &bind_point, qi::_1)\r\n\r\nnamespace qi = boost::spirit::qi;\r\nnamespace ascii = boost::spirit::ascii;\r\nnamespace phoenix = boost::phoenix;\r\n\r\nnamespace L\r\n{\r\n\tclass Function {\r\n\tprivate:\r\n\r\n\t\tstruct Command {\r\n\t\t\tstd::string commandName;\r\n\t\t\tstd::string param1;\r\n\t\t\tstd::string param2;\r\n\r\n\t\t\tCommand(const std::string& cmdName)\r\n\t\t\t\t: commandName(cmdName) {}\r\n\t\t};\r\n\r\n\t\tbool isValid = true;\r\n\t\tstd::string name;\r\n\t\tstd::vector param;\r\n\t\tstd::vector commands;\r\n\r\n\tpublic:\r\n\r\n\t\tFunction() = default;\r\n\r\n\t\tvoid SetName(const std::string& n) {\r\n\t\t\t\/\/std::cout << \"setting name \" << n << std::endl;\r\n\t\t\tname = n;\r\n\t\t}\r\n\r\n\t\tvoid AddFunctionParameter(const std::string& p) {\r\n\t\t\t\/\/std::cout << \"adding function parameter \" << p << std::endl;\r\n\t\t\tparam.push_back(p);\r\n\t\t}\r\n\r\n\t\tvoid AddCommand(const std::string& c) {\r\n\t\t\t\/\/std::cout << \"adding command \" << c << std::endl;\r\n\t\t\tcommands.emplace_back(c);\r\n\t\t}\r\n\r\n\t\tvoid AddCommandParameter(const std::string& p) {\r\n\t\t\t\/\/std::cout << \"adding command parameter \" << p << std::endl;\r\n\t\t\tif (!commands.empty()) {\r\n\t\t\t\tauto& b = commands.back();\r\n\t\t\t\tif (b.param1.empty()) {\r\n\t\t\t\t\tb.param1 = p;\r\n\t\t\t\t}\r\n\t\t\t\telse if (b.param2.empty()) {\r\n\t\t\t\t\tb.param2 = p;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tisValid = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tbool CheckValidity() {\r\n\t\t\tif (name.empty()) {\r\n\t\t\t\tisValid = false;\r\n\t\t\t}\r\n\t\t\treturn isValid;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate\r\n\tclass FunctionParser : public qi::grammar\r\n\t{\r\n\tprivate:\r\n\r\n\t\tqi::rule startRule;\r\n\t\tqi::rule paramRule;\r\n\t\tqi::rule bodyRule;\r\n\r\n\t\tFunction func;\r\n\r\n\tpublic:\r\n\r\n\t\tFunctionParser() : FunctionParser::base_type(startRule)\r\n\t\t{\r\n\t\t\tstartRule =\r\n\t\t\t\tqi::lit(\"create\")\r\n\t\t\t\t>> qi::as_string[+(qi::alnum - qi::char_('('))][BIND_VALUE(Function::SetName, func)]\r\n\t\t\t\t>> '('\r\n\t\t\t\t>> *paramRule\r\n\t\t\t\t>> qi::char_(')')\r\n\t\t\t\t>> qi::char_('{')\r\n\t\t\t\t>> -bodyRule\r\n\t\t\t\t>> qi::char_('}');\r\n\r\n\t\t\tparamRule =\r\n\t\t\t\tqi::as_string[+(qi::alnum)][BIND_VALUE(Function::AddFunctionParameter, func)]\r\n\t\t\t\t>> -qi::char_(',');\r\n\r\n\t\t\tbodyRule =\r\n\t\t\t\tqi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommand, func)]\r\n\t\t\t\t>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]\r\n\t\t\t\t>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]\r\n\t\t\t\t>> -(qi::char_(',') >> bodyRule);\r\n\t\t}\r\n\r\n\t\tFunction& GetParsedFunction() {\r\n\t\t\treturn func;\r\n\t\t}\r\n\t};\r\n}\r\n\r\ntemplate\r\nvoid ParseAndRun(It first, It end)\r\n{\r\n\tL::FunctionParser parser;\r\n\tbool succ = qi::phrase_parse(first, end, parser, ascii::space, std::string());\r\n\tauto& func = parser.GetParsedFunction();\r\n\r\n\t\/\/ TODO check first iterator\r\n\t\/\/ TODO replace first iterator with begin\r\n\tif (succ && func.CheckValidity()) {\r\n\t\tstd::cout << \"Parsing successful\" << std::endl;\r\n\t}\r\n\telse {\r\n\t\tstd::cout << \"Parsing failed\" << std::endl;\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tstd::string line;\r\n\r\n\tdo {\r\n\t\tstd::getline(std::cin, line);\r\n\t\tParseAndRun(line.cbegin(), line.cend());\r\n\t} while (!line.empty());\r\n\r\n\treturn 0;\r\n}\r\nqi::char_ update#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/**\r\n\tParser and executer of my primitive (not Turing complete) assembly-like language\r\n\r\n\tExample:\r\n\r\n\tcreate function_name(param1, param2,...) {\r\n\t\tcreate x\r\n\t\tcreate y\r\n\t\tsetval x 5\r\n\t\tsetval y 10\r\n\t\tadd y y\r\n\t\tmul x y\r\n\t\tsub y x\r\n\t\tdiv x y\r\n\t\tsetvar param1 x\r\n\t\tsetvar param2 y\r\n\t\tprint x\r\n\t}\r\n*\/\r\n\r\n#define BIND_VALUE(member_method, bind_point) phoenix::bind(&member_method, &bind_point, qi::_1)\r\n\r\nnamespace qi = boost::spirit::qi;\r\nnamespace ascii = boost::spirit::ascii;\r\nnamespace phoenix = boost::phoenix;\r\n\r\nnamespace L\r\n{\r\n\tclass Function {\r\n\tprivate:\r\n\r\n\t\tstruct Command {\r\n\t\t\tstd::string commandName;\r\n\t\t\tstd::string param1;\r\n\t\t\tstd::string param2;\r\n\r\n\t\t\tCommand(const std::string& cmdName)\r\n\t\t\t\t: commandName(cmdName) {}\r\n\t\t};\r\n\r\n\t\tbool isValid = true;\r\n\t\tstd::string name;\r\n\t\tstd::vector param;\r\n\t\tstd::vector commands;\r\n\r\n\tpublic:\r\n\r\n\t\tFunction() = default;\r\n\r\n\t\tvoid SetName(const std::string& n) {\r\n\t\t\t\/\/std::cout << \"setting name \" << n << std::endl;\r\n\t\t\tname = n;\r\n\t\t}\r\n\r\n\t\tvoid AddFunctionParameter(const std::string& p) {\r\n\t\t\t\/\/std::cout << \"adding function parameter \" << p << std::endl;\r\n\t\t\tparam.push_back(p);\r\n\t\t}\r\n\r\n\t\tvoid AddCommand(const std::string& c) {\r\n\t\t\t\/\/std::cout << \"adding command \" << c << std::endl;\r\n\t\t\tcommands.emplace_back(c);\r\n\t\t}\r\n\r\n\t\tvoid AddCommandParameter(const std::string& p) {\r\n\t\t\t\/\/std::cout << \"adding command parameter \" << p << std::endl;\r\n\t\t\tif (!commands.empty()) {\r\n\t\t\t\tauto& b = commands.back();\r\n\t\t\t\tif (b.param1.empty()) {\r\n\t\t\t\t\tb.param1 = p;\r\n\t\t\t\t}\r\n\t\t\t\telse if (b.param2.empty()) {\r\n\t\t\t\t\tb.param2 = p;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tisValid = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tbool CheckValidity() {\r\n\t\t\tif (name.empty()) {\r\n\t\t\t\tisValid = false;\r\n\t\t\t}\r\n\t\t\treturn isValid;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate\r\n\tclass FunctionParser : public qi::grammar\r\n\t{\r\n\tprivate:\r\n\r\n\t\tqi::rule startRule;\r\n\t\tqi::rule paramRule;\r\n\t\tqi::rule bodyRule;\r\n\r\n\t\tFunction func;\r\n\r\n\tpublic:\r\n\r\n\t\tFunctionParser() : FunctionParser::base_type(startRule)\r\n\t\t{\r\n\t\t\tstartRule =\r\n\t\t\t\tqi::lit(\"create\")\r\n\t\t\t\t>> qi::as_string[+(qi::alnum - qi::char_('('))][BIND_VALUE(Function::SetName, func)]\r\n\t\t\t\t>> qi::char_('(')\r\n\t\t\t\t>> *paramRule\r\n\t\t\t\t>> qi::char_(')')\r\n\t\t\t\t>> qi::char_('{')\r\n\t\t\t\t>> -bodyRule\r\n\t\t\t\t>> qi::char_('}');\r\n\r\n\t\t\tparamRule =\r\n\t\t\t\tqi::as_string[+(qi::alnum)][BIND_VALUE(Function::AddFunctionParameter, func)]\r\n\t\t\t\t>> -qi::char_(',');\r\n\r\n\t\t\tbodyRule =\r\n\t\t\t\tqi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommand, func)]\r\n\t\t\t\t>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]\r\n\t\t\t\t>> -qi::as_string[qi::lexeme[+qi::alnum - qi::char_('}')]][BIND_VALUE(Function::AddCommandParameter, func)]\r\n\t\t\t\t>> -(qi::char_(',') >> bodyRule);\r\n\t\t}\r\n\r\n\t\tFunction& GetParsedFunction() {\r\n\t\t\treturn func;\r\n\t\t}\r\n\t};\r\n}\r\n\r\ntemplate\r\nvoid ParseAndRun(It first, It end)\r\n{\r\n\tL::FunctionParser parser;\r\n\tbool succ = qi::phrase_parse(first, end, parser, ascii::space, std::string());\r\n\tauto& func = parser.GetParsedFunction();\r\n\r\n\t\/\/ TODO check first iterator\r\n\t\/\/ TODO replace first iterator with begin\r\n\tif (succ && func.CheckValidity()) {\r\n\t\tstd::cout << \"Parsing successful\" << std::endl;\r\n\t}\r\n\telse {\r\n\t\tstd::cout << \"Parsing failed\" << std::endl;\r\n\t}\r\n}\r\n\r\nint main() {\r\n\tstd::string line;\r\n\r\n\tdo {\r\n\t\tstd::getline(std::cin, line);\r\n\t\tParseAndRun(line.cbegin(), line.cend());\r\n\t} while (!line.empty());\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"\/**\n* Copyright (C) 2016 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\n#include \n\n#include \n#include \n#include \"..\/..\/..\/..\/repo_test_utils.h\"\n\nusing namespace repo::core::model;\n\nstd::vector identity =\n{ 1, 0, 0, 0,\n0, 1, 0, 0,\n0, 0, 1, 0,\n0, 0, 0, 1 };\n\nstd::vector notId =\n{ 1, 2, 3, 4,\n5, 6, 7, 8,\n9, 0.3f, 10, 11,\n5342, 31, 0.6f, 12 };\n\nstd::vector idInBoundary =\n{ 1, 0, 0, 0,\n0, 1, 0, (float)1e-6,\n0, 0, 1, 0,\n0, (float)1e-6, (float)1e-6, 1 };\n\nstd::vector notIdInBoundary = { 1, 0, 0, 0,\n0, 1, 0, (float)2e-5,\n0, 0, 2, 0,\n0, (float)2e-5, (float)2e-5, 1 };\n\nTransformationNode makeTransformationNode(\n\tconst std::vector &matrix)\n{\n\tRepoBSONBuilder bsonBuilder;\n\tRepoBSONBuilder rows;\n\tfor (uint32_t i = 0; i < 4; ++i)\n\t{\n\t\tRepoBSONBuilder columns;\n\t\tfor (uint32_t j = 0; j < 4; ++j){\n\t\t\tcolumns << std::to_string(j) << matrix[i * 4 + j];\n\t\t}\n\t\trows.appendArray(std::to_string(i), columns.obj());\n\t}\n\tbsonBuilder.appendArray(REPO_NODE_LABEL_MATRIX, rows.obj());\n\n\treturn bsonBuilder.obj();\n}\n\nTEST(RepoTransformationNodeTest, Constructor)\n{\n\tauto empty = TransformationNode();\n\n\tEXPECT_TRUE(empty.isEmpty());\n\tEXPECT_EQ(NodeType::TRANSFORMATION, empty.getTypeAsEnum());\n\n\tauto repoBson = RepoBSON(BSON(\"test\" << \"blah\" << \"test2\" << 2));\n\n\tauto fromRepoBSON = TransformationNode(repoBson);\n\tEXPECT_EQ(NodeType::TRANSFORMATION, fromRepoBSON.getTypeAsEnum());\n\tEXPECT_EQ(fromRepoBSON.nFields(), repoBson.nFields());\n\tEXPECT_EQ(0, fromRepoBSON.getFileList().size());\n}\n\nTEST(RepoTransformationNodeTest, IdentityTest)\n{\n\tauto empty = TransformationNode();\n\tEXPECT_TRUE(empty.isIdentity());\n\n\tEXPECT_TRUE(makeTransformationNode(identity).isIdentity());\n\tEXPECT_TRUE(makeTransformationNode(idInBoundary).isIdentity());\n\tEXPECT_FALSE(makeTransformationNode(notId).isIdentity());\n\tEXPECT_FALSE(makeTransformationNode(notIdInBoundary).isIdentity());\n}\n\nTEST(RepoTransformationNodeTest, IdentityTest2)\n{\n\tauto identity = TransformationNode::identityMat();\n\n\tASSERT_EQ(4, identity.size());\n\tfor (int i = 0; i < 4; ++i)\n\t{\n\t\tASSERT_EQ(4, identity[i].size());\n\t\tfor (int j = 0; j < 4; ++j)\n\t\t{\n\t\t\tfloat expectedOutcome = i % 4 == j ? 1 : 0;\n\t\t\tEXPECT_EQ(expectedOutcome, identity[i][j]);\n\t\t}\n\t}\n}\n\nTEST(RepoTransformationNodeTest, TypeTest)\n{\n\tTransformationNode node = TransformationNode();\n\n\tEXPECT_EQ(REPO_NODE_TYPE_TRANSFORMATION, node.getType());\n\tEXPECT_EQ(NodeType::TRANSFORMATION, node.getTypeAsEnum());\n}\n\nTEST(RepoTransformationNodeTest, PositionDependantTest)\n{\n\tTransformationNode node = TransformationNode();\n\t\/\/transformation node should always be position dependant\n\tEXPECT_TRUE(node.positionDependant());\n}\n\nTEST(RepoTransformationNodeTest, SEqualTest)\n{\n\tauto empty1 = TransformationNode();\n\tauto empty2 = TransformationNode();\n\n\tauto notEmpty1 = makeTransformationNode(notId);\n\tauto notEmpty2 = makeTransformationNode(notId);\n\tauto notEmpty3 = makeTransformationNode(identity);\n\n\tEXPECT_TRUE(empty1.sEqual(empty2));\n\tEXPECT_TRUE(empty2.sEqual(empty1));\n\tEXPECT_TRUE(empty1.sEqual(empty1));\n\tEXPECT_TRUE(notEmpty1.sEqual(notEmpty2));\n\tEXPECT_TRUE(notEmpty2.sEqual(notEmpty1));\n\tEXPECT_FALSE(notEmpty1.sEqual(empty2));\n\tEXPECT_TRUE(notEmpty3.sEqual(notEmpty3));\n\tEXPECT_FALSE(notEmpty3.sEqual(notEmpty2));\n\tEXPECT_FALSE(empty1.sEqual(notEmpty2));\n}\n\nTEST(RepoTransformationNodeTest, CloneAndApplyTransformationTest)\n{\n\tauto empty = TransformationNode();\n\n\tTransformationNode modifiedEmpty = empty.cloneAndApplyTransformation(notId);\n\n\tEXPECT_EQ(empty.getTransMatrix(false), identity);\n\tEXPECT_EQ(modifiedEmpty.getTransMatrix(false), notId);\n\n\tauto filled = makeTransformationNode(notId);\n\tTransformationNode modifiedFilled = filled.cloneAndApplyTransformation(std::vector());\n\n\tEXPECT_EQ(modifiedFilled.getTransMatrix(false).getData(), notId);\n}\n\nTEST(RepoTransformationNodeTest, GetTransMatrixTest)\n{\n\tTransformationNode empty = TransformationNode();\n\tEXPECT_EQ(identity, empty.getTransMatrix(false));\n\n\tTransformationNode notEmpty = makeTransformationNode(notId);\n\tEXPECT_EQ(notId, notEmpty.getTransMatrix(false));\n\n\t\/\/check transpose is done correctly\n\tauto notIdTransposed = notEmpty.getTransMatrix(true);\n\n\tauto notIdTransData = notIdTransposed.getData();\n\tASSERT_EQ(notId.size(), notIdTransData.size());\n\tfor (int i = 0; i < 4; ++i)\n\t{\n\t\tfor (int j = 0; j < 4; ++j)\n\t\t{\n\t\t\tint index = i * 4 + j;\n\t\t\tint transIndex = j * 4 + i;\n\t\t\tEXPECT_EQ(notId[index], notIdTransData[transIndex]);\n\t\t}\n\t}\n}#48 small commit\/**\n* Copyright (C) 2016 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\n#include \n\n#include \n#include \n#include \"..\/..\/..\/..\/repo_test_utils.h\"\n\nusing namespace repo::core::model;\n\nstd::vector identity =\n{ 1, 0, 0, 0,\n0, 1, 0, 0,\n0, 0, 1, 0,\n0, 0, 0, 1 };\n\nstd::vector notId =\n{ 1, 2, 3, 4,\n5, 6, 7, 8,\n9, 0.3f, 10, 11,\n5342, 31, 0.6f, 12 };\n\nstd::vector idInBoundary =\n{ 1, 0, 0, 0,\n0, 1, 0, (float)1e-6,\n0, 0, 1, 0,\n0, (float)1e-6, (float)1e-6, 1 };\n\nstd::vector notIdInBoundary = { 1, 0, 0, 0,\n0, 1, 0, (float)2e-5,\n0, 0, 2, 0,\n0, (float)2e-5, (float)2e-5, 1 };\n\nTransformationNode makeTransformationNode(\n\tconst std::vector &matrix)\n{\n\tRepoBSONBuilder bsonBuilder;\n\tRepoBSONBuilder rows;\n\tfor (uint32_t i = 0; i < 4; ++i)\n\t{\n\t\tRepoBSONBuilder columns;\n\t\tfor (uint32_t j = 0; j < 4; ++j){\n\t\t\tcolumns << std::to_string(j) << matrix[i * 4 + j];\n\t\t}\n\t\trows.appendArray(std::to_string(i), columns.obj());\n\t}\n\tbsonBuilder.appendArray(REPO_NODE_LABEL_MATRIX, rows.obj());\n\n\treturn bsonBuilder.obj();\n}\n\nTEST(RepoTransformationNodeTest, Constructor)\n{\n\tauto empty = TransformationNode();\n\n\tEXPECT_TRUE(empty.isEmpty());\n\tEXPECT_EQ(NodeType::TRANSFORMATION, empty.getTypeAsEnum());\n\n\tauto repoBson = RepoBSON(BSON(\"test\" << \"blah\" << \"test2\" << 2));\n\n\tauto fromRepoBSON = TransformationNode(repoBson);\n\tEXPECT_EQ(NodeType::TRANSFORMATION, fromRepoBSON.getTypeAsEnum());\n\tEXPECT_EQ(fromRepoBSON.nFields(), repoBson.nFields());\n\tEXPECT_EQ(0, fromRepoBSON.getFileList().size());\n}\n\nTEST(RepoTransformationNodeTest, IdentityTest)\n{\n\tauto empty = TransformationNode();\n\tEXPECT_TRUE(empty.isIdentity());\n\n\tEXPECT_TRUE(makeTransformationNode(identity).isIdentity());\n\tEXPECT_TRUE(makeTransformationNode(idInBoundary).isIdentity());\n\tEXPECT_FALSE(makeTransformationNode(notId).isIdentity());\n\tEXPECT_FALSE(makeTransformationNode(notIdInBoundary).isIdentity());\n}\n\nTEST(RepoTransformationNodeTest, IdentityTest2)\n{\n\tauto identity = TransformationNode::identityMat();\n\n\tASSERT_EQ(4, identity.size());\n\tfor (int i = 0; i < 4; ++i)\n\t{\n\t\tASSERT_EQ(4, identity[i].size());\n\t\tfor (int j = 0; j < 4; ++j)\n\t\t{\n\t\t\tfloat expectedOutcome = i % 4 == j ? 1 : 0;\n\t\t\tEXPECT_EQ(expectedOutcome, identity[i][j]);\n\t\t}\n\t}\n}\n\nTEST(RepoTransformationNodeTest, TypeTest)\n{\n\tTransformationNode node = TransformationNode();\n\n\tEXPECT_EQ(REPO_NODE_TYPE_TRANSFORMATION, node.getType());\n\tEXPECT_EQ(NodeType::TRANSFORMATION, node.getTypeAsEnum());\n}\n\nTEST(RepoTransformationNodeTest, PositionDependantTest)\n{\n\tTransformationNode node = TransformationNode();\n\t\/\/transformation node should always be position dependant\n\tEXPECT_TRUE(node.positionDependant());\n}\n\nTEST(RepoTransformationNodeTest, SEqualTest)\n{\n\tauto empty1 = TransformationNode();\n\tauto empty2 = TransformationNode();\n\n\tauto notEmpty1 = makeTransformationNode(notId);\n\tauto notEmpty2 = makeTransformationNode(notId);\n\tauto notEmpty3 = makeTransformationNode(identity);\n\n\tEXPECT_TRUE(empty1.sEqual(empty2));\n\tEXPECT_TRUE(empty2.sEqual(empty1));\n\tEXPECT_TRUE(empty1.sEqual(empty1));\n\tEXPECT_TRUE(notEmpty1.sEqual(notEmpty2));\n\tEXPECT_TRUE(notEmpty2.sEqual(notEmpty1));\n\tEXPECT_FALSE(notEmpty1.sEqual(empty2));\n\tEXPECT_TRUE(notEmpty3.sEqual(notEmpty3));\n\tEXPECT_FALSE(notEmpty3.sEqual(notEmpty2));\n\tEXPECT_FALSE(empty1.sEqual(notEmpty2));\n}\n\nTEST(RepoTransformationNodeTest, CloneAndApplyTransformationTest)\n{\n\tauto empty = TransformationNode();\n\n\tTransformationNode modifiedEmpty = empty.cloneAndApplyTransformation(notId);\n\n\tEXPECT_EQ(empty.getTransMatrix(false), identity);\n\tEXPECT_EQ(modifiedEmpty.getTransMatrix(false), notId);\n\n\tauto filled = makeTransformationNode(notId);\n\tTransformationNode modifiedFilled = filled.cloneAndApplyTransformation(std::vector());\n\n\tEXPECT_EQ(modifiedFilled.getTransMatrix(false), notId);\n}\n\nTEST(RepoTransformationNodeTest, GetTransMatrixTest)\n{\n\tTransformationNode empty = TransformationNode();\n\tEXPECT_EQ(identity, empty.getTransMatrix(false));\n\n\tTransformationNode notEmpty = makeTransformationNode(notId);\n\tEXPECT_EQ(notId, notEmpty.getTransMatrix(false));\n\n\t\/\/check transpose is done correctly\n\tauto notIdTransposed = notEmpty.getTransMatrix(true);\n\n\tauto notIdTransData = notIdTransposed.getData();\n\tASSERT_EQ(notId.size(), notIdTransData.size());\n\tfor (int i = 0; i < 4; ++i)\n\t{\n\t\tfor (int j = 0; j < 4; ++j)\n\t\t{\n\t\t\tint index = i * 4 + j;\n\t\t\tint transIndex = j * 4 + i;\n\t\t\tEXPECT_EQ(notId[index], notIdTransData[transIndex]);\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"\/\/ $Id: Sentence.cpp 1465 2007-09-27 14:16:28Z hieuhoang1972 $\n\/\/ vim:tabstop=2\n\n\/***********************************************************************\n Moses - factored phrase-based language decoder\n Copyright (C) 2006 University of Edinburgh\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 \"XmlOption.h\"\n#include \n#include \n#include \n#include \"Util.h\"\n#include \"StaticData.h\"\n\nnamespace {\n\nstd::string ParseXmlTagAttribute(const std::string& tag,const std::string& attributeName){\n\t\/*TODO deal with unescaping \\\"*\/\n\tstring tagOpen = attributeName + \"=\\\"\";\n\tsize_t contentsStart = tag.find(tagOpen);\n\tif (contentsStart == std::string::npos) return \"\";\n\tcontentsStart += tagOpen.size();\n\tsize_t contentsEnd = tag.find_first_of('\"',contentsStart+1);\n\tif (contentsEnd == std::string::npos) {\n\t\tTRACE_ERR(\"Malformed XML attribute: \"<< tag);\n\t\treturn \"\";\t\n\t}\n\tsize_t possibleEnd;\n\twhile (tag.at(contentsEnd-1) == '\\\\' && (possibleEnd = tag.find_first_of('\"',contentsEnd+1)) != std::string::npos) {\n\t\tcontentsEnd = possibleEnd;\n\t}\n\treturn tag.substr(contentsStart,contentsEnd-contentsStart);\n}\n\nstd::string TrimXml(const std::string& str) {\n\tif (str.size() < 2) return str;\n\tif (str[0] == '<' && str[str.size() - 1] == '>') {\n\t\treturn str.substr(1, str.size() - 2);\n\t} else { return str; }\n}\n\nbool isXmlTag(const std::string& tag)\n{\n\treturn tag[0] == '<';\n}\n\ninline std::vector TokenizeXml(const std::string& str)\n{\n\tstd::string lbrack = \"<\";\n\tstd::string rbrack = \">\";\n\tstd::vector tokens;\n\t\/\/ Find first \"non-delimiter\".\n\tstd::string::size_type cpos = 0;\n\tstd::string::size_type lpos = 0;\n\tstd::string::size_type rpos = 0;\n\n\twhile (cpos != str.size()) {\n \tlpos = str.find_first_of(lbrack, cpos);\n\t\tif (lpos != std::string::npos) {\n\t\t\trpos = str.find_first_of(rbrack, lpos);\n\t\t\tif (rpos == std::string::npos) {\n\t\t\t\tTRACE_ERR(\"ERROR: malformed XML: \" << str << endl);\n\t\t\t\treturn tokens;\n\t\t\t}\n\t\t} else {\n\t\t\ttokens.push_back(str.substr(cpos));\n\t\t\tbreak;\n\t\t}\n\t\tif (lpos - cpos > 0)\n\t\t\ttokens.push_back(str.substr(cpos, lpos - cpos));\n\t\ttokens.push_back(str.substr(lpos, rpos-lpos+1));\n\t\tcpos = rpos + 1;\n\t}\n\treturn tokens;\n}\n\n}\n\nstd::vector ProcessAndStripXMLTags(std::string& line) {\n\t\/\/parse XML markup in translation line\n\tstd::vector res;\n\tstd::string rstr;\n\tif (line.find_first_of('<') == std::string::npos) { return res; }\n\tstd::vector xmlTokens = TokenizeXml(line);\n\tstd::string tagName = \"\";\n\tstd::string tagContents = \"\";\n\tstd::vector altTexts;\n\tstd::vector altProbs;\n\tsize_t tagStart=0;\n\tsize_t tagEnd=0;\n\tsize_t curWord=0;\n\tint numUnary = 0;\n\tbool doClose = false;\n\tfor (size_t xmlTokenPos = 0 ; xmlTokenPos < xmlTokens.size() ; xmlTokenPos++)\n\t{\n\t\tif(!isXmlTag(xmlTokens[xmlTokenPos]))\n\t\t{\n\t\t\t\/\/phrase, not tag\n\t\t\trstr += xmlTokens[xmlTokenPos];\n\t\t\tcurWord = Tokenize(rstr).size();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/tag data\n\t\t\tstd::string tag = Trim(TrimXml(xmlTokens[xmlTokenPos]));\n\t\t\tVERBOSE(3,\"XML TAG IS: \" << tag << std::endl);\n\t\t\tstd::string::size_type endOfName = tag.find_first_of(' ');\n\t\t\tstd::string nextTagName = tag;\n\t\t\tbool isUnary = tag[tag.size() - 1] == '\/';\n\t\t\tbool isOpen = tag[1] != '\/';\n\t\t\tif (endOfName != std::string::npos) {\n\t\t\t\tnextTagName = tag.substr(0,endOfName);\n\t\t\t\ttagContents = tag.substr(endOfName+1);\n\t\t\t}\n\t\t\tif (isOpen)\n\t\t\t{\n\t\t\t\t\/\/this is an open tag\n\t\t\t\ttagName = nextTagName;\n\t\t\t\taltTexts = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,\"english\"), \"||\");\n\t\t\t\taltProbs = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,\"prob\"), \"||\");\n\t\t\t\tstd::string span = ParseXmlTagAttribute(tagContents,\"span\");\n\t\t\t\ttagStart = curWord;\n\t\t\t\tif (isUnary) {\n\t\t\t\t\tnumUnary++;\n\t\t\t\t\tif (span.empty()) {\n\t\t\t\t\t\tTRACE_ERR(\"ERROR: unary tags must have a span attribute: \" << line << endl);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tstd::vector ij = Tokenize(span, \",\");\n\t\t\t\t\tif (ij.size() != 2) {\n\t\t\t\t\t\tTRACE_ERR(\"ERROR: span tag must be of the form \\\"i,j\\\": \" << line << endl);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\ttagStart = atoi(ij[0].c_str());\n\t\t\t\t\ttagEnd = atoi(ij[1].c_str());\n\t\t\t\t\tif (tagEnd < tagStart) {\n\t\t\t\t\t\tTRACE_ERR(\"ERROR: span tag \" << span << \" invalid\" << endl);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tdoClose = true;\n\t\t\t\t\tVERBOSE(3,\"XML TAG IS UNARY\" << endl);\n\t\t\t\t}\n\t\t\t\tVERBOSE(3,\"XML TAG NAME IS: '\" << tagName << \"'\" << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG ENGLISH IS: '\" << altTexts[0] << \"'\" << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG PROB IS: '\" << altProbs[0] << \"'\" << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG STARTS AT WORD: \" << tagStart << endl);\t\t\t\t\t\n\t\t\t\tif (altTexts.size() != altProbs.size()) {\n\t\t\t\t\tTRACE_ERR(\"ERROR: Unequal number of probabilities and translation alternatives: \" << line << endl);\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ((nextTagName.size() == 0) || (nextTagName.at(0) != '\/') || (nextTagName.substr(1) != tagName)) \n\t\t\t{\n\t\t\t\t\/\/mismatched tag, abort!\n\t\t\t\tTRACE_ERR(\"ERROR: tried to parse malformed XML with xml-input enabled: \" << line << endl);\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdoClose = true;\n\t\t\t\ttagEnd = curWord-1; \/\/size is inclusive\n\t\t\t}\n\t\t\tif (doClose) {\n\t\t\t\tVERBOSE(3,\"XML END TAG IS: \" << nextTagName.substr(1) << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG ENDS AT WORD: \" << tagEnd << endl);\n\t\t\t\t\/\/store translation options into members\n\n\t\t\t\t\/\/TODO: deal with multiple XML options here\n\n\t\t\t\tif (StaticData::Instance().GetXmlInputType() != XmlIgnore) {\n\t\t\t\t\tfor (size_t i=0; i(altProbs[i]);\n\t\t\t\t\t\t\/\/Convert from prob to log-prob\n\t\t\t\t\t\tfloat scoreValue = FloorScore(TransformScore(probValue));\n\t\t\t\t\t\tXmlOption option(tagStart,tagEnd,altTexts[i],scoreValue);\n\t\t\t\t\t\tres.push_back(option);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttagName= \"\";\n\t\t\t\ttagContents = \"\";\n\t\t\t\taltTexts.clear();\n\t\t\t\taltProbs.clear();\n\t\t\t\tdoClose = false;\n\t\t\t}\n\t\t}\n\t}\n\tline = rstr;\n\treturn res;\n}\n\nfixed bug with XML markup\/\/ $Id: Sentence.cpp 1465 2007-09-27 14:16:28Z hieuhoang1972 $\n\/\/ vim:tabstop=2\n\n\/***********************************************************************\n Moses - factored phrase-based language decoder\n Copyright (C) 2006 University of Edinburgh\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 \"XmlOption.h\"\n#include \n#include \n#include \n#include \"Util.h\"\n#include \"StaticData.h\"\n\nnamespace {\n\nstd::string ParseXmlTagAttribute(const std::string& tag,const std::string& attributeName){\n\t\/*TODO deal with unescaping \\\"*\/\n\tstring tagOpen = attributeName + \"=\\\"\";\n\tsize_t contentsStart = tag.find(tagOpen);\n\tif (contentsStart == std::string::npos) return \"\";\n\tcontentsStart += tagOpen.size();\n\tsize_t contentsEnd = tag.find_first_of('\"',contentsStart+1);\n\tif (contentsEnd == std::string::npos) {\n\t\tTRACE_ERR(\"Malformed XML attribute: \"<< tag);\n\t\treturn \"\";\t\n\t}\n\tsize_t possibleEnd;\n\twhile (tag.at(contentsEnd-1) == '\\\\' && (possibleEnd = tag.find_first_of('\"',contentsEnd+1)) != std::string::npos) {\n\t\tcontentsEnd = possibleEnd;\n\t}\n\treturn tag.substr(contentsStart,contentsEnd-contentsStart);\n}\n\nstd::string TrimXml(const std::string& str) {\n\tif (str.size() < 2) return str;\n\tif (str[0] == '<' && str[str.size() - 1] == '>') {\n\t\treturn str.substr(1, str.size() - 2);\n\t} else { return str; }\n}\n\nbool isXmlTag(const std::string& tag)\n{\n\treturn tag[0] == '<';\n}\n\ninline std::vector TokenizeXml(const std::string& str)\n{\n\tstd::string lbrack = \"<\";\n\tstd::string rbrack = \">\";\n\tstd::vector tokens;\n\t\/\/ Find first \"non-delimiter\".\n\tstd::string::size_type cpos = 0;\n\tstd::string::size_type lpos = 0;\n\tstd::string::size_type rpos = 0;\n\n\twhile (cpos != str.size()) {\n \tlpos = str.find_first_of(lbrack, cpos);\n\t\tif (lpos != std::string::npos) {\n\t\t\trpos = str.find_first_of(rbrack, lpos);\n\t\t\tif (rpos == std::string::npos) {\n\t\t\t\tTRACE_ERR(\"ERROR: malformed XML: \" << str << endl);\n\t\t\t\treturn tokens;\n\t\t\t}\n\t\t} else {\n\t\t\ttokens.push_back(str.substr(cpos));\n\t\t\tbreak;\n\t\t}\n\t\tif (lpos - cpos > 0)\n\t\t\ttokens.push_back(str.substr(cpos, lpos - cpos));\n\t\ttokens.push_back(str.substr(lpos, rpos-lpos+1));\n\t\tcpos = rpos + 1;\n\t}\n\treturn tokens;\n}\n\n}\n\nstd::vector ProcessAndStripXMLTags(std::string& line) {\n\t\/\/parse XML markup in translation line\n\tstd::vector res;\n\tstd::string rstr;\n\tif (line.find_first_of('<') == std::string::npos) { return res; }\n\tstd::vector xmlTokens = TokenizeXml(line);\n\tstd::string tagName = \"\";\n\tstd::string tagContents = \"\";\n\tstd::vector altTexts;\n\tstd::vector altProbs;\n\tsize_t tagStart=0;\n\tsize_t tagEnd=0;\n\tsize_t curWord=0;\n\tint numUnary = 0;\n\tbool doClose = false;\n\tfor (size_t xmlTokenPos = 0 ; xmlTokenPos < xmlTokens.size() ; xmlTokenPos++)\n\t{\n\t\tif(!isXmlTag(xmlTokens[xmlTokenPos]))\n\t\t{\n\t\t\t\/\/phrase, not tag\n\t\t\trstr += xmlTokens[xmlTokenPos];\n\t\t\tcurWord = Tokenize(rstr).size();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/tag data\n\t\t\tstd::string tag = Trim(TrimXml(xmlTokens[xmlTokenPos]));\n\t\t\tVERBOSE(3,\"XML TAG IS: \" << tag << std::endl);\n\t\t\tstd::string::size_type endOfName = tag.find_first_of(' ');\n\t\t\tstd::string nextTagName = tag;\n\t\t\tbool isUnary = tag[tag.size() - 1] == '\/';\n\t\t\tbool isOpen = tag[0] != '\/';\n\t\t\tif (endOfName != std::string::npos) {\n\t\t\t\tnextTagName = tag.substr(0,endOfName);\n\t\t\t\ttagContents = tag.substr(endOfName+1);\n\t\t\t}\n\t\t\tif (isOpen)\n\t\t\t{\n\t\t\t\t\/\/this is an open tag\n\t\t\t\ttagName = nextTagName;\n\t\t\t\taltTexts = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,\"english\"), \"||\");\n\t\t\t\taltProbs = TokenizeMultiCharSeparator(ParseXmlTagAttribute(tagContents,\"prob\"), \"||\");\n\t\t\t\tstd::string span = ParseXmlTagAttribute(tagContents,\"span\");\n\t\t\t\ttagStart = curWord;\n\t\t\t\tif (isUnary) {\n\t\t\t\t\tnumUnary++;\n\t\t\t\t\tif (span.empty()) {\n\t\t\t\t\t\tTRACE_ERR(\"ERROR: unary tags must have a span attribute: \" << line << endl);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tstd::vector ij = Tokenize(span, \",\");\n\t\t\t\t\tif (ij.size() != 2) {\n\t\t\t\t\t\tTRACE_ERR(\"ERROR: span tag must be of the form \\\"i,j\\\": \" << line << endl);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\ttagStart = atoi(ij[0].c_str());\n\t\t\t\t\ttagEnd = atoi(ij[1].c_str());\n\t\t\t\t\tif (tagEnd < tagStart) {\n\t\t\t\t\t\tTRACE_ERR(\"ERROR: span tag \" << span << \" invalid\" << endl);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tdoClose = true;\n\t\t\t\t\tVERBOSE(3,\"XML TAG IS UNARY\" << endl);\n\t\t\t\t}\n\t\t\t\tVERBOSE(3,\"XML TAG NAME IS: '\" << tagName << \"'\" << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG ENGLISH IS: '\" << altTexts[0] << \"'\" << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG PROB IS: '\" << altProbs[0] << \"'\" << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG STARTS AT WORD: \" << tagStart << endl);\t\t\t\t\t\n\t\t\t\tif (altTexts.size() != altProbs.size()) {\n\t\t\t\t\tTRACE_ERR(\"ERROR: Unequal number of probabilities and translation alternatives: \" << line << endl);\n\t\t\t\t\treturn res;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ((nextTagName.size() == 0) || (nextTagName.at(0) != '\/') || (nextTagName.substr(1) != tagName)) \n\t\t\t{\n\t\t\t\t\/\/mismatched tag, abort!\n\t\t\t\tTRACE_ERR(\"ERROR: tried to parse malformed XML with xml-input enabled: \" << line << endl);\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdoClose = true;\n\t\t\t\ttagEnd = curWord-1; \/\/size is inclusive\n\t\t\t}\n\t\t\tif (doClose) {\n\t\t\t\tVERBOSE(3,\"XML END TAG IS: \" << nextTagName.substr(1) << endl);\n\t\t\t\tVERBOSE(3,\"XML TAG ENDS AT WORD: \" << tagEnd << endl);\n\t\t\t\t\/\/store translation options into members\n\n\t\t\t\t\/\/TODO: deal with multiple XML options here\n\n\t\t\t\tif (StaticData::Instance().GetXmlInputType() != XmlIgnore) {\n\t\t\t\t\tfor (size_t i=0; i(altProbs[i]);\n\t\t\t\t\t\t\/\/Convert from prob to log-prob\n\t\t\t\t\t\tfloat scoreValue = FloorScore(TransformScore(probValue));\n\t\t\t\t\t\tXmlOption option(tagStart,tagEnd,altTexts[i],scoreValue);\n\t\t\t\t\t\tres.push_back(option);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttagName= \"\";\n\t\t\t\ttagContents = \"\";\n\t\t\t\taltTexts.clear();\n\t\t\t\taltProbs.clear();\n\t\t\t\tdoClose = false;\n\t\t\t}\n\t\t}\n\t}\n\tline = rstr;\n\treturn res;\n}\n\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/lib\/stdio.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* COPYRIGHT International Business Machines Corp. 2011,2014 *\/\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#include \n#include \n#include \n\nclass SprintfBuffer : public Util::ConsoleBufferInterface\n{\n public:\n int putc(int c)\n {\n if ('\\b' == c)\n {\n iv_pos--;\n }\n else if (iv_pos < iv_size)\n {\n iv_buffer[iv_pos++] = c;\n }\n else\n {\n iv_pos++;\n }\n return c;\n }\n\n explicit SprintfBuffer(char* buf, size_t size = UINT64_MAX) :\n iv_pos(0), iv_size(size), iv_buffer(buf) {};\n\n size_t operator()(int c) { return putc(c); }\n\n private:\n size_t iv_pos;\n size_t iv_size;\n char * iv_buffer;\n};\n\nint sprintf(char *str, const char * format, ...)\n{\n using Util::vasprintf;\n\n va_list args;\n va_start(args, format);\n\n SprintfBuffer console(str);\n size_t count = vasprintf(console, format, args);\n\n va_end(args);\n console.putc('\\0');\n return count;\n}\n\nint snprintf(char *str, size_t size, const char * format, ...)\n{\n using Util::vasprintf;\n\n va_list args;\n va_start(args, format);\n\n SprintfBuffer console(str, size);\n size_t count = vasprintf(console, format, args);\n\n va_end(args);\n console.putc('\\0');\n return count;\n}\n\nint vsprintf(char *str, const char * format, va_list args)\n{\n using Util::vasprintf;\n\n SprintfBuffer console(str);\n size_t count = vasprintf(console, format, args);\n\n console.putc('\\0');\n return count;\n}\n\nint vsnprintf(char *str, size_t size, const char * format, va_list args)\n{\n SprintfBuffer console(str, size);\n size_t count = vasprintf(console, format, args);\n\n console.putc('\\0');\n return count;\n}\nMake snprintf always terminate the output buffer\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/lib\/stdio.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2011,2019 *\/\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#include \n#include \n#include \n\nclass SprintfBuffer : public Util::ConsoleBufferInterface\n{\n public:\n int putc(int c)\n {\n if ('\\b' == c)\n {\n if (iv_pos > 0)\n {\n iv_pos--;\n }\n }\n else if (iv_pos < iv_size)\n {\n iv_buffer[iv_pos++] = c;\n }\n else\n {\n iv_pos++;\n }\n return c;\n }\n\n void nullTerminate()\n {\n if (iv_size > 0)\n {\n if (iv_pos >= iv_size)\n {\n iv_pos = iv_size - 1;\n }\n\n putc('\\0');\n }\n }\n\n explicit SprintfBuffer(char* buf, size_t size = UINT64_MAX) :\n iv_pos(0), iv_size(size), iv_buffer(buf) {};\n\n size_t operator()(int c) { return putc(c); }\n\n private:\n size_t iv_pos;\n size_t iv_size;\n char * iv_buffer;\n};\n\nint sprintf(char *str, const char * format, ...)\n{\n using Util::vasprintf;\n\n va_list args;\n va_start(args, format);\n\n SprintfBuffer console(str);\n size_t count = vasprintf(console, format, args);\n\n va_end(args);\n console.nullTerminate();\n return count;\n}\n\nint snprintf(char *str, size_t size, const char * format, ...)\n{\n using Util::vasprintf;\n\n va_list args;\n va_start(args, format);\n\n SprintfBuffer console(str, size);\n size_t count = vasprintf(console, format, args);\n\n va_end(args);\n console.nullTerminate();\n return count;\n}\n\nint vsprintf(char *str, const char * format, va_list args)\n{\n using Util::vasprintf;\n\n SprintfBuffer console(str);\n size_t count = vasprintf(console, format, args);\n\n console.nullTerminate();\n return count;\n}\n\nint vsnprintf(char *str, size_t size, const char * format, va_list args)\n{\n SprintfBuffer console(str, size);\n size_t count = vasprintf(console, format, args);\n\n console.nullTerminate();\n return count;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"platform\/globals.h\"\n#if defined(DART_HOST_OS_MACOS)\n\n#include \"bin\/platform.h\"\n#include \"bin\/platform_macos.h\"\n\n#include \n\n#if !DART_HOST_OS_IOS\n#include \/\/ NOLINT\n#endif \/\/ !DART_HOST_OS_IOS\n#include \/\/ NOLINT\n#include \n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n\n#include \n\n#include \"bin\/console.h\"\n#include \"bin\/file.h\"\n#include \"bin\/platform_macos_cocoa.h\"\n\nnamespace dart {\nnamespace bin {\n\nconst char* Platform::executable_name_ = NULL;\nint Platform::script_index_ = 1;\nchar** Platform::argv_ = NULL;\n\nstatic void segv_handler(int signal, siginfo_t* siginfo, void* context) {\n Syslog::PrintErr(\n \"\\n===== CRASH =====\\n\"\n \"si_signo=%s(%d), si_code=%d, si_addr=%p\\n\",\n strsignal(siginfo->si_signo), siginfo->si_signo, siginfo->si_code,\n siginfo->si_addr);\n Dart_DumpNativeStackTrace(context);\n Dart_PrepareToAbort();\n abort();\n}\n\nbool Platform::Initialize() {\n \/\/ Turn off the signal handler for SIGPIPE as it causes the process\n \/\/ to terminate on writing to a closed pipe. Without the signal\n \/\/ handler error EPIPE is set instead.\n struct sigaction act = {};\n act.sa_handler = SIG_IGN;\n if (sigaction(SIGPIPE, &act, 0) != 0) {\n perror(\"Setting signal handler failed\");\n return false;\n }\n\n \/\/ tcsetattr raises SIGTTOU if we try to set console attributes when\n \/\/ backgrounded, which suspends the process. Ignoring the signal prevents\n \/\/ us from being suspended and lets us fail gracefully instead.\n sigset_t signal_mask;\n sigemptyset(&signal_mask);\n sigaddset(&signal_mask, SIGTTOU);\n if (sigprocmask(SIG_BLOCK, &signal_mask, NULL) < 0) {\n perror(\"Setting signal handler failed\");\n return false;\n }\n\n act.sa_flags = SA_SIGINFO;\n act.sa_sigaction = &segv_handler;\n if (sigemptyset(&act.sa_mask) != 0) {\n perror(\"sigemptyset() failed.\");\n return false;\n }\n if (sigaddset(&act.sa_mask, SIGPROF) != 0) {\n perror(\"sigaddset() failed\");\n return false;\n }\n if (sigaction(SIGSEGV, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n if (sigaction(SIGBUS, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n if (sigaction(SIGTRAP, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n if (sigaction(SIGILL, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n return true;\n}\n\nint Platform::NumberOfProcessors() {\n int32_t cpus = -1;\n size_t cpus_length = sizeof(cpus);\n if (sysctlbyname(\"hw.logicalcpu\", &cpus, &cpus_length, NULL, 0) == 0) {\n return cpus;\n } else {\n \/\/ Failed, fallback to using sysconf.\n return sysconf(_SC_NPROCESSORS_ONLN);\n }\n}\n\nconst char* Platform::OperatingSystem() {\n#if DART_HOST_OS_IOS\n return \"ios\";\n#else\n return \"macos\";\n#endif\n}\n\nconst char* Platform::OperatingSystemVersion() {\n std::string version(NSProcessInfoOperatingSystemVersionString());\n return DartUtils::ScopedCopyCString(version.c_str());\n}\n\nconst char* Platform::LibraryPrefix() {\n return \"lib\";\n}\n\nconst char* Platform::LibraryExtension() {\n return \"dylib\";\n}\n\nstatic const char* GetLocaleName() {\n CFLocaleRef locale = CFLocaleCopyCurrent();\n CFStringRef locale_string = CFLocaleGetIdentifier(locale);\n CFIndex len = CFStringGetLength(locale_string);\n CFIndex max_len =\n CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;\n char* result = reinterpret_cast(Dart_ScopeAllocate(max_len));\n ASSERT(result != NULL);\n bool success =\n CFStringGetCString(locale_string, result, max_len, kCFStringEncodingUTF8);\n CFRelease(locale);\n if (!success) {\n return NULL;\n }\n return result;\n}\n\nstatic const char* GetPreferredLanguageName() {\n CFArrayRef languages = CFLocaleCopyPreferredLanguages();\n CFIndex languages_length = CFArrayGetCount(languages);\n if (languages_length < 1) {\n CFRelease(languages);\n return NULL;\n }\n CFTypeRef item =\n reinterpret_cast(CFArrayGetValueAtIndex(languages, 0));\n CFTypeID item_type = CFGetTypeID(item);\n ASSERT(item_type == CFStringGetTypeID());\n CFStringRef language = reinterpret_cast(item);\n CFIndex len = CFStringGetLength(language);\n CFIndex max_len =\n CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;\n char* result = reinterpret_cast(Dart_ScopeAllocate(max_len));\n ASSERT(result != NULL);\n bool success =\n CFStringGetCString(language, result, max_len, kCFStringEncodingUTF8);\n CFRelease(languages);\n if (!success) {\n return NULL;\n }\n return result;\n}\n\nconst char* Platform::LocaleName() {\n \/\/ First see if there is a preferred language. If not, return the\n \/\/ current locale name.\n const char* preferred_language = GetPreferredLanguageName();\n return (preferred_language != NULL) ? preferred_language : GetLocaleName();\n}\n\nbool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {\n return gethostname(buffer, buffer_length) == 0;\n}\n\nchar** Platform::Environment(intptr_t* count) {\n#if DART_HOST_OS_IOS\n \/\/ TODO(zra,chinmaygarde): On iOS, environment variables are seldom used. Wire\n \/\/ this up if someone needs it. In the meantime, we return an empty array.\n char** result;\n result = reinterpret_cast(Dart_ScopeAllocate(1 * sizeof(*result)));\n if (result == NULL) {\n return NULL;\n }\n result[0] = NULL;\n *count = 0;\n return result;\n#else\n \/\/ Using environ directly is only safe as long as we do not\n \/\/ provide access to modifying environment variables.\n \/\/ On MacOS you have to do a bit of magic to get to the\n \/\/ environment strings.\n char** environ = *(_NSGetEnviron());\n intptr_t i = 0;\n char** tmp = environ;\n while (*(tmp++) != NULL) {\n i++;\n }\n *count = i;\n char** result;\n result = reinterpret_cast(Dart_ScopeAllocate(i * sizeof(*result)));\n for (intptr_t current = 0; current < i; current++) {\n result[current] = environ[current];\n }\n return result;\n#endif\n}\n\nconst char* Platform::GetExecutableName() {\n return executable_name_;\n}\n\nconst char* Platform::ResolveExecutablePath() {\n \/\/ Get the required length of the buffer.\n uint32_t path_size = 0;\n if (_NSGetExecutablePath(NULL, &path_size) == 0) {\n return NULL;\n }\n \/\/ Allocate buffer and get executable path.\n char* path = DartUtils::ScopedCString(path_size);\n if (_NSGetExecutablePath(path, &path_size) != 0) {\n return NULL;\n }\n \/\/ Return the canonical path as the returned path might contain symlinks.\n const char* canon_path = File::GetCanonicalPath(NULL, path);\n return canon_path;\n}\n\nintptr_t Platform::ResolveExecutablePathInto(char* result, size_t result_size) {\n \/\/ Get the required length of the buffer.\n uint32_t path_size = 0;\n if (_NSGetExecutablePath(nullptr, &path_size) == 0) {\n return -1;\n }\n if (path_size > result_size) {\n return -1;\n }\n if (_NSGetExecutablePath(result, &path_size) != 0) {\n return -1;\n }\n return path_size;\n}\n\nvoid Platform::SetProcessName(const char* name) {}\n\nvoid Platform::Exit(int exit_code) {\n Console::RestoreConfig();\n Dart_PrepareToAbort();\n exit(exit_code);\n}\n\nvoid Platform::SetCoreDumpResourceLimit(int value) {\n rlimit limit = {static_cast(value), static_cast(value)};\n setrlimit(RLIMIT_CORE, &limit);\n}\n\n} \/\/ namespace bin\n} \/\/ namespace dart\n\n#endif \/\/ defined(DART_HOST_OS_MACOS)\n[standalone, mac] Set the process title based on the main script.\/\/ Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"platform\/globals.h\"\n#if defined(DART_HOST_OS_MACOS)\n\n#include \"bin\/platform.h\"\n#include \"bin\/platform_macos.h\"\n\n#include \n\n#if !DART_HOST_OS_IOS\n#include \/\/ NOLINT\n#endif \/\/ !DART_HOST_OS_IOS\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n#include \/\/ NOLINT\n\n#include \n\n#include \"bin\/console.h\"\n#include \"bin\/file.h\"\n#include \"bin\/platform_macos_cocoa.h\"\n\nnamespace dart {\nnamespace bin {\n\nconst char* Platform::executable_name_ = NULL;\nint Platform::script_index_ = 1;\nchar** Platform::argv_ = NULL;\n\nstatic void segv_handler(int signal, siginfo_t* siginfo, void* context) {\n Syslog::PrintErr(\n \"\\n===== CRASH =====\\n\"\n \"si_signo=%s(%d), si_code=%d, si_addr=%p\\n\",\n strsignal(siginfo->si_signo), siginfo->si_signo, siginfo->si_code,\n siginfo->si_addr);\n Dart_DumpNativeStackTrace(context);\n Dart_PrepareToAbort();\n abort();\n}\n\nbool Platform::Initialize() {\n \/\/ Turn off the signal handler for SIGPIPE as it causes the process\n \/\/ to terminate on writing to a closed pipe. Without the signal\n \/\/ handler error EPIPE is set instead.\n struct sigaction act = {};\n act.sa_handler = SIG_IGN;\n if (sigaction(SIGPIPE, &act, 0) != 0) {\n perror(\"Setting signal handler failed\");\n return false;\n }\n\n \/\/ tcsetattr raises SIGTTOU if we try to set console attributes when\n \/\/ backgrounded, which suspends the process. Ignoring the signal prevents\n \/\/ us from being suspended and lets us fail gracefully instead.\n sigset_t signal_mask;\n sigemptyset(&signal_mask);\n sigaddset(&signal_mask, SIGTTOU);\n if (sigprocmask(SIG_BLOCK, &signal_mask, NULL) < 0) {\n perror(\"Setting signal handler failed\");\n return false;\n }\n\n act.sa_flags = SA_SIGINFO;\n act.sa_sigaction = &segv_handler;\n if (sigemptyset(&act.sa_mask) != 0) {\n perror(\"sigemptyset() failed.\");\n return false;\n }\n if (sigaddset(&act.sa_mask, SIGPROF) != 0) {\n perror(\"sigaddset() failed\");\n return false;\n }\n if (sigaction(SIGSEGV, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n if (sigaction(SIGBUS, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n if (sigaction(SIGTRAP, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n if (sigaction(SIGILL, &act, NULL) != 0) {\n perror(\"sigaction() failed.\");\n return false;\n }\n return true;\n}\n\nint Platform::NumberOfProcessors() {\n int32_t cpus = -1;\n size_t cpus_length = sizeof(cpus);\n if (sysctlbyname(\"hw.logicalcpu\", &cpus, &cpus_length, NULL, 0) == 0) {\n return cpus;\n } else {\n \/\/ Failed, fallback to using sysconf.\n return sysconf(_SC_NPROCESSORS_ONLN);\n }\n}\n\nconst char* Platform::OperatingSystem() {\n#if DART_HOST_OS_IOS\n return \"ios\";\n#else\n return \"macos\";\n#endif\n}\n\nconst char* Platform::OperatingSystemVersion() {\n std::string version(NSProcessInfoOperatingSystemVersionString());\n return DartUtils::ScopedCopyCString(version.c_str());\n}\n\nconst char* Platform::LibraryPrefix() {\n return \"lib\";\n}\n\nconst char* Platform::LibraryExtension() {\n return \"dylib\";\n}\n\nstatic const char* GetLocaleName() {\n CFLocaleRef locale = CFLocaleCopyCurrent();\n CFStringRef locale_string = CFLocaleGetIdentifier(locale);\n CFIndex len = CFStringGetLength(locale_string);\n CFIndex max_len =\n CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;\n char* result = reinterpret_cast(Dart_ScopeAllocate(max_len));\n ASSERT(result != NULL);\n bool success =\n CFStringGetCString(locale_string, result, max_len, kCFStringEncodingUTF8);\n CFRelease(locale);\n if (!success) {\n return NULL;\n }\n return result;\n}\n\nstatic const char* GetPreferredLanguageName() {\n CFArrayRef languages = CFLocaleCopyPreferredLanguages();\n CFIndex languages_length = CFArrayGetCount(languages);\n if (languages_length < 1) {\n CFRelease(languages);\n return NULL;\n }\n CFTypeRef item =\n reinterpret_cast(CFArrayGetValueAtIndex(languages, 0));\n CFTypeID item_type = CFGetTypeID(item);\n ASSERT(item_type == CFStringGetTypeID());\n CFStringRef language = reinterpret_cast(item);\n CFIndex len = CFStringGetLength(language);\n CFIndex max_len =\n CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;\n char* result = reinterpret_cast(Dart_ScopeAllocate(max_len));\n ASSERT(result != NULL);\n bool success =\n CFStringGetCString(language, result, max_len, kCFStringEncodingUTF8);\n CFRelease(languages);\n if (!success) {\n return NULL;\n }\n return result;\n}\n\nconst char* Platform::LocaleName() {\n \/\/ First see if there is a preferred language. If not, return the\n \/\/ current locale name.\n const char* preferred_language = GetPreferredLanguageName();\n return (preferred_language != NULL) ? preferred_language : GetLocaleName();\n}\n\nbool Platform::LocalHostname(char* buffer, intptr_t buffer_length) {\n return gethostname(buffer, buffer_length) == 0;\n}\n\nchar** Platform::Environment(intptr_t* count) {\n#if DART_HOST_OS_IOS\n \/\/ TODO(zra,chinmaygarde): On iOS, environment variables are seldom used. Wire\n \/\/ this up if someone needs it. In the meantime, we return an empty array.\n char** result;\n result = reinterpret_cast(Dart_ScopeAllocate(1 * sizeof(*result)));\n if (result == NULL) {\n return NULL;\n }\n result[0] = NULL;\n *count = 0;\n return result;\n#else\n \/\/ Using environ directly is only safe as long as we do not\n \/\/ provide access to modifying environment variables.\n \/\/ On MacOS you have to do a bit of magic to get to the\n \/\/ environment strings.\n char** environ = *(_NSGetEnviron());\n intptr_t i = 0;\n char** tmp = environ;\n while (*(tmp++) != NULL) {\n i++;\n }\n *count = i;\n char** result;\n result = reinterpret_cast(Dart_ScopeAllocate(i * sizeof(*result)));\n for (intptr_t current = 0; current < i; current++) {\n result[current] = environ[current];\n }\n return result;\n#endif\n}\n\nconst char* Platform::GetExecutableName() {\n return executable_name_;\n}\n\nconst char* Platform::ResolveExecutablePath() {\n \/\/ Get the required length of the buffer.\n uint32_t path_size = 0;\n if (_NSGetExecutablePath(NULL, &path_size) == 0) {\n return NULL;\n }\n \/\/ Allocate buffer and get executable path.\n char* path = DartUtils::ScopedCString(path_size);\n if (_NSGetExecutablePath(path, &path_size) != 0) {\n return NULL;\n }\n \/\/ Return the canonical path as the returned path might contain symlinks.\n const char* canon_path = File::GetCanonicalPath(NULL, path);\n return canon_path;\n}\n\nintptr_t Platform::ResolveExecutablePathInto(char* result, size_t result_size) {\n \/\/ Get the required length of the buffer.\n uint32_t path_size = 0;\n if (_NSGetExecutablePath(nullptr, &path_size) == 0) {\n return -1;\n }\n if (path_size > result_size) {\n return -1;\n }\n if (_NSGetExecutablePath(result, &path_size) != 0) {\n return -1;\n }\n return path_size;\n}\n\nvoid Platform::SetProcessName(const char* name) {\n pthread_setname_np(name);\n\n#if !defined(DART_HOST_OS_IOS) && !defined(DART_PRECOMPILED_RUNTIME)\n \/\/ Attempt to set the name displayed in ActivityMonitor.\n \/\/ https:\/\/codereview.chromium.org\/659007\/\n\n class ScopedDLHandle : public ValueObject {\n public:\n explicit ScopedDLHandle(void* handle) : handle_(handle) {}\n ~ScopedDLHandle() {\n if (handle_ != NULL) dlclose(handle_);\n }\n void* get() const { return handle_; }\n\n private:\n void* handle_;\n DISALLOW_COPY_AND_ASSIGN(ScopedDLHandle);\n };\n\n class ScopedCFStringRef : public ValueObject {\n public:\n explicit ScopedCFStringRef(const char* s)\n : ref_(CFStringCreateWithCString(NULL, (s), kCFStringEncodingUTF8)) {}\n ~ScopedCFStringRef() {\n if (ref_ != NULL) CFRelease(ref_);\n }\n CFStringRef get() const { return ref_; }\n\n private:\n CFStringRef ref_;\n DISALLOW_COPY_AND_ASSIGN(ScopedCFStringRef);\n };\n\n ScopedDLHandle application_services_handle(\n dlopen(\"\/System\/Library\/Frameworks\/ApplicationServices.framework\/\"\n \"Versions\/A\/ApplicationServices\",\n RTLD_LAZY | RTLD_LOCAL));\n if (application_services_handle.get() == NULL) return;\n\n ScopedCFStringRef launch_services_bundle_name(\"com.apple.LaunchServices\");\n CFBundleRef launch_services_bundle =\n CFBundleGetBundleWithIdentifier(launch_services_bundle_name.get());\n if (launch_services_bundle == NULL) return;\n\n#define GET_FUNC(name, cstr) \\\n ScopedCFStringRef name##_id(cstr); \\\n *reinterpret_cast(&name) = CFBundleGetFunctionPointerForName( \\\n launch_services_bundle, name##_id.get()); \\\n if (name == NULL) return;\n\n#define GET_DATA(name, cstr) \\\n ScopedCFStringRef name##_id(cstr); \\\n *reinterpret_cast(&name) = \\\n CFBundleGetDataPointerForName(launch_services_bundle, name##_id.get()); \\\n if (name == NULL) return;\n\n CFTypeRef (*_LSGetCurrentApplicationASN)(void);\n GET_FUNC(_LSGetCurrentApplicationASN, \"_LSGetCurrentApplicationASN\");\n\n OSStatus (*_LSSetApplicationInformationItem)(int, CFTypeRef, CFStringRef,\n CFStringRef, CFDictionaryRef*);\n GET_FUNC(_LSSetApplicationInformationItem,\n \"_LSSetApplicationInformationItem\");\n\n CFDictionaryRef (*_LSApplicationCheckIn)(int, CFDictionaryRef);\n GET_FUNC(_LSApplicationCheckIn, \"_LSApplicationCheckIn\");\n\n void (*_LSSetApplicationLaunchServicesServerConnectionStatus)(uint64_t,\n void*);\n GET_FUNC(_LSSetApplicationLaunchServicesServerConnectionStatus,\n \"_LSSetApplicationLaunchServicesServerConnectionStatus\");\n\n CFStringRef* _kLSDisplayNameKey;\n GET_DATA(_kLSDisplayNameKey, \"_kLSDisplayNameKey\");\n if (*_kLSDisplayNameKey == NULL) return;\n\n _LSSetApplicationLaunchServicesServerConnectionStatus(0, NULL);\n\n _LSApplicationCheckIn(-2, CFBundleGetInfoDictionary(CFBundleGetMainBundle()));\n\n CFTypeRef asn;\n asn = _LSGetCurrentApplicationASN();\n if (asn == NULL) return;\n\n ScopedCFStringRef cf_name(name);\n _LSSetApplicationInformationItem(-2, asn, *_kLSDisplayNameKey, cf_name.get(),\n NULL);\n#undef GET_DATA\n#undef GET_FUNC\n#endif \/\/ !defined(DART_HOST_OS_IOS)\n}\n\nvoid Platform::Exit(int exit_code) {\n Console::RestoreConfig();\n Dart_PrepareToAbort();\n exit(exit_code);\n}\n\nvoid Platform::SetCoreDumpResourceLimit(int value) {\n rlimit limit = {static_cast(value), static_cast(value)};\n setrlimit(RLIMIT_CORE, &limit);\n}\n\n} \/\/ namespace bin\n} \/\/ namespace dart\n\n#endif \/\/ defined(DART_HOST_OS_MACOS)\n<|endoftext|>"} {"text":"\n\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 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\/\/$Id$\n\n#ifndef RASTER_COLORIZER_HPP\n#define RASTER_COLORIZER_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing mapnik::color;\nusing std::vector;\n\nnamespace mapnik\n{\n struct MAPNIK_DECL color_band\n {\n float value_;\n color color_;\n unsigned midpoints_;\n bool is_interpolated_;\n color_band(float value, color c)\n : value_(value),\n color_(c),\n midpoints_(0),\n is_interpolated_(false) {}\n const bool is_interpolated() const\n {\n return is_interpolated_;\n }\n const unsigned get_midpoints() const\n {\n return midpoints_;\n }\n const float get_value() const\n {\n return value_;\n }\n const color& get_color() const\n {\n return color_;\n }\n bool operator==(color_band const& other) const\n {\n return value_ == other.value_ && color_ == other.color_;\n }\n std::string to_string() const\n {\n std::stringstream ss;\n ss << color_.to_string() << \" \" << value_;\n return ss.str();\n }\n };\n\n typedef vector color_bands;\n\n struct MAPNIK_DECL raster_colorizer\n {\n explicit raster_colorizer()\n : colors_() {}\n\n raster_colorizer(const raster_colorizer &ps)\n : colors_(ps.colors_) {}\n\n raster_colorizer(color_bands &colors)\n : colors_(colors) {}\n\n const color_bands& get_color_bands() const\n {\n return colors_;\n }\n void append_band (color_band band)\n {\n if (colors_.size() > 0 && colors_.back().value_ > band.value_) {\n#ifdef MAPNIK_DEBUG\n std::clog << \"prev.v=\" << colors_.back().value_ << \". band.v=\" << band.value_ << \"\\n\";\n#endif\n throw config_error(\n \"Bands must be appended in ascending value order\"\n );\n }\n colors_.push_back(band);\n }\n void append_band (color_band band, unsigned midpoints)\n {\n band.midpoints_ = midpoints;\n if (colors_.size() > 0 && midpoints > 0) {\n color_band lo = colors_.back();\n color_band const &hi = band;\n int steps = midpoints+1;\n float dv = (hi.value_ - lo.value_)\/steps;\n float da = (float(hi.color_.alpha()) - lo.color_.alpha())\/steps;\n float dr = (float(hi.color_.red()) - lo.color_.red())\/steps;\n float dg = (float(hi.color_.green()) - lo.color_.green())\/steps;\n float db = (float(hi.color_.blue()) - lo.color_.blue())\/steps;\n\n#ifdef MAPNIK_DEBUG\n std::clog << \"lo.v=\" << lo.value_ << \", hi.v=\" << hi.value_ << \", dv=\"<value) {\n hi = pos-1;\n } else {\n lo = pos+1;\n break;\n }\n }\n lo--;\n if ((0 <= lo && lo < last) ||\n (lo==last && colors_[last].value_==value))\n return colors_[lo].color_;\n else\n return color(0,0,0,0);\n }\n\n void colorize(mapnik::raster_ptr const& raster) const {\n float *rasterData = (float*)raster->data_.getBytes();\n unsigned *imageData = raster->data_.getData();\n unsigned i;\n for (i=0; idata_.width()*raster->data_.height(); i++)\n imageData[i] = get_color(rasterData[i]).rgba();\n }\n \n private:\n color_bands colors_;\n };\n\n typedef boost::shared_ptr raster_colorizer_ptr;\n}\n\n#endif \/\/RASTER_COLORIZER_HPP\n+ remove mapnik:: classification from inside namespace mapnik {} + use c++ style casts!\n\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 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\/\/$Id$\n\n#ifndef RASTER_COLORIZER_HPP\n#define RASTER_COLORIZER_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace mapnik\n{\nstruct MAPNIK_DECL color_band\n{\n float value_;\n color color_;\n unsigned midpoints_;\n bool is_interpolated_;\n color_band(float value, color c)\n\t: value_(value),\n\tcolor_(c),\n\tmidpoints_(0),\n\tis_interpolated_(false) {}\n const bool is_interpolated() const\n {\n\treturn is_interpolated_;\n }\n const unsigned get_midpoints() const\n {\n\treturn midpoints_;\n }\n const float get_value() const\n {\n\treturn value_;\n }\n const color& get_color() const\n {\n\treturn color_;\n }\n bool operator==(color_band const& other) const\n {\n\treturn value_ == other.value_ && color_ == other.color_;\n }\n std::string to_string() const\n {\n\tstd::stringstream ss;\n\tss << color_.to_string() << \" \" << value_;\n\treturn ss.str();\n }\n};\n\ntypedef std::vector color_bands;\n\nstruct MAPNIK_DECL raster_colorizer\n{\n explicit raster_colorizer()\n\t: colors_() {}\n\n raster_colorizer(const raster_colorizer &ps)\n\t: colors_(ps.colors_) {}\n\n raster_colorizer(color_bands &colors)\n\t: colors_(colors) {}\n\n const color_bands& get_color_bands() const\n {\n\treturn colors_;\n }\n void append_band (color_band band)\n {\n\tif (colors_.size() > 0 && colors_.back().value_ > band.value_) {\n#ifdef MAPNIK_DEBUG\n\t std::clog << \"prev.v=\" << colors_.back().value_ << \". band.v=\" << band.value_ << \"\\n\";\n#endif\n\t throw config_error(\n\t\t\"Bands must be appended in ascending value order\"\n\t\t);\n\t}\n\tcolors_.push_back(band);\n }\n void append_band (color_band band, unsigned midpoints)\n {\n\tband.midpoints_ = midpoints;\n\tif (colors_.size() > 0 && midpoints > 0) {\n\t color_band lo = colors_.back();\n\t color_band const &hi = band;\n\t int steps = midpoints+1;\n\t float dv = (hi.value_ - lo.value_)\/steps;\n\t float da = (float(hi.color_.alpha()) - lo.color_.alpha())\/steps;\n\t float dr = (float(hi.color_.red()) - lo.color_.red())\/steps;\n\t float dg = (float(hi.color_.green()) - lo.color_.green())\/steps;\n\t float db = (float(hi.color_.blue()) - lo.color_.blue())\/steps;\n\n#ifdef MAPNIK_DEBUG\n\t std::clog << \"lo.v=\" << lo.value_ << \", hi.v=\" << hi.value_ << \", dv=\"<value) {\n\t\thi = pos-1;\n\t } else {\n\t\tlo = pos+1;\n\t\tbreak;\n\t }\n\t}\n\tlo--;\n\tif ((0 <= lo && lo < last) ||\n\t (lo==last && colors_[last].value_==value))\n\t return colors_[lo].color_;\n\telse\n\t return color(0,0,0,0);\n }\n\n void colorize(raster_ptr const& raster) const \n {\n\tfloat *rasterData = reinterpret_cast(raster->data_.getBytes());\n\tunsigned *imageData = raster->data_.getData();\n\tunsigned i;\n\tfor (i=0; idata_.width()*raster->data_.height(); i++)\n\t{\n\t imageData[i] = get_color(rasterData[i]).rgba();\n\t}\n }\n \nprivate:\n color_bands colors_;\n};\n\ntypedef boost::shared_ptr raster_colorizer_ptr;\n\n} \/\/ mapnik namespace\n\n#endif \/\/RASTER_COLORIZER_HPP\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \n\n#include \"nova_renderer\/rhi_enums.hpp\"\n\n#include \"device_memory_resource.hpp\"\n#include \"shaderpack_data.hpp\"\n\nnamespace nova::renderer::rhi {\n\n#pragma region Structs\n struct BufferCreateInfo {\n uint64_t size = 0;\n\n BufferUsage buffer_usage{};\n };\n\n struct DeviceMemory {};\n\n \/*!\n * \\brief A resource\n *\n * Resources may by dynamic of static. Dynamic resources are updated after they are created, possibly by a shader,\n * while static resources are loaded once and that's that\n *\/\n struct Resource {\n ResourceType type = {};\n bool is_dynamic = true;\n };\n\n struct Sampler {};\n\n struct Image : Resource {\n bool is_depth_tex = false;\n };\n\n struct Buffer : Resource {\n uint32_t size = 0;\n };\n\n struct Framebuffer {\n glm::uvec2 size;\n\n uint32_t num_attachments;\n };\n\n struct Renderpass {};\n\n struct ResourceBindingDescription {\n \/*!\n * \\brief Descriptor set that his binding belongs to\n *\/\n uint32_t set;\n\n \/*!\n * \\brief Binding of this resource binding\n *\/\n uint32_t binding;\n\n \/*!\n * \\brief Number of bindings. Useful if you have an array of descriptors\n *\n * If this is a unbounded array, this count is the upper limit on the size of the array\n *\/\n uint32_t count;\n\n \/*!\n * \\brief If true, this binding is an unbounded array\n *\n * Unbounded descriptors must be the final binding in their descriptor set\n *\/\n bool is_unbounded;\n\n \/*!\n * \\brief The type of object that will be bound\n *\/\n DescriptorType type;\n\n \/*!\n * \\brief The shader stages that need access to this binding\n *\/\n ShaderStageFlags stages;\n\n bool operator==(const ResourceBindingDescription& other);\n\n bool operator!=(const ResourceBindingDescription& other);\n };\n\n \/*!\n * \\brief The interface for a pipeline. Includes both inputs (descriptors) and outputs (framebuffers)\n *\/\n struct PipelineInterface {\n std::unordered_map bindings;\n };\n\n struct Pipeline {};\n\n struct Semaphore {};\n\n struct PresentSemaphore {};\n\n struct Fence {};\n\n struct DescriptorPool {};\n\n struct DescriptorSet {};\n\n \/\/ TODO: This struct actually maps pretty directly to a Vulkan barrier, so it doesn't map well to a D3D12 barrier. Figure out how to\n \/\/ make it D3D12-friendly\n struct ResourceBarrier {\n Resource* resource_to_barrier;\n\n \/*!\n * \\brief The resource access that much finish before this barrier executed\n *\/\n AccessFlags access_before_barrier;\n\n \/*!\n * \\brief The resource access that must wait for this battier to finish executing\n *\/\n AccessFlags access_after_barrier;\n\n \/*!\n * \\brief How you're going to access this resource just before this barrier\n *\n * Will a shader read from it before the barrier? Will the fragment depth by copied to a depth buffer before\n * this barrier? Will the resource be used as a indirect draw command buffer right before this barrier?\n *\/\n ResourceState old_state;\n\n \/*!\n * \\brief How you're going to access this resource after this barrier\n *\n * Will a shader read from it after the barrier? Will the fragment depth by copied to a depth buffer after\n * this barrier? Will the resource be used as a indirect draw command buffer right after this barrier?\n *\/\n ResourceState new_state;\n\n QueueType source_queue;\n QueueType destination_queue;\n\n union {\n struct {\n ImageAspectFlags aspect;\n } image_memory_barrier;\n\n struct {\n uint64_t offset;\n uint64_t size;\n } buffer_memory_barrier;\n };\n };\n\n struct DescriptorImageUpdate {\n const Image* image;\n shaderpack::TextureFormat format;\n Sampler* sampler;\n };\n\n struct DescriptorBufferWrite {\n const Buffer* buffer;\n };\n\n struct DescriptorSetWrite {\n \/*!\n * \\brief Pointer to the descriptor set to write to\n *\/\n DescriptorSet* set;\n\n \/*!\n * \\brief The specific binding in the set that you want to write to\n *\/\n uint32_t binding;\n\n \/*!\n * \\brief The type of descriptor you're writing to\n *\/\n DescriptorType type;\n\n union {\n \/*!\n * \\brief Information to update an image descriptor\n *\/\n DescriptorImageUpdate image_info;\n\n \/*!\n * \\brief Information to update a buffer descriptor\n *\/\n DescriptorBufferWrite buffer_info;\n };\n };\n#pragma endregion\n\n ShaderStageFlags operator|=(ShaderStageFlags lhs, ShaderStageFlags rhs);\n} \/\/ namespace nova::renderer::rhi\n[rhi] Support for updating descriptors as arrays of resources#pragma once\n\n#include \n#include \n\n#include \n\n#include \"nova_renderer\/rhi_enums.hpp\"\n\n#include \"device_memory_resource.hpp\"\n#include \"shaderpack_data.hpp\"\n\nnamespace nova::renderer::rhi {\n\n#pragma region Structs\n struct BufferCreateInfo {\n uint64_t size = 0;\n\n BufferUsage buffer_usage{};\n };\n\n struct DeviceMemory {};\n\n \/*!\n * \\brief A resource\n *\n * Resources may by dynamic of static. Dynamic resources are updated after they are created, possibly by a shader,\n * while static resources are loaded once and that's that\n *\/\n struct Resource {\n ResourceType type = {};\n bool is_dynamic = true;\n };\n\n struct Sampler {};\n\n struct Image : Resource {\n bool is_depth_tex = false;\n };\n\n struct Buffer : Resource {\n uint32_t size = 0;\n };\n\n struct Framebuffer {\n glm::uvec2 size;\n\n uint32_t num_attachments;\n };\n\n struct Renderpass {};\n\n struct ResourceBindingDescription {\n \/*!\n * \\brief Descriptor set that his binding belongs to\n *\/\n uint32_t set;\n\n \/*!\n * \\brief Binding of this resource binding\n *\/\n uint32_t binding;\n\n \/*!\n * \\brief Number of bindings. Useful if you have an array of descriptors\n *\n * If this is a unbounded array, this count is the upper limit on the size of the array\n *\/\n uint32_t count;\n\n \/*!\n * \\brief If true, this binding is an unbounded array\n *\n * Unbounded descriptors must be the final binding in their descriptor set\n *\/\n bool is_unbounded;\n\n \/*!\n * \\brief The type of object that will be bound\n *\/\n DescriptorType type;\n\n \/*!\n * \\brief The shader stages that need access to this binding\n *\/\n ShaderStageFlags stages;\n\n bool operator==(const ResourceBindingDescription& other);\n\n bool operator!=(const ResourceBindingDescription& other);\n };\n\n \/*!\n * \\brief The interface for a pipeline. Includes both inputs (descriptors) and outputs (framebuffers)\n *\/\n struct PipelineInterface {\n std::unordered_map bindings;\n };\n\n struct Pipeline {};\n\n struct Semaphore {};\n\n struct PresentSemaphore {};\n\n struct Fence {};\n\n struct DescriptorPool {};\n\n struct DescriptorSet {};\n\n \/\/ TODO: This struct actually maps pretty directly to a Vulkan barrier, so it doesn't map well to a D3D12 barrier. Figure out how to\n \/\/ make it D3D12-friendly\n struct ResourceBarrier {\n Resource* resource_to_barrier;\n\n \/*!\n * \\brief The resource access that much finish before this barrier executed\n *\/\n AccessFlags access_before_barrier;\n\n \/*!\n * \\brief The resource access that must wait for this battier to finish executing\n *\/\n AccessFlags access_after_barrier;\n\n \/*!\n * \\brief How you're going to access this resource just before this barrier\n *\n * Will a shader read from it before the barrier? Will the fragment depth by copied to a depth buffer before\n * this barrier? Will the resource be used as a indirect draw command buffer right before this barrier?\n *\/\n ResourceState old_state;\n\n \/*!\n * \\brief How you're going to access this resource after this barrier\n *\n * Will a shader read from it after the barrier? Will the fragment depth by copied to a depth buffer after\n * this barrier? Will the resource be used as a indirect draw command buffer right after this barrier?\n *\/\n ResourceState new_state;\n\n QueueType source_queue;\n QueueType destination_queue;\n\n union {\n struct {\n ImageAspectFlags aspect;\n } image_memory_barrier;\n\n struct {\n uint64_t offset;\n uint64_t size;\n } buffer_memory_barrier;\n };\n };\n\n struct DescriptorImageInfo {\n const Image* image;\n shaderpack::TextureFormat format;\n Sampler* sampler;\n };\n\n struct DescriptorBufferInfo {\n const Buffer* buffer;\n };\n\n\tunion DescriptorResourceInfo {\n\t\t\/*!\n\t\t * \\brief Information to update an image descriptor\n\t\t *\/\n\t\tDescriptorImageInfo image_info;\n\n\t\t\/*!\n\t\t * \\brief Information to update a buffer descriptor\n\t\t *\/\n\t\tDescriptorBufferInfo buffer_info;\n\t};\n\n struct DescriptorSetWrite {\n \/*!\n * \\brief Pointer to the descriptor set to write to\n *\/\n DescriptorSet* set;\n\n \/*!\n * \\brief The specific binding in the set that you want to write to\n *\/\n uint32_t first_binding;\n\n \/*!\n * \\brief The type of descriptor you're writing to\n *\/\n DescriptorType type;\n\n \/*!\n * \\brief Information about th\n *\/\n std::vector bindings;\n };\n#pragma endregion\n\n ShaderStageFlags operator|=(ShaderStageFlags lhs, ShaderStageFlags rhs);\n} \/\/ namespace nova::renderer::rhi\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_xbus_clear_firs.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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 p9_io_xbus_clear_firs.C\n\/\/\/ @brief Clears I\/O Firs\n\/\/\/-----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Chris Steffen \n\/\/\/ *HWP HWP Backup Owner : Gary Peterson \n\/\/\/ *HWP FW Owner : Jamie Knight \n\/\/\/ *HWP Team : IO\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : FSP:HB\n\/\/\/-----------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/\n\/\/\/ Clears I\/O Xbus FIRs on the PHY Rx\/Tx.\n\/\/\/\n\/\/\/ Clocks must be running.\n\/\/\/\n\/\/\/ @endverbatim\n\/\/\/----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------\n#include \n#include \n#include \n\n\/\/-----------------------------------------------------------------------------\n\/\/ Definitions\n\/\/-----------------------------------------------------------------------------\nfapi2::ReturnCode io_rx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group);\n\nfapi2::ReturnCode io_tx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group);\n\n\/**\n * @brief A HWP that runs on every instance of the XBUS(EDI+)\n * @param[in] i_target FAPI2 Target\n * @param[in] i_clock_group Clock Group\n * @retval ReturnCode\n *\/\nfapi2::ReturnCode p9_io_xbus_clear_firs(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group)\n{\n FAPI_IMP(\"I\/O Start Xbus Clear FIRs\");\n\n FAPI_TRY(io_tx_fir_reset(i_target, i_clock_group), \"Tx Reset Failed\");\n\n FAPI_TRY(io_rx_fir_reset(i_target, i_clock_group), \"Rx Reset Failed\");\n\nfapi_try_exit:\n FAPI_IMP(\"I\/O End Xbus Clear FIRs\");\n return fapi2::current_err;\n}\n\n\/**\n * @brief This function resets the Rx Firs on a EDI+ Xbus\n * @param[in] i_target FAPI2 Target\n * @param[in] i_clock_group Clock Group\n * @retval ReturnCode\n *\/\nfapi2::ReturnCode io_rx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group)\n{\n Register < EDIP_RX_GLBSM_CNTLX1_EO_PG > rx_fir_reg;\n\n FAPI_TRY(rx_fir_reg.read(i_target, i_clock_group),\n \"Reading Rx Fir Reg Failed\");\n\n rx_fir_reg.set(0);\n FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),\n \"Writing Rx Fir Reg Failed\");\n\n rx_fir_reg.set(1);\n FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),\n \"Writing rx Fir Reg Failed\");\n\n rx_fir_reg.set(0);\n FAPI_TRY(rx_fir_reg.write(i_target, i_clock_group),\n \"Writing Rx Fir Reg Failed\");\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/**\n * @brief This function resets the Tx Firs on a EDI+ Xbus\n * @param[in] i_target FAPI2 Target\n * @param[in] i_clock_group Clock Group\n * @retval ReturnCode\n *\/\nfapi2::ReturnCode io_tx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group)\n{\n Register < EDIP_TX_FIR_RESET_PG > tx_fir_reg;\n\n FAPI_TRY(tx_fir_reg.read(i_target, i_clock_group),\n \"Reading Tx Fir Reg Failed\");\n\n tx_fir_reg.set(0);\n FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),\n \"Writing Tx Fir Reg Failed\");\n\n tx_fir_reg.set(1);\n FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),\n \"Writing Tx Fir Reg Failed\");\n\n tx_fir_reg.set(0);\n FAPI_TRY(tx_fir_reg.write(i_target, i_clock_group),\n \"Writing Tx Fir Reg Failed\");\n\nfapi_try_exit:\n return fapi2::current_err;\n}\nio scom access conversion\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_xbus_clear_firs.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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 p9_io_xbus_clear_firs.C\n\/\/\/ @brief Clears I\/O Firs\n\/\/\/-----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Chris Steffen \n\/\/\/ *HWP HWP Backup Owner : Gary Peterson \n\/\/\/ *HWP FW Owner : Jamie Knight \n\/\/\/ *HWP Team : IO\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : FSP:HB\n\/\/\/-----------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/\n\/\/\/ Clears I\/O Xbus FIRs on the PHY Rx\/Tx.\n\/\/\/\n\/\/\/ Clocks must be running.\n\/\/\/\n\/\/\/ @endverbatim\n\/\/\/----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------\n#include \n#include \n#include \n\n\/\/-----------------------------------------------------------------------------\n\/\/ Definitions\n\/\/-----------------------------------------------------------------------------\nfapi2::ReturnCode io_rx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group );\n\nfapi2::ReturnCode io_tx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group );\n\n\/**\n * @brief Clears PHY Rx\/Tx FIRs on the XBUS(EDI+) specified target. The FIRs\n * are cleared by toggling a rx & tx fir reset bit.\n * @param[in] i_target FAPI2 Target\n * @param[in] i_clock_group Clock Group\n * @retval ReturnCode\n *\/\nfapi2::ReturnCode p9_io_xbus_clear_firs(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group )\n{\n FAPI_IMP( \"I\/O Start Xbus Clear FIRs\" );\n\n FAPI_TRY( io_tx_fir_reset( i_target, i_clock_group ), \"Tx Reset Failed\" );\n\n FAPI_TRY( io_rx_fir_reset( i_target, i_clock_group ), \"Rx Reset Failed\" );\n\nfapi_try_exit:\n FAPI_IMP( \"I\/O End Xbus Clear FIRs\" );\n return fapi2::current_err;\n}\n\n\/**\n * @brief This function resets the Rx Firs on a EDI+ Xbus\n * @param[in] i_target FAPI2 Target\n * @param[in] i_clock_group Clock Group\n * @retval ReturnCode\n *\/\nfapi2::ReturnCode io_rx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group)\n{\n const uint8_t LANE_00 = 0;\n uint64_t l_data = 0;\n\n FAPI_TRY( io::read( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Reading Rx Fir Reg Failed\");\n\n io::set (EDIP_RX_FIR_RESET, 0, l_data);\n FAPI_TRY(io::write( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Writing Rx Fir Reg Failed\");\n\n io::set (EDIP_RX_FIR_RESET, 1, l_data);\n FAPI_TRY(io::write( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Writing Rx Fir Reg Failed\");\n\n io::set (EDIP_RX_FIR_RESET, 0, l_data);\n FAPI_TRY(io::write( EDIP_RX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Writing Rx Fir Reg Failed\");\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/**\n * @brief This function resets the Tx Firs on a EDI+ Xbus\n * @param[in] i_target FAPI2 Target\n * @param[in] i_clock_group Clock Group\n * @retval ReturnCode\n *\/\nfapi2::ReturnCode io_tx_fir_reset(\n const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_target,\n const uint8_t& i_clock_group)\n{\n const uint8_t LANE_00 = 0;\n uint64_t l_data = 0;\n\n FAPI_TRY( io::read( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Reading Tx Fir Reg Failed\");\n\n io::set (EDIP_TX_FIR_RESET, 0, l_data);\n FAPI_TRY(io::write( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Writing Tx Fir Reg Failed\");\n\n io::set (EDIP_TX_FIR_RESET, 1, l_data);\n FAPI_TRY(io::write( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Writing Tx Fir Reg Failed\");\n\n io::set (EDIP_TX_FIR_RESET, 0, l_data);\n FAPI_TRY(io::write( EDIP_TX_FIR_RESET, i_target, i_clock_group, LANE_00, l_data ),\n \"Writing Tx Fir Reg Failed\");\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#pragma once\n\n#include \"include\/aclTypes.h\"\n#include \"platform\/context.hpp\"\n#include \"platform\/object.hpp\"\n#include \"platform\/memory.hpp\"\n#include \"devwavelimiter.hpp\"\n#include \"comgrctx.hpp\"\n\n#if defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)\n#ifndef USE_COMGR_LIBRARY\n#include \"driver\/AmdCompiler.h\"\n#endif\n\/\/#include \"llvm\/Support\/AMDGPUMetadata.h\"\n\nnamespace llvm {\n namespace AMDGPU {\n namespace HSAMD {\n struct Metadata;\n namespace Kernel {\n struct Metadata;\n}}}}\n\n#define LC_METADATA 1\ntypedef llvm::AMDGPU::HSAMD::Metadata CodeObjectMD;\ntypedef llvm::AMDGPU::HSAMD::Kernel::Metadata KernelMD;\n\/\/typedef llvm::AMDGPU::HSAMD::Kernel::Arg::Metadata KernelArgMD;\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)\n\n#ifndef LC_METADATA\ntypedef char CodeObjectMD;\n#endif\n\nnamespace amd {\n namespace hsa {\n namespace loader {\n class Symbol;\n } \/\/ loader\n namespace code {\n namespace Kernel {\n class Metadata;\n } \/\/ Kernel\n } \/\/ code\n } \/\/ hsa\n} \/\/ amd\n\nnamespace amd {\n\nclass Device;\nclass Program;\n\nnamespace option {\n class Options;\n} \/\/ option\n}\n\nnamespace device {\nclass ClBinary;\nclass Kernel;\n\n\/\/! A program object for a specific device.\nclass Program : public amd::HeapObject {\n public:\n typedef std::pair binary_t;\n typedef std::unordered_map kernels_t;\n \/\/ type of the program\n typedef enum {\n TYPE_NONE = 0, \/\/ uncompiled\n TYPE_COMPILED, \/\/ compiled\n TYPE_LIBRARY, \/\/ linked library\n TYPE_EXECUTABLE, \/\/ linked executable\n TYPE_INTERMEDIATE \/\/ intermediate\n } type_t;\n\n private:\n \/\/! The device target for this binary.\n amd::SharedReference device_;\n\n kernels_t kernels_; \/\/!< The kernel entry points this binary.\n type_t type_; \/\/!< type of this program\n\n protected:\n union {\n struct {\n uint32_t isNull_ : 1; \/\/!< Null program no memory allocations\n uint32_t internal_ : 1; \/\/!< Internal blit program\n uint32_t isLC_ : 1; \/\/!< LC was used for the program compilation\n uint32_t hasGlobalStores_ : 1; \/\/!< Program has writable program scope variables\n uint32_t xnackEnabled_ : 1; \/\/!< Xnack was enabled during compilation\n uint32_t sramEccEnabled_ : 1; \/\/!< SRAM ECC was enabled during compilation\n };\n uint32_t flags_; \/\/!< Program flags\n };\n\n ClBinary* clBinary_; \/\/!< The CL program binary file\n std::string llvmBinary_; \/\/!< LLVM IR binary code\n amd::OclElf::oclElfSections elfSectionType_; \/\/!< LLVM IR binary code is in SPIR format\n std::string compileOptions_; \/\/!< compile\/build options.\n std::string linkOptions_; \/\/!< link options.\n \/\/!< the option arg passed in to clCompileProgram(), clLinkProgram(),\n \/\/! or clBuildProgram(), whichever is called last\n aclBinaryOptions binOpts_; \/\/!< Binary options to create aclBinary\n aclBinary* binaryElf_; \/\/!< Binary for the new compiler library\n\n std::string lastBuildOptionsArg_;\n mutable std::string buildLog_; \/\/!< build log.\n cl_int buildStatus_; \/\/!< build status.\n cl_int buildError_; \/\/!< build error\n\n const char* machineTarget_; \/\/!< Machine target for this program\n aclTargetInfo info_; \/\/!< The info target for this binary.\n size_t globalVariableTotalSize_;\n amd::option::Options* programOptions_;\n\n\n#if defined(USE_COMGR_LIBRARY)\n amd_comgr_metadata_node_t* metadata_; \/\/!< COMgr metadata\n std::map kernelMetadataMap_; \/\/!< Map of kernel metadata\n#else\n CodeObjectMD* metadata_; \/\/!< Runtime metadata\n#endif\n\n public:\n \/\/! Construct a section.\n Program(amd::Device& device);\n\n \/\/! Destroy this binary image.\n virtual ~Program();\n\n \/\/! Destroy all the kernels\n void clear();\n\n \/\/! Return the compiler options passed to build this program\n amd::option::Options* getCompilerOptions() const { return programOptions_; }\n\n \/\/! Compile the device program.\n cl_int compile(const std::string& sourceCode, const std::vector& headers,\n const char** headerIncludeNames, const char* origOptions,\n amd::option::Options* options);\n\n \/\/! Builds the device program.\n cl_int link(const std::vector& inputPrograms, const char* origOptions,\n amd::option::Options* options);\n\n \/\/! Builds the device program.\n cl_int build(const std::string& sourceCode, const char* origOptions,\n amd::option::Options* options);\n\n \/\/! Returns the device object, associated with this program.\n const amd::Device& device() const { return device_(); }\n\n \/\/! Return the compiler options used to build the program.\n const std::string& compileOptions() const { return compileOptions_; }\n\n \/\/! Return the option arg passed in to clCompileProgram(), clLinkProgram(),\n \/\/! or clBuildProgram(), whichever is called last\n const std::string lastBuildOptionsArg() const { return lastBuildOptionsArg_; }\n\n \/\/! Return the build log.\n const std::string& buildLog() const { return buildLog_; }\n\n \/\/! Return the build status.\n cl_build_status buildStatus() const { return buildStatus_; }\n\n \/\/! Return the build error.\n cl_int buildError() const { return buildError_; }\n\n \/\/! Return the symbols vector.\n const kernels_t& kernels() const { return kernels_; }\n kernels_t& kernels() { return kernels_; }\n\n \/\/! Return the binary image.\n inline const binary_t binary() const;\n inline binary_t binary();\n\n \/\/! Returns the CL program binary file\n ClBinary* clBinary() { return clBinary_; }\n const ClBinary* clBinary() const { return clBinary_; }\n\n bool setBinary(const char* binaryIn, size_t size);\n\n type_t type() const { return type_; }\n\n void setGlobalVariableTotalSize(size_t size) { globalVariableTotalSize_ = size; }\n\n size_t globalVariableTotalSize() const { return globalVariableTotalSize_; }\n\n \/\/! Returns the aclBinary associated with the program\n aclBinary* binaryElf() const { return static_cast(binaryElf_); }\n\n \/\/! Returns TRUE if the program just compiled\n bool isNull() const { return isNull_; }\n\n \/\/! Returns TRUE if the program used internally by runtime\n bool isInternal() const { return internal_; }\n\n \/\/! Returns TRUE if Lightning compiler was used for this program\n bool isLC() const { return isLC_; }\n\n \/\/! Global variables are a part of the code segment\n bool hasGlobalStores() const { return hasGlobalStores_; }\n\n#if defined(USE_COMGR_LIBRARY)\n const amd_comgr_metadata_node_t* metadata() const { return metadata_; }\n\n \/\/! Get the kernel metadata\n const amd_comgr_metadata_node_t* getKernelMetadata(const std::string name) const {\n auto it = kernelMetadataMap_.find(name);\n return (it == kernelMetadataMap_.end()) ? nullptr : &(it->second);\n }\n#else\n const CodeObjectMD* metadata() const { return metadata_; }\n#endif\n\n \/\/! Get the machine target for the program\n const char* machineTarget() const { return machineTarget_; }\n\n \/\/! Check if xnack is enable\n const bool xnackEnable() const { return (xnackEnabled_ == 1); }\n\n \/\/! Check if SRAM ECC is enable\n const bool sramEccEnable() const { return (sramEccEnabled_ == 1); }\n\n virtual bool findGlobalSymbols(void** dptr, size_t* bytes, const char* globalName) const {\n ShouldNotReachHere();\n }\n\n protected:\n \/\/! pre-compile setup\n bool initBuild(amd::option::Options* options);\n\n \/\/! post-compile cleanup\n bool finiBuild(bool isBuildGood);\n\n \/*! \\brief Compiles GPU CL program to LLVM binary (compiler frontend)\n *\n * \\return True if we successefully compiled a GPU program\n *\/\n virtual bool compileImpl(\n const std::string& sourceCode, \/\/!< the program's source code\n const std::vector& headers,\n const char** headerIncludeNames,\n amd::option::Options* options \/\/!< compile options's object\n );\n\n \/\/! Link the device program.\n virtual bool linkImpl(amd::option::Options* options);\n\n \/\/! Link the device programs.\n virtual bool linkImpl(const std::vector& inputPrograms, amd::option::Options* options,\n bool createLibrary);\n\n virtual bool createBinary(amd::option::Options* options) = 0;\n\n \/\/! Initialize Binary (used only for clCreateProgramWithBinary()).\n bool initClBinary(const char* binaryIn, size_t size);\n\n \/\/! Initialize Binary\n virtual bool initClBinary();\n\n virtual bool saveBinaryAndSetType(type_t type) = 0;\n\n \/\/! Release the Binary\n void releaseClBinary();\n\n \/\/! return target info\n virtual const aclTargetInfo& info(const char* str = \"\") = 0;\n\n virtual bool setKernels(\n amd::option::Options* options, void* binary, size_t binSize) { return true; }\n\n \/\/! Returns all the options to be appended while passing to the compiler library\n std::string ProcessOptions(amd::option::Options* options);\n\n \/\/! At linking time, get the set of compile options to be used from\n \/\/! the set of input program, warn if they have inconsisten compile options.\n bool getCompileOptionsAtLinking(const std::vector& inputPrograms,\n const amd::option::Options* linkOptions);\n\n void setType(type_t newType) { type_ = newType; }\n\n#if defined(WITH_LIGHTNING_COMPILER) && !defined(USE_COMGR_LIBRARY)\n \/\/! Return a new transient compiler instance.\n static std::unique_ptr newCompilerInstance();\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)\n\n \/* \\brief Returns the next stage to compile from, based on sections in binary,\n * also returns completeStages in a vector, which contains at least ACL_TYPE_DEFAULT,\n * sets needOptionsCheck to true if options check is needed to decide whether or not to recompile\n *\/\n aclType getCompilationStagesFromBinary(\n std::vector& completeStages,\n bool& needOptionsCheck);\n\n \/* \\brief Returns the next stage to compile from, based on sections and options in binary\n *\/\n aclType getNextCompilationStageFromBinary(amd::option::Options* options);\n\n \/\/! Finds the total size of all global variables in the program\n bool FindGlobalVarSize(void* binary, size_t binSize);\n\n bool isElf(const char* bin) const { return amd::isElfMagic(bin); }\n\n private:\n \/\/! Compile the device program with LC path\n bool compileImplLC(const std::string& sourceCode,\n const std::vector& headers,\n const char** headerIncludeNames, amd::option::Options* options);\n\n \/\/! Compile the device program with HSAIL path\n bool compileImplHSAIL(const std::string& sourceCode,\n const std::vector& headers,\n const char** headerIncludeNames, amd::option::Options* options);\n\n \/\/! Link the device programs with LC path\n bool linkImplLC(const std::vector& inputPrograms,\n amd::option::Options* options, bool createLibrary);\n\n \/\/! Link the device programs with HSAIL path\n bool linkImplHSAIL(const std::vector& inputPrograms,\n amd::option::Options* options, bool createLibrary);\n\n \/\/! Link the device program with LC path\n bool linkImplLC(amd::option::Options* options);\n\n \/\/! Link the device program with HSAIL path\n bool linkImplHSAIL(amd::option::Options* options);\n\n#if defined(USE_COMGR_LIBRARY)\n \/\/! Dump the log data object to the build log, if both are present\n amd_comgr_status_t extractBuildLog(const char* buildLog,\n amd_comgr_data_set_t dataSet);\n \/\/! Dump the code object data\n amd_comgr_status_t extractByteCodeBinary(const amd_comgr_data_set_t inDataSet,\n const amd_comgr_data_kind_t dataKind, const std::string& outFileName,\n char* outBinary[] = nullptr, size_t* outSize = nullptr);\n\n \/\/! Set the OCL language and target triples with feature\n void setLangAndTargetStr(const char* clStd, amd_comgr_language_t* oclver,\n std::string& targetIdent);\n\n \/\/! Create code object and add it into the data set\n amd_comgr_status_t addCodeObjData(const char *source,\n const size_t size, const amd_comgr_data_kind_t type,\n const char* name, amd_comgr_data_set_t* dataSet);\n\n \/\/! Create action for the specified language, target and options\n amd_comgr_status_t createAction(const amd_comgr_language_t oclvar,\n const std::string& targetIdent, const std::string& options,\n amd_comgr_action_info_t* action, bool* hasAction);\n\n \/\/! Create the bitcode of the linked input dataset\n bool linkLLVMBitcode(const amd_comgr_data_set_t inputs,\n const std::string& options, const bool requiredDump,\n amd::option::Options* amdOptions, amd_comgr_data_set_t* output,\n char* binary[] = nullptr, size_t* binarySize = nullptr);\n\n \/\/! Create the bitcode of the compiled input dataset\n bool compileToLLVMBitcode(const amd_comgr_data_set_t inputs,\n const std::string& options, amd::option::Options* amdOptions,\n char* binary[], size_t* binarySize);\n\n \/\/! Compile and create the excutable of the input dataset\n bool compileAndLinkExecutable(const amd_comgr_data_set_t inputs,\n const std::string& options, amd::option::Options* amdOptions,\n char* executable[], size_t* executableSize);\n\n \/\/! Create the map for the kernel name and its metadata for fast access\n bool createKernelMetadataMap();\n#endif\n\n \/\/! Disable default copy constructor\n Program(const Program&);\n\n \/\/! Disable operator=\n Program& operator=(const Program&);\n};\n\n} \/\/ namespace device\nP4 to Git Change 1757956 by kjayapra@1_HIPWS_SL_IPC on 2019\/03\/18 18:47:13\/\/\n\/\/ Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#pragma once\n\n#include \"include\/aclTypes.h\"\n#include \"platform\/context.hpp\"\n#include \"platform\/object.hpp\"\n#include \"platform\/memory.hpp\"\n#include \"devwavelimiter.hpp\"\n#include \"comgrctx.hpp\"\n\n#if defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)\n#ifndef USE_COMGR_LIBRARY\n#include \"driver\/AmdCompiler.h\"\n#endif\n\/\/#include \"llvm\/Support\/AMDGPUMetadata.h\"\n\nnamespace llvm {\n namespace AMDGPU {\n namespace HSAMD {\n struct Metadata;\n namespace Kernel {\n struct Metadata;\n}}}}\n\n#define LC_METADATA 1\ntypedef llvm::AMDGPU::HSAMD::Metadata CodeObjectMD;\ntypedef llvm::AMDGPU::HSAMD::Kernel::Metadata KernelMD;\n\/\/typedef llvm::AMDGPU::HSAMD::Kernel::Arg::Metadata KernelArgMD;\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)\n\n#ifndef LC_METADATA\ntypedef char CodeObjectMD;\n#endif\n\nnamespace amd {\n namespace hsa {\n namespace loader {\n class Symbol;\n } \/\/ loader\n namespace code {\n namespace Kernel {\n class Metadata;\n } \/\/ Kernel\n } \/\/ code\n } \/\/ hsa\n} \/\/ amd\n\nnamespace amd {\n\nclass Device;\nclass Program;\n\nnamespace option {\n class Options;\n} \/\/ option\n}\n\nnamespace device {\nclass ClBinary;\nclass Kernel;\n\n\/\/! A program object for a specific device.\nclass Program : public amd::HeapObject {\n public:\n typedef std::pair binary_t;\n typedef std::unordered_map kernels_t;\n \/\/ type of the program\n typedef enum {\n TYPE_NONE = 0, \/\/ uncompiled\n TYPE_COMPILED, \/\/ compiled\n TYPE_LIBRARY, \/\/ linked library\n TYPE_EXECUTABLE, \/\/ linked executable\n TYPE_INTERMEDIATE \/\/ intermediate\n } type_t;\n\n private:\n \/\/! The device target for this binary.\n amd::SharedReference device_;\n\n kernels_t kernels_; \/\/!< The kernel entry points this binary.\n type_t type_; \/\/!< type of this program\n\n protected:\n union {\n struct {\n uint32_t isNull_ : 1; \/\/!< Null program no memory allocations\n uint32_t internal_ : 1; \/\/!< Internal blit program\n uint32_t isLC_ : 1; \/\/!< LC was used for the program compilation\n uint32_t hasGlobalStores_ : 1; \/\/!< Program has writable program scope variables\n uint32_t xnackEnabled_ : 1; \/\/!< Xnack was enabled during compilation\n uint32_t sramEccEnabled_ : 1; \/\/!< SRAM ECC was enabled during compilation\n };\n uint32_t flags_; \/\/!< Program flags\n };\n\n ClBinary* clBinary_; \/\/!< The CL program binary file\n std::string llvmBinary_; \/\/!< LLVM IR binary code\n amd::OclElf::oclElfSections elfSectionType_; \/\/!< LLVM IR binary code is in SPIR format\n std::string compileOptions_; \/\/!< compile\/build options.\n std::string linkOptions_; \/\/!< link options.\n \/\/!< the option arg passed in to clCompileProgram(), clLinkProgram(),\n \/\/! or clBuildProgram(), whichever is called last\n aclBinaryOptions binOpts_; \/\/!< Binary options to create aclBinary\n aclBinary* binaryElf_; \/\/!< Binary for the new compiler library\n\n std::string lastBuildOptionsArg_;\n mutable std::string buildLog_; \/\/!< build log.\n cl_int buildStatus_; \/\/!< build status.\n cl_int buildError_; \/\/!< build error\n\n const char* machineTarget_; \/\/!< Machine target for this program\n aclTargetInfo info_; \/\/!< The info target for this binary.\n size_t globalVariableTotalSize_;\n amd::option::Options* programOptions_;\n\n\n#if defined(USE_COMGR_LIBRARY)\n amd_comgr_metadata_node_t* metadata_; \/\/!< COMgr metadata\n std::map kernelMetadataMap_; \/\/!< Map of kernel metadata\n#else\n CodeObjectMD* metadata_; \/\/!< Runtime metadata\n#endif\n\n public:\n \/\/! Construct a section.\n Program(amd::Device& device);\n\n \/\/! Destroy this binary image.\n virtual ~Program();\n\n \/\/! Destroy all the kernels\n void clear();\n\n \/\/! Return the compiler options passed to build this program\n amd::option::Options* getCompilerOptions() const { return programOptions_; }\n\n \/\/! Compile the device program.\n cl_int compile(const std::string& sourceCode, const std::vector& headers,\n const char** headerIncludeNames, const char* origOptions,\n amd::option::Options* options);\n\n \/\/! Builds the device program.\n cl_int link(const std::vector& inputPrograms, const char* origOptions,\n amd::option::Options* options);\n\n \/\/! Builds the device program.\n cl_int build(const std::string& sourceCode, const char* origOptions,\n amd::option::Options* options);\n\n \/\/! Returns the device object, associated with this program.\n const amd::Device& device() const { return device_(); }\n\n \/\/! Return the compiler options used to build the program.\n const std::string& compileOptions() const { return compileOptions_; }\n\n \/\/! Return the option arg passed in to clCompileProgram(), clLinkProgram(),\n \/\/! or clBuildProgram(), whichever is called last\n const std::string lastBuildOptionsArg() const { return lastBuildOptionsArg_; }\n\n \/\/! Return the build log.\n const std::string& buildLog() const { return buildLog_; }\n\n \/\/! Return the build status.\n cl_build_status buildStatus() const { return buildStatus_; }\n\n \/\/! Return the build error.\n cl_int buildError() const { return buildError_; }\n\n \/\/! Return the symbols vector.\n const kernels_t& kernels() const { return kernels_; }\n kernels_t& kernels() { return kernels_; }\n\n \/\/! Return the binary image.\n inline const binary_t binary() const;\n inline binary_t binary();\n\n \/\/! Returns the CL program binary file\n ClBinary* clBinary() { return clBinary_; }\n const ClBinary* clBinary() const { return clBinary_; }\n\n bool setBinary(const char* binaryIn, size_t size);\n\n type_t type() const { return type_; }\n\n void setGlobalVariableTotalSize(size_t size) { globalVariableTotalSize_ = size; }\n\n size_t globalVariableTotalSize() const { return globalVariableTotalSize_; }\n\n \/\/! Returns the aclBinary associated with the program\n aclBinary* binaryElf() const { return static_cast(binaryElf_); }\n\n \/\/! Returns TRUE if the program just compiled\n bool isNull() const { return isNull_; }\n\n \/\/! Returns TRUE if the program used internally by runtime\n bool isInternal() const { return internal_; }\n\n \/\/! Returns TRUE if Lightning compiler was used for this program\n bool isLC() const { return isLC_; }\n\n \/\/! Global variables are a part of the code segment\n bool hasGlobalStores() const { return hasGlobalStores_; }\n\n#if defined(USE_COMGR_LIBRARY)\n const amd_comgr_metadata_node_t* metadata() const { return metadata_; }\n\n \/\/! Get the kernel metadata\n const amd_comgr_metadata_node_t* getKernelMetadata(const std::string name) const {\n auto it = kernelMetadataMap_.find(name);\n return (it == kernelMetadataMap_.end()) ? nullptr : &(it->second);\n }\n#else\n const CodeObjectMD* metadata() const { return metadata_; }\n#endif\n\n \/\/! Get the machine target for the program\n const char* machineTarget() const { return machineTarget_; }\n\n \/\/! Check if xnack is enable\n const bool xnackEnable() const { return (xnackEnabled_ == 1); }\n\n \/\/! Check if SRAM ECC is enable\n const bool sramEccEnable() const { return (sramEccEnabled_ == 1); }\n\n virtual bool findGlobalSymbols(void** dptr, size_t* bytes, const char* globalName) const {\n ShouldNotReachHere();\n return false;\n }\n\n protected:\n \/\/! pre-compile setup\n bool initBuild(amd::option::Options* options);\n\n \/\/! post-compile cleanup\n bool finiBuild(bool isBuildGood);\n\n \/*! \\brief Compiles GPU CL program to LLVM binary (compiler frontend)\n *\n * \\return True if we successefully compiled a GPU program\n *\/\n virtual bool compileImpl(\n const std::string& sourceCode, \/\/!< the program's source code\n const std::vector& headers,\n const char** headerIncludeNames,\n amd::option::Options* options \/\/!< compile options's object\n );\n\n \/\/! Link the device program.\n virtual bool linkImpl(amd::option::Options* options);\n\n \/\/! Link the device programs.\n virtual bool linkImpl(const std::vector& inputPrograms, amd::option::Options* options,\n bool createLibrary);\n\n virtual bool createBinary(amd::option::Options* options) = 0;\n\n \/\/! Initialize Binary (used only for clCreateProgramWithBinary()).\n bool initClBinary(const char* binaryIn, size_t size);\n\n \/\/! Initialize Binary\n virtual bool initClBinary();\n\n virtual bool saveBinaryAndSetType(type_t type) = 0;\n\n \/\/! Release the Binary\n void releaseClBinary();\n\n \/\/! return target info\n virtual const aclTargetInfo& info(const char* str = \"\") = 0;\n\n virtual bool setKernels(\n amd::option::Options* options, void* binary, size_t binSize) { return true; }\n\n \/\/! Returns all the options to be appended while passing to the compiler library\n std::string ProcessOptions(amd::option::Options* options);\n\n \/\/! At linking time, get the set of compile options to be used from\n \/\/! the set of input program, warn if they have inconsisten compile options.\n bool getCompileOptionsAtLinking(const std::vector& inputPrograms,\n const amd::option::Options* linkOptions);\n\n void setType(type_t newType) { type_ = newType; }\n\n#if defined(WITH_LIGHTNING_COMPILER) && !defined(USE_COMGR_LIBRARY)\n \/\/! Return a new transient compiler instance.\n static std::unique_ptr newCompilerInstance();\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER) || defined(USE_COMGR_LIBRARY)\n\n \/* \\brief Returns the next stage to compile from, based on sections in binary,\n * also returns completeStages in a vector, which contains at least ACL_TYPE_DEFAULT,\n * sets needOptionsCheck to true if options check is needed to decide whether or not to recompile\n *\/\n aclType getCompilationStagesFromBinary(\n std::vector& completeStages,\n bool& needOptionsCheck);\n\n \/* \\brief Returns the next stage to compile from, based on sections and options in binary\n *\/\n aclType getNextCompilationStageFromBinary(amd::option::Options* options);\n\n \/\/! Finds the total size of all global variables in the program\n bool FindGlobalVarSize(void* binary, size_t binSize);\n\n bool isElf(const char* bin) const { return amd::isElfMagic(bin); }\n\n private:\n \/\/! Compile the device program with LC path\n bool compileImplLC(const std::string& sourceCode,\n const std::vector& headers,\n const char** headerIncludeNames, amd::option::Options* options);\n\n \/\/! Compile the device program with HSAIL path\n bool compileImplHSAIL(const std::string& sourceCode,\n const std::vector& headers,\n const char** headerIncludeNames, amd::option::Options* options);\n\n \/\/! Link the device programs with LC path\n bool linkImplLC(const std::vector& inputPrograms,\n amd::option::Options* options, bool createLibrary);\n\n \/\/! Link the device programs with HSAIL path\n bool linkImplHSAIL(const std::vector& inputPrograms,\n amd::option::Options* options, bool createLibrary);\n\n \/\/! Link the device program with LC path\n bool linkImplLC(amd::option::Options* options);\n\n \/\/! Link the device program with HSAIL path\n bool linkImplHSAIL(amd::option::Options* options);\n\n#if defined(USE_COMGR_LIBRARY)\n \/\/! Dump the log data object to the build log, if both are present\n amd_comgr_status_t extractBuildLog(const char* buildLog,\n amd_comgr_data_set_t dataSet);\n \/\/! Dump the code object data\n amd_comgr_status_t extractByteCodeBinary(const amd_comgr_data_set_t inDataSet,\n const amd_comgr_data_kind_t dataKind, const std::string& outFileName,\n char* outBinary[] = nullptr, size_t* outSize = nullptr);\n\n \/\/! Set the OCL language and target triples with feature\n void setLangAndTargetStr(const char* clStd, amd_comgr_language_t* oclver,\n std::string& targetIdent);\n\n \/\/! Create code object and add it into the data set\n amd_comgr_status_t addCodeObjData(const char *source,\n const size_t size, const amd_comgr_data_kind_t type,\n const char* name, amd_comgr_data_set_t* dataSet);\n\n \/\/! Create action for the specified language, target and options\n amd_comgr_status_t createAction(const amd_comgr_language_t oclvar,\n const std::string& targetIdent, const std::string& options,\n amd_comgr_action_info_t* action, bool* hasAction);\n\n \/\/! Create the bitcode of the linked input dataset\n bool linkLLVMBitcode(const amd_comgr_data_set_t inputs,\n const std::string& options, const bool requiredDump,\n amd::option::Options* amdOptions, amd_comgr_data_set_t* output,\n char* binary[] = nullptr, size_t* binarySize = nullptr);\n\n \/\/! Create the bitcode of the compiled input dataset\n bool compileToLLVMBitcode(const amd_comgr_data_set_t inputs,\n const std::string& options, amd::option::Options* amdOptions,\n char* binary[], size_t* binarySize);\n\n \/\/! Compile and create the excutable of the input dataset\n bool compileAndLinkExecutable(const amd_comgr_data_set_t inputs,\n const std::string& options, amd::option::Options* amdOptions,\n char* executable[], size_t* executableSize);\n\n \/\/! Create the map for the kernel name and its metadata for fast access\n bool createKernelMetadataMap();\n#endif\n\n \/\/! Disable default copy constructor\n Program(const Program&);\n\n \/\/! Disable operator=\n Program& operator=(const Program&);\n};\n\n} \/\/ namespace device\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: VKey.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: oj $ $Date: 2002-11-12 09:17:39 $\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#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_\n#include \"connectivity\/sdbcx\/VKey.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_\n#include \"connectivity\/sdbcx\/VCollection.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n\/\/ -------------------------------------------------------------------------\nusing namespace connectivity;\nusing namespace connectivity::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::lang;\n\n\/\/ -----------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OKey::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)\n{\n if(isNew())\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VKeyDescription\");\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VKey\");\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OKey::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)\n{\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);\n if(isNew())\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.KeyDescription\");\n else\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.Key\");\n\n return aSupported;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool SAL_CALL OKey::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)\n{\n Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());\n const ::rtl::OUString* pSupported = aSupported.getConstArray();\n const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();\n for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)\n ;\n\n return pSupported != pEnd;\n}\n\/\/ -------------------------------------------------------------------------\nOKey::OKey(sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)\n , ODescriptor(ODescriptor_BASE::rBHelper,_bCase,sal_True)\n , m_pColumns(NULL)\n{\n}\n\/\/ -------------------------------------------------------------------------\nOKey::OKey( const ::rtl::OUString& _Name,\n const ::rtl::OUString& _ReferencedTable,\n sal_Int32 _Type,\n sal_Int32 _UpdateRule,\n sal_Int32 _DeleteRule,\n sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)\n ,ODescriptor(ODescriptor_BASE::rBHelper,_bCase)\n ,m_pColumns(NULL)\n ,m_ReferencedTable(_ReferencedTable)\n ,m_Type(_Type)\n ,m_UpdateRule(_UpdateRule)\n ,m_DeleteRule(_DeleteRule)\n{\n m_Name = _Name;\n}\n\/\/ -------------------------------------------------------------------------\nOKey::~OKey( )\n{\n delete m_pColumns;\n}\n\/\/ -------------------------------------------------------------------------\nAny SAL_CALL OKey::queryInterface( const Type & rType ) throw(RuntimeException)\n{\n Any aRet = ODescriptor::queryInterface( rType);\n if(!aRet.hasValue())\n {\n if(!isNew())\n aRet = OKey_BASE::queryInterface(rType);\n if(!aRet.hasValue())\n aRet = ODescriptor_BASE::queryInterface( rType);\n }\n\n return aRet;\n}\n\/\/ -------------------------------------------------------------------------\nSequence< Type > SAL_CALL OKey::getTypes( ) throw(RuntimeException)\n{\n if(isNew())\n return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes());\n\n return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes(),OKey_BASE::getTypes());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OKey::construct()\n{\n ODescriptor::construct();\n\n sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;\n\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REFERENCEDTABLE), PROPERTY_ID_REFERENCEDTABLE, nAttrib,&m_ReferencedTable, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_UPDATERULE), PROPERTY_ID_UPDATERULE, nAttrib,&m_UpdateRule, ::getCppuType(reinterpret_cast(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DELETERULE), PROPERTY_ID_DELETERULE, nAttrib,&m_DeleteRule, ::getCppuType(reinterpret_cast(NULL)));\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OKey::disposing()\n{\n OPropertySetHelper::disposing();\n\n ::osl::MutexGuard aGuard(m_aMutex);\n\n if(m_pColumns)\n m_pColumns->disposing();\n\n ODescriptor_BASE::disposing();\n}\n\/\/ -------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper* OKey::createArrayHelper(sal_Int32 _nId ) const\n{\n Sequence< Property > aProps;\n describeProperties(aProps);\n changePropertyAttributte(aProps);\n return new ::cppu::OPropertyArrayHelper(aProps);\n}\n\/\/ -------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper & OKey::getInfoHelper()\n{\n return *const_cast(this)->getArrayHelper(isNew() ? 1 : 0);\n}\n\/\/ -------------------------------------------------------------------------\nReference< ::com::sun::star::container::XNameAccess > SAL_CALL OKey::getColumns( ) throw(RuntimeException)\n{\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);\n\n try\n {\n if ( !m_pColumns )\n refreshColumns();\n }\n catch( const RuntimeException& )\n {\n \/\/ allowed to leave this method\n throw;\n }\n catch( const Exception& )\n {\n \/\/ allowed\n }\n\n return const_cast(this)->m_pColumns;\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > SAL_CALL OKey::createDataDescriptor( ) throw(RuntimeException)\n{\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);\n\n\n return this;\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OKey::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());\n}\n\/\/ -----------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OKey::getName( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return m_Name;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OKey::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ XInterface\nvoid SAL_CALL OKey::acquire() throw()\n{\n ODescriptor_BASE::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OKey::release() throw()\n{\n ODescriptor_BASE::release();\n}\n\/\/ -----------------------------------------------------------------------------\n\nINTEGRATION: CWS ooo19126 (1.13.320); FILE MERGED 2005\/09\/05 17:25:55 rt 1.13.320.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: VKey.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:44:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _CONNECTIVITY_SDBCX_KEY_HXX_\n#include \"connectivity\/sdbcx\/VKey.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_\n#include \"connectivity\/sdbcx\/VColumn.hxx\"\n#endif\n#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_\n#include \"connectivity\/sdbcx\/VCollection.hxx\"\n#endif\n#ifndef CONNECTIVITY_CONNECTION_HXX\n#include \"TConnection.hxx\"\n#endif\n\/\/ -------------------------------------------------------------------------\nusing namespace connectivity;\nusing namespace connectivity::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::lang;\n\n\/\/ -----------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OKey::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException)\n{\n if(isNew())\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VKeyDescription\");\n return ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.VKey\");\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OKey::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException)\n{\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1);\n if(isNew())\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.KeyDescription\");\n else\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.sdbcx.Key\");\n\n return aSupported;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool SAL_CALL OKey::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException)\n{\n Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());\n const ::rtl::OUString* pSupported = aSupported.getConstArray();\n const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();\n for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)\n ;\n\n return pSupported != pEnd;\n}\n\/\/ -------------------------------------------------------------------------\nOKey::OKey(sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)\n , ODescriptor(ODescriptor_BASE::rBHelper,_bCase,sal_True)\n , m_pColumns(NULL)\n{\n}\n\/\/ -------------------------------------------------------------------------\nOKey::OKey( const ::rtl::OUString& _Name,\n const ::rtl::OUString& _ReferencedTable,\n sal_Int32 _Type,\n sal_Int32 _UpdateRule,\n sal_Int32 _DeleteRule,\n sal_Bool _bCase) : ODescriptor_BASE(m_aMutex)\n ,ODescriptor(ODescriptor_BASE::rBHelper,_bCase)\n ,m_pColumns(NULL)\n ,m_ReferencedTable(_ReferencedTable)\n ,m_Type(_Type)\n ,m_UpdateRule(_UpdateRule)\n ,m_DeleteRule(_DeleteRule)\n{\n m_Name = _Name;\n}\n\/\/ -------------------------------------------------------------------------\nOKey::~OKey( )\n{\n delete m_pColumns;\n}\n\/\/ -------------------------------------------------------------------------\nAny SAL_CALL OKey::queryInterface( const Type & rType ) throw(RuntimeException)\n{\n Any aRet = ODescriptor::queryInterface( rType);\n if(!aRet.hasValue())\n {\n if(!isNew())\n aRet = OKey_BASE::queryInterface(rType);\n if(!aRet.hasValue())\n aRet = ODescriptor_BASE::queryInterface( rType);\n }\n\n return aRet;\n}\n\/\/ -------------------------------------------------------------------------\nSequence< Type > SAL_CALL OKey::getTypes( ) throw(RuntimeException)\n{\n if(isNew())\n return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes());\n\n return ::comphelper::concatSequences(ODescriptor::getTypes(),ODescriptor_BASE::getTypes(),OKey_BASE::getTypes());\n}\n\/\/ -------------------------------------------------------------------------\nvoid OKey::construct()\n{\n ODescriptor::construct();\n\n sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY;\n\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_REFERENCEDTABLE), PROPERTY_ID_REFERENCEDTABLE, nAttrib,&m_ReferencedTable, ::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_TYPE), PROPERTY_ID_TYPE, nAttrib,&m_Type, ::getCppuType(reinterpret_cast(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_UPDATERULE), PROPERTY_ID_UPDATERULE, nAttrib,&m_UpdateRule, ::getCppuType(reinterpret_cast(NULL)));\n registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_DELETERULE), PROPERTY_ID_DELETERULE, nAttrib,&m_DeleteRule, ::getCppuType(reinterpret_cast(NULL)));\n}\n\/\/ -------------------------------------------------------------------------\nvoid SAL_CALL OKey::disposing()\n{\n OPropertySetHelper::disposing();\n\n ::osl::MutexGuard aGuard(m_aMutex);\n\n if(m_pColumns)\n m_pColumns->disposing();\n\n ODescriptor_BASE::disposing();\n}\n\/\/ -------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper* OKey::createArrayHelper(sal_Int32 _nId ) const\n{\n Sequence< Property > aProps;\n describeProperties(aProps);\n changePropertyAttributte(aProps);\n return new ::cppu::OPropertyArrayHelper(aProps);\n}\n\/\/ -------------------------------------------------------------------------\n::cppu::IPropertyArrayHelper & OKey::getInfoHelper()\n{\n return *const_cast(this)->getArrayHelper(isNew() ? 1 : 0);\n}\n\/\/ -------------------------------------------------------------------------\nReference< ::com::sun::star::container::XNameAccess > SAL_CALL OKey::getColumns( ) throw(RuntimeException)\n{\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);\n\n try\n {\n if ( !m_pColumns )\n refreshColumns();\n }\n catch( const RuntimeException& )\n {\n \/\/ allowed to leave this method\n throw;\n }\n catch( const Exception& )\n {\n \/\/ allowed\n }\n\n return const_cast(this)->m_pColumns;\n}\n\/\/ -------------------------------------------------------------------------\nReference< XPropertySet > SAL_CALL OKey::createDataDescriptor( ) throw(RuntimeException)\n{\n ::osl::MutexGuard aGuard(m_aMutex);\n checkDisposed(ODescriptor_BASE::rBHelper.bDisposed);\n\n\n return this;\n}\n\/\/ -----------------------------------------------------------------------------\n::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OKey::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());\n}\n\/\/ -----------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OKey::getName( ) throw(::com::sun::star::uno::RuntimeException)\n{\n return m_Name;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OKey::setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException)\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ XInterface\nvoid SAL_CALL OKey::acquire() throw()\n{\n ODescriptor_BASE::acquire();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid SAL_CALL OKey::release() throw()\n{\n ODescriptor_BASE::release();\n}\n\/\/ -----------------------------------------------------------------------------\n\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_cpu_special_wakeup.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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\/**\n * @file : p9_cpu_special_wakeup.C\n * @brief : HWP to perform special wakeup of core, EQ or EX.\n * @HWP HW Owner : Greg Still \n * @HWP FW Owner : Prem S Jha \n * @HWP Team : PM\n * @HWP Level : L1\n * @HWP Consumed by : OCC, FSP, HOST\n *\/\n\n\/\/ ---------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------\n#include \n\nfapi2::ReturnCode\np9_cpu_special_wakeup( CONST_FAPI2_WAKEUP_CHIPLET& i_chipletTarget,\n PROC_SPCWKUP_OPS i_operation,\n PROC_SPCWKUP_ENTITY i_entity )\n{\n FAPI_IMP(\"Entering... \");\n\n FAPI_IMP(\"Exit...\" );\n return fapi2::FAPI2_RC_SUCCESS;\n}\nPM: Added make file for special wakeup HWP and fixed prolog.\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_cpu_special_wakeup.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\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\/\/\/\n\/\/\/ @file : p9_cpu_special_wakeup.C\n\/\/\/ @brief : HWP to perform special wakeup of core, EQ or EX.\n\n\/\/ *HWP HW Owner : Greg Still \n\/\/ *HWP FW Owner : Prem S Jha \n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 1\n\/\/ *HWP Consumed by : OCC:FSP:HOST\n\n\/\/ ---------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------\n#include \n\nusing namespace p9specialWakeup;\nenum\n{\n NUM_SPCWKUP_ENTITIES = 4,\n NUM_SPCWKUP_OPS = 3,\n};\n\nfapi2::ReturnCode\np9_cpu_special_wakeup( const FAPI2_WAKEUP_CHIPLET& i_chipletTarget,\n const PROC_SPCWKUP_OPS i_operation,\n const PROC_SPCWKUP_ENTITY i_entity )\n{\n FAPI_DBG(\"Entering p9_cpu_special_wakeup\");\n\n FAPI_DBG(\"Exit p9_cpu_special_wakeup\" );\n return fapi2::FAPI2_RC_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \"itkCommandLineArgumentParser.h\"\n#include \"CommandLineArgumentHelper.h\"\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkStatisticsImageFilter.h\"\n#include \"itkInvertIntensityImageFilter.h\"\n\n\/** This program inverts the intensity of an image:\n * new = max - old,\n * where max is the maximum of an image.\n *\/\n\n\/\/-------------------------------------------------------------------------------------\n\n\/** run: A macro to call a function. *\/\n#define run( function, type, dim ) \\\nif ( ComponentTypeIn == #type && Dimension == dim ) \\\n{ \\\n typedef itk::Image< type, dim > InputImageType; \\\n function< InputImageType >( inputFileName, outputFileName ); \\\n supported = true; \\\n}\n\n\/\/-------------------------------------------------------------------------------------\n\n\/** Declare InvertIntensity. *\/\ntemplate< class InputImageType >\nvoid InvertIntensity(\n const std::string & inputFileName,\n const std::string & outputFileName );\n\n\/** Declare PrintHelp. *\/\nvoid PrintHelp( void );\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char ** argv )\n{\n \/** Check arguments for help. *\/\n if ( argc < 3 )\n {\n PrintHelp();\n return 1;\n }\n\n \/** Create a command line argument parser. *\/\n itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n parser->SetCommandLineArguments( argc, argv );\n\n \/** Get arguments. *\/\n std::string inputFileName = \"\";\n bool retin = parser->GetCommandLineArgument( \"-in\", inputFileName );\n if ( !retin )\n {\n std::cerr << \"ERROR: You should specify \\\"-in\\\".\" << std::endl;\n return 1;\n }\n\n std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( \".\" ) );\n outputFileName += \"INVERTED.mhd\";\n parser->GetCommandLineArgument( \"-out\", outputFileName );\n\n \/** Determine image properties. *\/\n std::string ComponentTypeIn = \"short\";\n std::string PixelType; \/\/we don't use this\n unsigned int Dimension = 2;\n unsigned int NumberOfComponents = 1;\n std::vector imagesize( Dimension, 0 );\n int retgip = GetImageProperties(\n inputFileName,\n PixelType,\n ComponentTypeIn,\n Dimension,\n NumberOfComponents,\n imagesize );\n if ( retgip != 0 )\n {\n return 1;\n }\n\n \/** Check for vector images. *\/\n if ( NumberOfComponents > 1 )\n {\n std::cerr << \"ERROR: The NumberOfComponents is larger than 1!\" << std::endl;\n std::cerr << \"Vector images are not supported.\" << std::endl;\n return 1;\n }\n\n \/** Get rid of the possible \"_\" in ComponentType. *\/\n ReplaceUnderscoreWithSpace( ComponentTypeIn );\n\n \/** Run the program. *\/\n bool supported = false;\n try\n {\n \/** 2D. *\/\n run( InvertIntensity, char, 2 );\n run( InvertIntensity, unsigned char, 2 );\n run( InvertIntensity, short, 2 );\n run( InvertIntensity, unsigned short, 2 );\n run( InvertIntensity, float, 2 );\n run( InvertIntensity, double, 2 );\n\n \/** 3D. *\/\n run( InvertIntensity, char, 3 );\n run( InvertIntensity, unsigned char, 3 );\n run( InvertIntensity, short, 3 );\n run( InvertIntensity, unsigned short, 3 );\n run( InvertIntensity, float, 3 );\n run( InvertIntensity, double, 3 );\n\n } \/\/ end run\n catch ( itk::ExceptionObject &e )\n {\n std::cerr << \"Caught ITK exception: \" << e << std::endl;\n return 1;\n }\n if ( !supported )\n {\n std::cerr << \"ERROR: this combination of pixeltype and dimension is not supported!\" << std::endl;\n std::cerr\n << \"pixel (component) type = \" << ComponentTypeIn\n << \" ; dimension = \" << Dimension\n << std::endl;\n return 1;\n }\n\n \/** End program. *\/\n return 0;\n\n} \/\/ end main\n\n\n \/**\n * ******************* InvertIntensity *******************\n *\n * The resize function templated over the input pixel type.\n *\/\n\ntemplate< class InputImageType >\nvoid InvertIntensity( const std::string & inputFileName,\n const std::string & outputFileName )\n{\n \/** Some typedef's. *\/\n typedef typename InputImageType::PixelType InputPixelType;\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n typedef itk::ImageFileWriter< InputImageType > WriterType;\n typedef itk::StatisticsImageFilter< InputImageType > StatisticsFilterType;\n typedef typename StatisticsFilterType::RealType RealType;\n typedef itk::InvertIntensityImageFilter< InputImageType > InvertIntensityFilterType;\n\n \/** Create reader. *\/\n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( inputFileName.c_str() );\n\n \/** Create statistics filter. *\/\n typename StatisticsFilterType::Pointer statistics = StatisticsFilterType::New();\n statistics->SetInput( reader->GetOutput() );\n statistics->Update();\n\n \/** Get all the output stuff. *\/\n InputPixelType max = statistics->GetMaximum();\n\n \/** Create invert filter. *\/\n typename InvertIntensityFilterType::Pointer invertFilter = InvertIntensityFilterType::New();\n invertFilter->SetInput( reader->GetOutput() );\n invertFilter->SetMaximum( max );\n\n \/** Create writer. *\/\n typename WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( outputFileName.c_str() );\n writer->SetInput( invertFilter->GetOutput() );\n writer->Update();\n\n} \/\/ end InvertIntensity()\n\n\n\/**\n * ******************* PrintHelp *******************\n *\/\n\nvoid PrintHelp( void )\n{\n std::cout << \"This program inverts the intensities of an image.\" << std::endl;\n std::cout << \"Usage:\" << std::endl << \"pxinvertintensityimagefilter\" << std::endl;\n std::cout << \" -in inputFilename\" << std::endl;\n std::cout << \" [-out] outputFilename; default: in + INVERTED.mhd\" << std::endl;\n std::cout << \"Supported: 2D, 3D, (unsigned) char, (unsigned) short, float, double.\" << std::endl;\n\n} \/\/ end PrintHelp()\n\nNew style arguments for invertintensityimagefilter#include \"itkCommandLineArgumentParser.h\"\n#include \"CommandLineArgumentHelper.h\"\n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkStatisticsImageFilter.h\"\n#include \"itkInvertIntensityImageFilter.h\"\n\n\/** This program inverts the intensity of an image:\n * new = max - old,\n * where max is the maximum of an image.\n *\/\n\n\/\/-------------------------------------------------------------------------------------\n\n\/** run: A macro to call a function. *\/\n#define run( function, type, dim ) \\\nif ( ComponentTypeIn == #type && Dimension == dim ) \\\n{ \\\n typedef itk::Image< type, dim > InputImageType; \\\n function< InputImageType >( inputFileName, outputFileName ); \\\n supported = true; \\\n}\n\n\/\/-------------------------------------------------------------------------------------\n\n\/** Declare InvertIntensity. *\/\ntemplate< class InputImageType >\nvoid InvertIntensity(\n const std::string & inputFileName,\n const std::string & outputFileName );\n\n\/** Declare PrintHelp. *\/\nstd::string PrintHelp( void );\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char ** argv )\n{\n \/** Create a command line argument parser. *\/\n itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();\n parser->SetCommandLineArguments( argc, argv );\n parser->SetProgramHelpText(PrintHelp());\n parser->MarkArgumentAsRequired( \"-in\", \"The input filename.\" );\n bool validateArguments = parser->CheckForRequiredArguments();\n\n if(!validateArguments)\n {\n return EXIT_FAILURE;\n }\n\n \/** Get arguments. *\/\n std::string inputFileName = \"\";\n parser->GetCommandLineArgument( \"-in\", inputFileName );\n\n std::string outputFileName = inputFileName.substr( 0, inputFileName.rfind( \".\" ) );\n outputFileName += \"INVERTED.mhd\";\n parser->GetCommandLineArgument( \"-out\", outputFileName );\n\n \/** Determine image properties. *\/\n std::string ComponentTypeIn = \"short\";\n std::string PixelType; \/\/we don't use this\n unsigned int Dimension = 2;\n unsigned int NumberOfComponents = 1;\n std::vector imagesize( Dimension, 0 );\n int retgip = GetImageProperties(\n inputFileName,\n PixelType,\n ComponentTypeIn,\n Dimension,\n NumberOfComponents,\n imagesize );\n if ( retgip != 0 )\n {\n return 1;\n }\n\n \/** Check for vector images. *\/\n if ( NumberOfComponents > 1 )\n {\n std::cerr << \"ERROR: The NumberOfComponents is larger than 1!\" << std::endl;\n std::cerr << \"Vector images are not supported.\" << std::endl;\n return 1;\n }\n\n \/** Get rid of the possible \"_\" in ComponentType. *\/\n ReplaceUnderscoreWithSpace( ComponentTypeIn );\n\n \/** Run the program. *\/\n bool supported = false;\n try\n {\n \/** 2D. *\/\n run( InvertIntensity, char, 2 );\n run( InvertIntensity, unsigned char, 2 );\n run( InvertIntensity, short, 2 );\n run( InvertIntensity, unsigned short, 2 );\n run( InvertIntensity, float, 2 );\n run( InvertIntensity, double, 2 );\n\n \/** 3D. *\/\n run( InvertIntensity, char, 3 );\n run( InvertIntensity, unsigned char, 3 );\n run( InvertIntensity, short, 3 );\n run( InvertIntensity, unsigned short, 3 );\n run( InvertIntensity, float, 3 );\n run( InvertIntensity, double, 3 );\n\n } \/\/ end run\n catch ( itk::ExceptionObject &e )\n {\n std::cerr << \"Caught ITK exception: \" << e << std::endl;\n return 1;\n }\n if ( !supported )\n {\n std::cerr << \"ERROR: this combination of pixeltype and dimension is not supported!\" << std::endl;\n std::cerr\n << \"pixel (component) type = \" << ComponentTypeIn\n << \" ; dimension = \" << Dimension\n << std::endl;\n return 1;\n }\n\n \/** End program. *\/\n return 0;\n\n} \/\/ end main\n\n\n \/**\n * ******************* InvertIntensity *******************\n *\n * The resize function templated over the input pixel type.\n *\/\n\ntemplate< class InputImageType >\nvoid InvertIntensity( const std::string & inputFileName,\n const std::string & outputFileName )\n{\n \/** Some typedef's. *\/\n typedef typename InputImageType::PixelType InputPixelType;\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n typedef itk::ImageFileWriter< InputImageType > WriterType;\n typedef itk::StatisticsImageFilter< InputImageType > StatisticsFilterType;\n typedef typename StatisticsFilterType::RealType RealType;\n typedef itk::InvertIntensityImageFilter< InputImageType > InvertIntensityFilterType;\n\n \/** Create reader. *\/\n typename ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( inputFileName.c_str() );\n\n \/** Create statistics filter. *\/\n typename StatisticsFilterType::Pointer statistics = StatisticsFilterType::New();\n statistics->SetInput( reader->GetOutput() );\n statistics->Update();\n\n \/** Get all the output stuff. *\/\n InputPixelType max = statistics->GetMaximum();\n\n \/** Create invert filter. *\/\n typename InvertIntensityFilterType::Pointer invertFilter = InvertIntensityFilterType::New();\n invertFilter->SetInput( reader->GetOutput() );\n invertFilter->SetMaximum( max );\n\n \/** Create writer. *\/\n typename WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( outputFileName.c_str() );\n writer->SetInput( invertFilter->GetOutput() );\n writer->Update();\n\n} \/\/ end InvertIntensity()\n\n\n\/**\n * ******************* PrintHelp *******************\n *\/\n\nstd::string PrintHelp( void )\n{\n std::string helpText = \"This program inverts the intensities of an image. \\\n Usage:\\\n pxinvertintensityimagefilter \\\n -in inputFilename \\\n [-out] outputFilename; default: in + INVERTED.mhd \\\n Supported: 2D, 3D, (unsigned) char, (unsigned) short, float, double.\";\n\n return helpText;\n\n} \/\/ end PrintHelp()\n\n<|endoftext|>"} {"text":"#include \n#include \"demoloop.h\"\n#include \"graphics\/2d_primitives.h\"\n#include \"hsl.h\"\nusing namespace std;\nusing namespace demoloop;\n\nfloat t = 0;\nconst float CYCLE_LENGTH = 10;\n\nclass Loop5 : public Demoloop {\npublic:\n Loop5() : Demoloop(150, 150, 150) {\n glDisable(GL_DEPTH_TEST);\n }\n\n void Update(float dt) {\n t += dt;\n\n const float RADIUS = height \/ 3;\n\n float cycle = fmod(t, CYCLE_LENGTH);\n float cycle_ratio = cycle \/ CYCLE_LENGTH;\n int ox = width \/ 2, oy = height \/ 2;\n\n const int num_vertices = 5;\n const float interval = (DEMOLOOP_M_PI * 2) \/ num_vertices;\n float xCoords[num_vertices];\n float yCoords[num_vertices];\n for (int i = 0; i < num_vertices; ++i) {\n float t = i;\n xCoords[i] = cos(interval * t - DEMOLOOP_M_PI \/ 10) * RADIUS + ox;\n yCoords[i] = sin(interval * t - DEMOLOOP_M_PI \/ 10) * RADIUS + oy;\n }\n\n auto color = hsl2rgb(cycle_ratio, 1, 0.5);\n setColor(color);\n polygon(gl, xCoords, yCoords, num_vertices);\n\n const int dot_count = 20;\n for (int v = 0; v < num_vertices; ++v) {\n const float angularOffset = interval * v;\n for (int t = 0; t < dot_count; ++t) {\n float i = t;\n const float interval_cycle_ratio = fmod(i \/ dot_count + cycle_ratio, 1);\n\n const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n\n setColor(0, 0, 0, 255 * interval_cycle_ratio);\n circle(gl, x1 + ox, y1 + oy, 3);\n\n if (t == 0) {\n const int n = (v + 1) % num_vertices;\n const float x2 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n const float y2 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n const float x3 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + (interval * n)) * interval_cycle_ratio * RADIUS;\n const float y3 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + (interval * n)) * interval_cycle_ratio * RADIUS;\n\n setColor(0, 0, 0);\n line(gl, x2 + ox, y2 + oy, xCoords[v], yCoords[v]);\n line(gl, x2 + ox, y2 + oy, x3 + ox, y3 + oy);\n }\n }\n }\n\n for (float i = 0; i < dot_count; ++i) {\n const float interval_cycle_ratio = fmod(i \/ dot_count + cycle_ratio, 1);\n\n const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2) * RADIUS;\n const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2) * RADIUS;\n\n setColor(0, 0, 0);\n circle(gl, x1 + ox, y1 + oy, 3);\n }\n }\n\nprivate:\n};\n\nint main(int, char**){\n Loop5 loop;\n loop.Run();\n\n return 0;\n}\ngreatly increase loop 5 rendering speed#include \n#include \"demoloop.h\"\n#include \"graphics\/2d_primitives.h\"\nusing namespace std;\nusing namespace demoloop;\n\nfloat t = 0;\nconst float CYCLE_LENGTH = 10;\n\nconst int num_circle_verts = 10;\nconst int num_vertices = 5;\nconst int dot_count = 20;\n\nclass Loop5 : public Demoloop {\npublic:\n Loop5() : Demoloop(150, 150, 150) {\n glDisable(GL_DEPTH_TEST);\n }\n\n void Update(float dt) {\n t += dt;\n\n const float RADIUS = height \/ 3;\n\n float cycle = fmod(t, CYCLE_LENGTH);\n float cycle_ratio = cycle \/ CYCLE_LENGTH;\n int ox = width \/ 2, oy = height \/ 2;\n\n const float interval = (DEMOLOOP_M_PI * 2) \/ num_vertices;\n float xCoords[num_vertices];\n float yCoords[num_vertices];\n for (int i = 0; i < num_vertices; ++i) {\n float t = i;\n xCoords[i] = cos(interval * t - DEMOLOOP_M_PI \/ 10) * RADIUS + ox;\n yCoords[i] = sin(interval * t - DEMOLOOP_M_PI \/ 10) * RADIUS + oy;\n }\n\n auto color = hsl2rgb(cycle_ratio, 1, 0.5);\n setColor(color);\n polygon(gl, xCoords, yCoords, num_vertices);\n\n int count = 0;\n\n const RGB black = {0, 0, 0};\n setColor(black);\n for (int v = 0; v < num_vertices; ++v) {\n const float angularOffset = interval * v;\n for (int t = 0; t < dot_count; ++t) {\n const float interval_cycle_ratio = fmod(static_cast(t) \/ dot_count + cycle_ratio, 1);\n\n const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n\n Matrix4 m;\n m.translate(x1 + ox, y1 + oy);\n for (uint32_t i = 0; i < num_circle_verts - 1; ++i) {\n circleVerts[count].x = cosf(0) * 3;\n circleVerts[count].y = sinf(0) * 3;\n circleVerts[count].z = 1;\n circleVerts[count].a = 255 * interval_cycle_ratio;\n applyColor(circleVerts[count], black);\n applyMatrix(circleVerts[count], m);\n count++;\n\n circleVerts[count].x = cosf(interval * i) * 3;\n circleVerts[count].y = sinf(interval * i) * 3;\n circleVerts[count].z = 1;\n circleVerts[count].a = 255 * interval_cycle_ratio;\n applyColor(circleVerts[count], black);\n applyMatrix(circleVerts[count], m);\n count++;\n\n circleVerts[count].x = cosf(interval * (i + 1)) * 3;\n circleVerts[count].y = sinf(interval * (i + 1)) * 3;\n circleVerts[count].z = 1;\n circleVerts[count].a = 255 * interval_cycle_ratio;\n applyColor(circleVerts[count], black);\n applyMatrix(circleVerts[count], m);\n count++;\n }\n\n\n if (t == 0) {\n const int n = (v + 1) % num_vertices;\n const float x2 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n const float y2 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + angularOffset) * interval_cycle_ratio * RADIUS;\n const float x3 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + (interval * n)) * interval_cycle_ratio * RADIUS;\n const float y3 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2 + (interval * n)) * interval_cycle_ratio * RADIUS;\n\n line(gl, x2 + ox, y2 + oy, xCoords[v], yCoords[v]);\n line(gl, x2 + ox, y2 + oy, x3 + ox, y3 + oy);\n }\n }\n }\n\n for (float i = 0; i < dot_count; ++i) {\n const float interval_cycle_ratio = fmod(i \/ dot_count + cycle_ratio, 1);\n\n const float x1 = cos(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2) * RADIUS;\n const float y1 = sin(interval_cycle_ratio * DEMOLOOP_M_PI * 2 - DEMOLOOP_M_PI \/ 2) * RADIUS;\n\n Matrix4 m;\n m.translate(x1 + ox, y1 + oy);\n for (uint32_t i = 0; i < num_circle_verts - 1; ++i) {\n circleVerts[count].x = cosf(0) * 3;\n circleVerts[count].y = sinf(0) * 3;\n circleVerts[count].z = 1;\n applyColor(circleVerts[count], black);\n applyMatrix(circleVerts[count], m);\n count++;\n\n circleVerts[count].x = cosf(interval * i) * 3;\n circleVerts[count].y = sinf(interval * i) * 3;\n circleVerts[count].z = 1;\n applyColor(circleVerts[count], black);\n applyMatrix(circleVerts[count], m);\n count++;\n\n circleVerts[count].x = cosf(interval * (i + 1)) * 3;\n circleVerts[count].y = sinf(interval * (i + 1)) * 3;\n circleVerts[count].z = 1;\n applyColor(circleVerts[count], black);\n applyMatrix(circleVerts[count], m);\n count++;\n }\n }\n\n gl.triangles(circleVerts, count);\n }\n\nprivate:\n Vertex circleVerts[(num_circle_verts - 1) * 3 * dot_count * (num_vertices + 1)];\n};\n\nint main(int, char**){\n Loop5 loop;\n loop.Run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n nucBedMain.cpp\n\n (c) 2009 - Aaron Quinlan\n Hall Laboratory\n Department of Biochemistry and Molecular Genetics\n University of Virginia\n aaronquinlan@gmail.com\n\n Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\n#include \"nucBed.h\"\n#include \"version.h\"\n\nusing namespace std;\n\n\/\/ define our program name\n#define PROGRAM_NAME \"bedtools nuc\"\n\n\n\/\/ define our parameter checking macro\n#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)\n\n\/\/ function declarations\nvoid nuc_help(void);\n\nint nuc_main(int argc, char* argv[]) {\n\n \/\/ our configuration variables\n bool showHelp = false;\n\n \/\/ input files\n string fastaDbFile;\n string bedFile;\n string pattern;\n\n \/\/ checks for existence of parameters\n bool haveFastaDb = false;\n bool haveBed = false;\n bool printSeq = false;\n bool hasPattern = false;\n bool forceStrand = false;\n bool ignoreCase = false;\n bool useFullHeader = false;\n\n \/\/ check to see if we should print out some help\n if(argc <= 1) showHelp = true;\n\n for(int i = 1; i < argc; i++) {\n int parameterLength = (int)strlen(argv[i]);\n\n if((PARAMETER_CHECK(\"-h\", 2, parameterLength)) ||\n (PARAMETER_CHECK(\"--help\", 5, parameterLength))) {\n showHelp = true;\n }\n }\n\n if(showHelp) nuc_help();\n\n \/\/ do some parsing (all of these parameters require 2 strings)\n for(int i = 1; i < argc; i++) {\n\n int parameterLength = (int)strlen(argv[i]);\n\n if(PARAMETER_CHECK(\"-fi\", 3, parameterLength)) {\n if ((i+1) < argc) {\n haveFastaDb = true;\n fastaDbFile = argv[i + 1];\n i++;\n }\n }\n else if(PARAMETER_CHECK(\"-bed\", 4, parameterLength)) {\n if ((i+1) < argc) {\n haveBed = true;\n bedFile = argv[i + 1];\n i++;\n }\n }\n else if(PARAMETER_CHECK(\"-seq\", 4, parameterLength)) {\n printSeq = true;\n }\n else if(PARAMETER_CHECK(\"-s\", 2, parameterLength)) {\n forceStrand = true;\n }\n else if(PARAMETER_CHECK(\"-C\", 2, parameterLength)) {\n ignoreCase = true;\n }\n else if(PARAMETER_CHECK(\"-pattern\", 8, parameterLength)) {\n if ((i+1) < argc) {\n hasPattern = true;\n pattern = argv[i + 1];\n i++;\n }\n\t}\n else if(PARAMETER_CHECK(\"-useFullHeader\", 11, parameterLength)) {\n useFullHeader = true;\n }\n else {\n cerr << \"*****ERROR: Unrecognized parameter: \" << argv[i] << \" *****\" << endl << endl;\n showHelp = true;\n }\n }\n\n if (!haveFastaDb || !haveBed) {\n showHelp = true;\n }\n\n if (!showHelp) {\n\n NucBed *nuc = new NucBed(fastaDbFile, bedFile, printSeq, \n hasPattern, pattern, forceStrand, ignoreCase,\n\t\t\t\t useFullHeader);\n delete nuc;\n }\n else {\n nuc_help();\n }\n return 0;\n}\n\nvoid nuc_help(void) {\n\n cerr << \"\\nTool: bedtools nuc (aka nucBed)\" << endl;\n cerr << \"Version: \" << VERSION << \"\\n\"; \n cerr << \"Summary: Profiles the nucleotide content of intervals in a fasta file.\" << endl << endl;\n\n cerr << \"Usage: \" << PROGRAM_NAME << \" [OPTIONS] -fi -bed \" << endl << endl;\n\n cerr << \"Options: \" << endl;\n\n cerr << \"\\t-fi\\tInput FASTA file\" << endl << endl;\n\n cerr << \"\\t-bed\\tBED\/GFF\/VCF file of ranges to extract from -fi\" << endl << endl;\n\n cerr << \"\\t-s\\tProfile the sequence according to strand.\" << endl << endl;\n\n cerr << \"\\t-seq\\tPrint the extracted sequence\" << endl << endl;\n\n cerr << \"\\t-pattern\\tReport the number of times a user-defined sequence\" << endl;\n cerr << \"\\t\\t\\tis observed (case-sensitive).\" << endl << endl; \n\n cerr << \"\\t-C\\tIgnore case when matching -pattern. By defaulty, case matters.\" << endl << endl;\n\n cerr << \"\\t-fullHeader\\tUse full fasta header.\" << endl;\n cerr << \"\\t\\t- By default, only the word before the first space or tab \"\n\t << \"is used.\" << endl << endl;\n\n cerr << \"Output format: \" << endl;\n cerr << \"\\tThe following information will be reported after each BED entry:\" << endl;\n cerr << \"\\t 1) %AT content\" << endl;\n cerr << \"\\t 2) %GC content\" << endl;\n cerr << \"\\t 3) Number of As observed\" << endl;\n cerr << \"\\t 4) Number of Cs observed\" << endl;\n cerr << \"\\t 5) Number of Gs observed\" << endl;\n cerr << \"\\t 6) Number of Ts observed\" << endl;\n cerr << \"\\t 7) Number of Ns observed\" << endl;\n cerr << \"\\t 8) Number of other bases observed\" << endl;\n cerr << \"\\t 9) The length of the explored sequence\/interval.\" << endl;\n cerr << \"\\t 10) The seq. extracted from the FASTA file. (opt., if -seq is used)\" << endl;\n cerr << \"\\t 11) The number of times a user's pattern was observed.\" << endl;\n cerr << \"\\t (opt., if -pattern is used.)\" << endl << endl;\n \/\/ end the program here\n exit(1);\n\n}\ntypo on option -useFullHeader\/*****************************************************************************\n nucBedMain.cpp\n\n (c) 2009 - Aaron Quinlan\n Hall Laboratory\n Department of Biochemistry and Molecular Genetics\n University of Virginia\n aaronquinlan@gmail.com\n\n Licenced under the GNU General Public License 2.0 license.\n******************************************************************************\/\n#include \"nucBed.h\"\n#include \"version.h\"\n\nusing namespace std;\n\n\/\/ define our program name\n#define PROGRAM_NAME \"bedtools nuc\"\n\n\n\/\/ define our parameter checking macro\n#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)\n\n\/\/ function declarations\nvoid nuc_help(void);\n\nint nuc_main(int argc, char* argv[]) {\n\n \/\/ our configuration variables\n bool showHelp = false;\n\n \/\/ input files\n string fastaDbFile;\n string bedFile;\n string pattern;\n\n \/\/ checks for existence of parameters\n bool haveFastaDb = false;\n bool haveBed = false;\n bool printSeq = false;\n bool hasPattern = false;\n bool forceStrand = false;\n bool ignoreCase = false;\n bool useFullHeader = false;\n\n \/\/ check to see if we should print out some help\n if(argc <= 1) showHelp = true;\n\n for(int i = 1; i < argc; i++) {\n int parameterLength = (int)strlen(argv[i]);\n\n if((PARAMETER_CHECK(\"-h\", 2, parameterLength)) ||\n (PARAMETER_CHECK(\"--help\", 5, parameterLength))) {\n showHelp = true;\n }\n }\n\n if(showHelp) nuc_help();\n\n \/\/ do some parsing (all of these parameters require 2 strings)\n for(int i = 1; i < argc; i++) {\n\n int parameterLength = (int)strlen(argv[i]);\n\n if(PARAMETER_CHECK(\"-fi\", 3, parameterLength)) {\n if ((i+1) < argc) {\n haveFastaDb = true;\n fastaDbFile = argv[i + 1];\n i++;\n }\n }\n else if(PARAMETER_CHECK(\"-bed\", 4, parameterLength)) {\n if ((i+1) < argc) {\n haveBed = true;\n bedFile = argv[i + 1];\n i++;\n }\n }\n else if(PARAMETER_CHECK(\"-seq\", 4, parameterLength)) {\n printSeq = true;\n }\n else if(PARAMETER_CHECK(\"-s\", 2, parameterLength)) {\n forceStrand = true;\n }\n else if(PARAMETER_CHECK(\"-C\", 2, parameterLength)) {\n ignoreCase = true;\n }\n else if(PARAMETER_CHECK(\"-pattern\", 8, parameterLength)) {\n if ((i+1) < argc) {\n hasPattern = true;\n pattern = argv[i + 1];\n i++;\n }\n\t}\n else if(PARAMETER_CHECK(\"-fullHeader\", 11, parameterLength)) {\n useFullHeader = true;\n }\n else {\n cerr << \"*****ERROR: Unrecognized parameter: \" << argv[i] << \" *****\" << endl << endl;\n showHelp = true;\n }\n }\n\n if (!haveFastaDb || !haveBed) {\n showHelp = true;\n }\n\n if (!showHelp) {\n\n NucBed *nuc = new NucBed(fastaDbFile, bedFile, printSeq, \n hasPattern, pattern, forceStrand, ignoreCase,\n\t\t\t\t useFullHeader);\n delete nuc;\n }\n else {\n nuc_help();\n }\n return 0;\n}\n\nvoid nuc_help(void) {\n\n cerr << \"\\nTool: bedtools nuc (aka nucBed)\" << endl;\n cerr << \"Version: \" << VERSION << \"\\n\"; \n cerr << \"Summary: Profiles the nucleotide content of intervals in a fasta file.\" << endl << endl;\n\n cerr << \"Usage: \" << PROGRAM_NAME << \" [OPTIONS] -fi -bed \" << endl << endl;\n\n cerr << \"Options: \" << endl;\n\n cerr << \"\\t-fi\\tInput FASTA file\" << endl << endl;\n\n cerr << \"\\t-bed\\tBED\/GFF\/VCF file of ranges to extract from -fi\" << endl << endl;\n\n cerr << \"\\t-s\\tProfile the sequence according to strand.\" << endl << endl;\n\n cerr << \"\\t-seq\\tPrint the extracted sequence\" << endl << endl;\n\n cerr << \"\\t-pattern\\tReport the number of times a user-defined sequence\" << endl;\n cerr << \"\\t\\t\\tis observed (case-sensitive).\" << endl << endl; \n\n cerr << \"\\t-C\\tIgnore case when matching -pattern. By defaulty, case matters.\" << endl << endl;\n\n cerr << \"\\t-fullHeader\\tUse full fasta header.\" << endl;\n cerr << \"\\t\\t- By default, only the word before the first space or tab \"\n\t << \"is used.\" << endl << endl;\n\n cerr << \"Output format: \" << endl;\n cerr << \"\\tThe following information will be reported after each BED entry:\" << endl;\n cerr << \"\\t 1) %AT content\" << endl;\n cerr << \"\\t 2) %GC content\" << endl;\n cerr << \"\\t 3) Number of As observed\" << endl;\n cerr << \"\\t 4) Number of Cs observed\" << endl;\n cerr << \"\\t 5) Number of Gs observed\" << endl;\n cerr << \"\\t 6) Number of Ts observed\" << endl;\n cerr << \"\\t 7) Number of Ns observed\" << endl;\n cerr << \"\\t 8) Number of other bases observed\" << endl;\n cerr << \"\\t 9) The length of the explored sequence\/interval.\" << endl;\n cerr << \"\\t 10) The seq. extracted from the FASTA file. (opt., if -seq is used)\" << endl;\n cerr << \"\\t 11) The number of times a user's pattern was observed.\" << endl;\n cerr << \"\\t (opt., if -pattern is used.)\" << endl << endl;\n \/\/ end the program here\n exit(1);\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"GlowneOkno.hpp\"\n#include \"WyborPortu.hpp\"\n#include \"KodyWyjsciowe.hpp\"\n\nconst char* bledy[14]=\n{\n\t\"Brak błędu\",\n\t\"Nie znaleziono urządzenia\",\n\t\"Brak uprawnień (być może port jest używany przez inny program)\",\n\t\"Port jest już otwarty\",\n\t\"Błąd parzystości\",\n\t\"Błąd ramki\",\n\t\"Błąd stanu przerwy (rodzaj błędu ramki)\",\n\t\"Ogólny błąd wysyłania\",\n\t\"Ogólny błąd odczytu\",\n\t\"Błąd zasobów (np. port został odłączony w czasie pracy programu)\",\n\t\"Niedozwolona operacja\",\n\t\"Nieznany błąd\",\n\t\"Upłynął limit czasu oczekiwania\",\n\t\"Port nie został prawidłowo otwarty\"\n};\n\nGlowneOkno::GlowneOkno(QWidget* parent):QMainWindow(parent)\n{\n\tsetupRS();\n\t\n\tsetupOkno();\n setupRozklad();\n setupWyslij();\n setupReset();\n setupTemperatura();\n setupWykres();\n \n okno_->show();\n}\n \nGlowneOkno::~GlowneOkno()\n{\n\tzadanaTemperatura_->setValue(0);\n\tustawTemperature();\n rs232_->close();\n \n delete rs232_;\n delete zadanaTemperatura_;\n delete wyslij_;\n delete reset_;\n delete wykres_;\n \/\/delete danePomiaroweWykres_;\n \n czas_.clear();\n temperatura_.clear();\n \n delete okno_;\n}\n\nvoid GlowneOkno::setupOkno(void)\n{\n\tokno_=new QWidget();\n\tokno_->resize(800,600);\n\tokno_->setWindowTitle(\"Kontroler temperatury\");\n}\n\nvoid GlowneOkno::setupRozklad(void)\n{\n\tglownyRozmieszczacz_=new QVBoxLayout(okno_);\n\tokno_->setLayout(glownyRozmieszczacz_);\n}\n\nvoid GlowneOkno::setupRS(void)\n{\n\trs232_=new QSerialPort(this);\n\tQStringList itemList;\n\tint wybor=QMessageBox::Retry;\n\tdo\n\t{\n\t\titemList.clear();\n\t\tQ_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts()) \n\t\t{\n\t\t\titemList<setPortName(dialog.poleKombi()->currentText());\n\t\tif(wynik==QDialog::Rejected)\n\t\t{\n\t\t\tQMessageBox(QMessageBox::Critical, \"Nie wybrano portu szeregowego!\", \"Koniec programu.\", QMessageBox::Ok).exec();\n\t\t\texit(2);\n\t\t}\n\t}\n\twhile(wynik != QDialog::Accepted);\n\t\n\trs232_->open (QIODevice::ReadWrite);\n\trs232_->setBaudRate (QSerialPort::Baud57600);\n\trs232_->setDataBits (QSerialPort::Data8);\n\trs232_->setStopBits (QSerialPort::OneStop);\n\trs232_->setParity (QSerialPort::NoParity);\n\trs232_->setFlowControl (QSerialPort::NoFlowControl);\n\trs232_->clear();\n std::cerr<error()<addWidget(zadanaTemperatura_);\n zadanaTemperatura_->setRange(0, 999);\n zadanaTemperatura_->setSingleStep(1);\n zadanaTemperatura_->setSuffix(\" ℃\"); \n}\n\nvoid GlowneOkno::setupWyslij(void)\n{\n\twyslij_=new QPushButton(\"Ustaw\");\n\twyslij_->setFixedSize(100,20);\n\tglownyRozmieszczacz_->addWidget(wyslij_);\n\t\n\tQObject::connect(wyslij_, SIGNAL(clicked(bool)),this, SLOT(ustawTemperature()));\n}\n\nvoid GlowneOkno::setupZatrzymajGrzanie(void)\n{\n\tzatrzymajGrzanie_=new QPushButton(\"ZatrzymajGrzanie\");\n\tzatrzymajGrzanie_->setFixedSize(100,20);\n\tglownyRozmieszczacz_->addWidget(zatrzymajGrzanie_);\n}\n\nvoid GlowneOkno::setupReset(void)\n{\n\treset_=new QPushButton(\"Reset\");\n\treset_->setFixedSize(100,20);\n\tglownyRozmieszczacz_->addWidget(reset_);\n\t\n\tQObject::connect(reset_, SIGNAL(clicked(bool)),this, SLOT(zrestartujUrzadenie()));\n}\n\nvoid GlowneOkno::setupWykres(void)\n{\n\twykres_=new QwtPlot;\n\tglownyRozmieszczacz_->addWidget(wykres_);\n\twykres_->setTitle (\"Bieżąca temperatura próbki\");\n\twykres_->setAxisTitle (QwtPlot::xBottom, \"Czas \/s\");\n\twykres_->setAxisTitle (QwtPlot::yLeft, \"Temperatura \/℃\");\n\twykres_->setCanvasBackground(QBrush (Qt::white));\n\twykres_->setAxisScale (QwtPlot::xBottom, 0, 120);\n\twykres_->setAxisScale (QwtPlot::yLeft, 0, 800);\n\t\n\tdanePomiaroweWykres_=new QwtPlotCurve;\n\t\n\tdanePomiaroweWykres_->setTitle(\"Temperatura\");\n\tdanePomiaroweWykres_->setPen(QPen(Qt::blue, 3) ),\n\tdanePomiaroweWykres_->setRenderHint(QwtPlotItem::RenderAntialiased, true);\t\n}\n\nbool GlowneOkno::wyslijRozkaz(const char* rozkaz)\n{\n\tQSerialPort::SerialPortError error;\n\tbool stan=true;\n\tdo\n\t{\n\t\terror=rs232_->error();\n\t\tif(error!=QSerialPort::NoError)\n\t\t{\n\t\t\tstan=obsluzBladRS(error);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstan=false;\n\t\t}\n\t}\n\twhile(stan);\n\t\n\tif(error==QSerialPort::NoError)\n\t{\n\t\trs232_->write(rozkaz);\n\t\treturn OK;\n\t}\n\treturn BLAD_PORTU;\n}\n\nvoid GlowneOkno::ustawTemperature(void)\n{\n\tchar tmp[4];\n\tint t=zadanaTemperatura_->value();\n\tsprintf(tmp,\"T%03i\",t);\n\t\n\tif(wyslijRozkaz(tmp)==OK)\n\t\tstd::cerr<readLine(tmpTekst,1023);\n\trs232_->clear();\n\tsscanf(tmpTekst,\"%u,%u,%s\",&(tmpCzas),&(tmpTemperatura),tmp);\n\t\n\tczas_.push_back((double)tmpCzas);\n\ttemperatura_.push_back((double)tmpTemperatura);\n\t\n\tdanePomiaroweWykres_->setSamples(czas_,temperatura_);\n\tdanePomiaroweWykres_->attach(wykres_);\n\t\n\tif(czas_.last()>120)\n\t\twykres_->setAxisScale (QwtPlot::xBottom, czas_.last()-120, czas_.last());\n\telse\n\t\twykres_->setAxisScale (QwtPlot::xBottom, 0, 120);\n\t\t\n\twykres_->replot();\n\tstd::cout<Przy odbiorze komunikatów z układu program będzie sprawdzał, czy wysyłana wiadomość jest wynikiem pomiaru. Ponieważ wyniki pomiarów mają stałą długość (liczby są uzupełniane zerami), to można kontrolować zgodność przez sprawdzenie, czy przecinki rozdzielające wartości występują w konkretnych punktach łańcucha znaków.#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"GlowneOkno.hpp\"\n#include \"WyborPortu.hpp\"\n#include \"KodyWyjsciowe.hpp\"\n\nconst char* bledy[14]=\n{\n\t\"Brak błędu\",\n\t\"Nie znaleziono urządzenia\",\n\t\"Brak uprawnień (być może port jest używany przez inny program)\",\n\t\"Port jest już otwarty\",\n\t\"Błąd parzystości\",\n\t\"Błąd ramki\",\n\t\"Błąd stanu przerwy (rodzaj błędu ramki)\",\n\t\"Ogólny błąd wysyłania\",\n\t\"Ogólny błąd odczytu\",\n\t\"Błąd zasobów (np. port został odłączony w czasie pracy programu)\",\n\t\"Niedozwolona operacja\",\n\t\"Nieznany błąd\",\n\t\"Upłynął limit czasu oczekiwania\",\n\t\"Port nie został prawidłowo otwarty\"\n};\n\nGlowneOkno::GlowneOkno(QWidget* parent):QMainWindow(parent)\n{\n\tsetupRS();\n\t\n\tsetupOkno();\n setupRozklad();\n setupWyslij();\n setupReset();\n setupTemperatura();\n setupWykres();\n \n okno_->show();\n}\n \nGlowneOkno::~GlowneOkno()\n{\n\tzadanaTemperatura_->setValue(0);\n\tustawTemperature();\n rs232_->close();\n \n delete rs232_;\n delete zadanaTemperatura_;\n delete wyslij_;\n delete reset_;\n delete wykres_;\n \/\/delete danePomiaroweWykres_;\n \n czas_.clear();\n temperatura_.clear();\n \n delete okno_;\n}\n\nvoid GlowneOkno::setupOkno(void)\n{\n\tokno_=new QWidget();\n\tokno_->resize(800,600);\n\tokno_->setWindowTitle(\"Kontroler temperatury\");\n}\n\nvoid GlowneOkno::setupRozklad(void)\n{\n\tglownyRozmieszczacz_=new QVBoxLayout(okno_);\n\tokno_->setLayout(glownyRozmieszczacz_);\n}\n\nvoid GlowneOkno::setupRS(void)\n{\n\trs232_=new QSerialPort(this);\n\tQStringList itemList;\n\tint wybor=QMessageBox::Retry;\n\tdo\n\t{\n\t\titemList.clear();\n\t\tQ_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts()) \n\t\t{\n\t\t\titemList<setPortName(dialog.poleKombi()->currentText());\n\t\tif(wynik==QDialog::Rejected)\n\t\t{\n\t\t\tQMessageBox(QMessageBox::Critical, \"Nie wybrano portu szeregowego!\", \"Koniec programu.\", QMessageBox::Ok).exec();\n\t\t\texit(2);\n\t\t}\n\t}\n\twhile(wynik != QDialog::Accepted);\n\t\n\trs232_->open (QIODevice::ReadWrite);\n\trs232_->setBaudRate (QSerialPort::Baud57600);\n\trs232_->setDataBits (QSerialPort::Data8);\n\trs232_->setStopBits (QSerialPort::OneStop);\n\trs232_->setParity (QSerialPort::NoParity);\n\trs232_->setFlowControl (QSerialPort::NoFlowControl);\n\trs232_->clear();\n std::cerr<error()<addWidget(zadanaTemperatura_);\n zadanaTemperatura_->setRange(0, 999);\n zadanaTemperatura_->setSingleStep(1);\n zadanaTemperatura_->setSuffix(\" ℃\"); \n}\n\nvoid GlowneOkno::setupWyslij(void)\n{\n\twyslij_=new QPushButton(\"Ustaw\");\n\twyslij_->setFixedSize(100,20);\n\tglownyRozmieszczacz_->addWidget(wyslij_);\n\t\n\tQObject::connect(wyslij_, SIGNAL(clicked(bool)),this, SLOT(ustawTemperature()));\n}\n\nvoid GlowneOkno::setupZatrzymajGrzanie(void)\n{\n\tzatrzymajGrzanie_=new QPushButton(\"ZatrzymajGrzanie\");\n\tzatrzymajGrzanie_->setFixedSize(100,20);\n\tglownyRozmieszczacz_->addWidget(zatrzymajGrzanie_);\n}\n\nvoid GlowneOkno::setupReset(void)\n{\n\treset_=new QPushButton(\"Reset\");\n\treset_->setFixedSize(100,20);\n\tglownyRozmieszczacz_->addWidget(reset_);\n\t\n\tQObject::connect(reset_, SIGNAL(clicked(bool)),this, SLOT(zrestartujUrzadenie()));\n}\n\nvoid GlowneOkno::setupWykres(void)\n{\n\twykres_=new QwtPlot;\n\tglownyRozmieszczacz_->addWidget(wykres_);\n\twykres_->setTitle (\"Bieżąca temperatura próbki\");\n\twykres_->setAxisTitle (QwtPlot::xBottom, \"Czas \/s\");\n\twykres_->setAxisTitle (QwtPlot::yLeft, \"Temperatura \/℃\");\n\twykres_->setCanvasBackground(QBrush (Qt::white));\n\twykres_->setAxisScale (QwtPlot::xBottom, 0, 120);\n\twykres_->setAxisScale (QwtPlot::yLeft, 0, 800);\n\t\n\tdanePomiaroweWykres_=new QwtPlotCurve;\n\t\n\tdanePomiaroweWykres_->setTitle(\"Temperatura\");\n\tdanePomiaroweWykres_->setPen(QPen(Qt::blue, 3) ),\n\tdanePomiaroweWykres_->setRenderHint(QwtPlotItem::RenderAntialiased, true);\t\n}\n\nbool GlowneOkno::wyslijRozkaz(const char* rozkaz)\n{\n\tQSerialPort::SerialPortError error;\n\tbool stan=true;\n\tdo\n\t{\n\t\terror=rs232_->error();\n\t\tif(error!=QSerialPort::NoError)\n\t\t{\n\t\t\tstan=obsluzBladRS(error);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstan=false;\n\t\t}\n\t}\n\twhile(stan);\n\t\n\tif(error==QSerialPort::NoError)\n\t{\n\t\trs232_->write(rozkaz);\n\t\treturn OK;\n\t}\n\treturn BLAD_PORTU;\n}\n\nvoid GlowneOkno::ustawTemperature(void)\n{\n\tchar tmp[4];\n\tint t=zadanaTemperatura_->value();\n\tsprintf(tmp,\"T%03i\",t);\n\t\n\tif(wyslijRozkaz(tmp)==OK)\n\t\tstd::cerr<readLine(tmpTekst,1023);\n\trs232_->clear();\n\t\n\tif((tmpTekst[10]==',')&&(tmpTekst[17]==','))\n\t{\n\t\tsscanf(tmpTekst,\"%u,%u,%s\",&(tmpCzas),&(tmpTemperatura),tmp);\n\t\n\t\tczas_.push_back((double)tmpCzas);\n\t\ttemperatura_.push_back((double)tmpTemperatura);\n\t\n\t\tdanePomiaroweWykres_->setSamples(czas_,temperatura_);\n\t\tdanePomiaroweWykres_->attach(wykres_);\n\t\n\t\tif(czas_.last()>120)\n\t\t\twykres_->setAxisScale (QwtPlot::xBottom, czas_.last()-120, czas_.last());\n\t\telse\n\t\t\twykres_->setAxisScale (QwtPlot::xBottom, 0, 120);\n\t\t\n\t\twykres_->replot();\n\t\tstd::cout<"} {"text":"#include \"seatest.h\"\n\n#include \n\n#include \"picture.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ EXTERNAL FUNCTIONS\nunsigned get_block_sad(picture *pic, picture *ref, \n int pic_x, int pic_y, int ref_x, int ref_y, \n int block_width, int block_height);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DEFINES\n#define TEST_SAD(X, Y) get_block_sad(g_pic, g_ref, 0, 0, (X), (Y), 8, 8)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GLOBALS\nconst uint8_t ref_data[64] = {\n 1,2,2,2,2,2,2,3,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 7,8,8,8,8,8,8,9\n};\n\nconst uint8_t pic_data[64] = {\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1\n};\n\npicture *g_pic = 0;\npicture *g_ref = 0;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SETUP, TEARDOWN AND HELPER FUNCTIONS\nvoid sad_setup(void)\n{\n unsigned i;\n g_pic = picture_init(8, 8, 1, 1);\n for (i = 0; i < 64; ++i) {\n g_pic->y_data[i] = pic_data[i] + 48;\n }\n\n g_ref = picture_init(8, 8, 1, 1);\n for (i = 0; i < 64; ++i) {\n g_ref->y_data[i] = ref_data[i] + 48;\n }\n}\n\nvoid sad_teardown(void)\n{\n free(g_pic); g_pic = 0;\n free(g_ref); g_ref = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TESTS\nvoid test_topleft(void)\n{\n assert_ulong_equal(\n 1*(4*4) + (2+4)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(-3, -3));\n}\n\nvoid test_top(void)\n{\n assert_ulong_equal(\n (1+3)*4 + 2*(6*4) + (4+6)*4 + 5*(6*4) - 64,\n TEST_SAD(0, -3));\n}\n\nvoid test_topright(void)\n{\n assert_ulong_equal(\n 3*(4*4) + (2+6)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(3, -3));\n}\n\nvoid test_left(void)\n{\n assert_ulong_equal(\n (1+7)*4 + 4*(6*4) + (2+8)*4 + 5*(6*4) - 64,\n TEST_SAD(-3, 0));\n}\n\nvoid test_no_offset(void)\n{\n assert_ulong_equal(\n (1+3+7+9) + (2+4+6+8)*6 + 5*(6*6) - 64,\n TEST_SAD(0, 0));\n}\n\nvoid test_right(void)\n{\n assert_ulong_equal(\n (3+9)*4 + 6*(4*6) + (2+8)*4 + 5*(6*4) - 64,\n TEST_SAD(3, 0));\n}\n\nvoid test_bottomleft(void)\n{\n assert_ulong_equal(\n 7*(4*4) + (4+8)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(-3, 3));\n}\n\nvoid test_bottom(void)\n{\n assert_ulong_equal(\n (7+9)*4 + 8*(6*4) + (4+6)*4 + 5*(6*4) - 64,\n TEST_SAD(0, 3));\n}\n\nvoid test_bottomright(void)\n{\n assert_ulong_equal(\n 9*(4*4) + (6+8)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(3, 3));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TEST FIXTURES\nvoid sad_tests(void)\n{\n test_fixture_start();\n fixture_setup(sad_setup);\n\n run_test(test_topleft);\n run_test(test_top);\n run_test(test_topright);\n\n run_test(test_left);\n run_test(test_no_offset);\n run_test(test_right);\n\n run_test(test_bottomleft);\n run_test(test_bottom);\n run_test(test_bottomright);\n\n fixture_teardown(sad_teardown);\n test_fixture_end();\n}\n\nAdd tests for movement vectors that are completely out of frame.#include \"seatest.h\"\n\n#include \n\n#include \"picture.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ EXTERNAL FUNCTIONS\nunsigned get_block_sad(picture *pic, picture *ref, \n int pic_x, int pic_y, int ref_x, int ref_y, \n int block_width, int block_height);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DEFINES\n#define TEST_SAD(X, Y) get_block_sad(g_pic, g_ref, 0, 0, (X), (Y), 8, 8)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ GLOBALS\nconst uint8_t ref_data[64] = {\n 1,2,2,2,2,2,2,3,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 4,5,5,5,5,5,5,6,\n 7,8,8,8,8,8,8,9\n};\n\nconst uint8_t pic_data[64] = {\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,1\n};\n\npicture *g_pic = 0;\npicture *g_ref = 0;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SETUP, TEARDOWN AND HELPER FUNCTIONS\nvoid sad_setup(void)\n{\n unsigned i;\n g_pic = picture_init(8, 8, 1, 1);\n for (i = 0; i < 64; ++i) {\n g_pic->y_data[i] = pic_data[i] + 48;\n }\n\n g_ref = picture_init(8, 8, 1, 1);\n for (i = 0; i < 64; ++i) {\n g_ref->y_data[i] = ref_data[i] + 48;\n }\n}\n\nvoid sad_teardown(void)\n{\n free(g_pic); g_pic = 0;\n free(g_ref); g_ref = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OVERLAPPING BOUNDARY TESTS\nvoid test_topleft(void)\n{\n assert_ulong_equal(\n 1*(4*4) + (2+4)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(-3, -3));\n}\n\nvoid test_top(void)\n{\n assert_ulong_equal(\n (1+3)*4 + 2*(6*4) + (4+6)*4 + 5*(6*4) - 64,\n TEST_SAD(0, -3));\n}\n\nvoid test_topright(void)\n{\n assert_ulong_equal(\n 3*(4*4) + (2+6)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(3, -3));\n}\n\nvoid test_left(void)\n{\n assert_ulong_equal(\n (1+7)*4 + 4*(6*4) + (2+8)*4 + 5*(6*4) - 64,\n TEST_SAD(-3, 0));\n}\n\nvoid test_no_offset(void)\n{\n assert_ulong_equal(\n (1+3+7+9) + (2+4+6+8)*6 + 5*(6*6) - 64,\n TEST_SAD(0, 0));\n}\n\nvoid test_right(void)\n{\n assert_ulong_equal(\n (3+9)*4 + 6*(4*6) + (2+8)*4 + 5*(6*4) - 64,\n TEST_SAD(3, 0));\n}\n\nvoid test_bottomleft(void)\n{\n assert_ulong_equal(\n 7*(4*4) + (4+8)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(-3, 3));\n}\n\nvoid test_bottom(void)\n{\n assert_ulong_equal(\n (7+9)*4 + 8*(6*4) + (4+6)*4 + 5*(6*4) - 64,\n TEST_SAD(0, 3));\n}\n\nvoid test_bottomright(void)\n{\n assert_ulong_equal(\n 9*(4*4) + (6+8)*(4*4) + 5*(4*4) - 64,\n TEST_SAD(3, 3));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OUT OF FRAME TESTS\n\nvoid test_topleft_out(void)\n{\n assert_ulong_equal(\n 1*(8*8) - 64,\n TEST_SAD(-8, -8));\n}\n\nvoid test_top_out(void)\n{\n assert_ulong_equal(\n (1+3)*8 + 2*(6*8) - 64,\n TEST_SAD(0, -8));\n}\n\nvoid test_topright_out(void)\n{\n assert_ulong_equal(\n 3*(8*8) - 64,\n TEST_SAD(8, -8));\n}\n\nvoid test_left_out(void)\n{\n assert_ulong_equal(\n (1+7)*8 + 4*(6*8) - 64,\n TEST_SAD(-8, 0));\n}\n\nvoid test_right_out(void)\n{\n assert_ulong_equal(\n (3+9)*8 + 6*(6*8) - 64,\n TEST_SAD(8, 0));\n}\n\nvoid test_bottomleft_out(void)\n{\n assert_ulong_equal(\n 7*(8*8) - 64,\n TEST_SAD(-8, 8));\n}\n\nvoid test_bottom_out(void)\n{\n assert_ulong_equal(\n (7+9)*8 + 8*(6*8) - 64,\n TEST_SAD(0, 8));\n}\n\nvoid test_bottomright_out(void)\n{\n assert_ulong_equal(\n 9*(8*8) - 64,\n TEST_SAD(8, 8));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TEST FIXTURES\nvoid sad_tests(void)\n{\n test_fixture_start();\n fixture_setup(sad_setup);\n\n\n \/\/ Tests for movement vectors that overlap frame.\n run_test(test_topleft);\n run_test(test_top);\n run_test(test_topright);\n\n run_test(test_left);\n run_test(test_no_offset);\n run_test(test_right);\n\n run_test(test_bottomleft);\n run_test(test_bottom);\n run_test(test_bottomright);\n\n \/\/ Tests for movement vectors that are outside the frame.\n run_test(test_topleft_out);\n run_test(test_top_out);\n run_test(test_topright_out);\n\n run_test(test_left_out);\n run_test(test_right_out);\n\n run_test(test_bottomleft_out);\n run_test(test_bottom_out);\n run_test(test_bottomright_out);\n\n\n fixture_teardown(sad_teardown);\n test_fixture_end();\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n\nusing namespace std;\n\n\n\nint main(int argc, char* argv[]) {\n string line;\n\tint linenumber = 0;\n\tint category =0;\n\tdouble value = 0.0;\n\tint errors = 0;\n\n\n if(argc < 2) {\n cerr << \"provide at least one argument\" << endl;\n return 1;\n }\n cout << \"* trying to open and read: \" << argv[1] << endl;\n\n ifstream f (argv[1]);\n\n\tdouble absValOne = 0.0;\n\n\tdouble aV1_1 = 0.0;\n\tdouble aV1_2 = 0.0;\n\n double absValTwo = 0.0;\n\n double aV2_1 = 0.0;\n double aV2_2 = 0.0;\n\n int wB1 = 0;\n int wB2 = 0;\n\n\tint cntOne = 0;\n\tint cntTwo = 0;\n\n int track = 0;\n\n\n while(getline(f, line)) {\n\t\tsize_t posr;\n track++;\n\n\t\tif((posr = line.find(\"#\")) == 0){\n\t\t\t\/\/std::cout << \"ignoring line\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(line[0] == '\\n'){\n\t\t\t\/\/std::cout << \"ignoring line\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\n std::string s = line;\n\t\tstd::string delimiter = \";\";\n\n\t\tint cat = 0;\n\t\tsize_t pos = 0;\n\t\tstd::string token;\n\n\n\t\twhile ((pos = s.find(delimiter)) != std::string::npos) {\n\n\t\t\ttoken = s.substr(0, pos);\n\n\t\t\tif(cat==0){\n\t\t\t\ttry{\n\t\t\t\t\tlinenumber = std::stoi(token);\n\t\t\t\t}catch(...){\n\t\t\t\t\terrors++;\n \/\/std::cout << \"linenumber\" << std::endl;\n \/\/std::cout << track << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcat=1;\n\t\t\t\ts.erase(0, pos + delimiter.length());\n\t\t\t}\n\n\t\t\telse if(cat==1){\n\t\t\t\ttry{\n\t\t\t\t\tcategory = std::stoi(token);\n\t\t\t\t}catch(...){\n\t\t\t\t\terrors++;\n \/\/std::cout << \"cat\" << std::endl;\n \/\/ std::cout << track << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\ts.erase(0, pos + delimiter.length());\n\n\t\t\t\ttry{\n\t\t\t\t\tvalue = std::stod(s);\n\n\t\t\t\t\t\/\/Checking if value is a proper double format\n\t\t\t\t\tif(!(value < 0.0 || value >= 0.0)){\n\t\t\t\t\t\terrors++;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\n if(value<=0){\n \/\/std::cout << \"errsth0\" << std::endl;\n break;\n }\n\n\t\t\t\t}catch(...){\n\t\t\t\t\terrors++;\n \/\/std::cout << \"val\" << std::endl;\n \/\/std::cout << track << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif(category==1){\n\t\t\t\t\tcntOne++;\n\t\t\t\t\tabsValOne+= log(value);\n\n\n\n\t\t\t\t}\n\t\t\t\telse if(category==2){\n\t\t\t\t\tcntTwo++;\n\t\t\t\t\tabsValTwo += log(value);\n\n\t\t\t\t}\n else break;\n\t\t\t\tcat=0;\n\n\n\t\t\t}\n\n\t\t}\n\n\t\t\/*if(linenumber%100000==0){\n\t\t\t\t\tstd::cout << linenumber << std::endl;\n\t\t\t\t\tstd::cout << \"Category One\" << std::endl;\n\t\t\t\t\tstd::cout << aV1_1 << std::endl;\n\t\t\t\t\tstd::cout << aV1_2 << std::endl;\n\t\t\t\t\tstd::cout << cntOne << std::endl;\n\t\t\t\t\tstd::cout << absValOne\/cntOne << std::endl;\n\t\t\t\t\tstd::cout << \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" << std::endl;\n\n\t\t\t\t\tstd::cout << \"Category Two\" << std::endl;\n\t\t\t\t\tstd::cout << aV2_1 << std::endl;\n\t\t\t\t\tstd::cout << aV2_2 << std::endl;\n\t\t\t\t\tstd::cout << cntTwo << std::endl;\n\t\t\t\t\tstd::cout << absValTwo\/cntTwo << std::endl;\n\t\t\t\t\tstd::cout << \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" << std::endl;\n\n\t\t\t\t\tstd::cout << \"Errors occured\" << std::endl;\n\t\t\t\t\tstd::cout << errors << std::endl;\n\t\t\t\t\tstd::cout << \"\\n\" << std::endl;\n\t\t\t}*\/\n\n\n }\n\n\tf.close();\n std::cout << \"Results:\" << std::endl;\n\tstd::cout << \"Category One\" << std::endl;\n\tstd::cout << \"Valid lines: \";\n\tstd::cout << cntOne << std::endl;\n\tstd::cout << \"Geo Mean: \";\n\t\/\/std::cout << exp(aV1_1\/cntOne + aV1_2\/cntOne) << std::endl;\n\tstd::cout << exp(absValOne\/cntOne) << std::endl;\n\tstd::cout << \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" << std::endl;\n\n\tstd::cout << \"Category Two\" << std::endl;\n\tstd::cout << \"Valid lines: \";\n\tstd::cout << cntTwo << std::endl;\n\tstd::cout << \"Geo Mean: \";\n\t\/\/std::cout << exp(aV2_1\/cntOne + aV2_2\/cntOne) << std::endl;\n\tstd::cout << exp(absValTwo\/cntTwo) << std::endl;\n\tstd::cout << \"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\" << std::endl;\n\n\tstd::cout << \"Errors occured\" << std::endl;\n\tstd::cout << errors << std::endl;\n\n\n return 0;\n}\n\n\n\n\nDelete ass01_01.cpp<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\/\/\n\/\/ ------------------------------------------------\n\/\/ Extrapolation Miniapp: PDE-based extrapolation\n\/\/ ------------------------------------------------\n\/\/\n\/\/ Compile with: make extrapolate\n\/\/\n\/\/ Sample runs:\n\/\/ mpirun -np 4 extrapolate -o 3\n\/\/ mpirun -np 4 extrapolate -rs 3 -dt 0.002 -o 2 -p 1\n\n#include \n#include \n#include \"..\/common\/mfem-common.hpp\"\n#include \"marking.hpp\"\n\nusing namespace std;\nusing namespace mfem;\n\nint problem = 0;\n\ndouble domainLS(const Vector &coord)\n{\n \/\/ Map from [0,1] to [-1,1].\n const int dim = coord.Size();\n const double x = coord(0)*2.0 - 1.0,\n y = coord(1)*2.0 - 1.0,\n z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;\n switch(problem)\n {\n case 0:\n {\n \/\/ 2d circle.\n return 0.75 - sqrt(x*x + y*y + 1e-12);\n }\n case 1:\n {\n \/\/ 2d star.\n return 0.60 - sqrt(x*x + y*y + 1e-12) +\n 0.25 * (y*y*y*y*y + 5.0*x*x*x*x*y - 10.0*x*x*y*y*y) \/\n pow(x*x + y*y + 1e-12, 2.5);\n }\n default: MFEM_ABORT(\"Bad option for --problem!\"); return 0.0;\n }\n}\n\ndouble solution0(const Vector &coord)\n{\n \/\/ Map from [0,1] to [-1,1].\n const int dim = coord.Size();\n const double x = coord(0)*2.0 - 1.0,\n y = coord(1)*2.0 - 1.0,\n z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;\n\n if (domainLS(coord) > 0.0)\n {\n return std::cos(M_PI * x) * std::sin(M_PI * y);\n }\n else { return 0.0; }\n}\n\nclass LevelSetNormalGradCoeff : public VectorCoefficient\n{\nprivate:\n const ParGridFunction &ls_gf;\n\npublic:\n LevelSetNormalGradCoeff(const ParGridFunction &ls) :\n VectorCoefficient(ls.ParFESpace()->GetMesh()->Dimension()), ls_gf(ls) { }\n\n virtual void Eval(Vector &V, ElementTransformation &T,\n const IntegrationPoint &ip)\n {\n Vector grad_ls(vdim), n(vdim);\n ls_gf.GetGradient(T, grad_ls);\n const double norm_grad = grad_ls.Norml2();\n V = grad_ls;\n if (norm_grad > 0.0) { V \/= norm_grad; }\n\n \/\/ Since positive level set values correspond to the known region, we\n \/\/ transport into the opposite direction of the gradient.\n V *= -1;\n }\n};\n\nclass NormalGradCoeff : public Coefficient\n{\nprivate:\n const ParGridFunction &u_gf;\n LevelSetNormalGradCoeff &n_coeff;\n\npublic:\n NormalGradCoeff(const ParGridFunction &u, LevelSetNormalGradCoeff &n) :\n u_gf(u), n_coeff(n) { }\n\n virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)\n {\n const int dim = T.GetDimension();\n Vector n(dim), grad_u(dim);\n n_coeff.Eval(n, T, ip);\n u_gf.GetGradient(T, grad_u);\n return n * grad_u;\n }\n\n};\n\nclass Extrapolator : public TimeDependentOperator\n{\nprivate:\n Array &active_zones;\n ParBilinearForm &M, &K;\n const Vector &b;\n Solver *M_prec;\n CGSolver M_solver;\n\npublic:\n Extrapolator(Array &zones,\n ParBilinearForm &Mbf, ParBilinearForm &Kbf, const Vector &rhs)\n : TimeDependentOperator(Mbf.Size()),\n active_zones(zones),\n M(Mbf), K(Kbf),\n b(rhs), M_prec(NULL), M_solver(M.ParFESpace()->GetComm()) { }\n\n virtual void Mult(const Vector &x, Vector &dx) const\n {\n K.BilinearForm::operator=(0.0);\n K.Assemble();\n\n ParFiniteElementSpace &pfes = *M.ParFESpace();\n const int NE = pfes.GetNE();\n const int nd = pfes.GetFE(0)->GetDof();\n\n Vector rhs(x.Size());\n HypreParMatrix *K_mat = K.ParallelAssemble(&K.SpMat());\n K_mat->Mult(x, rhs);\n rhs += b;\n\n Array dofs(nd);\n DenseMatrix M_loc(nd);\n DenseMatrixInverse M_loc_inv(&M_loc);\n Vector rhs_loc(nd), dx_loc(nd);\n for (int k = 0; k < NE; k++)\n {\n pfes.GetElementDofs(k, dofs);\n\n if (active_zones[k] == false)\n {\n dx.SetSubVector(dofs, 0.0);\n continue;\n }\n\n rhs.GetSubVector(dofs, rhs_loc);\n M.SpMat().GetSubMatrix(dofs, dofs, M_loc);\n M_loc_inv.Factor();\n M_loc_inv.Mult(rhs_loc, dx_loc);\n dx.SetSubVector(dofs, dx_loc);\n }\n }\n};\n\n\nint main(int argc, char *argv[])\n{\n \/\/ Initialize MPI.\n MPI_Session mpi;\n int myid = mpi.WorldRank();\n\n \/\/ Parse command-line options.\n const char *mesh_file = \"..\/..\/data\/inline-quad.mesh\";\n int rs_levels = 2;\n int order = 2;\n int ode_solver_type = 2;\n double dt = 0.005;\n bool visualization = true;\n int vis_steps = 5;\n\n OptionsParser args(argc, argv);\n args.AddOption(&mesh_file, \"-m\", \"--mesh\",\n \"Mesh file to use.\");\n args.AddOption(&rs_levels, \"-rs\", \"--refine-serial\",\n \"Number of times to refine the mesh uniformly in serial.\");\n args.AddOption(&order, \"-o\", \"--order\",\n \"Finite element order (polynomial degree) or -1 for\"\n \" isoparametric space.\");\n args.AddOption(&ode_solver_type, \"-s\", \"--ode-solver\",\n \"ODE solver: 1 - Forward Euler,\\n\\t\"\n \" 2 - RK2 SSP,\\n\\t\"\n \" 3 - RK3 SSP\");\n args.AddOption(&problem, \"-p\", \"--problem\",\n \"0 - 2D circle,\\n\\t\"\n \"1 - 2D star\");\n args.AddOption(&dt, \"-dt\", \"--time-step\", \"Time step.\");\n args.AddOption(&visualization, \"-vis\", \"--visualization\", \"-no-vis\",\n \"--no-visualization\",\n \"Enable or disable GLVis visualization.\");\n args.AddOption(&vis_steps, \"-vs\", \"--visualization-steps\",\n \"Visualize every n-th timestep.\");\n args.Parse();\n if (!args.Good())\n {\n if (myid == 0) { args.PrintUsage(cout); }\n return 1;\n }\n if (myid == 0) { args.PrintOptions(cout); }\n\n char vishost[] = \"localhost\";\n int visport = 19916, wsize = 500;\n socketstream sock_grad_u_n, sock_u;\n\n \/\/ Refine the mesh.\n Mesh mesh(mesh_file, 1, 1);\n for (int lev = 0; lev < rs_levels; lev++) { mesh.UniformRefinement(); }\n\n \/\/ MPI distribution.\n ParMesh pmesh(MPI_COMM_WORLD, mesh);\n mesh.Clear();\n const int dim = pmesh.Dimension(), NE = pmesh.GetNE();\n\n FunctionCoefficient ls_coeff(domainLS), u0_coeff(solution0);\n\n L2_FECollection fec_L2(order, dim, BasisType::GaussLobatto);\n ParFiniteElementSpace pfes_L2(&pmesh, &fec_L2);\n ParGridFunction u(&pfes_L2);\n u.ProjectCoefficient(u0_coeff);\n\n \/\/ Initialize the level set.\n H1_FECollection fec(order, dim);\n ParFiniteElementSpace pfes_H1(&pmesh, &fec);\n ParGridFunction level_set(&pfes_H1);\n level_set.ProjectCoefficient(ls_coeff);\n if (visualization)\n {\n socketstream sol_sock_w;\n common::VisualizeField(sol_sock_w, vishost, visport, level_set,\n \"Domain level set\", 0, 0, wsize, wsize,\n \"rRjmm********A\");\n MPI_Barrier(pmesh.GetComm());\n }\n \/\/ Setup a VectorCoefficient for n = - grad_ls \/ |grad_ls|.\n \/\/ The sign makes it point out of the known region.\n LevelSetNormalGradCoeff ls_n_coeff(level_set);\n\n \/\/ Mark elements.\n Array elem_marker, dofs;\n ShiftedFaceMarker marker(pmesh, pfes_L2, false);\n level_set.ExchangeFaceNbrData();\n marker.MarkElements(level_set, elem_marker);\n\n \/\/ Trim to the known values (only elements inside the known region).\n ParGridFunction u_known(u);\n for (int k = 0; k < NE; k++)\n {\n pfes_L2.GetElementDofs(k, dofs);\n if (elem_marker[k] != ShiftedFaceMarker::INSIDE)\n { u_known.SetSubVector(dofs, 0.0); }\n }\n if (visualization)\n {\n socketstream sol_socks;\n common::VisualizeField(sol_socks, vishost, visport, u_known,\n \"Fixed (known) u values\", wsize, 0, wsize, wsize,\n \"rRjmm********A\");\n }\n u = u_known;\n\n \/\/ Normal derivative function.\n ParGridFunction grad_u_n(&pfes_L2);\n NormalGradCoeff grad_u_n_coeff(u, ls_n_coeff);\n grad_u_n.ProjectCoefficient(grad_u_n_coeff);\n if (visualization)\n {\n socketstream sol_sock;\n common::VisualizeField(sol_sock, vishost, visport, grad_u_n,\n \"grad_u n\", 2*wsize, 0, wsize, wsize,\n \"rRjmm********A\");\n }\n\n \/\/ The active zones are where we extrapolate (where the PDE is solved).\n Array active_zones(NE);\n for (int k = 0; k < NE; k++)\n {\n \/\/ Extrapolation is done in zones that are CUT or OUTSIDE.\n active_zones[k] = (elem_marker[k] == ShiftedFaceMarker::INSIDE) ? false : true;\n }\n\n ParBilinearForm lhs_bf(&pfes_L2), rhs_bf(&pfes_L2);\n lhs_bf.AddDomainIntegrator(new MassIntegrator);\n const double alpha = -1.0;\n rhs_bf.AddDomainIntegrator(new ConvectionIntegrator(ls_n_coeff, alpha));\n auto trace_i = new NonconservativeDGTraceIntegrator(ls_n_coeff, alpha);\n rhs_bf.AddInteriorFaceIntegrator(trace_i);\n rhs_bf.KeepNbrBlock(true);\n\n lhs_bf.Assemble();\n lhs_bf.Finalize();\n rhs_bf.Assemble(0);\n rhs_bf.Finalize(0);\n\n Vector rhs(pfes_L2.GetVSize());\n rhs = 0.0;\n\n \/\/ Time loop\n double t = 0.0;\n ODESolver *ode_solver = NULL;\n switch (ode_solver_type)\n {\n case 1: ode_solver = new ForwardEulerSolver; break;\n case 2: ode_solver = new RK2Solver(1.0); break;\n case 3: ode_solver = new RK3SSPSolver; break;\n default:\n {\n if (myid == 0)\n { cout << \"Unknown ODE solver type: \" << ode_solver_type << '\\n'; }\n return 3;\n }\n }\n\n Extrapolator ext(active_zones, lhs_bf, rhs_bf, rhs);\n ode_solver->Init(ext);\n\n bool done = false;\n const double t_final = 0.4;\n for (int ti = 0; !done;)\n {\n double dt_real = min(dt, t_final - t);\n ode_solver->Step(grad_u_n, t, dt_real);\n ti++;\n\n done = (t >= t_final - 1e-8*dt);\n\n if (done || ti % vis_steps == 0)\n {\n if (myid == 0)\n {\n cout << \"time step: \" << ti << \", time: \" << t << endl;\n }\n\n if (visualization)\n {\n common::VisualizeField(sock_grad_u_n, vishost, visport, grad_u_n,\n \"Solution\", 2*wsize, 570, wsize, wsize,\n \"rRjmm********A\");\n MPI_Barrier(pmesh.GetComm());\n }\n }\n }\n\n lhs_bf.Mult(grad_u_n, rhs);\n done = false;\n t = 0.0;\n for (int ti = 0; !done;)\n {\n double dt_real = min(dt, t_final - t);\n ode_solver->Step(u, t, dt_real);\n ti++;\n\n done = (t >= t_final - 1e-8*dt);\n\n if (done || ti % vis_steps == 0)\n {\n if (myid == 0)\n {\n cout << \"time step: \" << ti << \", time: \" << t << endl;\n }\n\n if (visualization)\n {\n common::VisualizeField(sock_u, vishost, visport, u,\n \"Solution\", wsize, 570, wsize, wsize,\n \"rRjmm********A\");\n MPI_Barrier(pmesh.GetComm());\n }\n }\n }\n\n \/\/ ParaView output.\n ParaViewDataCollection dacol(\"ParaViewExtrapolate\", &pmesh);\n dacol.SetLevelsOfDetail(order);\n dacol.RegisterField(\"filtered_level_set\", &level_set);\n dacol.SetTime(1.0);\n dacol.SetCycle(1);\n dacol.Save();\n\n return 0;\n}\nAutomatic dt calculation.\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\/\/\n\/\/ ------------------------------------------------\n\/\/ Extrapolation Miniapp: PDE-based extrapolation\n\/\/ ------------------------------------------------\n\/\/\n\/\/ Compile with: make extrapolate\n\/\/\n\/\/ Sample runs:\n\/\/ mpirun -np 4 extrapolate -o 3\n\/\/ mpirun -np 4 extrapolate -rs 3 -o 2 -p 1\n\n#include \n#include \n#include \"..\/common\/mfem-common.hpp\"\n#include \"marking.hpp\"\n\nusing namespace std;\nusing namespace mfem;\n\nint problem = 0;\n\ndouble domainLS(const Vector &coord)\n{\n \/\/ Map from [0,1] to [-1,1].\n const int dim = coord.Size();\n const double x = coord(0)*2.0 - 1.0,\n y = coord(1)*2.0 - 1.0,\n z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;\n switch(problem)\n {\n case 0:\n {\n \/\/ 2d circle.\n return 0.75 - sqrt(x*x + y*y + 1e-12);\n }\n case 1:\n {\n \/\/ 2d star.\n return 0.60 - sqrt(x*x + y*y + 1e-12) +\n 0.25 * (y*y*y*y*y + 5.0*x*x*x*x*y - 10.0*x*x*y*y*y) \/\n pow(x*x + y*y + 1e-12, 2.5);\n }\n default: MFEM_ABORT(\"Bad option for --problem!\"); return 0.0;\n }\n}\n\ndouble solution0(const Vector &coord)\n{\n \/\/ Map from [0,1] to [-1,1].\n const int dim = coord.Size();\n const double x = coord(0)*2.0 - 1.0,\n y = coord(1)*2.0 - 1.0,\n z = (dim > 2) ? coord(2)*2.0 - 1.0 : 0.0;\n\n if (domainLS(coord) > 0.0)\n {\n return std::cos(M_PI * x) * std::sin(M_PI * y);\n }\n else { return 0.0; }\n}\n\nclass LevelSetNormalGradCoeff : public VectorCoefficient\n{\nprivate:\n const ParGridFunction &ls_gf;\n\npublic:\n LevelSetNormalGradCoeff(const ParGridFunction &ls) :\n VectorCoefficient(ls.ParFESpace()->GetMesh()->Dimension()), ls_gf(ls) { }\n\n virtual void Eval(Vector &V, ElementTransformation &T,\n const IntegrationPoint &ip)\n {\n Vector grad_ls(vdim), n(vdim);\n ls_gf.GetGradient(T, grad_ls);\n const double norm_grad = grad_ls.Norml2();\n V = grad_ls;\n if (norm_grad > 0.0) { V \/= norm_grad; }\n\n \/\/ Since positive level set values correspond to the known region, we\n \/\/ transport into the opposite direction of the gradient.\n V *= -1;\n }\n};\n\nclass NormalGradCoeff : public Coefficient\n{\nprivate:\n const ParGridFunction &u_gf;\n LevelSetNormalGradCoeff &n_coeff;\n\npublic:\n NormalGradCoeff(const ParGridFunction &u, LevelSetNormalGradCoeff &n) :\n u_gf(u), n_coeff(n) { }\n\n virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)\n {\n const int dim = T.GetDimension();\n Vector n(dim), grad_u(dim);\n n_coeff.Eval(n, T, ip);\n u_gf.GetGradient(T, grad_u);\n return n * grad_u;\n }\n\n};\n\nclass Extrapolator : public TimeDependentOperator\n{\nprivate:\n Array &active_zones;\n ParBilinearForm &M, &K;\n const Vector &b;\n Solver *M_prec;\n CGSolver M_solver;\n\npublic:\n Extrapolator(Array &zones,\n ParBilinearForm &Mbf, ParBilinearForm &Kbf, const Vector &rhs)\n : TimeDependentOperator(Mbf.Size()),\n active_zones(zones),\n M(Mbf), K(Kbf),\n b(rhs), M_prec(NULL), M_solver(M.ParFESpace()->GetComm()) { }\n\n virtual void Mult(const Vector &x, Vector &dx) const\n {\n K.BilinearForm::operator=(0.0);\n K.Assemble();\n\n ParFiniteElementSpace &pfes = *M.ParFESpace();\n const int NE = pfes.GetNE();\n const int nd = pfes.GetFE(0)->GetDof();\n\n Vector rhs(x.Size());\n HypreParMatrix *K_mat = K.ParallelAssemble(&K.SpMat());\n K_mat->Mult(x, rhs);\n rhs += b;\n\n Array dofs(nd);\n DenseMatrix M_loc(nd);\n DenseMatrixInverse M_loc_inv(&M_loc);\n Vector rhs_loc(nd), dx_loc(nd);\n for (int k = 0; k < NE; k++)\n {\n pfes.GetElementDofs(k, dofs);\n\n if (active_zones[k] == false)\n {\n dx.SetSubVector(dofs, 0.0);\n continue;\n }\n\n rhs.GetSubVector(dofs, rhs_loc);\n M.SpMat().GetSubMatrix(dofs, dofs, M_loc);\n M_loc_inv.Factor();\n M_loc_inv.Mult(rhs_loc, dx_loc);\n dx.SetSubVector(dofs, dx_loc);\n }\n }\n};\n\nint main(int argc, char *argv[])\n{\n \/\/ Initialize MPI.\n MPI_Session mpi;\n int myid = mpi.WorldRank();\n\n \/\/ Parse command-line options.\n const char *mesh_file = \"..\/..\/data\/inline-quad.mesh\";\n int rs_levels = 2;\n int order = 2;\n int ode_solver_type = 2;\n bool visualization = true;\n int vis_steps = 5;\n\n OptionsParser args(argc, argv);\n args.AddOption(&mesh_file, \"-m\", \"--mesh\",\n \"Mesh file to use.\");\n args.AddOption(&rs_levels, \"-rs\", \"--refine-serial\",\n \"Number of times to refine the mesh uniformly in serial.\");\n args.AddOption(&order, \"-o\", \"--order\",\n \"Finite element order (polynomial degree) or -1 for\"\n \" isoparametric space.\");\n args.AddOption(&ode_solver_type, \"-s\", \"--ode-solver\",\n \"ODE solver: 1 - Forward Euler,\\n\\t\"\n \" 2 - RK2 SSP,\\n\\t\"\n \" 3 - RK3 SSP\");\n args.AddOption(&problem, \"-p\", \"--problem\",\n \"0 - 2D circle,\\n\\t\"\n \"1 - 2D star\");\n args.AddOption(&visualization, \"-vis\", \"--visualization\", \"-no-vis\",\n \"--no-visualization\",\n \"Enable or disable GLVis visualization.\");\n args.AddOption(&vis_steps, \"-vs\", \"--visualization-steps\",\n \"Visualize every n-th timestep.\");\n args.Parse();\n if (!args.Good())\n {\n if (myid == 0) { args.PrintUsage(cout); }\n return 1;\n }\n if (myid == 0) { args.PrintOptions(cout); }\n\n char vishost[] = \"localhost\";\n int visport = 19916, wsize = 500;\n socketstream sock_grad_u_n, sock_u;\n\n \/\/ Refine the mesh.\n Mesh mesh(mesh_file, 1, 1);\n for (int lev = 0; lev < rs_levels; lev++) { mesh.UniformRefinement(); }\n\n \/\/ MPI distribution.\n ParMesh pmesh(MPI_COMM_WORLD, mesh);\n mesh.Clear();\n const int dim = pmesh.Dimension(), NE = pmesh.GetNE();\n\n FunctionCoefficient ls_coeff(domainLS), u0_coeff(solution0);\n\n L2_FECollection fec_L2(order, dim, BasisType::GaussLobatto);\n ParFiniteElementSpace pfes_L2(&pmesh, &fec_L2);\n ParGridFunction u(&pfes_L2);\n u.ProjectCoefficient(u0_coeff);\n\n \/\/ Initialize the level set.\n H1_FECollection fec(order, dim);\n ParFiniteElementSpace pfes_H1(&pmesh, &fec);\n ParGridFunction level_set(&pfes_H1);\n level_set.ProjectCoefficient(ls_coeff);\n if (visualization)\n {\n socketstream sol_sock_w;\n common::VisualizeField(sol_sock_w, vishost, visport, level_set,\n \"Domain level set\", 0, 0, wsize, wsize,\n \"rRjmm********A\");\n MPI_Barrier(pmesh.GetComm());\n }\n \/\/ Setup a VectorCoefficient for n = - grad_ls \/ |grad_ls|.\n \/\/ The sign makes it point out of the known region.\n LevelSetNormalGradCoeff ls_n_coeff(level_set);\n\n \/\/ Mark elements.\n Array elem_marker, dofs;\n ShiftedFaceMarker marker(pmesh, pfes_L2, false);\n level_set.ExchangeFaceNbrData();\n marker.MarkElements(level_set, elem_marker);\n\n \/\/ Trim to the known values (only elements inside the known region).\n ParGridFunction u_known(u);\n for (int k = 0; k < NE; k++)\n {\n pfes_L2.GetElementDofs(k, dofs);\n if (elem_marker[k] != ShiftedFaceMarker::INSIDE)\n { u_known.SetSubVector(dofs, 0.0); }\n }\n if (visualization)\n {\n socketstream sol_socks;\n common::VisualizeField(sol_socks, vishost, visport, u_known,\n \"Fixed (known) u values\", wsize, 0, wsize, wsize,\n \"rRjmm********A\");\n }\n u = u_known;\n\n \/\/ Normal derivative function.\n ParGridFunction grad_u_n(&pfes_L2);\n NormalGradCoeff grad_u_n_coeff(u, ls_n_coeff);\n grad_u_n.ProjectCoefficient(grad_u_n_coeff);\n if (visualization)\n {\n socketstream sol_sock;\n common::VisualizeField(sol_sock, vishost, visport, grad_u_n,\n \"grad_u n\", 2*wsize, 0, wsize, wsize,\n \"rRjmm********A\");\n }\n\n \/\/ The active zones are where we extrapolate (where the PDE is solved).\n Array active_zones(NE);\n for (int k = 0; k < NE; k++)\n {\n \/\/ Extrapolation is done in zones that are CUT or OUTSIDE.\n active_zones[k] = (elem_marker[k] == ShiftedFaceMarker::INSIDE) ? false : true;\n }\n\n ParBilinearForm lhs_bf(&pfes_L2), rhs_bf(&pfes_L2);\n lhs_bf.AddDomainIntegrator(new MassIntegrator);\n const double alpha = -1.0;\n rhs_bf.AddDomainIntegrator(new ConvectionIntegrator(ls_n_coeff, alpha));\n auto trace_i = new NonconservativeDGTraceIntegrator(ls_n_coeff, alpha);\n rhs_bf.AddInteriorFaceIntegrator(trace_i);\n rhs_bf.KeepNbrBlock(true);\n\n lhs_bf.Assemble();\n lhs_bf.Finalize();\n rhs_bf.Assemble(0);\n rhs_bf.Finalize(0);\n\n Vector rhs(pfes_L2.GetVSize());\n rhs = 0.0;\n\n \/\/ Compute a CFL time step.\n double h_min = std::numeric_limits::infinity();\n for (int k = 0; k < NE; k++)\n {\n h_min = std::min(h_min, pmesh.GetElementSize(k));\n }\n MPI_Allreduce(MPI_IN_PLACE, &h_min, 1, MPI_DOUBLE, MPI_MIN,\n pfes_L2.GetComm());\n h_min \/= order;\n \/\/ The propagation speed is 1.\n double dt = 0.25 * h_min \/ 1.0;\n\n \/\/ Time loop\n double t = 0.0;\n ODESolver *ode_solver = NULL;\n switch (ode_solver_type)\n {\n case 1: ode_solver = new ForwardEulerSolver; break;\n case 2: ode_solver = new RK2Solver(1.0); break;\n case 3: ode_solver = new RK3SSPSolver; break;\n default:\n {\n if (myid == 0)\n { cout << \"Unknown ODE solver type: \" << ode_solver_type << '\\n'; }\n return 3;\n }\n }\n\n Extrapolator ext(active_zones, lhs_bf, rhs_bf, rhs);\n ode_solver->Init(ext);\n\n bool done = false;\n const double t_final = 0.4;\n for (int ti = 0; !done;)\n {\n double dt_real = min(dt, t_final - t);\n ode_solver->Step(grad_u_n, t, dt_real);\n ti++;\n\n done = (t >= t_final - 1e-8*dt);\n\n if (done || ti % vis_steps == 0)\n {\n if (myid == 0)\n {\n cout << \"time step: \" << ti << \", time: \" << t << endl;\n }\n\n if (visualization)\n {\n common::VisualizeField(sock_grad_u_n, vishost, visport, grad_u_n,\n \"Solution\", 2*wsize, 570, wsize, wsize,\n \"rRjmm********A\");\n MPI_Barrier(pmesh.GetComm());\n }\n }\n }\n\n lhs_bf.Mult(grad_u_n, rhs);\n done = false;\n t = 0.0;\n for (int ti = 0; !done;)\n {\n double dt_real = min(dt, t_final - t);\n ode_solver->Step(u, t, dt_real);\n ti++;\n\n done = (t >= t_final - 1e-8*dt);\n\n if (done || ti % vis_steps == 0)\n {\n if (myid == 0)\n {\n cout << \"time step: \" << ti << \", time: \" << t << endl;\n }\n\n if (visualization)\n {\n common::VisualizeField(sock_u, vishost, visport, u,\n \"Solution\", wsize, 570, wsize, wsize,\n \"rRjmm********A\");\n MPI_Barrier(pmesh.GetComm());\n }\n }\n }\n\n \/\/ ParaView output.\n ParaViewDataCollection dacol(\"ParaViewExtrapolate\", &pmesh);\n dacol.SetLevelsOfDetail(order);\n dacol.RegisterField(\"filtered_level_set\", &level_set);\n dacol.SetTime(1.0);\n dacol.SetCycle(1);\n dacol.Save();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"player.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid init(vector &nums, vector &teams, vector &input, vector &roster);\r\n\r\n\/\/use is .\/program.exe file.csv rosters.txt\r\nint main(int argc, char* argv[]) \r\n{\r\n\tifstream statsin(argv[1]); \/\/ input player stats .csv file\r\n\tifstream playersin(argv[2]); \/\/ input team rosters\r\n\r\n\tstring x;\r\n\tvector input; \/\/ vector of player stats \r\n\tvector players; \/\/\r\n\tvector roster; \/\/ vector of team roster\r\n\tvector obs; \/\/ vector of player objects\r\n\tvector nums; \/\/ vecotr of available numbers\r\n\tvector teams; \/\/\r\n\r\n\tinit(nums, teams, input, roster); \/\/ initialize player numbers and NFL teams\t\r\n\r\n\tfor(int i=0; i &nums, vector &teams, vector &input, vector &roster){\r\n\tnums.push_back(\"1\");\r\n\tnums.push_back(\"2\");\r\n\tnums.push_back(\"3\");\r\n\tnums.push_back(\"4\");\r\n\tnums.push_back(\"5\");\r\n\tnums.push_back(\"6\");\r\n\tnums.push_back(\"7\");\r\n\tnums.push_back(\"8\");\r\n\tnums.push_back(\"9\");\r\n\tnums.push_back(\"0\");\r\n\tteams.push_back(\"ARI\");\r\n\tteams.push_back(\"ATL\");\r\n\tteams.push_back(\"BAL\");\r\n\tteams.push_back(\"BUF\");\r\n\tteams.push_back(\"CAR\");\r\n\tteams.push_back(\"CHI\");\r\n\tteams.push_back(\"CIN\");\r\n\tteams.push_back(\"CLE\");\r\n\tteams.push_back(\"DAL\");\r\n\tteams.push_back(\"DEN\");\r\n\tteams.push_back(\"DET\");\r\n\tteams.push_back(\"GB\");\r\n\tteams.push_back(\"HOU\");\r\n\tteams.push_back(\"IND\");\r\n\tteams.push_back(\"JAX\");\r\n\tteams.push_back(\"KC\");\r\n\tteams.push_back(\"MIA\");\r\n\tteams.push_back(\"MIN\");\r\n\tteams.push_back(\"NE\");\r\n\tteams.push_back(\"NO\");\r\n\tteams.push_back(\"NYG\");\r\n\tteams.push_back(\"NYJ\")\r\n\tteams.push_back(\"OAK\");\r\n\tteams.push_back(\"PHI\");\r\n\tteams.push_back(\"PIT\");\r\n\tteams.push_back(\"SD\");\r\n\tteams.push_back(\"SEA\");\r\n\tteams.push_back(\"SF\");\r\n\tteams.push_back(\"STL\");\r\n\tteams.push_back(\"TB\");\r\n\tteams.push_back(\"TEN\");\r\n\tteams.push_back(\"WAS\");\r\n\t\r\n\twhile(statsin >> x) \/\/ pushback player stats to a vector\r\n\t{\r\n\t\tinput.push_back(x);\r\n\t}\r\n\twhile(playersin >> x) \/\/ pushback player names to a vector\r\n\t{\r\n\t\troster.push_back(x);\r\n\t}\r\n}\r\n\r\n\r\n\r\nMinor fix#include \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#include \"player.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid init(vector &nums, vector &teams, vector &input, vector &roster, ifstream &statsin, ifstream &playersin);\r\n\r\n\/\/use is .\/program.exe file.csv rosters.txt\r\nint main(int argc, char* argv[]) \r\n{\r\n\tifstream statsin(argv[1]); \/\/ input player stats .csv file\r\n\tifstream playersin(argv[2]); \/\/ input team rosters\r\n\r\n\tvector input; \/\/ vector of player stats \r\n\tvector players; \/\/\r\n\tvector roster; \/\/ vector of team roster\r\n\tvector obs; \/\/ vector of player objects\r\n\tvector nums; \/\/ vecotr of available numbers\r\n\tvector teams; \/\/\r\n\r\n\tinit(nums, teams, input, roster,statsin,playersin); \/\/ initialize player numbers and NFL teams\t\r\n\r\n\tfor(int i=0; i &nums, vector &teams, vector &input, vector &roster, ifstream &statsin, ifstream &playersin)\r\n{\r\n\tstring x;\r\n\tnums.push_back(\"1\");\r\n\tnums.push_back(\"2\");\r\n\tnums.push_back(\"3\");\r\n\tnums.push_back(\"4\");\r\n\tnums.push_back(\"5\");\r\n\tnums.push_back(\"6\");\r\n\tnums.push_back(\"7\");\r\n\tnums.push_back(\"8\");\r\n\tnums.push_back(\"9\");\r\n\tnums.push_back(\"0\");\r\n\tteams.push_back(\"ARI\");\r\n\tteams.push_back(\"ATL\");\r\n\tteams.push_back(\"BAL\");\r\n\tteams.push_back(\"BUF\");\r\n\tteams.push_back(\"CAR\");\r\n\tteams.push_back(\"CHI\");\r\n\tteams.push_back(\"CIN\");\r\n\tteams.push_back(\"CLE\");\r\n\tteams.push_back(\"DAL\");\r\n\tteams.push_back(\"DEN\");\r\n\tteams.push_back(\"DET\");\r\n\tteams.push_back(\"GB\");\r\n\tteams.push_back(\"HOU\");\r\n\tteams.push_back(\"IND\");\r\n\tteams.push_back(\"JAX\");\r\n\tteams.push_back(\"KC\");\r\n\tteams.push_back(\"MIA\");\r\n\tteams.push_back(\"MIN\");\r\n\tteams.push_back(\"NE\");\r\n\tteams.push_back(\"NO\");\r\n\tteams.push_back(\"NYG\");\r\n\tteams.push_back(\"NYJ\");\r\n\tteams.push_back(\"OAK\");\r\n\tteams.push_back(\"PHI\");\r\n\tteams.push_back(\"PIT\");\r\n\tteams.push_back(\"SD\");\r\n\tteams.push_back(\"SEA\");\r\n\tteams.push_back(\"SF\");\r\n\tteams.push_back(\"STL\");\r\n\tteams.push_back(\"TB\");\r\n\tteams.push_back(\"TEN\");\r\n\tteams.push_back(\"WAS\");\r\n\t\r\n\twhile(statsin >> x) \/\/ pushback player stats to a vector\r\n\t{\r\n\t\tinput.push_back(x);\r\n\t}\r\n\twhile(playersin >> x) \/\/ pushback player names to a vector\r\n\t{\r\n\t\troster.push_back(x);\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"#include \"material.h\"\n\n#include \n\n#include \"comp_math.h\"\n#include \"context.h\"\n#include \"decayer.h\"\n#include \"error.h\"\n#include \"logger.h\"\n\nnamespace cyclus {\n\nconst ResourceType Material::kType = \"Material\";\n\nMaterial::~Material() {}\n\nMaterial::Ptr Material::Create(Agent* creator, double quantity,\n Composition::Ptr c) {\n Material::Ptr m(new Material(creator->context(), quantity, c));\n m->tracker_.Create(creator);\n return m;\n}\n\nMaterial::Ptr Material::CreateUntracked(double quantity,\n Composition::Ptr c) {\n Material::Ptr m(new Material(NULL, quantity, c));\n return m;\n}\n\nint Material::qual_id() const {\n return comp_->id();\n}\n\nconst ResourceType Material::type() const {\n return Material::kType;\n}\n\nResource::Ptr Material::Clone() const {\n Material* m = new Material(*this);\n Resource::Ptr c(m);\n m->tracker_.DontTrack();\n return c;\n}\n\nvoid Material::Record(Context* ctx) const {\n \/\/ Note that no time field is needed because the resource ID changes\n \/\/ every time the resource changes - state_id by itself is already unique.\n ctx_->NewDatum(\"MaterialInfo\")\n ->AddVal(\"ResourceId\", state_id())\n ->AddVal(\"PrevDecayTime\", prev_decay_time_)\n ->Record();\n\n comp_->Record(ctx);\n}\n\nstd::string Material::units() const {\n return \"kg\";\n}\n\ndouble Material::quantity() const {\n return qty_;\n}\n\nResource::Ptr Material::ExtractRes(double qty) {\n return boost::static_pointer_cast(ExtractQty(qty));\n}\n\nMaterial::Ptr Material::ExtractQty(double qty) {\n return ExtractComp(qty, comp_);\n}\n\nMaterial::Ptr Material::ExtractComp(double qty, Composition::Ptr c,\n double threshold) {\n if (qty_ < qty) {\n throw ValueError(\"mass extraction causes negative quantity\");\n }\n if (comp_ != c) {\n CompMap v(comp_->mass());\n compmath::Normalize(&v, qty_);\n CompMap otherv(c->mass());\n compmath::Normalize(&otherv, qty);\n CompMap newv = compmath::Sub(v, otherv);\n compmath::ApplyThreshold(&newv, threshold);\n comp_ = Composition::CreateFromMass(newv);\n }\n\n qty_ -= qty;\n\n Material::Ptr other(new Material(ctx_, qty, c));\n\n tracker_.Extract(&other->tracker_);\n\n return other;\n}\n\nvoid Material::Absorb(Material::Ptr mat) {\n if (comp_ != mat->comp()) {\n CompMap v(comp_->mass());\n compmath::Normalize(&v, qty_);\n CompMap otherv(mat->comp()->mass());\n compmath::Normalize(&otherv, mat->quantity());\n comp_ = Composition::CreateFromMass(compmath::Add(v, otherv));\n }\n qty_ += mat->qty_;\n mat->qty_ = 0;\n tracker_.Absorb(&mat->tracker_);\n}\n\nvoid Material::Transmute(Composition::Ptr c) {\n comp_ = c;\n tracker_.Modify();\n}\n\nvoid Material::Decay(int curr_time) {\n int dt = curr_time - prev_decay_time_;\n double eps = 1e-3;\n bool decay = false;\n\n const CompMap c = comp_->atom();\n if (c.size() > 100) {\n decay = true;\n } else {\n CompMap::const_iterator it;\n for (it = c.end(); it != c.begin(); --it) {\n int nuc = it->first;\n \/\/ 2419200 == secs \/ month\n double lambda_months = pyne::decay_const(nuc) * 2419200;\n\n if (eps <= 1 - std::exp(-lambda_months * dt)) {\n decay = true;\n break;\n }\n }\n }\n\n if (decay) {\n prev_decay_time_ = curr_time;\n if (dt > 0) {\n Transmute(comp_->Decay(dt));\n }\n }\n}\n\nComposition::Ptr Material::comp() const {\n return comp_;\n}\n\nMaterial::Material(Context* ctx, double quantity, Composition::Ptr c)\n : qty_(quantity),\n comp_(c),\n tracker_(ctx, this),\n ctx_(ctx),\n prev_decay_time_(0) {\n if (ctx != NULL) {\n prev_decay_time_ = ctx->time();\n } else {\n tracker_.DontTrack();\n }\n}\n\nMaterial::Ptr NewBlankMaterial(double quantity) {\n Composition::Ptr comp = Composition::CreateFromMass(CompMap());\n return Material::CreateUntracked(quantity, comp);\n}\n\n} \/\/ namespace cyclus\nonly decay if decayallowed is true#include \"material.h\"\n\n#include \n\n#include \"comp_math.h\"\n#include \"context.h\"\n#include \"decayer.h\"\n#include \"error.h\"\n#include \"logger.h\"\n\nnamespace cyclus {\n\nconst ResourceType Material::kType = \"Material\";\n\nMaterial::~Material() {}\n\nMaterial::Ptr Material::Create(Agent* creator, double quantity,\n Composition::Ptr c) {\n Material::Ptr m(new Material(creator->context(), quantity, c));\n m->tracker_.Create(creator);\n return m;\n}\n\nMaterial::Ptr Material::CreateUntracked(double quantity,\n Composition::Ptr c) {\n Material::Ptr m(new Material(NULL, quantity, c));\n return m;\n}\n\nint Material::qual_id() const {\n return comp_->id();\n}\n\nconst ResourceType Material::type() const {\n return Material::kType;\n}\n\nResource::Ptr Material::Clone() const {\n Material* m = new Material(*this);\n Resource::Ptr c(m);\n m->tracker_.DontTrack();\n return c;\n}\n\nvoid Material::Record(Context* ctx) const {\n \/\/ Note that no time field is needed because the resource ID changes\n \/\/ every time the resource changes - state_id by itself is already unique.\n ctx_->NewDatum(\"MaterialInfo\")\n ->AddVal(\"ResourceId\", state_id())\n ->AddVal(\"PrevDecayTime\", prev_decay_time_)\n ->Record();\n\n comp_->Record(ctx);\n}\n\nstd::string Material::units() const {\n return \"kg\";\n}\n\ndouble Material::quantity() const {\n return qty_;\n}\n\nResource::Ptr Material::ExtractRes(double qty) {\n return boost::static_pointer_cast(ExtractQty(qty));\n}\n\nMaterial::Ptr Material::ExtractQty(double qty) {\n return ExtractComp(qty, comp_);\n}\n\nMaterial::Ptr Material::ExtractComp(double qty, Composition::Ptr c,\n double threshold) {\n if (qty_ < qty) {\n throw ValueError(\"mass extraction causes negative quantity\");\n }\n if (comp_ != c) {\n CompMap v(comp_->mass());\n compmath::Normalize(&v, qty_);\n CompMap otherv(c->mass());\n compmath::Normalize(&otherv, qty);\n CompMap newv = compmath::Sub(v, otherv);\n compmath::ApplyThreshold(&newv, threshold);\n comp_ = Composition::CreateFromMass(newv);\n }\n\n qty_ -= qty;\n\n Material::Ptr other(new Material(ctx_, qty, c));\n\n tracker_.Extract(&other->tracker_);\n\n return other;\n}\n\nvoid Material::Absorb(Material::Ptr mat) {\n if (comp_ != mat->comp()) {\n CompMap v(comp_->mass());\n compmath::Normalize(&v, qty_);\n CompMap otherv(mat->comp()->mass());\n compmath::Normalize(&otherv, mat->quantity());\n comp_ = Composition::CreateFromMass(compmath::Add(v, otherv));\n }\n qty_ += mat->qty_;\n mat->qty_ = 0;\n tracker_.Absorb(&mat->tracker_);\n}\n\nvoid Material::Transmute(Composition::Ptr c) {\n comp_ = c;\n tracker_.Modify();\n}\n\nvoid Material::Decay(int curr_time) {\n if (context()->decay() == true) {\n int dt = curr_time - prev_decay_time_;\n double eps = 1e-3;\n bool decay = false;\n \n const CompMap c = comp_->atom();\n if (c.size() > 100) {\n decay = true;\n } else {\n CompMap::const_iterator it;\n for (it = c.end(); it != c.begin(); --it) {\n int nuc = it->first;\n \/\/ 2419200 == secs \/ month\n double lambda_months = pyne::decay_const(nuc) * 2419200;\n \n if (eps <= 1 - std::exp(-lambda_months * dt)) {\n decay = true;\n break;\n }\n }\n }\n \n if (decay) {\n prev_decay_time_ = curr_time;\n if (dt > 0) {\n Transmute(comp_->Decay(dt));\n }\n }\n }\n}\n\nComposition::Ptr Material::comp() const {\n return comp_;\n}\n\nMaterial::Material(Context* ctx, double quantity, Composition::Ptr c)\n : qty_(quantity),\n comp_(c),\n tracker_(ctx, this),\n ctx_(ctx),\n prev_decay_time_(0) {\n if (ctx != NULL) {\n prev_decay_time_ = ctx->time();\n } else {\n tracker_.DontTrack();\n }\n}\n\nMaterial::Ptr NewBlankMaterial(double quantity) {\n Composition::Ptr comp = Composition::CreateFromMass(CompMap());\n return Material::CreateUntracked(quantity, comp);\n}\n\n} \/\/ namespace cyclus\n<|endoftext|>"} {"text":"#include \"ff_source_syntax.h\"\n\n#include \n#include \n\n#include \"sentence_metadata.h\"\n#include \"array2d.h\"\n#include \"filelib.h\"\n\nusing namespace std;\n\n\/\/ implements the source side syntax features described in Blunsom et al. (EMNLP 2008)\n\/\/ source trees must be represented in Penn Treebank format, e.g.\n\/\/ (S (NP John) (VP (V left)))\n\n\/\/ log transform to make long spans cluster together\n\/\/ but preserve differences\ninline int SpanSizeTransform(unsigned span_size) {\n if (!span_size) return 0;\n return static_cast(log(span_size+1) \/ log(1.39)) - 1;\n}\n\nstruct SourceSyntaxFeaturesImpl {\n SourceSyntaxFeaturesImpl() {}\n\n void InitializeGrids(const string& tree, unsigned src_len) {\n assert(tree.size() > 0);\n \/\/fids_cat.clear();\n fids_ef.clear();\n src_tree.clear();\n \/\/fids_cat.resize(src_len, src_len + 1);\n fids_ef.resize(src_len, src_len + 1);\n src_tree.resize(src_len, src_len + 1, TD::Convert(\"XX\"));\n ParseTreeString(tree, src_len);\n }\n\n void ParseTreeString(const string& tree, unsigned src_len) {\n stack > stk; \/\/ first = i, second = category\n pair cur_cat; cur_cat.first = -1;\n unsigned i = 0;\n unsigned p = 0;\n while(p < tree.size()) {\n const char cur = tree[p];\n if (cur == '(') {\n stk.push(cur_cat);\n ++p;\n unsigned k = p + 1;\n while (k < tree.size() && tree[k] != ' ') { ++k; }\n cur_cat.first = i;\n cur_cat.second = TD::Convert(tree.substr(p, k - p));\n \/\/ cerr << \"NT: '\" << tree.substr(p, k-p) << \"' (i=\" << i << \")\\n\";\n p = k + 1;\n } else if (cur == ')') {\n unsigned k = p;\n while (k < tree.size() && tree[k] == ')') { ++k; }\n const unsigned num_closes = k - p;\n for (unsigned ci = 0; ci < num_closes; ++ci) {\n \/\/ cur_cat.second spans from cur_cat.first to i\n \/\/ cerr << TD::Convert(cur_cat.second) << \" from \" << cur_cat.first << \" to \" << i << endl;\n \/\/ NOTE: unary rule chains end up being labeled with the top-most category\n src_tree(cur_cat.first, i) = cur_cat.second;\n cur_cat = stk.top();\n stk.pop();\n }\n p = k;\n while (p < tree.size() && (tree[p] == ' ' || tree[p] == '\\t')) { ++p; }\n } else if (cur == ' ' || cur == '\\t') {\n cerr << \"Unexpected whitespace in: \" << tree << endl;\n abort();\n } else { \/\/ terminal symbol\n unsigned k = p + 1;\n do {\n while (k < tree.size() && tree[k] != ')' && tree[k] != ' ') { ++k; }\n \/\/ cerr << \"TERM: '\" << tree.substr(p, k-p) << \"' (i=\" << i << \")\\n\";\n ++i;\n assert(i <= src_len);\n while (k < tree.size() && tree[k] == ' ') { ++k; }\n p = k;\n } while (p < tree.size() && tree[p] != ')');\n }\n }\n \/\/ cerr << \"i=\" << i << \" src_len=\" << src_len << endl;\n assert(i == src_len); \/\/ make sure tree specified in src_tree is\n \/\/ the same length as the source sentence\n }\n\n WordID FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector* feats) {\n \/\/cerr << \"fire features: \" << rule.AsString() << \" for \" << i << \",\" << j << endl;\n const WordID lhs = src_tree(i,j);\n \/\/int& fid_cat = fids_cat(i,j);\n int& fid_ef = fids_ef(i,j)[&rule];\n if (fid_ef <= 0) {\n ostringstream os;\n \/\/ostringstream os2;\n os << \"SYN:\" << TD::Convert(lhs);\n \/\/os2 << \"SYN:\" << TD::Convert(lhs) << '_' << SpanSizeTransform(j - i);\n \/\/fid_cat = FD::Convert(os2.str());\n os << ':';\n unsigned ntc = 0;\n for (unsigned k = 0; k < rule.f_.size(); ++k) {\n if (k > 0) os << '_';\n int fj = rule.f_[k];\n if (fj <= 0) {\n os << '[' << TD::Convert(ants[ntc++]) << ']';\n } else {\n os << TD::Convert(fj);\n }\n }\n os << ':';\n for (unsigned k = 0; k < rule.e_.size(); ++k) {\n const int ei = rule.e_[k];\n if (k > 0) os << '_';\n if (ei <= 0)\n os << '[' << (1-ei) << ']';\n else\n os << TD::Convert(ei);\n }\n fid_ef = FD::Convert(os.str());\n }\n \/\/if (fid_cat > 0)\n \/\/ feats->set_value(fid_cat, 1.0);\n if (fid_ef > 0)\n feats->set_value(fid_ef, 1.0);\n return lhs;\n }\n\n Array2D src_tree; \/\/ src_tree(i,j) NT = type\n \/\/ mutable Array2D fids_cat; \/\/ this tends to overfit baddly\n mutable Array2D > fids_ef; \/\/ fires for fully lexicalized\n};\n\nSourceSyntaxFeatures::SourceSyntaxFeatures(const string& param) :\n FeatureFunction(sizeof(WordID)) {\n impl = new SourceSyntaxFeaturesImpl;\n}\n\nSourceSyntaxFeatures::~SourceSyntaxFeatures() {\n delete impl;\n impl = NULL;\n}\n\nvoid SourceSyntaxFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,\n const Hypergraph::Edge& edge,\n const vector& ant_contexts,\n SparseVector* features,\n SparseVector* estimated_features,\n void* context) const {\n WordID ants[8];\n for (unsigned i = 0; i < ant_contexts.size(); ++i)\n ants[i] = *static_cast(ant_contexts[i]);\n\n *static_cast(context) =\n impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);\n}\n\nvoid SourceSyntaxFeatures::PrepareForInput(const SentenceMetadata& smeta) {\n impl->InitializeGrids(smeta.GetSGMLValue(\"src_tree\"), smeta.GetSourceLength());\n}\n\nstruct SourceSpanSizeFeaturesImpl {\n SourceSpanSizeFeaturesImpl() {}\n\n void InitializeGrids(unsigned src_len) {\n fids.clear();\n fids.resize(src_len, src_len + 1);\n }\n\n int FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector* feats) {\n if (rule.Arity() > 0) {\n int& fid = fids(i,j)[&rule];\n if (fid <= 0) {\n ostringstream os;\n os << \"SSS:\";\n unsigned ntc = 0;\n for (unsigned k = 0; k < rule.f_.size(); ++k) {\n if (k > 0) os << '_';\n int fj = rule.f_[k];\n if (fj <= 0) {\n os << '[' << TD::Convert(-fj) << ants[ntc++] << ']';\n } else {\n os << TD::Convert(fj);\n }\n }\n fid = FD::Convert(os.str());\n }\n if (fid > 0)\n feats->set_value(fid, 1.0);\n }\n return SpanSizeTransform(j - i);\n }\n\n mutable Array2D > fids;\n};\n\nSourceSpanSizeFeatures::SourceSpanSizeFeatures(const string& param) :\n FeatureFunction(sizeof(char)) {\n impl = new SourceSpanSizeFeaturesImpl;\n}\n\nSourceSpanSizeFeatures::~SourceSpanSizeFeatures() {\n delete impl;\n impl = NULL;\n}\n\nvoid SourceSpanSizeFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,\n const Hypergraph::Edge& edge,\n const vector& ant_contexts,\n SparseVector* features,\n SparseVector* estimated_features,\n void* context) const {\n int ants[8];\n for (unsigned i = 0; i < ant_contexts.size(); ++i)\n ants[i] = *static_cast(ant_contexts[i]);\n\n *static_cast(context) =\n impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);\n}\n\nvoid SourceSpanSizeFeatures::PrepareForInput(const SentenceMetadata& smeta) {\n impl->InitializeGrids(smeta.GetSourceLength());\n}\n\n\nadd target side for sss features#include \"ff_source_syntax.h\"\n\n#include \n#include \n\n#include \"sentence_metadata.h\"\n#include \"array2d.h\"\n#include \"filelib.h\"\n\nusing namespace std;\n\n\/\/ implements the source side syntax features described in Blunsom et al. (EMNLP 2008)\n\/\/ source trees must be represented in Penn Treebank format, e.g.\n\/\/ (S (NP John) (VP (V left)))\n\n\/\/ log transform to make long spans cluster together\n\/\/ but preserve differences\ninline int SpanSizeTransform(unsigned span_size) {\n if (!span_size) return 0;\n return static_cast(log(span_size+1) \/ log(1.39)) - 1;\n}\n\nstruct SourceSyntaxFeaturesImpl {\n SourceSyntaxFeaturesImpl() {}\n\n void InitializeGrids(const string& tree, unsigned src_len) {\n assert(tree.size() > 0);\n \/\/fids_cat.clear();\n fids_ef.clear();\n src_tree.clear();\n \/\/fids_cat.resize(src_len, src_len + 1);\n fids_ef.resize(src_len, src_len + 1);\n src_tree.resize(src_len, src_len + 1, TD::Convert(\"XX\"));\n ParseTreeString(tree, src_len);\n }\n\n void ParseTreeString(const string& tree, unsigned src_len) {\n stack > stk; \/\/ first = i, second = category\n pair cur_cat; cur_cat.first = -1;\n unsigned i = 0;\n unsigned p = 0;\n while(p < tree.size()) {\n const char cur = tree[p];\n if (cur == '(') {\n stk.push(cur_cat);\n ++p;\n unsigned k = p + 1;\n while (k < tree.size() && tree[k] != ' ') { ++k; }\n cur_cat.first = i;\n cur_cat.second = TD::Convert(tree.substr(p, k - p));\n \/\/ cerr << \"NT: '\" << tree.substr(p, k-p) << \"' (i=\" << i << \")\\n\";\n p = k + 1;\n } else if (cur == ')') {\n unsigned k = p;\n while (k < tree.size() && tree[k] == ')') { ++k; }\n const unsigned num_closes = k - p;\n for (unsigned ci = 0; ci < num_closes; ++ci) {\n \/\/ cur_cat.second spans from cur_cat.first to i\n \/\/ cerr << TD::Convert(cur_cat.second) << \" from \" << cur_cat.first << \" to \" << i << endl;\n \/\/ NOTE: unary rule chains end up being labeled with the top-most category\n src_tree(cur_cat.first, i) = cur_cat.second;\n cur_cat = stk.top();\n stk.pop();\n }\n p = k;\n while (p < tree.size() && (tree[p] == ' ' || tree[p] == '\\t')) { ++p; }\n } else if (cur == ' ' || cur == '\\t') {\n cerr << \"Unexpected whitespace in: \" << tree << endl;\n abort();\n } else { \/\/ terminal symbol\n unsigned k = p + 1;\n do {\n while (k < tree.size() && tree[k] != ')' && tree[k] != ' ') { ++k; }\n \/\/ cerr << \"TERM: '\" << tree.substr(p, k-p) << \"' (i=\" << i << \")\\n\";\n ++i;\n assert(i <= src_len);\n while (k < tree.size() && tree[k] == ' ') { ++k; }\n p = k;\n } while (p < tree.size() && tree[p] != ')');\n }\n }\n \/\/ cerr << \"i=\" << i << \" src_len=\" << src_len << endl;\n assert(i == src_len); \/\/ make sure tree specified in src_tree is\n \/\/ the same length as the source sentence\n }\n\n WordID FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector* feats) {\n \/\/cerr << \"fire features: \" << rule.AsString() << \" for \" << i << \",\" << j << endl;\n const WordID lhs = src_tree(i,j);\n \/\/int& fid_cat = fids_cat(i,j);\n int& fid_ef = fids_ef(i,j)[&rule];\n if (fid_ef <= 0) {\n ostringstream os;\n \/\/ostringstream os2;\n os << \"SYN:\" << TD::Convert(lhs);\n \/\/os2 << \"SYN:\" << TD::Convert(lhs) << '_' << SpanSizeTransform(j - i);\n \/\/fid_cat = FD::Convert(os2.str());\n os << ':';\n unsigned ntc = 0;\n for (unsigned k = 0; k < rule.f_.size(); ++k) {\n if (k > 0) os << '_';\n int fj = rule.f_[k];\n if (fj <= 0) {\n os << '[' << TD::Convert(ants[ntc++]) << ']';\n } else {\n os << TD::Convert(fj);\n }\n }\n os << ':';\n for (unsigned k = 0; k < rule.e_.size(); ++k) {\n const int ei = rule.e_[k];\n if (k > 0) os << '_';\n if (ei <= 0)\n os << '[' << (1-ei) << ']';\n else\n os << TD::Convert(ei);\n }\n fid_ef = FD::Convert(os.str());\n }\n \/\/if (fid_cat > 0)\n \/\/ feats->set_value(fid_cat, 1.0);\n if (fid_ef > 0)\n feats->set_value(fid_ef, 1.0);\n return lhs;\n }\n\n Array2D src_tree; \/\/ src_tree(i,j) NT = type\n \/\/ mutable Array2D fids_cat; \/\/ this tends to overfit baddly\n mutable Array2D > fids_ef; \/\/ fires for fully lexicalized\n};\n\nSourceSyntaxFeatures::SourceSyntaxFeatures(const string& param) :\n FeatureFunction(sizeof(WordID)) {\n impl = new SourceSyntaxFeaturesImpl;\n}\n\nSourceSyntaxFeatures::~SourceSyntaxFeatures() {\n delete impl;\n impl = NULL;\n}\n\nvoid SourceSyntaxFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,\n const Hypergraph::Edge& edge,\n const vector& ant_contexts,\n SparseVector* features,\n SparseVector* estimated_features,\n void* context) const {\n WordID ants[8];\n for (unsigned i = 0; i < ant_contexts.size(); ++i)\n ants[i] = *static_cast(ant_contexts[i]);\n\n *static_cast(context) =\n impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);\n}\n\nvoid SourceSyntaxFeatures::PrepareForInput(const SentenceMetadata& smeta) {\n impl->InitializeGrids(smeta.GetSGMLValue(\"src_tree\"), smeta.GetSourceLength());\n}\n\nstruct SourceSpanSizeFeaturesImpl {\n SourceSpanSizeFeaturesImpl() {}\n\n void InitializeGrids(unsigned src_len) {\n fids.clear();\n fids.resize(src_len, src_len + 1);\n }\n\n int FireFeatures(const TRule& rule, const int i, const int j, const WordID* ants, SparseVector* feats) {\n if (rule.Arity() > 0) {\n int& fid = fids(i,j)[&rule];\n if (fid <= 0) {\n ostringstream os;\n os << \"SSS:\";\n unsigned ntc = 0;\n for (unsigned k = 0; k < rule.f_.size(); ++k) {\n if (k > 0) os << '_';\n int fj = rule.f_[k];\n if (fj <= 0) {\n os << '[' << TD::Convert(-fj) << ants[ntc++] << ']';\n } else {\n os << TD::Convert(fj);\n }\n }\n os << ':';\n for (unsigned k = 0; k < rule.e_.size(); ++k) {\n const int ei = rule.e_[k];\n if (k > 0) os << '_';\n if (ei <= 0)\n os << '[' << (1-ei) << ']';\n else\n os << TD::Convert(ei);\n }\n fid = FD::Convert(os.str());\n }\n if (fid > 0)\n feats->set_value(fid, 1.0);\n }\n return SpanSizeTransform(j - i);\n }\n\n mutable Array2D > fids;\n};\n\nSourceSpanSizeFeatures::SourceSpanSizeFeatures(const string& param) :\n FeatureFunction(sizeof(char)) {\n impl = new SourceSpanSizeFeaturesImpl;\n}\n\nSourceSpanSizeFeatures::~SourceSpanSizeFeatures() {\n delete impl;\n impl = NULL;\n}\n\nvoid SourceSpanSizeFeatures::TraversalFeaturesImpl(const SentenceMetadata& smeta,\n const Hypergraph::Edge& edge,\n const vector& ant_contexts,\n SparseVector* features,\n SparseVector* estimated_features,\n void* context) const {\n int ants[8];\n for (unsigned i = 0; i < ant_contexts.size(); ++i)\n ants[i] = *static_cast(ant_contexts[i]);\n\n *static_cast(context) =\n impl->FireFeatures(*edge.rule_, edge.i_, edge.j_, ants, features);\n}\n\nvoid SourceSpanSizeFeatures::PrepareForInput(const SentenceMetadata& smeta) {\n impl->InitializeGrids(smeta.GetSourceLength());\n}\n\n\n<|endoftext|>"} {"text":"#include \"message.hpp\"\n#include \"server.hpp\"\n#include \"Cereal.hpp\"\n#include \n#include \n\nusing namespace std;\n\n\nMqttFixedHeader::MqttFixedHeader():\n type(), dup(), qos(), retain(), remaining() {\n}\n\nMqttFixedHeader::MqttFixedHeader(MqttType t, bool d, ubyte q, bool rt, uint re):\n type(t), dup(d), qos(q), retain(rt), remaining(re) {\n}\n\nvoid MqttFixedHeader::cerealise(Cereal& cereal) {\n cereal.grainBits(type, 4);\n cereal.grainBits(dup, 1);\n cereal.grainBits(qos, 2);\n cereal.grainBits(retain, 1);\n\n switch(cereal.getType()) {\n case Cereal::Type::Write:\n setRemainingSize(cereal);\n break;\n\n case Cereal::Type::Read:\n remaining = getRemainingSize(cereal);\n break;\n }\n}\n\nuint MqttFixedHeader::getRemainingSize(Cereal& cereal) {\n \/\/algorithm straight from the MQTT spec\n int multiplier = 1;\n uint value = 0;\n ubyte digit;\n do {\n cereal.grain(digit);\n value += (digit & 127) * multiplier;\n multiplier *= 128;\n } while((digit & 128) != 0);\n\n return value;\n}\n\nvoid MqttFixedHeader::setRemainingSize(Cereal& cereal) const {\n \/\/algorithm straight from the MQTT spec\n vector digits;\n uint x = remaining;\n do {\n ubyte digit = x % 128;\n x \/= 128;\n if(x > 0) {\n digit = digit | 0x80;\n }\n digits.push_back(digit);\n } while(x > 0);\n\n for(auto b: digits) cereal.grain(b);\n}\n\n\nclass MqttConnect: public MqttMessage {\n public:\n\n MqttConnect(MqttFixedHeader h):header(h) { }\n\n void cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(protoName);\n cereal.grain(protoVersion);\n\n cereal.grainBits(hasUserName, 1);\n cereal.grainBits(hasPassword, 1);\n cereal.grainBits(hasWillRetain, 1);\n cereal.grainBits(willQos, 2);\n cereal.grainBits(hasWill, 1);\n cereal.grainBits(hasClear, 1);\n cereal.grainBits(reserved, 1);\n\n cereal.grain(keepAlive);\n cereal.grain(clientId);\n\n if(hasWill) cereal.grain(willTopic);\n if(hasWill) cereal.grain(willMessage);\n if(hasUserName) cereal.grain(userName);\n if(hasPassword) cereal.grain(password);\n }\n\n bool isBadClientId() const { return clientId.length() < 1 || clientId.length() > 23; }\n\n MqttFixedHeader header;\n string protoName;\n ubyte protoVersion;\n bool hasUserName; \/\/1\n bool hasPassword; \/\/1\n bool hasWillRetain; \/\/1\n ubyte willQos; \/\/2\n bool hasWill; \/\/1\n bool hasClear; \/\/1\n bool reserved; \/\/1\n ushort keepAlive;\n string clientId;\n string willTopic;\n string willMessage;\n string userName;\n string password;\n};\n\n\nclass MqttConnack: public MqttMessage {\npublic:\n enum class Code {\n ACCEPTED = 0,\n BAD_VERSION = 1,\n BAD_ID = 2,\n SERVER_UNAVAILABLE = 3,\n BAD_USER_OR_PWD = 4,\n NO_AUTH = 5,\n };\n\n MqttConnack():\n header(MqttType::CONNACK, false, 0, false, 2) {\n }\n\n MqttConnack(Code c):\n MqttConnack() {\n code = c;\n }\n\n void cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(reserved);\n cereal.grainBits(code, 8);\n }\n\n MqttFixedHeader header;\n ubyte reserved;\n Code code;\n};\n\n\nclass MqttPublish: public MqttMessage {\npublic:\n MqttPublish(MqttFixedHeader h):header(h) {\n\n }\n\n MqttPublish(string topic, std::vector payload, ushort msgId = 0):\n MqttPublish(false, 0, false, topic, payload, msgId) {\n }\n\n MqttPublish(bool dup, ubyte qos, bool retain, string t, std::vector p, ushort mid = 0) {\n const auto topicLen = t.length() + 2; \/\/2 for length\n auto remaining = qos ? topicLen + 2 \/*msgId*\/ : topicLen;\n remaining += p.size();\n\n header = MqttFixedHeader(MqttType::PUBLISH, dup, qos, retain, remaining);\n topic = t;\n payload = std::move(p);\n msgId = mid;\n }\n\n void cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(topic);\n\n auto payloadLen = header.remaining - (topic.length() + MqttFixedHeader::SIZE);\n if(header.qos) {\n if(header.remaining < 7 && cereal.getType() == Cereal::Type::Read) {\n cerr << \"Error: PUBLISH message with QOS but no message ID\" << endl;\n } else {\n cereal.grain(msgId);\n payloadLen -= 2;\n }\n }\n if(cereal.getType() == Cereal::Type::Read) payload.resize(payloadLen);\n for(auto& b: payload) cereal.grain(b);\n }\n\n void handle(MqttServer& server, MqttConnection& connection) const override {\n (void)connection;\n server.publish(topic, payload);\n }\n\n MqttFixedHeader header;\n string topic;\n std::vector payload;\n ushort msgId;\n};\n\n\nMqttSubscribe::MqttSubscribe(MqttFixedHeader h):header(h) {\n\n}\n\nvoid MqttSubscribe::handle(MqttServer& server, MqttConnection& connection) const {\n server.subscribe(connection, msgId, topics);\n}\n\nvoid MqttSubscribe::Topic::cerealise(Cereal& cereal) {\n cereal.grain(topic);\n cereal.grain(qos);\n}\n\n\nvoid MqttSubscribe::cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(msgId);\n ushort size;\n cereal.grain(size);\n if(topics.size() != size) topics.resize(size);\n for(auto& t: topics) cereal.grain(t);\n}\n\n\n\/\/ class MqttSuback: MqttMessage {\n\/\/ public:\n\n\/\/ this(MqttFixedHeader header) {\n\/\/ this.header = header;\n\/\/ }\n\n\/\/ this(in ushort msgId, in std::vector qos) {\n\/\/ this.header = MqttFixedHeader(MqttType.SUBACK, false, 0, false, cast(uint)qos.length + 2);\n\/\/ this.msgId = msgId;\n\/\/ this.qos = qos.dup;\n\/\/ }\n\n\/\/ MqttFixedHeader header;\n\/\/ ushort msgId;\n\/\/ @RawArray std::vector qos;\n\/\/ }\n\n\/\/ class MqttUnsubscribe: MqttMessage {\n\/\/ this(MqttFixedHeader header) {\n\/\/ this.header = header;\n\/\/ }\n\n\/\/ override void handle(MqttServer server, MqttConnection connection) const {\n\/\/ server.unsubscribe(connection, msgId, topics);\n\/\/ }\n\n\/\/ MqttFixedHeader header;\n\/\/ ushort msgId;\n\/\/ @RawArray string[] topics;\n\/\/ }\n\n\/\/ class MqttUnsuback: MqttMessage {\n\/\/ this(in ushort msgId) {\n\/\/ this.header = MqttFixedHeader(MqttType.UNSUBACK, false, 0, false, 2);\n\/\/ this.msgId = msgId;\n\/\/ }\n\n\/\/ this(MqttFixedHeader header) {\n\/\/ this.header = header;\n\/\/ }\n\n\/\/ MqttFixedHeader header;\n\/\/ ushort msgId;\n\/\/ }\n\n\/\/ class MqttDisconnect: MqttMessage {\n\/\/ override void handle(MqttServer server, MqttConnection connection) const {\n\/\/ server.unsubscribe(connection);\n\/\/ connection.disconnect();\n\/\/ }\n\/\/ }\n\n\/\/ class MqttPingReq: MqttMessage {\n\/\/ override void handle(MqttServer server, MqttConnection connection) const {\n\/\/ server.ping(connection);\n\/\/ }\n\/\/ }\n\n\/\/ class MqttPingResp: MqttMessage {\n\/\/ const(std::vector) encode() const {\n\/\/ return [0xd0, 0x00];\n\/\/ }\n\/\/ }\nUncommented MqttSuback#include \"message.hpp\"\n#include \"server.hpp\"\n#include \"Cereal.hpp\"\n#include \n#include \n\nusing namespace std;\n\n\nMqttFixedHeader::MqttFixedHeader():\n type(), dup(), qos(), retain(), remaining() {\n}\n\nMqttFixedHeader::MqttFixedHeader(MqttType t, bool d, ubyte q, bool rt, uint re):\n type(t), dup(d), qos(q), retain(rt), remaining(re) {\n}\n\nvoid MqttFixedHeader::cerealise(Cereal& cereal) {\n cereal.grainBits(type, 4);\n cereal.grainBits(dup, 1);\n cereal.grainBits(qos, 2);\n cereal.grainBits(retain, 1);\n\n switch(cereal.getType()) {\n case Cereal::Type::Write:\n setRemainingSize(cereal);\n break;\n\n case Cereal::Type::Read:\n remaining = getRemainingSize(cereal);\n break;\n }\n}\n\nuint MqttFixedHeader::getRemainingSize(Cereal& cereal) {\n \/\/algorithm straight from the MQTT spec\n int multiplier = 1;\n uint value = 0;\n ubyte digit;\n do {\n cereal.grain(digit);\n value += (digit & 127) * multiplier;\n multiplier *= 128;\n } while((digit & 128) != 0);\n\n return value;\n}\n\nvoid MqttFixedHeader::setRemainingSize(Cereal& cereal) const {\n \/\/algorithm straight from the MQTT spec\n vector digits;\n uint x = remaining;\n do {\n ubyte digit = x % 128;\n x \/= 128;\n if(x > 0) {\n digit = digit | 0x80;\n }\n digits.push_back(digit);\n } while(x > 0);\n\n for(auto b: digits) cereal.grain(b);\n}\n\n\nclass MqttConnect: public MqttMessage {\n public:\n\n MqttConnect(MqttFixedHeader h):header(h) { }\n\n void cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(protoName);\n cereal.grain(protoVersion);\n\n cereal.grainBits(hasUserName, 1);\n cereal.grainBits(hasPassword, 1);\n cereal.grainBits(hasWillRetain, 1);\n cereal.grainBits(willQos, 2);\n cereal.grainBits(hasWill, 1);\n cereal.grainBits(hasClear, 1);\n cereal.grainBits(reserved, 1);\n\n cereal.grain(keepAlive);\n cereal.grain(clientId);\n\n if(hasWill) cereal.grain(willTopic);\n if(hasWill) cereal.grain(willMessage);\n if(hasUserName) cereal.grain(userName);\n if(hasPassword) cereal.grain(password);\n }\n\n bool isBadClientId() const { return clientId.length() < 1 || clientId.length() > 23; }\n\n MqttFixedHeader header;\n string protoName;\n ubyte protoVersion;\n bool hasUserName; \/\/1\n bool hasPassword; \/\/1\n bool hasWillRetain; \/\/1\n ubyte willQos; \/\/2\n bool hasWill; \/\/1\n bool hasClear; \/\/1\n bool reserved; \/\/1\n ushort keepAlive;\n string clientId;\n string willTopic;\n string willMessage;\n string userName;\n string password;\n};\n\n\nclass MqttConnack: public MqttMessage {\npublic:\n enum class Code {\n ACCEPTED = 0,\n BAD_VERSION = 1,\n BAD_ID = 2,\n SERVER_UNAVAILABLE = 3,\n BAD_USER_OR_PWD = 4,\n NO_AUTH = 5,\n };\n\n MqttConnack():\n header(MqttType::CONNACK, false, 0, false, 2) {\n }\n\n MqttConnack(Code c):\n MqttConnack() {\n code = c;\n }\n\n void cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(reserved);\n cereal.grainBits(code, 8);\n }\n\n MqttFixedHeader header;\n ubyte reserved;\n Code code;\n};\n\n\nclass MqttPublish: public MqttMessage {\npublic:\n MqttPublish(MqttFixedHeader h):header(h) {\n\n }\n\n MqttPublish(string topic, std::vector payload, ushort msgId = 0):\n MqttPublish(false, 0, false, topic, payload, msgId) {\n }\n\n MqttPublish(bool dup, ubyte qos, bool retain, string t, std::vector p, ushort mid = 0) {\n const auto topicLen = t.length() + 2; \/\/2 for length\n auto remaining = qos ? topicLen + 2 \/*msgId*\/ : topicLen;\n remaining += p.size();\n\n header = MqttFixedHeader(MqttType::PUBLISH, dup, qos, retain, remaining);\n topic = t;\n payload = std::move(p);\n msgId = mid;\n }\n\n void cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(topic);\n\n auto payloadLen = header.remaining - (topic.length() + MqttFixedHeader::SIZE);\n if(header.qos) {\n if(header.remaining < 7 && cereal.getType() == Cereal::Type::Read) {\n cerr << \"Error: PUBLISH message with QOS but no message ID\" << endl;\n } else {\n cereal.grain(msgId);\n payloadLen -= 2;\n }\n }\n if(cereal.getType() == Cereal::Type::Read) payload.resize(payloadLen);\n for(auto& b: payload) cereal.grain(b);\n }\n\n void handle(MqttServer& server, MqttConnection& connection) const override {\n (void)connection;\n server.publish(topic, payload);\n }\n\n MqttFixedHeader header;\n string topic;\n std::vector payload;\n ushort msgId;\n};\n\n\nMqttSubscribe::MqttSubscribe(MqttFixedHeader h):header(h) {\n\n}\n\nvoid MqttSubscribe::handle(MqttServer& server, MqttConnection& connection) const {\n server.subscribe(connection, msgId, topics);\n}\n\nvoid MqttSubscribe::Topic::cerealise(Cereal& cereal) {\n cereal.grain(topic);\n cereal.grain(qos);\n}\n\n\nvoid MqttSubscribe::cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(msgId);\n ushort size;\n cereal.grain(size);\n if(topics.size() != size) topics.resize(size);\n for(auto& t: topics) cereal.grain(t);\n}\n\n\nclass MqttSuback: MqttMessage {\npublic:\n\n MqttSuback(MqttFixedHeader h):header(h) {\n\n }\n\n MqttSuback(ushort m, std::vector q):\n header(MqttType::SUBACK, false, 0, false, qos.size() + 2),\n msgId(m),\n qos(std::move(q)) {\n }\n\n void cerealise(Cereal& cereal) {\n cereal.grain(header);\n cereal.grain(msgId);\n ushort size;\n cereal.grain(size);\n if(qos.size() != size) qos.resize(size);\n for(auto& q: qos) cereal.grain(q);\n }\n\n MqttFixedHeader header;\n ushort msgId;\n std::vector qos;\n};\n\n\/\/ class MqttUnsubscribe: MqttMessage {\n\/\/ this(MqttFixedHeader header) {\n\/\/ this.header = header;\n\/\/ }\n\n\/\/ override void handle(MqttServer server, MqttConnection connection) const {\n\/\/ server.unsubscribe(connection, msgId, topics);\n\/\/ }\n\n\/\/ MqttFixedHeader header;\n\/\/ ushort msgId;\n\/\/ @RawArray string[] topics;\n\/\/ }\n\n\/\/ class MqttUnsuback: MqttMessage {\n\/\/ this(in ushort msgId) {\n\/\/ this.header = MqttFixedHeader(MqttType.UNSUBACK, false, 0, false, 2);\n\/\/ this.msgId = msgId;\n\/\/ }\n\n\/\/ this(MqttFixedHeader header) {\n\/\/ this.header = header;\n\/\/ }\n\n\/\/ MqttFixedHeader header;\n\/\/ ushort msgId;\n\/\/ }\n\n\/\/ class MqttDisconnect: MqttMessage {\n\/\/ override void handle(MqttServer server, MqttConnection connection) const {\n\/\/ server.unsubscribe(connection);\n\/\/ connection.disconnect();\n\/\/ }\n\/\/ }\n\n\/\/ class MqttPingReq: MqttMessage {\n\/\/ override void handle(MqttServer server, MqttConnection connection) const {\n\/\/ server.ping(connection);\n\/\/ }\n\/\/ }\n\n\/\/ class MqttPingResp: MqttMessage {\n\/\/ const(std::vector) encode() const {\n\/\/ return [0xd0, 0x00];\n\/\/ }\n\/\/ }\n<|endoftext|>"} {"text":"#include \"core\/tz.hpp\"\n#include \"core\/window.hpp\"\n#include \"core\/profiling\/zone.hpp\"\n#include \"core\/matrix_transform.hpp\"\n#include \"core\/time.hpp\"\n#include \"gl\/device.hpp\"\n#include \"gl\/renderer.hpp\"\n#include \"gl\/resource.hpp\"\n#include \"gl\/imported_shaders.hpp\"\n\n#include ImportedShaderHeader(tz_terrain_demo, vertex)\n#include ImportedShaderHeader(tz_terrain_demo, tesscon)\n#include ImportedShaderHeader(tz_terrain_demo, tesseval)\n#include ImportedShaderHeader(tz_terrain_demo, fragment)\n\nint main()\n{\n\ttz::initialise\n\t({\n\t\t.name = \"tz_terrain_demo\",\n\t});\n\t{\n\t\tstruct BufferData\n\t\t{\n\t\t\ttz::Mat4 model = tz::model({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f});\n\t\t\ttz::Mat4 view = tz::Mat4::identity();\n\t\t\ttz::Mat4 projection = tz::Mat4::identity();\n\t\t};\n\n\t\ttz::gl::Device dev;\n\n\t\ttz::gl::BufferResource buf = tz::gl::BufferResource::from_one(BufferData{}, tz::gl::ResourceAccess::DynamicFixed);\n\n\t\ttz::gl::RendererInfo rinfo;\n\t\ttz::gl::ResourceHandle bufh = rinfo.add_resource(buf);\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::Vertex, ImportedShaderSource(tz_terrain_demo, vertex));\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::TessellationControl, ImportedShaderSource(tz_terrain_demo, tesscon));\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::TessellationEvaluation, ImportedShaderSource(tz_terrain_demo, tesseval));\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::Fragment, ImportedShaderSource(tz_terrain_demo, fragment));\n\t\trinfo.set_clear_colour({0.0f, 0.765f, 1.0f, 1.0f});\n\n\t\ttz::gl::Renderer renderer = dev.create_renderer(rinfo);\n\t\ttz::Vec3 camera_position{0.0f, 2.0f, 1.0f};\n\t\ttz::Vec3 cam_rot{0.0f, 0.0f, 0.0f};\n\t\tbool wireframe_mode = false;\n\t\tusing namespace tz::literals;\n\t\ttz::Delay fixed_update{25_ms};\n\n\t\tconstexpr float multiplier = 1.5f;\n\t\twhile(!tz::window().is_close_requested())\n\t\t{\n\t\t\tTZ_FRAME_BEGIN;\n\t\t\ttz::window().update();\n\t\t\trenderer.render(2);\n\t\t\tTZ_FRAME_END;\n\n\t\t\t\/\/ Every 25ms, we do a fixed-update.\n\t\t\tif(fixed_update.done())\n\t\t\t{\n\t\t\t\tfixed_update.reset();\n\n\t\t\t\t\/\/ If Q is pressed, toggle wireframe mode via renderer edit.\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Q))\n\t\t\t\t{\n\t\t\t\t\trenderer.edit\n\t\t\t\t\t({\n\t\t\t\t\t\t.render_state_edit = tz::gl::RendererStateEditRequest\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t.wireframe_mode = wireframe_mode\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\twireframe_mode = !wireframe_mode;\n\t\t\t\t}\n\t\t\t\t\/\/ Retrieve the dynamic buffer resource data.\n\t\t\t\tBufferData& bufd = renderer.get_resource(bufh)->data_as().front();\n\n\t\t\t\t\/\/ Dragging the mouse influences the camera rotation.\n\t\t\t\tstatic tz::Vec2i mouse_position;\n\t\t\t\tauto mpi = static_cast(tz::window().get_mouse_position_state().get_mouse_position());\n\t\t\t\tif(tz::window().get_mouse_button_state().is_mouse_button_down(tz::MouseButton::Left))\n\t\t\t\t{\n\t\t\t\t\t\/\/ Get mouse delta since last frame.\n\t\t\t\t\ttz::Vec2i mouse_delta = mpi - mouse_position;\n\t\t\t\t\tconstexpr float rot_multiplier = 0.003f;\n\t\t\t\t\tcam_rot[1] -= mouse_delta[0] * rot_multiplier;\n\t\t\t\t\tcam_rot[0] -= mouse_delta[1] * rot_multiplier;\n\t\t\t\t}\n\t\t\t\tmouse_position = mpi;\n\n\t\t\t\tbufd.view = tz::view(camera_position, cam_rot);\n\t\t\t\t\/\/ Recalculate projection every fixed update. This is a massive waste of time but easily guarantees no distortion if the window is ever resized.\n\t\t\t\tconst float aspect_ratio = static_cast(tz::window().get_width()) \/ tz::window().get_height();\n\t\t\t\tbufd.projection = tz::perspective(1.6f, aspect_ratio, 0.1f, 1000.0f);\n\t\t\t\t\/\/ WASD move the camera position around. Space and LeftShift move camera directly up or down.\n\n\t\t\t\ttz::Vec4 cam_forward4 = bufd.view * tz::Vec4{0.0f, 0.0f, -1.0f, 0.0f};\n\t\t\t\ttz::Vec4 cam_right4 = bufd.view * tz::Vec4{-1.0f, 0.0f, 0.0f, 0.0f};\n\t\t\t\ttz::Vec3 cam_forward = cam_forward4.swizzle<0, 1, 2>();\n\t\t\t\ttz::Vec3 cam_right = cam_right4.swizzle<0, 1, 2>();\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::W))\n\t\t\t\t{\n\t\t\t\t\tcamera_position += cam_forward * multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::S))\n\t\t\t\t{\n\t\t\t\t\tcamera_position -= cam_forward * multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Space))\n\t\t\t\t{\n\t\t\t\t\tcamera_position[1] += multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::LeftShift))\n\t\t\t\t{\n\t\t\t\t\tcamera_position[1] -= multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::A))\n\t\t\t\t{\n\t\t\t\t\tcamera_position += cam_right * multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::D))\n\t\t\t\t{\n\t\t\t\t\tcamera_position -= cam_right * multiplier;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\ttz::terminate();\n}\n* tz_terrain_demo - Camera now spawns slightly above terrain as previously you could be clipping inside the terrain#include \"core\/tz.hpp\"\n#include \"core\/window.hpp\"\n#include \"core\/profiling\/zone.hpp\"\n#include \"core\/matrix_transform.hpp\"\n#include \"core\/time.hpp\"\n#include \"gl\/device.hpp\"\n#include \"gl\/renderer.hpp\"\n#include \"gl\/resource.hpp\"\n#include \"gl\/imported_shaders.hpp\"\n\n#include ImportedShaderHeader(tz_terrain_demo, vertex)\n#include ImportedShaderHeader(tz_terrain_demo, tesscon)\n#include ImportedShaderHeader(tz_terrain_demo, tesseval)\n#include ImportedShaderHeader(tz_terrain_demo, fragment)\n\nint main()\n{\n\ttz::initialise\n\t({\n\t\t.name = \"tz_terrain_demo\",\n\t});\n\t{\n\t\tstruct BufferData\n\t\t{\n\t\t\ttz::Mat4 model = tz::model({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f});\n\t\t\ttz::Mat4 view = tz::Mat4::identity();\n\t\t\ttz::Mat4 projection = tz::Mat4::identity();\n\t\t};\n\n\t\ttz::gl::Device dev;\n\n\t\ttz::gl::BufferResource buf = tz::gl::BufferResource::from_one(BufferData{}, tz::gl::ResourceAccess::DynamicFixed);\n\n\t\ttz::gl::RendererInfo rinfo;\n\t\ttz::gl::ResourceHandle bufh = rinfo.add_resource(buf);\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::Vertex, ImportedShaderSource(tz_terrain_demo, vertex));\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::TessellationControl, ImportedShaderSource(tz_terrain_demo, tesscon));\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::TessellationEvaluation, ImportedShaderSource(tz_terrain_demo, tesseval));\n\t\trinfo.shader().set_shader(tz::gl::ShaderStage::Fragment, ImportedShaderSource(tz_terrain_demo, fragment));\n\t\trinfo.set_clear_colour({0.0f, 0.765f, 1.0f, 1.0f});\n\n\t\ttz::gl::Renderer renderer = dev.create_renderer(rinfo);\n\t\ttz::Vec3 camera_position{0.0f, 50.0f, 1.0f};\n\t\ttz::Vec3 cam_rot{0.0f, 0.0f, 0.0f};\n\t\tbool wireframe_mode = false;\n\t\tusing namespace tz::literals;\n\t\ttz::Delay fixed_update{25_ms};\n\n\t\tconstexpr float multiplier = 1.5f;\n\t\twhile(!tz::window().is_close_requested())\n\t\t{\n\t\t\tTZ_FRAME_BEGIN;\n\t\t\ttz::window().update();\n\t\t\trenderer.render(2);\n\t\t\tTZ_FRAME_END;\n\n\t\t\t\/\/ Every 25ms, we do a fixed-update.\n\t\t\tif(fixed_update.done())\n\t\t\t{\n\t\t\t\tfixed_update.reset();\n\n\t\t\t\t\/\/ If Q is pressed, toggle wireframe mode via renderer edit.\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Q))\n\t\t\t\t{\n\t\t\t\t\trenderer.edit\n\t\t\t\t\t({\n\t\t\t\t\t\t.render_state_edit = tz::gl::RendererStateEditRequest\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t.wireframe_mode = wireframe_mode\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\twireframe_mode = !wireframe_mode;\n\t\t\t\t}\n\t\t\t\t\/\/ Retrieve the dynamic buffer resource data.\n\t\t\t\tBufferData& bufd = renderer.get_resource(bufh)->data_as().front();\n\n\t\t\t\t\/\/ Dragging the mouse influences the camera rotation.\n\t\t\t\tstatic tz::Vec2i mouse_position;\n\t\t\t\tauto mpi = static_cast(tz::window().get_mouse_position_state().get_mouse_position());\n\t\t\t\tif(tz::window().get_mouse_button_state().is_mouse_button_down(tz::MouseButton::Left))\n\t\t\t\t{\n\t\t\t\t\t\/\/ Get mouse delta since last frame.\n\t\t\t\t\ttz::Vec2i mouse_delta = mpi - mouse_position;\n\t\t\t\t\tconstexpr float rot_multiplier = 0.003f;\n\t\t\t\t\tcam_rot[1] -= mouse_delta[0] * rot_multiplier;\n\t\t\t\t\tcam_rot[0] -= mouse_delta[1] * rot_multiplier;\n\t\t\t\t}\n\t\t\t\tmouse_position = mpi;\n\n\t\t\t\tbufd.view = tz::view(camera_position, cam_rot);\n\t\t\t\t\/\/ Recalculate projection every fixed update. This is a massive waste of time but easily guarantees no distortion if the window is ever resized.\n\t\t\t\tconst float aspect_ratio = static_cast(tz::window().get_width()) \/ tz::window().get_height();\n\t\t\t\tbufd.projection = tz::perspective(1.6f, aspect_ratio, 0.1f, 1000.0f);\n\t\t\t\t\/\/ WASD move the camera position around. Space and LeftShift move camera directly up or down.\n\n\t\t\t\ttz::Vec4 cam_forward4 = bufd.view * tz::Vec4{0.0f, 0.0f, -1.0f, 0.0f};\n\t\t\t\ttz::Vec4 cam_right4 = bufd.view * tz::Vec4{-1.0f, 0.0f, 0.0f, 0.0f};\n\t\t\t\ttz::Vec3 cam_forward = cam_forward4.swizzle<0, 1, 2>();\n\t\t\t\ttz::Vec3 cam_right = cam_right4.swizzle<0, 1, 2>();\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::W))\n\t\t\t\t{\n\t\t\t\t\tcamera_position += cam_forward * multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::S))\n\t\t\t\t{\n\t\t\t\t\tcamera_position -= cam_forward * multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::Space))\n\t\t\t\t{\n\t\t\t\t\tcamera_position[1] += multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::LeftShift))\n\t\t\t\t{\n\t\t\t\t\tcamera_position[1] -= multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::A))\n\t\t\t\t{\n\t\t\t\t\tcamera_position += cam_right * multiplier;\n\t\t\t\t}\n\t\t\t\tif(tz::window().get_keyboard_state().is_key_down(tz::KeyCode::D))\n\t\t\t\t{\n\t\t\t\t\tcamera_position -= cam_right * multiplier;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\ttz::terminate();\n}\n<|endoftext|>"} {"text":"import java.util.Scanner;\n\npublic class MergeSort {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int day = Integer.parseInt(scanner.nextLine());\n int month = Integer.parseInt(scanner.nextLine());\n\n switch(month) {\n case 2:\n if (day + 5 > 28) {\n month++;\n day = day + 5 - 28;\n }\n else {\n day += 5;\n }\n break;\n case 4:\n case 6:\n case 9:\n case 11:\n if (day + 5 > 30) {\n month++;\n day = day + 5 - 30;\n }\n else {\n day += 5;\n }\n break;\n case 1:\n case 3:\n case 5:\n case 7:\n case 8:\n case 10:\n if (day + 5 > 31) {\n month++;\n day = day + 5 - 31;\n }\n else {\n day += 5;\n }\n break;\n case 12:\n if (day + 5 > 31) {\n month = 1;\n day = day + 5 - 31;\n }\n else {\n day += 5;\n }\n break;\n default:\n break;\n }\n\n System.out.print(day + \".\");\n if (month < 10) {\n System.out.print(\"0\");\n }\n System.out.print(month);\n }\n}\nUpdate 05.DateAfter5Days.cppimport java.util.Scanner;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n int day = Integer.parseInt(scanner.nextLine());\n int month = Integer.parseInt(scanner.nextLine());\n\n switch(month) {\n case 2:\n if (day + 5 > 28) {\n month++;\n day = day + 5 - 28;\n }\n else {\n day += 5;\n }\n break;\n case 4:\n case 6:\n case 9:\n case 11:\n if (day + 5 > 30) {\n month++;\n day = day + 5 - 30;\n }\n else {\n day += 5;\n }\n break;\n case 1:\n case 3:\n case 5:\n case 7:\n case 8:\n case 10:\n if (day + 5 > 31) {\n month++;\n day = day + 5 - 31;\n }\n else {\n day += 5;\n }\n break;\n case 12:\n if (day + 5 > 31) {\n month = 1;\n day = day + 5 - 31;\n }\n else {\n day += 5;\n }\n break;\n default:\n break;\n }\n\n System.out.print(day + \".\");\n if (month < 10) {\n System.out.print(\"0\");\n }\n System.out.print(month);\n }\n}\n<|endoftext|>"} {"text":"#include \"paintarea.h\"\n\n#define STARTING_X 10\n\n\/\/Padding from the right side of the window\n#define RIGHT_SIDE_PADDING 50\n#define STARTING_Y 10\n\nPaintArea::PaintArea(QWidget *parent) :\n QWidget(parent)\n{\n currentX = STARTING_X;\n currentY = STARTING_Y;\n totalWidth = 0;\n\n webpage = new Document;\n positionSet = false;\n\n currentCharacter = new QString;\n\n nextWordChecked = false;\n}\n\nvoid PaintArea::setDocument(Document *documentToSet)\n{\n webpage = documentToSet;\n}\n\nvoid PaintArea::paintEvent(QPaintEvent *event)\n{\n Q_UNUSED(event);\n\n if (webpage->getFirstNode() != NULL)\n {\n\n QPainter qPainter(this);\n paintNodesVector = webpage->getFirstNode()->getPaintNodes();\n drawDocument(&qPainter, paintNodesVector);\n\n \/\/Prevents document from moving around while being redrawn.\n positionSet = true;\n\n \/\/This is necessary to show the entire paint area in the scroll area.\n setMinimumHeight(currentY);\n }\n}\n\nvoid PaintArea::drawDocument(QPainter *qPainter,\n std::vector *paintNodes)\n{\n std::vector::iterator i = paintNodes->begin();\n\n for (; i != paintNodes->end(); i++)\n {\n paintCurrentNode(*i, qPainter, paintNodes);\n }\n}\n\nvoid PaintArea::insertLineBreak()\n{\n QFont font = currentFont;\n QFontMetrics fm(font);\n\n currentX = STARTING_X;\n currentY += 2 * fm.height();\n totalWidth = 0;\n}\n\nvoid PaintArea::paintCurrentNode(PaintNode *currentPaintNode,\n QPainter *qPainter,\n std::vector *paintNodes)\n{\n if (currentPaintNode->getTypeOfPaintNode() == \"char\")\n {\n \/\/Draw the text contained within each paragraph node. New lines are\n \/\/only added after each paragraph node--not any other element.\n if (positionSet)\n {\n updateCurrentPosition();\n }\n\n char *character = currentPaintNode->getCharacter();\n *currentCharacter = QString(*character);\n\n currentFont = qPainter->font();\n\n if (currentPaintNode->getWeight() == QFont::Bold)\n {\n currentFont.setBold(true);\n }\n else\n {\n currentFont.setBold(false);\n }\n\n QFontMetrics fm(currentFont);\n\n if (!nextWordChecked)\n {\n if (totalWidth >= this->width() - 200)\n {\n int currentLineWidth = totalWidth;\n currentLineWidth += getNextWordWidth(paintNodes, qPainter);\n\n if (currentLineWidth + STARTING_X >= this->width() - RIGHT_SIDE_PADDING)\n {\n totalWidth = 0;\n currentY += fm.height();\n currentX = STARTING_X;\n }\n\n nextWordChecked = true;\n }\n }\n\n QRect box(QPoint(currentX, currentY), QSize(fm.width(*character),\n fm.height()));\n\n qPainter->setFont(currentFont);\n qPainter->drawText(box, Qt::AlignCenter, QString(*character));\n\n if (isspace(*character))\n {\n nextWordChecked = false;\n }\n\n updateCurrentPosition();\n }\n\n else if (currentPaintNode->getTypeOfPaintNode() == \"node\")\n {\n \/\/Call the function again on each of the PaintNode's child paint nodes.\n \/\/This ensures that all of the child nodes of the overall parent node\n \/\/are drawn.\n std::vector *childPaintNodes = currentPaintNode->\n returnNode()->getPaintNodes();\n drawDocument(qPainter, childPaintNodes);\n if (currentPaintNode->returnNode()->getTypeOfRenderNode() == \"p\")\n {\n insertLineBreak();\n }\n }\n}\n\n\/\/This adjusts the location where the next character will be drawn, including\n\/\/changing lines when the total length exceeds the width of the window.\nvoid PaintArea::updateCurrentPosition()\n{\n\n \/\/positionSet is only true when the entire text has been drawn.\n \/\/If it is false, then it is safe to set the character to the spot\n \/\/after the current character.\n if (!positionSet)\n {\n QFontMetrics fm(currentFont);\n\n totalWidth += fm.width(*currentCharacter);\n currentX += fm.width(*currentCharacter);\n\n if (totalWidth + STARTING_X >= this->width())\n {\n setMinimumWidth(totalWidth + STARTING_X);\n }\n }\n\n \/\/However, if positionSet is true, then it is time to draw the entire\n \/\/document again, so we reset the current position to the initial state.\n else\n {\n currentX = STARTING_X;\n currentY = STARTING_Y;\n totalWidth = 0;\n positionSet = false;\n }\n}\n\nint PaintArea::getNextWordWidth(std::vector *paintNodes, QPainter *qPainter)\n{\n int wordWidth = 0;\n bool wordEndReached = false;\n\n std::vector::iterator currentNode = paintNodes->begin();\n\n for (; !wordEndReached; currentNode++)\n {\n if (currentNode == paintNodes->end())\n {\n wordEndReached = true;\n }\n\n else if ((*currentNode)->getTypeOfPaintNode() == \"char\")\n {\n if (!isspace(*(*currentNode)->getCharacter()))\n {\n QFont font = qPainter->font();\n QFontMetrics fm(font);\n wordWidth += fm.width((*currentNode)->getCharacter());\n }\n else\n {\n wordEndReached = true;\n }\n }\n\n else if ((*currentNode)->getTypeOfPaintNode() == \"node\")\n {\n wordWidth += getNextWordWidth(paintNodes, qPainter);\n }\n }\n\n return wordWidth;\n}\nFix bug with text not shrinking to match resized window.#include \"paintarea.h\"\n\n#define STARTING_X 10\n\n\/\/Padding from the right side of the window\n#define RIGHT_SIDE_PADDING 50\n#define STARTING_Y 10\n\nPaintArea::PaintArea(QWidget *parent) :\n QWidget(parent)\n{\n currentX = STARTING_X;\n currentY = STARTING_Y;\n totalWidth = 0;\n\n webpage = new Document;\n positionSet = false;\n\n currentCharacter = new QString;\n\n nextWordChecked = false;\n}\n\nvoid PaintArea::setDocument(Document *documentToSet)\n{\n webpage = documentToSet;\n}\n\nvoid PaintArea::paintEvent(QPaintEvent *event)\n{\n Q_UNUSED(event);\n\n if (webpage->getFirstNode() != NULL)\n {\n\n QPainter qPainter(this);\n paintNodesVector = webpage->getFirstNode()->getPaintNodes();\n drawDocument(&qPainter, paintNodesVector);\n\n \/\/Prevents document from moving around while being redrawn.\n positionSet = true;\n\n \/\/This is necessary to show the entire paint area in the scroll area.\n setMinimumHeight(currentY);\n }\n}\n\nvoid PaintArea::drawDocument(QPainter *qPainter,\n std::vector *paintNodes)\n{\n std::vector::iterator i = paintNodes->begin();\n\n for (; i != paintNodes->end(); i++)\n {\n paintCurrentNode(*i, qPainter, paintNodes);\n }\n}\n\nvoid PaintArea::insertLineBreak()\n{\n QFont font = currentFont;\n QFontMetrics fm(font);\n\n currentX = STARTING_X;\n currentY += 2 * fm.height();\n totalWidth = 0;\n}\n\nvoid PaintArea::paintCurrentNode(PaintNode *currentPaintNode,\n QPainter *qPainter,\n std::vector *paintNodes)\n{\n if (currentPaintNode->getTypeOfPaintNode() == \"char\")\n {\n \/\/Draw the text contained within each paragraph node. New lines are\n \/\/only added after each paragraph node--not any other element.\n if (positionSet)\n {\n updateCurrentPosition();\n }\n\n char *character = currentPaintNode->getCharacter();\n *currentCharacter = QString(*character);\n\n currentFont = qPainter->font();\n\n if (currentPaintNode->getWeight() == QFont::Bold)\n {\n currentFont.setBold(true);\n }\n else\n {\n currentFont.setBold(false);\n }\n\n QFontMetrics fm(currentFont);\n\n if (!nextWordChecked)\n {\n if (totalWidth >= this->width() - 200)\n {\n int currentLineWidth = totalWidth;\n currentLineWidth += getNextWordWidth(paintNodes, qPainter);\n\n if (currentLineWidth + STARTING_X >= this->width() - RIGHT_SIDE_PADDING)\n {\n totalWidth = 0;\n currentY += fm.height();\n currentX = STARTING_X;\n }\n\n nextWordChecked = true;\n }\n }\n\n QRect box(QPoint(currentX, currentY), QSize(fm.width(*character),\n fm.height()));\n\n qPainter->setFont(currentFont);\n qPainter->drawText(box, Qt::AlignCenter, QString(*character));\n\n if (isspace(*character))\n {\n nextWordChecked = false;\n }\n\n updateCurrentPosition();\n }\n\n else if (currentPaintNode->getTypeOfPaintNode() == \"node\")\n {\n \/\/Call the function again on each of the PaintNode's child paint nodes.\n \/\/This ensures that all of the child nodes of the overall parent node\n \/\/are drawn.\n std::vector *childPaintNodes = currentPaintNode->\n returnNode()->getPaintNodes();\n drawDocument(qPainter, childPaintNodes);\n if (currentPaintNode->returnNode()->getTypeOfRenderNode() == \"p\")\n {\n insertLineBreak();\n }\n }\n}\n\n\/\/This adjusts the location where the next character will be drawn, including\n\/\/changing lines when the total length exceeds the width of the window.\nvoid PaintArea::updateCurrentPosition()\n{\n\n \/\/positionSet is only true when the entire text has been drawn.\n \/\/If it is false, then it is safe to set the character to the spot\n \/\/after the current character.\n if (!positionSet)\n {\n QFontMetrics fm(currentFont);\n\n totalWidth += fm.width(*currentCharacter);\n currentX += fm.width(*currentCharacter);\n }\n\n \/\/However, if positionSet is true, then it is time to draw the entire\n \/\/document again, so we reset the current position to the initial state.\n else\n {\n currentX = STARTING_X;\n currentY = STARTING_Y;\n totalWidth = 0;\n positionSet = false;\n }\n}\n\nint PaintArea::getNextWordWidth(std::vector *paintNodes, QPainter *qPainter)\n{\n int wordWidth = 0;\n bool wordEndReached = false;\n\n std::vector::iterator currentNode = paintNodes->begin();\n\n for (; !wordEndReached; currentNode++)\n {\n if (currentNode == paintNodes->end())\n {\n wordEndReached = true;\n }\n\n else if ((*currentNode)->getTypeOfPaintNode() == \"char\")\n {\n if (!isspace(*(*currentNode)->getCharacter()))\n {\n QFont font = qPainter->font();\n QFontMetrics fm(font);\n wordWidth += fm.width((*currentNode)->getCharacter());\n }\n else\n {\n wordEndReached = true;\n }\n }\n\n else if ((*currentNode)->getTypeOfPaintNode() == \"node\")\n {\n wordWidth += getNextWordWidth(paintNodes, qPainter);\n }\n }\n\n return wordWidth;\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright 2014, Planet Labs, 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 \"compositor.h\"\n\n\/************************************************************************\/\n\/* PercentileQuality *\/\n\/************************************************************************\/\n\nclass PercentileQuality : public QualityMethodBase \n{\n PLCInput *input;\n std::vector targetQuality;\n double percentileRatio; \n\npublic:\n PercentileQuality() : QualityMethodBase(\"percentile\") {}\n ~PercentileQuality() {}\n\n \/********************************************************************\/\n QualityMethodBase *create(PLCContext* context, WJElement node) {\n PercentileQuality *obj = new PercentileQuality();\n\n if( node == NULL )\n {\n CPLString default_percentile;\n if( EQUAL(context->getStratParam(\"compositor\", \"quality\"),\n \"median\") )\n default_percentile = \"50\";\n else\n default_percentile = \"100\";\n\n \/\/ 50 is true median, 100 is best quality, 0 is worst quality.\n obj->percentileRatio = atof(\n context->getStratParam(\"quality_percentile\", \n default_percentile)) \/ 100.0;\n\n \/\/ median_ratio is here for backwards compatability, quality_percentile\n \/\/ Eventually it should be removed.\n if( context->getStratParam(\"median_ratio\", NULL) != NULL )\n obj->percentileRatio = atof(context->getStratParam(\"median_ratio\", NULL));\n\n CPLDebug(\"PLC\", \"Percentile quality in effect, ratio=%.3f\",\n obj->percentileRatio);\n }\n else\n {\n obj->percentileRatio = WJEDouble(node, \"quality_percentile\", \n WJE_GET, 50.0) \/ 100.0;\n }\n return obj;\n }\n\n \/********************************************************************\/\n void mergeQuality(PLCInput *input, PLCLine *line) {\n float *quality = line->getQuality();\n float *newQuality = line->getNewQuality();\n\n \/\/ In this case we copy the new quality over the old since it already incorporates\n \/\/ the old. \n for(int i=0; i < line->getWidth(); i++)\n {\n quality[i] = newQuality[i];\n newQuality[i] = 1.0;\n }\n }\n\n \/********************************************************************\/\n int computeQuality(PLCInput *input, PLCLine *lineObj) {\n float *newQuality = lineObj->getNewQuality();\n float *oldQuality = lineObj->getQuality();\n\n for(int i=lineObj->getWidth()-1; i >= 0; i--)\n {\n if( oldQuality[i] <= 0 )\n newQuality[i] = -1;\n else\n newQuality[i] = 1.0 - fabs(oldQuality[i] - targetQuality[i]); \/\/ rescale?\n }\n \n return TRUE;\n }\n\n \/********************************************************************\/\n int computeStackQuality(PLCContext *context, std::vector& lines) {\n\n unsigned int i;\n std::vector inputQualities;\n\n targetQuality.resize(context->width);\n\n for(i = 0; i < context->inputFiles.size(); i++ )\n inputQualities.push_back(lines[i]->getQuality());\n\n std::vector pixelQualities;\n pixelQualities.resize(context->width);\n\n for(int iPixel=0; iPixel < context->width; iPixel++)\n {\n int activeCandidates = 0;\n\n for(i=0; i < inputQualities.size(); i++)\n {\n if( inputQualities[i][iPixel] > 0.0 )\n pixelQualities[activeCandidates++] = inputQualities[i][iPixel];\n }\n\n if( activeCandidates > 1 )\n {\n std::sort(pixelQualities.begin(),\n pixelQualities.begin()+activeCandidates);\n \n int bestCandidate = \n MAX(0,MIN(activeCandidates-1,\n ((int) floor(activeCandidates*percentileRatio))));\n targetQuality[iPixel] = pixelQualities[bestCandidate];\n \n }\n else if( activeCandidates == 1 )\n targetQuality[iPixel] = pixelQualities[0];\n else\n targetQuality[iPixel] = -1.0;\n }\n\n return QualityMethodBase::computeStackQuality(context, lines);\n }\n};\n\nstatic PercentileQuality percentileQualityTemplateInstance;\n\n\ndebug output for percentile value added\/**\n * Copyright 2014, Planet Labs, 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 \"compositor.h\"\n\n\/************************************************************************\/\n\/* PercentileQuality *\/\n\/************************************************************************\/\n\nclass PercentileQuality : public QualityMethodBase \n{\n PLCInput *input;\n std::vector targetQuality;\n double percentileRatio; \n\npublic:\n PercentileQuality() : QualityMethodBase(\"percentile\") {}\n ~PercentileQuality() {}\n\n \/********************************************************************\/\n QualityMethodBase *create(PLCContext* context, WJElement node) {\n PercentileQuality *obj = new PercentileQuality();\n\n if( node == NULL )\n {\n CPLString default_percentile;\n if( EQUAL(context->getStratParam(\"compositor\", \"quality\"),\n \"median\") )\n default_percentile = \"50\";\n else\n default_percentile = \"100\";\n\n \/\/ 50 is true median, 100 is best quality, 0 is worst quality.\n obj->percentileRatio = atof(\n context->getStratParam(\"quality_percentile\", \n default_percentile)) \/ 100.0;\n\n \/\/ median_ratio is here for backwards compatability, quality_percentile\n \/\/ Eventually it should be removed.\n if( context->getStratParam(\"median_ratio\", NULL) != NULL )\n obj->percentileRatio = atof(context->getStratParam(\"median_ratio\", NULL));\n\n CPLDebug(\"PLC\", \"Percentile quality in effect, ratio=%.3f\",\n obj->percentileRatio);\n }\n else\n {\n obj->percentileRatio = WJEDouble(node, \"quality_percentile\", \n WJE_GET, 50.0) \/ 100.0;\n CPLDebug(\"PLC\", \"Percentile Quality: %.2f.\", obj->percentileRatio);\n }\n return obj;\n }\n\n \/********************************************************************\/\n void mergeQuality(PLCInput *input, PLCLine *line) {\n float *quality = line->getQuality();\n float *newQuality = line->getNewQuality();\n\n \/\/ In this case we copy the new quality over the old since it already incorporates\n \/\/ the old. \n for(int i=0; i < line->getWidth(); i++)\n {\n quality[i] = newQuality[i];\n newQuality[i] = 1.0;\n }\n }\n\n \/********************************************************************\/\n int computeQuality(PLCInput *input, PLCLine *lineObj) {\n float *newQuality = lineObj->getNewQuality();\n float *oldQuality = lineObj->getQuality();\n\n for(int i=lineObj->getWidth()-1; i >= 0; i--)\n {\n if( oldQuality[i] <= 0 )\n newQuality[i] = -1;\n else\n newQuality[i] = 1.0 - fabs(oldQuality[i] - targetQuality[i]); \/\/ rescale?\n }\n \n return TRUE;\n }\n\n \/********************************************************************\/\n int computeStackQuality(PLCContext *context, std::vector& lines) {\n\n unsigned int i;\n std::vector inputQualities;\n\n targetQuality.resize(context->width);\n\n for(i = 0; i < context->inputFiles.size(); i++ )\n inputQualities.push_back(lines[i]->getQuality());\n\n std::vector pixelQualities;\n pixelQualities.resize(context->width);\n\n for(int iPixel=0; iPixel < context->width; iPixel++)\n {\n int activeCandidates = 0;\n\n for(i=0; i < inputQualities.size(); i++)\n {\n if( inputQualities[i][iPixel] > 0.0 )\n pixelQualities[activeCandidates++] = inputQualities[i][iPixel];\n }\n\n if( activeCandidates > 1 )\n {\n std::sort(pixelQualities.begin(),\n pixelQualities.begin()+activeCandidates);\n \n int bestCandidate = \n MAX(0,MIN(activeCandidates-1,\n ((int) floor(activeCandidates*percentileRatio))));\n targetQuality[iPixel] = pixelQualities[bestCandidate];\n \n }\n else if( activeCandidates == 1 )\n targetQuality[iPixel] = pixelQualities[0];\n else\n targetQuality[iPixel] = -1.0;\n }\n\n return QualityMethodBase::computeStackQuality(context, lines);\n }\n};\n\nstatic PercentileQuality percentileQualityTemplateInstance;\n\n\n<|endoftext|>"} {"text":"\/* \n *\n * This file is part of the x0 web server project and is released under LGPL-3.\n * http:\/\/www.xzero.ws\/\n *\n * (c) 2009-2010 Christian Parpart \n *\/\n\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\n\/**\n * \\ingroup plugins\n * \\brief implements an accesslog log facility - in spirit of \"combined\" mode of apache's accesslog logs.\n *\/\nclass accesslog_plugin :\n\tpublic x0::HttpPlugin\n{\nprivate:\n\tx0::HttpServer::RequestPostHook::Connection c;\n\n\tstruct context : public x0::ScopeValue\n\t{\n\t\tstd::string filename_;\n\t\tint fd_;\n\n\t\tcontext() :\n\t\t\tfilename_(),\n\t\t\tfd_(-1)\n\t\t{\n\t\t}\n\n\t\t~context()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tstd::error_code open(const std::string& filename)\n\t\t{\n\t\t\tif (fd_ >= 0)\n\t\t\t\t::close(fd_);\n\n\t\t\tfd_ = ::open(filename.c_str(), O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644);\n\t\t\tif (fd_ < 0)\n\t\t\t\treturn std::make_error_code(static_cast(errno));\n\n\t\t\tfilename_ = filename;\n\t\t\treturn std::error_code();\n\t\t}\n\n\t\tvoid write(const std::string message)\n\t\t{\n\t\t\tif (fd_ < 0)\n\t\t\t\treturn;\n\n\t\t\tint rv = ::write(fd_, message.c_str(), message.size());\n\n\t\t\tif (rv < 0)\n\t\t\t\tDEBUG(\"Couldn't write to accesslog(%s): %s\", filename_.c_str(), strerror(errno));\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (fd_ >= 0)\n\t\t\t{\n\t\t\t\t::close(fd_);\n\t\t\t\tfd_ = -1;\n\t\t\t}\n\t\t}\n\n\t\tvoid reopen()\n\t\t{\n\t\t\tclose();\n\t\t\topen(filename_);\n\t\t}\n\n\t\tvirtual void merge(const x0::ScopeValue *value)\n\t\t{\n\t\t\tif (auto cx = dynamic_cast(value))\n\t\t\t{\n\t\t\t\tif (filename_.empty())\n\t\t\t\t{\n\t\t\t\t\tfilename_ = cx->filename_;\n\t\t\t\t\treopen();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\npublic:\n\taccesslog_plugin(x0::HttpServer& srv, const std::string& name) :\n\t\tx0::HttpPlugin(srv, name)\n\t{\n\t\tusing namespace std::placeholders;\n\t\tc = srv.onRequestDone.connect(this);\n\n\t\tdeclareCVar(\"AccessLog\", x0::HttpContext::server | x0::HttpContext::host, &accesslog_plugin::setup_log);\n\t}\n\n\t~accesslog_plugin()\n\t{\n\t\tserver_.onRequestDone.disconnect(c);\n\t}\n\nprivate:\n\tstd::error_code setup_log(const x0::SettingsValue& cvar, x0::Scope& s)\n\t{\n\t\tstd::string filename;\n\n\t\tstd::error_code ec = cvar.load(filename);\n\t\tif (ec)\n\t\t\treturn ec;\n\n\t\tauto cx = s.acquire(this);\n\t\tec = cx->open(filename);\n\n\t\treturn std::error_code();\n\t}\n\n\tvoid request_done(x0::HttpRequest *in, x0::HttpResponse *out)\n\t{\n\t\tif (auto stream = server().resolveHost(in->hostid())->get(this))\n\t\t{\n\t\t\tstd::stringstream sstr;\n\t\t\tsstr << hostname(in);\n\t\t\tsstr << \" - \"; \/\/ identity as of identd\n\t\t\tsstr << username(in) << ' ';\n\t\t\tsstr << server_.now().htlog_str().c_str() << \" \\\"\";\n\t\t\tsstr << request_line(in) << \"\\\" \";\n\t\t\tsstr << out->status << ' ';\n\t\t\tsstr << out->headers[\"Content-Length\"] << ' ';\n\t\t\tsstr << '\"' << getheader(in, \"Referer\") << \"\\\" \";\n\t\t\tsstr << '\"' << getheader(in, \"User-Agent\") << '\"';\n\t\t\tsstr << std::endl;\n\n\t\t\tstream->write(sstr.str());\n\t\t}\n\t}\n\n\tinline context *getlogstream(x0::HttpRequest *in)\n\t{\n\t\treturn server_.resolveHost(in->hostid())->get(this);\n\t}\n\n\tinline std::string hostname(x0::HttpRequest *in)\n\t{\n\t\tstd::string name = in->connection.remote_ip();\n\t\treturn !name.empty() ? name : \"-\";\n\t}\n\n\tinline std::string username(x0::HttpRequest *in)\n\t{\n\t\treturn !in->username.empty() ? in->username.str() : \"-\";\n\t}\n\n\tinline std::string request_line(x0::HttpRequest *in)\n\t{\n\t\tstd::stringstream str;\n\n\t\tstr << in->method.str() << ' ' << in->uri.str()\n\t\t\t<< \" HTTP\/\" << in->http_version_major << '.' << in->http_version_minor;\n\n\t\treturn str.str();\n\t}\n\n\tinline std::string getheader(const x0::HttpRequest *in, const std::string& name)\n\t{\n\t\tx0::BufferRef value(in->header(name));\n\t\treturn !value.empty() ? value.str() : \"-\";\n\t}\n};\n\nX0_EXPORT_PLUGIN(accesslog);\n[plugins] accesslog: fixes status code logging\/* \n *\n * This file is part of the x0 web server project and is released under LGPL-3.\n * http:\/\/www.xzero.ws\/\n *\n * (c) 2009-2010 Christian Parpart \n *\/\n\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\n\/**\n * \\ingroup plugins\n * \\brief implements an accesslog log facility - in spirit of \"combined\" mode of apache's accesslog logs.\n *\/\nclass accesslog_plugin :\n\tpublic x0::HttpPlugin\n{\nprivate:\n\tx0::HttpServer::RequestPostHook::Connection c;\n\n\tstruct context : public x0::ScopeValue\n\t{\n\t\tstd::string filename_;\n\t\tint fd_;\n\n\t\tcontext() :\n\t\t\tfilename_(),\n\t\t\tfd_(-1)\n\t\t{\n\t\t}\n\n\t\t~context()\n\t\t{\n\t\t\tclose();\n\t\t}\n\n\t\tstd::error_code open(const std::string& filename)\n\t\t{\n\t\t\tif (fd_ >= 0)\n\t\t\t\t::close(fd_);\n\n\t\t\tfd_ = ::open(filename.c_str(), O_APPEND | O_WRONLY | O_CREAT | O_LARGEFILE, 0644);\n\t\t\tif (fd_ < 0)\n\t\t\t\treturn std::make_error_code(static_cast(errno));\n\n\t\t\tfilename_ = filename;\n\t\t\treturn std::error_code();\n\t\t}\n\n\t\tvoid write(const std::string message)\n\t\t{\n\t\t\tif (fd_ < 0)\n\t\t\t\treturn;\n\n\t\t\tint rv = ::write(fd_, message.c_str(), message.size());\n\n\t\t\tif (rv < 0)\n\t\t\t\tDEBUG(\"Couldn't write to accesslog(%s): %s\", filename_.c_str(), strerror(errno));\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (fd_ >= 0)\n\t\t\t{\n\t\t\t\t::close(fd_);\n\t\t\t\tfd_ = -1;\n\t\t\t}\n\t\t}\n\n\t\tvoid reopen()\n\t\t{\n\t\t\tclose();\n\t\t\topen(filename_);\n\t\t}\n\n\t\tvirtual void merge(const x0::ScopeValue *value)\n\t\t{\n\t\t\tif (auto cx = dynamic_cast(value))\n\t\t\t{\n\t\t\t\tif (filename_.empty())\n\t\t\t\t{\n\t\t\t\t\tfilename_ = cx->filename_;\n\t\t\t\t\treopen();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\npublic:\n\taccesslog_plugin(x0::HttpServer& srv, const std::string& name) :\n\t\tx0::HttpPlugin(srv, name)\n\t{\n\t\tusing namespace std::placeholders;\n\t\tc = srv.onRequestDone.connect(this);\n\n\t\tdeclareCVar(\"AccessLog\", x0::HttpContext::server | x0::HttpContext::host, &accesslog_plugin::setup_log);\n\t}\n\n\t~accesslog_plugin()\n\t{\n\t\tserver_.onRequestDone.disconnect(c);\n\t}\n\nprivate:\n\tstd::error_code setup_log(const x0::SettingsValue& cvar, x0::Scope& s)\n\t{\n\t\tstd::string filename;\n\n\t\tstd::error_code ec = cvar.load(filename);\n\t\tif (ec)\n\t\t\treturn ec;\n\n\t\tauto cx = s.acquire(this);\n\t\tec = cx->open(filename);\n\n\t\treturn std::error_code();\n\t}\n\n\tvoid request_done(x0::HttpRequest *in, x0::HttpResponse *out)\n\t{\n\t\tif (auto stream = server().resolveHost(in->hostid())->get(this))\n\t\t{\n\t\t\tstd::stringstream sstr;\n\t\t\tsstr << hostname(in);\n\t\t\tsstr << \" - \"; \/\/ identity as of identd\n\t\t\tsstr << username(in) << ' ';\n\t\t\tsstr << server_.now().htlog_str().c_str() << \" \\\"\";\n\t\t\tsstr << request_line(in) << \"\\\" \";\n\t\t\tsstr << static_cast(out->status) << ' ';\n\t\t\tsstr << out->headers[\"Content-Length\"] << ' ';\n\t\t\tsstr << '\"' << getheader(in, \"Referer\") << \"\\\" \";\n\t\t\tsstr << '\"' << getheader(in, \"User-Agent\") << '\"';\n\t\t\tsstr << std::endl;\n\n\t\t\tstream->write(sstr.str());\n\t\t}\n\t}\n\n\tinline context *getlogstream(x0::HttpRequest *in)\n\t{\n\t\treturn server_.resolveHost(in->hostid())->get(this);\n\t}\n\n\tinline std::string hostname(x0::HttpRequest *in)\n\t{\n\t\tstd::string name = in->connection.remote_ip();\n\t\treturn !name.empty() ? name : \"-\";\n\t}\n\n\tinline std::string username(x0::HttpRequest *in)\n\t{\n\t\treturn !in->username.empty() ? in->username.str() : \"-\";\n\t}\n\n\tinline std::string request_line(x0::HttpRequest *in)\n\t{\n\t\tstd::stringstream str;\n\n\t\tstr << in->method.str() << ' ' << in->uri.str()\n\t\t\t<< \" HTTP\/\" << in->http_version_major << '.' << in->http_version_minor;\n\n\t\treturn str.str();\n\t}\n\n\tinline std::string getheader(const x0::HttpRequest *in, const std::string& name)\n\t{\n\t\tx0::BufferRef value(in->header(name));\n\t\treturn !value.empty() ? value.str() : \"-\";\n\t}\n};\n\nX0_EXPORT_PLUGIN(accesslog);\n<|endoftext|>"} {"text":"#include \"command.hh\"\n#include \"common-args.hh\"\n#include \"shared.hh\"\n#include \"store-api.hh\"\n#include \"eval.hh\"\n#include \"json.hh\"\n#include \"value-to-json.hh\"\n\nusing namespace nix;\n\nstruct CmdEval : MixJSON, InstallableCommand\n{\n bool raw = false;\n\n CmdEval()\n {\n mkFlag(0, \"raw\", \"print strings unquoted\", &raw);\n }\n\n std::string name() override\n {\n return \"eval\";\n }\n\n std::string description() override\n {\n return \"evaluate a Nix expression\";\n }\n\n Examples examples() override\n {\n return {\n Example{\n \"To evaluate a Nix expression given on the command line:\",\n \"nix eval '(1 + 2)'\"\n },\n Example{\n \"To evaluate a Nix expression from a file or URI:\",\n \"nix eval -f channel:nixos-17.09 hello.name\"\n },\n Example{\n \"To get the current version of Nixpkgs:\",\n \"nix eval --raw nixpkgs.lib.nixpkgsVersion\"\n },\n Example{\n \"To print the store path of the Hello package:\",\n \"nix eval --raw nixpkgs.hello\"\n },\n };\n }\n\n void run(ref store) override\n {\n if (raw && json)\n throw UsageError(\"--raw and --json are mutually exclusive\");\n\n auto state = getEvalState();\n\n auto v = installable->toValue(*state);\n PathSet context;\n if (raw) {\n std::cout << state->coerceToString(noPos, *v, context);\n } else if (json) {\n JSONPlaceholder jsonOut(std::cout);\n printValueAsJSON(*state, true, *v, jsonOut, context);\n } else {\n state->forceValueDeep(*v);\n std::cout << *v << \"\\n\";\n }\n }\n};\n\nstatic RegisterCommand r1(make_ref());\nnix eval: Stop progress bar before printing the result#include \"command.hh\"\n#include \"common-args.hh\"\n#include \"shared.hh\"\n#include \"store-api.hh\"\n#include \"eval.hh\"\n#include \"json.hh\"\n#include \"value-to-json.hh\"\n#include \"progress-bar.hh\"\n\nusing namespace nix;\n\nstruct CmdEval : MixJSON, InstallableCommand\n{\n bool raw = false;\n\n CmdEval()\n {\n mkFlag(0, \"raw\", \"print strings unquoted\", &raw);\n }\n\n std::string name() override\n {\n return \"eval\";\n }\n\n std::string description() override\n {\n return \"evaluate a Nix expression\";\n }\n\n Examples examples() override\n {\n return {\n Example{\n \"To evaluate a Nix expression given on the command line:\",\n \"nix eval '(1 + 2)'\"\n },\n Example{\n \"To evaluate a Nix expression from a file or URI:\",\n \"nix eval -f channel:nixos-17.09 hello.name\"\n },\n Example{\n \"To get the current version of Nixpkgs:\",\n \"nix eval --raw nixpkgs.lib.nixpkgsVersion\"\n },\n Example{\n \"To print the store path of the Hello package:\",\n \"nix eval --raw nixpkgs.hello\"\n },\n };\n }\n\n void run(ref store) override\n {\n if (raw && json)\n throw UsageError(\"--raw and --json are mutually exclusive\");\n\n auto state = getEvalState();\n\n auto v = installable->toValue(*state);\n PathSet context;\n\n stopProgressBar();\n\n if (raw) {\n std::cout << state->coerceToString(noPos, *v, context);\n } else if (json) {\n JSONPlaceholder jsonOut(std::cout);\n printValueAsJSON(*state, true, *v, jsonOut, context);\n } else {\n state->forceValueDeep(*v);\n std::cout << *v << \"\\n\";\n }\n }\n};\n\nstatic RegisterCommand r1(make_ref());\n<|endoftext|>"} {"text":"#ifndef MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP\n#define MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP\n#include \n#include \n#include \n#include \n\n\/\/\n\/\/ Dynamic variable is a (non-) physical parameter in a system that has\n\/\/ (virtual) mass, velocity and force and updated by integrator.\n\/\/\nnamespace mjolnir\n{\n\ntemplate\nstruct DynamicVariableBase\n{\n using real_type = realT;\n\n real_type x, v, f;\n real_type m, gamma;\n real_type lower, upper;\n\n DynamicVariableBase(real_type x_, real_type v_, real_type f_,\n real_type m_, real_type gamma_,\n real_type lower_, real_type upper_)\n : x(x_), v(v_), f(f_), m(m_), gamma(gamma_), lower(lower_), upper(upper_)\n {}\n virtual ~DynamicVariableBase() = default;\n virtual void update(real_type x, real_type v, real_type f) noexcept = 0;\n virtual DynamicVariableBase* clone() const = 0;\n};\n\n\/\/ It makes `DynamicVariable`s copyable and easier to handle.\ntemplate\nstruct DynamicVariable\n{\n using real_type = typename DynamicVariableBase::real_type;\n\n template\n explicit DynamicVariable(DynVar&& dynvar)\n : resource_(make_unique>(std::forward(dynvar)))\n {\n static_assert(std::is_base_of, DynVar>::value, \"\");\n }\n\n DynamicVariable(const DynamicVariable& other)\n : resource_(other.resource_->clone())\n {}\n DynamicVariable& operator=(const DynamicVariable& other)\n {\n this->resource_.reset(other.resource_->clone());\n return *this;\n }\n DynamicVariable(DynamicVariable&&) = default;\n DynamicVariable& operator=(DynamicVariable&&) = default;\n ~DynamicVariable() = default;\n\n real_type x() const noexcept {return resource_->x;}\n real_type v() const noexcept {return resource_->v;}\n real_type f() const noexcept {return resource_->f;}\n real_type m() const noexcept {return resource_->m;}\n real_type gamma() const noexcept {return resource_->gamma;}\n\n void update(real_type x, real_type v, real_type f) const noexcept\n {\n resource_->update(x, v, f);\n }\n\n private:\n std::unique_ptr> resource_;\n};\n\ntemplate\nstruct DefaultDynamicVariable : public DynamicVariableBase\n{\n using base_type = DynamicVariableBase;\n using real_type = typename base_type::real_type;\n\n DefaultDynamicVariable(const real_type x, const real_type v, const real_type f,\n const real_type m, const real_type gamma)\n : base_type{x, v, f, m, gamma,\n -std::numeric_limits::infinity(),\n std::numeric_limits::infinity()}\n {}\n ~DefaultDynamicVariable() override = default;\n\n void update(real_type x, real_type v, real_type f) noexcept override\n {\n this->x = x;\n this->v = v;\n this->f = f;\n return;\n }\n DynamicVariableBase* clone() const override\n {\n return new DefaultDynamicVariable(*this);\n }\n};\n\ntemplate\nstruct PeriodicDynamicVariable : public DynamicVariableBase\n{\n using base_type = DynamicVariableBase;\n using real_type = typename base_type::real_type;\n\n PeriodicDynamicVariable(const real_type x, const real_type v, const real_type f,\n const real_type m, const real_type gamma,\n const real_type lower, const real_type upper)\n : base_type(x, v, f, m, gamma, lower, upper)\n {}\n ~PeriodicDynamicVariable() override = default;\n\n void update(real_type x, real_type v, real_type f) noexcept override\n {\n this->x = x;\n if (this->x < this->lower) {this->x += (this->upper - this->lower);}\n else if (this->upper <= this->x) {this->x -= (this->upper - this->lower);}\n this->v = v;\n this->f = f;\n return;\n }\n DynamicVariableBase* clone() const override\n {\n return new PeriodicDynamicVariable(*this);\n }\n};\n\ntemplate\nstruct RepulsiveDynamicVariable : public DynamicVariableBase\n{\n using base_type = DynamicVariableBase;\n using real_type = typename base_type::real_type;\n\n RepulsiveDynamicVariable(const real_type x, const real_type v, const real_type f,\n const real_type m, const real_type gamma,\n const real_type lower, const real_type upper)\n : base_type(x, v, f, m, gamma, lower, upper)\n {}\n ~RepulsiveDynamicVariable() override = default;\n\n void update(real_type x, real_type v, real_type f) noexcept override\n {\n if(x < this->lower)\n {\n this->x = 2 * this->lower - x; \/\/ lower + (lower - x)\n this->v = -v;\n }\n else if (this->upper < x)\n {\n this->x = 2 * this->upper - x; \/\/ upper - (x - upper)\n this->v = -v;\n }\n else\n {\n this->x = x;\n this->v = v;\n }\n this->f = f;\n return;\n }\n DynamicVariableBase* clone() const override\n {\n return new RepulsiveDynamicVariable(*this);\n }\n};\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template class DynamicVariableBase;\nextern template class DynamicVariableBase;\nextern template class DynamicVariable;\nextern template class DynamicVariable;\nextern template class DefaultDynamicVariable;\nextern template class DefaultDynamicVariable;\nextern template class PeriodicDynamicVariable;\nextern template class PeriodicDynamicVariable;\nextern template class RepulsiveDynamicVariable;\nextern template class RepulsiveDynamicVariable;\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP\nfeat: add default ctor to dynvar#ifndef MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP\n#define MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP\n#include \n#include \n#include \n#include \n\n\/\/\n\/\/ Dynamic variable is a (non-) physical parameter in a system that has\n\/\/ (virtual) mass, velocity and force and updated by integrator.\n\/\/\nnamespace mjolnir\n{\n\ntemplate\nstruct DynamicVariableBase\n{\n using real_type = realT;\n\n real_type x, v, f;\n real_type m, gamma;\n real_type lower, upper;\n\n DynamicVariableBase(real_type x_, real_type v_, real_type f_,\n real_type m_, real_type gamma_,\n real_type lower_, real_type upper_)\n : x(x_), v(v_), f(f_), m(m_), gamma(gamma_), lower(lower_), upper(upper_)\n {}\n virtual ~DynamicVariableBase() = default;\n virtual void update(real_type x, real_type v, real_type f) noexcept = 0;\n virtual DynamicVariableBase* clone() const = 0;\n};\n\n\/\/ It makes `DynamicVariable`s copyable and easier to handle.\ntemplate\nstruct DynamicVariable\n{\n using real_type = typename DynamicVariableBase::real_type;\n\n template\n explicit DynamicVariable(DynVar&& dynvar)\n : resource_(make_unique>(std::forward(dynvar)))\n {\n static_assert(std::is_base_of, DynVar>::value, \"\");\n }\n DynamicVariable(): resource_(nullptr) {}\n\n DynamicVariable(const DynamicVariable& other)\n : resource_(other.resource_->clone())\n {}\n DynamicVariable& operator=(const DynamicVariable& other)\n {\n this->resource_.reset(other.resource_->clone());\n return *this;\n }\n DynamicVariable(DynamicVariable&&) = default;\n DynamicVariable& operator=(DynamicVariable&&) = default;\n ~DynamicVariable() = default;\n\n real_type x() const noexcept {return resource_->x;}\n real_type v() const noexcept {return resource_->v;}\n real_type f() const noexcept {return resource_->f;}\n real_type m() const noexcept {return resource_->m;}\n real_type gamma() const noexcept {return resource_->gamma;}\n\n void update(real_type x, real_type v, real_type f) const noexcept\n {\n resource_->update(x, v, f);\n }\n\n private:\n std::unique_ptr> resource_;\n};\n\ntemplate\nstruct DefaultDynamicVariable : public DynamicVariableBase\n{\n using base_type = DynamicVariableBase;\n using real_type = typename base_type::real_type;\n\n DefaultDynamicVariable(const real_type x, const real_type v, const real_type f,\n const real_type m, const real_type gamma)\n : base_type{x, v, f, m, gamma,\n -std::numeric_limits::infinity(),\n std::numeric_limits::infinity()}\n {}\n ~DefaultDynamicVariable() override = default;\n\n void update(real_type x, real_type v, real_type f) noexcept override\n {\n this->x = x;\n this->v = v;\n this->f = f;\n return;\n }\n DynamicVariableBase* clone() const override\n {\n return new DefaultDynamicVariable(*this);\n }\n};\n\ntemplate\nstruct PeriodicDynamicVariable : public DynamicVariableBase\n{\n using base_type = DynamicVariableBase;\n using real_type = typename base_type::real_type;\n\n PeriodicDynamicVariable(const real_type x, const real_type v, const real_type f,\n const real_type m, const real_type gamma,\n const real_type lower, const real_type upper)\n : base_type(x, v, f, m, gamma, lower, upper)\n {}\n ~PeriodicDynamicVariable() override = default;\n\n void update(real_type x, real_type v, real_type f) noexcept override\n {\n this->x = x;\n if (this->x < this->lower) {this->x += (this->upper - this->lower);}\n else if (this->upper <= this->x) {this->x -= (this->upper - this->lower);}\n this->v = v;\n this->f = f;\n return;\n }\n DynamicVariableBase* clone() const override\n {\n return new PeriodicDynamicVariable(*this);\n }\n};\n\ntemplate\nstruct RepulsiveDynamicVariable : public DynamicVariableBase\n{\n using base_type = DynamicVariableBase;\n using real_type = typename base_type::real_type;\n\n RepulsiveDynamicVariable(const real_type x, const real_type v, const real_type f,\n const real_type m, const real_type gamma,\n const real_type lower, const real_type upper)\n : base_type(x, v, f, m, gamma, lower, upper)\n {}\n ~RepulsiveDynamicVariable() override = default;\n\n void update(real_type x, real_type v, real_type f) noexcept override\n {\n if(x < this->lower)\n {\n this->x = 2 * this->lower - x; \/\/ lower + (lower - x)\n this->v = -v;\n }\n else if (this->upper < x)\n {\n this->x = 2 * this->upper - x; \/\/ upper - (x - upper)\n this->v = -v;\n }\n else\n {\n this->x = x;\n this->v = v;\n }\n this->f = f;\n return;\n }\n DynamicVariableBase* clone() const override\n {\n return new RepulsiveDynamicVariable(*this);\n }\n};\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template class DynamicVariableBase;\nextern template class DynamicVariableBase;\nextern template class DynamicVariable;\nextern template class DynamicVariable;\nextern template class DefaultDynamicVariable;\nextern template class DefaultDynamicVariable;\nextern template class PeriodicDynamicVariable;\nextern template class PeriodicDynamicVariable;\nextern template class RepulsiveDynamicVariable;\nextern template class RepulsiveDynamicVariable;\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_CORE_DYNAMIC_VARIABLE_HPP\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2012, Zeex\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\/\/\r\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this\r\n\/\/ list of conditions and the following disclaimer. \r\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer in the documentation\r\n\/\/ and\/or other materials provided with the distribution. \r\n\/\/\r\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n\/\/ ANY 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\n\/\/ ANY 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#include \"os.h\"\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 \r\n#include \r\n#include \r\n#include \r\n\r\n#ifndef _GNU_SOURCE\r\n\t#define _GNU_SOURCE 1 \/\/ for dladdr()\r\n#endif\r\n#include \r\n\r\nconst char os::kDirSepChar = '\/';\r\n\r\nstd::string os::GetModulePath(void *address, std::size_t maxLength) {\r\n\tstd::vector name(maxLength + 1);\r\n\tif (address != 0) {\r\n\t\tDl_info info;\r\n\t\tdladdr(address, &info);\r\n\t\tstrncpy(name.data(), info.dli_fname, maxLength);\r\n\t}\t\r\n\treturn std::string(name.data());\r\n}\r\n\r\n\/\/ The crash handler - it is set via SetCrashHandler()\r\nstatic void (*crashHandler)() = 0;\r\n\r\n\/\/ Previous SIGSEGV handler\r\nstatic void (*previousSIGSEGVHandler)(int);\r\n\r\nstatic void HandleSIGSEGV(int sig)\r\n{\r\n\tif (::crashHandler != 0) {\r\n\t\t::crashHandler();\r\n\t}\r\n\tsignal(sig, SIG_DFL);\r\n}\r\n\r\nvoid os::SetCrashHandler(void (*handler)()) {\r\n\t::crashHandler = handler;\r\n\tif (handler != 0) {\r\n\t\t::previousSIGSEGVHandler = signal(SIGSEGV, HandleSIGSEGV);\r\n\t} else {\r\n\t\tsignal(SIGSEGV, ::previousSIGSEGVHandler);\r\n\t}\r\n}\r\n\r\n\/\/ The interrupt (Ctrl+C) handler - set via SetInterruptHandler\r\nstatic void (*interruptHandler)();\r\n\r\n\/\/ Previous SIGINT handler\r\nstatic void (*previousSIGINTHandler)(int);\r\n\r\n\/\/ Out SIGINT handler\r\nstatic void HandleSIGINT(int sig) {\r\n\tif (::interruptHandler != 0) {\r\n\t\t::interruptHandler();\r\n\t}\r\n\tsignal(sig, ::previousSIGINTHandler);\r\n\traise(sig);\r\n}\r\n\r\nvoid os::SetInterruptHandler(void (*handler)()) {\r\n\t::interruptHandler = handler;\r\n\t::previousSIGINTHandler = signal(SIGINT, HandleSIGINT);\r\n}\r\n\r\nstd::string os::GetSymbolName(void *address, std::size_t maxLength) {\r\n\tchar **symbols = backtrace_symbols(&address, 1);\r\n\tstd::string symbol(symbols[0]);\r\n\tstd::free(symbols);\r\n\r\n\tstd::string::size_type lp = symbol.find('(');\r\n\tstd::string::size_type rp = symbol.find_first_of(\")+-\");\r\n\r\n\tstd::string name;\r\n\tif (lp != std::string::npos && rp != std::string::npos) {\r\n\t\tname.assign(symbol.begin() + lp + 1, symbol.begin() + rp);\r\n\t}\r\n\r\n\tif (!name.empty()) {\r\n\t\tchar *demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, 0);\r\n\t\tif (demangled_name != 0) {\r\n\t\t\tname.assign(demangled_name);\r\n\t\t}\r\n\t}\t\r\n\r\n\treturn name;\r\n}\r\n\r\nvoid os::ListDirectoryFiles(const std::string &directory, const std::string &pattern,\r\n\t\tbool (*callback)(const char *, void *), void *userData) \r\n{\r\n\tDIR *dp;\r\n\tif ((dp = opendir(directory.c_str())) != 0) {\r\n\t\tstruct dirent *dirp;\r\n\t\twhile ((dirp = readdir(dp)) != 0) {\r\n\t\t\tif (!fnmatch(pattern.c_str(), dirp->d_name, FNM_CASEFOLD | FNM_NOESCAPE | FNM_PERIOD)) {\r\n\t\t\t\tcallback(dirp->d_name, userData);\r\n\t\t\t}\r\n\t\t}\r\n\t\tclosedir(dp);\r\n\t}\r\n}\r\nos-unix: Make GetSymbolName() strip type information from C++ names\/\/ Copyright (c) 2011-2012, Zeex\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\/\/\r\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this\r\n\/\/ list of conditions and the following disclaimer. \r\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\r\n\/\/ this list of conditions and the following disclaimer in the documentation\r\n\/\/ and\/or other materials provided with the distribution. \r\n\/\/\r\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\n\/\/ ANY 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 THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\n\/\/ ANY 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#include \"os.h\"\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 \r\n#include \r\n#include \r\n#include \r\n\r\n#ifndef _GNU_SOURCE\r\n\t#define _GNU_SOURCE 1 \/\/ for dladdr()\r\n#endif\r\n#include \r\n\r\nconst char os::kDirSepChar = '\/';\r\n\r\nstd::string os::GetModulePath(void *address, std::size_t maxLength) {\r\n\tstd::vector name(maxLength + 1);\r\n\tif (address != 0) {\r\n\t\tDl_info info;\r\n\t\tdladdr(address, &info);\r\n\t\tstrncpy(name.data(), info.dli_fname, maxLength);\r\n\t}\t\r\n\treturn std::string(name.data());\r\n}\r\n\r\n\/\/ The crash handler - it is set via SetCrashHandler()\r\nstatic void (*crashHandler)() = 0;\r\n\r\n\/\/ Previous SIGSEGV handler\r\nstatic void (*previousSIGSEGVHandler)(int);\r\n\r\nstatic void HandleSIGSEGV(int sig)\r\n{\r\n\tif (::crashHandler != 0) {\r\n\t\t::crashHandler();\r\n\t}\r\n\tsignal(sig, SIG_DFL);\r\n}\r\n\r\nvoid os::SetCrashHandler(void (*handler)()) {\r\n\t::crashHandler = handler;\r\n\tif (handler != 0) {\r\n\t\t::previousSIGSEGVHandler = signal(SIGSEGV, HandleSIGSEGV);\r\n\t} else {\r\n\t\tsignal(SIGSEGV, ::previousSIGSEGVHandler);\r\n\t}\r\n}\r\n\r\n\/\/ The interrupt (Ctrl+C) handler - set via SetInterruptHandler\r\nstatic void (*interruptHandler)();\r\n\r\n\/\/ Previous SIGINT handler\r\nstatic void (*previousSIGINTHandler)(int);\r\n\r\n\/\/ Out SIGINT handler\r\nstatic void HandleSIGINT(int sig) {\r\n\tif (::interruptHandler != 0) {\r\n\t\t::interruptHandler();\r\n\t}\r\n\tsignal(sig, ::previousSIGINTHandler);\r\n\traise(sig);\r\n}\r\n\r\nvoid os::SetInterruptHandler(void (*handler)()) {\r\n\t::interruptHandler = handler;\r\n\t::previousSIGINTHandler = signal(SIGINT, HandleSIGINT);\r\n}\r\n\r\nstd::string os::GetSymbolName(void *address, std::size_t maxLength) {\r\n\tchar **symbols = backtrace_symbols(&address, 1);\r\n\tstd::string symbol(symbols[0]);\r\n\tstd::free(symbols);\r\n\r\n\tstd::string::size_type lp = symbol.find('(');\r\n\tstd::string::size_type rp = symbol.find_first_of(\")+-\");\r\n\r\n\tstd::string name;\r\n\tif (lp != std::string::npos && rp != std::string::npos) {\r\n\t\tname.assign(symbol.begin() + lp + 1, symbol.begin() + rp);\r\n\t}\r\n\r\n\tif (!name.empty()) {\r\n\t\tchar *demangled_name = abi::__cxa_demangle(name.c_str(), 0, 0, 0);\r\n\t\tif (demangled_name != 0) {\r\n\t\t\tname.assign(demangled_name);\r\n\r\n\t\t\t\/\/ Cut argment type information e.g. (int*, char*, void*).\r\n\t\t\tstd::string::size_type end = name.find('(');\r\n\t\t\tif (end != std::string::npos) {\r\n\t\t\t\tname.erase(end);\r\n\t\t\t}\r\n\t\t}\r\n\t}\t\r\n\r\n\treturn name;\r\n}\r\n\r\nvoid os::ListDirectoryFiles(const std::string &directory, const std::string &pattern,\r\n\t\tbool (*callback)(const char *, void *), void *userData) \r\n{\r\n\tDIR *dp;\r\n\tif ((dp = opendir(directory.c_str())) != 0) {\r\n\t\tstruct dirent *dirp;\r\n\t\twhile ((dirp = readdir(dp)) != 0) {\r\n\t\t\tif (!fnmatch(pattern.c_str(), dirp->d_name, FNM_CASEFOLD | FNM_NOESCAPE | FNM_PERIOD)) {\r\n\t\t\t\tcallback(dirp->d_name, userData);\r\n\t\t\t}\r\n\t\t}\r\n\t\tclosedir(dp);\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2017 Alexandr 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 \"TelegramServerConfig.hpp\"\n#include \"TelegramServerUser.hpp\"\n#include \"DcConfiguration.hpp\"\n#include \"LocalCluster.hpp\"\n#include \"Session.hpp\"\n\n#include \"Utils.hpp\"\n#include \n#include \n#include \n\nusing namespace Telegram::Server;\n\n#ifdef USE_DBUS_NOTIFIER\n#include \n#include \n#include \"DefaultAuthorizationProvider.hpp\"\n\nclass DBusCodeAuthProvider : public Authorization::DefaultProvider\n{\nprotected:\n Authorization::Code generateCode(Session *session, const QString &identifier) override;\n};\n\nAuthorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)\n{\n Authorization::Code code = DefaultProvider::generateCode(session, identifier);\n QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral(\"org.freedesktop.Notifications\"),\n QStringLiteral(\"\/org\/freedesktop\/Notifications\"),\n QStringLiteral(\"org.freedesktop.Notifications\"),\n QStringLiteral(\"Notify\"));\n message.setArguments({\n QCoreApplication::applicationName(),\n QVariant::fromValue(0u),\n QString(),\n QStringLiteral(\"New auth code request\"),\n QStringLiteral(\"Auth code for account %1 is %2. Peer IP: %3\").arg(identifier, code.code, session->ip),\n QStringList(),\n QVariantMap(),\n 3000\n });\n\n \/\/ QString app_name, uint replaces_id, QString app_icon, QString summary,\n \/\/ QString body, QStringList actions, QVariantMap hints, int timeout\n QDBusConnection::sessionBus().send(message);\n return code;\n}\n#endif \/\/ USE_DBUS_NOTIFIER\n\nint main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n a.setOrganizationName(QStringLiteral(\"TelegramQt\"));\n a.setApplicationName(QStringLiteral(\"TelegramQt Server\"));\n Telegram::initialize();\n\n Config config;\n if (!config.load()) {\n \/\/ create \"default\" config file to ease editing\n config.save();\n }\n\n const Telegram::RsaKey key = Telegram::RsaKey::fromFile(config.privateKeyFile());\n if (!key.isValid()) {\n qCritical() << \"Unable to read RSA key. Please read README.md for more information.\";\n return -1;\n }\n\n LocalCluster cluster;\n cluster.setServerPrivateRsaKey(key);\n cluster.setServerConfiguration(config.serverConfiguration());\n\n#ifdef USE_DBUS_NOTIFIER\n DBusCodeAuthProvider authProvider;\n cluster.setAuthorizationProvider(&authProvider);\n qInfo() << \"DBus auth code provider enabled\";\n#endif\n\n cluster.start();\n\n return a.exec();\n}\nServer: add command line option to specify config location\/*\n Copyright (C) 2017 Alexandr 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 \"TelegramServerConfig.hpp\"\n#include \"TelegramServerUser.hpp\"\n#include \"DcConfiguration.hpp\"\n#include \"LocalCluster.hpp\"\n#include \"Session.hpp\"\n\n#include \"Utils.hpp\"\n#include \n#include \n#include \n#include \n\nusing namespace Telegram::Server;\n\n#ifdef USE_DBUS_NOTIFIER\n#include \n#include \n#include \"DefaultAuthorizationProvider.hpp\"\n\nclass DBusCodeAuthProvider : public Authorization::DefaultProvider\n{\nprotected:\n Authorization::Code generateCode(Session *session, const QString &identifier) override;\n};\n\nAuthorization::Code DBusCodeAuthProvider::generateCode(Session *session, const QString &identifier)\n{\n Authorization::Code code = DefaultProvider::generateCode(session, identifier);\n QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral(\"org.freedesktop.Notifications\"),\n QStringLiteral(\"\/org\/freedesktop\/Notifications\"),\n QStringLiteral(\"org.freedesktop.Notifications\"),\n QStringLiteral(\"Notify\"));\n message.setArguments({\n QCoreApplication::applicationName(),\n QVariant::fromValue(0u),\n QString(),\n QStringLiteral(\"New auth code request\"),\n QStringLiteral(\"Auth code for account %1 is %2. Peer IP: %3\").arg(identifier, code.code, session->ip),\n QStringList(),\n QVariantMap(),\n 3000\n });\n\n \/\/ QString app_name, uint replaces_id, QString app_icon, QString summary,\n \/\/ QString body, QStringList actions, QVariantMap hints, int timeout\n QDBusConnection::sessionBus().send(message);\n return code;\n}\n#endif \/\/ USE_DBUS_NOTIFIER\n\nint main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n a.setOrganizationName(QStringLiteral(\"TelegramQt\"));\n a.setApplicationName(QStringLiteral(\"TelegramQt Server\"));\n\n Telegram::initialize();\n\n QCommandLineParser parser;\n parser.addHelpOption();\n\n QCommandLineOption configFileOption(QStringList{ QStringLiteral(\"c\"), QStringLiteral(\"config\") });\n configFileOption.setDescription(QStringLiteral(\"Path to config file\"));\n configFileOption.setValueName(QStringLiteral(\"configFilePath\"));\n parser.addOption(configFileOption);\n\n parser.process(a);\n\n \/\/ where to load config file from?\n QString configFilePath;\n if (parser.isSet(configFileOption)) {\n configFilePath = parser.value(configFileOption);\n }\n\n \/\/ Load config\n Config config(configFilePath);\n if (!config.load()) {\n \/\/ create \"default\" config file to ease editing\n config.save();\n }\n\n const Telegram::RsaKey key = Telegram::RsaKey::fromFile(config.privateKeyFile());\n if (!key.isValid()) {\n qCritical() << \"Unable to read RSA key. Please read README.md for more information.\";\n return -1;\n }\n\n LocalCluster cluster;\n cluster.setServerPrivateRsaKey(key);\n cluster.setServerConfiguration(config.serverConfiguration());\n\n#ifdef USE_DBUS_NOTIFIER\n DBusCodeAuthProvider authProvider;\n cluster.setAuthorizationProvider(&authProvider);\n qInfo() << \"DBus auth code provider enabled\";\n#endif\n\n cluster.start();\n\n return a.exec();\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 \n\n#include \n#include \n#include \n\n#include \"liblibreoffice.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#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star;\n\nclass LibLODocument_Impl;\nclass LibLibreOffice_Impl;\n\nstatic LibLibreOffice_Impl *gImpl = NULL;\n\ntypedef struct {\n const char *extn;\n const char *filterName;\n} ExtensionMap;\n\nstatic const ExtensionMap\naWriterExtensionMap[] = {\n { \"doc\", \"MS Word 97\" },\n { \"docx\", \"MS Word 2007 XML\" },\n { \"fodt\", \"OpenDocument Text Flat XML\" },\n { \"html\", \"HTML (StarWriter)\" },\n { \"odt\", \"writer8\" },\n { \"ott\", \"writer8_template\" },\n { \"pdf\", \"writer_pdf_Export\" },\n { \"txt\", \"Text\" },\n { \"xhtml\", \"XHTML Writer File\" },\n { NULL, NULL }\n};\n\nstatic const ExtensionMap\naCalcExtensionMap[] = {\n { \"csv\", \"Text - txt - csv (StarCalc)\" },\n { \"fods\", \"OpenDocument Spreadsheet Flat XML\" },\n { \"html\", \"HTML (StarCalc)\" },\n { \"ods\", \"calc8\" },\n { \"ots\", \"calc8_template\" },\n { \"pdf\", \"calc_pdf_Export\" },\n { \"xhtml\", \"XHTML Calc File\" },\n { \"xls\", \"MS Excel 97\" },\n { \"xlsx\", \"Calc MS Excel 2007 XML\" },\n { NULL, NULL }\n};\n\nstatic const ExtensionMap\naImpressExtensionMap[] = {\n { \"fodp\", \"OpenDocument Presentation Flat XML\" },\n { \"html\", \"impress_html_Export\" },\n { \"odg\", \"impress8_draw\" },\n { \"odp\", \"impress8\" },\n { \"otp\", \"impress8_template\" },\n { \"pdf\", \"impress_pdf_Export\" },\n { \"potm\", \"Impress MS PowerPoint 2007 XML Template\" },\n { \"pot\", \"MS PowerPoint 97 Vorlage\" },\n { \"pptx\", \"Impress MS PowerPoint 2007 XML\" },\n { \"pps\", \"MS PowerPoint 97 Autoplay\" },\n { \"ppt\", \"MS PowerPoint 97\" },\n { \"svg\", \"impress_svg_Export\" },\n { \"swf\", \"impress_flash_Export\" },\n { \"xhtml\", \"XHTML Impress File\" },\n { NULL, NULL }\n};\n\nextern \"C\" {\n\nSAL_DLLPUBLIC_EXPORT LibreOffice *liblibreoffice_hook(void);\n\nstatic void doc_destroy( LibreOfficeDocument *pThis );\nstatic int doc_saveAs( LibreOfficeDocument *pThis, const char *pUrl, const char *pFormat );\n\nstruct LibLODocument_Impl : public _LibreOfficeDocument\n{\n uno::Reference < css::lang::XComponent > mxComponent;\n\n LibLODocument_Impl( const uno::Reference < css::lang::XComponent > &xComponent )\n : mxComponent( xComponent )\n {\n nSize = sizeof( LibreOffice );\n\n destroy = doc_destroy;\n saveAs = doc_saveAs;\n }\n};\n\nstatic void doc_destroy( LibreOfficeDocument *pThis )\n{\n LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );\n delete pDocument;\n}\n\nstatic void lo_destroy (LibreOffice *pThis);\nstatic int lo_initialize (LibreOffice *pThis,\n const char *pInstallPath);\nstatic LibreOfficeDocument *lo_documentLoad (LibreOffice *pThis,\n const char *pURL);\nstatic char * lo_getError (LibreOffice *pThis);\n\nstruct LibLibreOffice_Impl : public _LibreOffice\n{\n rtl::OUString maLastExceptionMsg;\n\n LibLibreOffice_Impl()\n {\n nSize = sizeof( LibreOfficeDocument );\n\n destroy = lo_destroy;\n initialize = lo_initialize;\n documentLoad = lo_documentLoad;\n getError = lo_getError;\n }\n};\n\n\/\/ Wonder global state ...\nstatic uno::Reference xContext;\nstatic uno::Reference xSFactory;\nstatic uno::Reference xFactory;\n\nstatic OUString getUString( const char *str )\n{\n if( !str )\n return OUString( \"\" );\n return OStringToOUString( OString( str, strlen (str) ),\n RTL_TEXTENCODING_UTF8 );\n}\n\n\/\/ Try to convert a relative URL to an absolute one\nstatic OUString getAbsoluteURL( const char *pURL )\n{\n OUString aURL( getUString( pURL ) );\n OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;\n\n \/\/ FIXME: this would appear to kill non-file URLs.\n osl_getProcessWorkingDir(&sWorkingDir.pData);\n osl::FileBase::getFileURLFromSystemPath( aURL, sDocPathUrl );\n osl::FileBase::getAbsoluteFileURL(sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);\n\n return sAbsoluteDocUrl;\n}\n\nstatic LibreOfficeDocument *\nlo_documentLoad( LibreOffice *pThis, const char *pURL )\n{\n LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );\n\n OUString aURL = getAbsoluteURL( pURL );\n\n uno::Reference < css::frame::XDesktop2 > xComponentLoader =\n css::frame::Desktop::create(xContext);\n\n pLib->maLastExceptionMsg = \"\";\n try {\n uno::Reference < css::lang::XComponent > xComponent =\n xComponentLoader->loadComponentFromURL(\n aURL, OUString(\"_blank\"), 0,\n uno::Sequence < css::beans::PropertyValue >());\n if( xComponentLoader.is() )\n return new LibLODocument_Impl( xComponent );\n else\n pLib->maLastExceptionMsg = \"unknown load failure\";\n } catch (const uno::Exception &ex) {\n pLib->maLastExceptionMsg = ex.Message;\n }\n return NULL;\n}\n\nstatic int\ndoc_saveAs( LibreOfficeDocument *pThis,\n const char *url, const char *format )\n{\n LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );\n\n OUString sFormat = getUString( format );\n\n OUString aURL = getAbsoluteURL( url );\n\n try {\n uno::Reference< frame::XModel > xDocument( pDocument->mxComponent,\n uno::UNO_QUERY_THROW );\n uno::Sequence< beans::PropertyValue > aSeq = xDocument->getArgs();\n\n OUString aDocumentService;\n for( sal_Int32 i = 0; i < aSeq.getLength(); ++i )\n {\n if( aSeq[i].Name == \"DocumentService\" )\n aSeq[i].Value >>= aDocumentService;\n OUString aValue;\n aSeq[i].Value >>= aValue;\n }\n\n if( aDocumentService == \"\")\n {\n gImpl->maLastExceptionMsg = \"Unknown document type\";\n return false;\n }\n const ExtensionMap *pMap;\n\n if( aDocumentService == \"com.sun.star.sheet.SpreadsheetDocument\" )\n pMap = (const ExtensionMap *)aCalcExtensionMap;\n else if( aDocumentService == \"com.sun.star.presentation.PresentationDocument\" )\n pMap = (const ExtensionMap *)aImpressExtensionMap;\n else \/\/ for the sake of argument only writer documents ...\n pMap = (const ExtensionMap *)aWriterExtensionMap;\n\n if( ! format )\n {\n \/\/ sniff from the extension\n sal_Int32 idx = aURL.lastIndexOf( \".\" );\n if( idx > 0 )\n {\n sFormat = aURL.copy( idx + 1 );\n }\n else\n {\n gImpl->maLastExceptionMsg = \"input filename without a suffix\";\n return false;\n }\n }\n\n OUString aFilterName;\n for( sal_Int32 i = 0; pMap[i].extn; i++ )\n {\n if( sFormat.equalsIgnoreAsciiCaseAscii( pMap[i].extn ) )\n {\n aFilterName = getUString( pMap[i].filterName );\n break;\n }\n }\n if( ! aFilterName.getLength() )\n {\n gImpl->maLastExceptionMsg = \"no output filter found for provided suffix\";\n return false;\n }\n\n aSeq.realloc(2);\n aSeq[0].Name = \"Overwrite\";\n aSeq[0].Value <<= sal_True;\n aSeq[1].Name = \"FilterName\";\n aSeq[1].Value <<= aFilterName;\n\n uno::Reference< frame::XStorable > xStorable( pDocument->mxComponent,\n uno::UNO_QUERY_THROW );\n xStorable->storeToURL( aURL, aSeq );\n\n return true;\n } catch (const uno::Exception &ex) {\n gImpl->maLastExceptionMsg = \"exception \" + ex.Message;\n return false;\n }\n}\n\nstatic char *\nlo_getError (LibreOffice *pThis)\n{\n LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );\n OString aStr = rtl::OUStringToOString( pLib->maLastExceptionMsg, RTL_TEXTENCODING_UTF8 );\n char *pMem = (char *) malloc (aStr.getLength() + 1);\n strcpy( pMem, aStr.getStr() );\n return pMem;\n}\n\nstatic void\nforce_c_locale( void )\n{\n \/\/ force locale (and resource files loaded) to en-US\n OUString aLangISO( \"en-US\" );\n LanguageTag aLocale( aLangISO );\n ResMgr::SetDefaultLocale( aLocale );\n SvtSysLocaleOptions aLocalOptions;\n aLocalOptions.SetLocaleConfigString( aLangISO );\n aLocalOptions.SetUILocaleConfigString( aLangISO );\n}\n\nstatic void\naBasicErrorFunc( const OUString &rErr, const OUString &rAction )\n{\n OStringBuffer aErr( \"Unexpected dialog: \" );\n aErr.append( OUStringToOString( rAction, RTL_TEXTENCODING_ASCII_US ) );\n aErr.append( \" Error: \" );\n aErr.append( OUStringToOString( rErr, RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"Unexpected basic error dialog '%s'\\n\", aErr.getStr() );\n}\n\nstatic void\ninitialize_uno( const OUString &aAppURL )\n{\n rtl::Bootstrap::setIniFilename( aAppURL + \"\/fundamentalrc\" );\n\n rtl::Bootstrap::set( \"CONFIGURATION_LAYERS\",\n \"xcsxcu:${BRAND_BASE_DIR}\/\" LIBO_SHARE_FOLDER \"\/registry \"\n \"res:${BRAND_BASE_DIR}\/\" LIBO_SHARE_FOLDER \"\/registry \"\n\/\/ \"bundledext:${${BRAND_BASE_DIR}\/\" LIBO_ETC_FOLDER \"\/unorc:BUNDLED_EXTENSIONS_USER}\/registry\/com.sun.star.comp.deployment.configuration.PackageRegistryBackend\/configmgr.ini \" );\n\/\/ \"sharedext:${${BRAND_BASE_DIR}\/\" LIBO_ETC_FOLDER \"\/unorc:SHARED_EXTENSIONS_USER}\/registry\/com.sun.star.comp.deployment.configuration.PackageRegistryBackend\/configmgr.ini \"\n\/\/ \"userext:${${BRAND_BASE_DIR}\/\" LIBO_ETC_FOLDER \"\/unorc:UNO_USER_PACKAGES_CACHE}\/registry\/com.sun.star.comp.deployment.configuration.PackageRegistryBackend\/configmgr.ini \"\n\/\/ \"user:${$BRAND_BASE_DIR\/\" LIBO_ETC_FOLDER \"\/bootstraprc:UserInstallation}\/user\/registrymodifications.xcu\"\n );\n\n xContext = cppu::defaultBootstrap_InitialComponentContext();\n fprintf( stderr, \"Uno initialized %d\\n\", xContext.is() );\n xFactory = xContext->getServiceManager();\n xSFactory = uno::Reference(xFactory, uno::UNO_QUERY_THROW);\n comphelper::setProcessServiceFactory(xSFactory);\n\n \/\/ set UserInstallation to user profile dir in test\/user-template\n\/\/ rtl::Bootstrap aDefaultVars;\n\/\/ aDefaultVars.set(OUString(\"UserInstallation\"), aAppURL + \"..\/registry\" );\n \/\/ configmgr setup ?\n}\n\nstatic int\nlo_initialize( LibreOffice *pThis, const char *app_path )\n{\n (void) pThis;\n\n static bool bInitialized = false;\n if( bInitialized )\n return 1;\n\n if( !app_path )\n return 0;\n\n OUString aAppPath( app_path, strlen( app_path ), RTL_TEXTENCODING_UTF8 );\n OUString aAppURL;\n if( osl::FileBase::getFileURLFromSystemPath( aAppPath, aAppURL ) !=\n osl::FileBase::E_None )\n return 0;\n\n try {\n initialize_uno( aAppURL );\n force_c_locale();\n\n \/\/ Force headless\n rtl::Bootstrap::set( \"SAL_USE_VCLPLUGIN\", \"svp\" );\n InitVCL();\n Application::EnableHeadlessMode(true);\n\n ErrorHandler::RegisterDisplay( aBasicErrorFunc );\n\n fprintf( stderr, \"initialized\\n\" );\n bInitialized = true;\n } catch (css::uno::Exception & e) {\n fprintf( stderr, \"bootstrapping exception '%s'\\n\",\n OUStringToOString( e.Message, RTL_TEXTENCODING_UTF8 ).getStr() );\n }\n return bInitialized;\n}\n\nLibreOffice *liblibreoffice_hook(void)\n{\n if( !gImpl )\n {\n fprintf( stderr, \"create libreoffice object\\n\" );\n gImpl = new LibLibreOffice_Impl();\n }\n return static_cast< LibreOffice *>( gImpl );\n}\n\nstatic void lo_destroy (LibreOffice *pThis)\n{\n LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );\n delete pLib;\n gImpl = NULL;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n-Werror,-Wmismatched-tags\/* -*- 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 \n\n#include \n#include \n#include \n\n#include \"liblibreoffice.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#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star;\n\nstruct LibLODocument_Impl;\nstruct LibLibreOffice_Impl;\n\nstatic LibLibreOffice_Impl *gImpl = NULL;\n\ntypedef struct {\n const char *extn;\n const char *filterName;\n} ExtensionMap;\n\nstatic const ExtensionMap\naWriterExtensionMap[] = {\n { \"doc\", \"MS Word 97\" },\n { \"docx\", \"MS Word 2007 XML\" },\n { \"fodt\", \"OpenDocument Text Flat XML\" },\n { \"html\", \"HTML (StarWriter)\" },\n { \"odt\", \"writer8\" },\n { \"ott\", \"writer8_template\" },\n { \"pdf\", \"writer_pdf_Export\" },\n { \"txt\", \"Text\" },\n { \"xhtml\", \"XHTML Writer File\" },\n { NULL, NULL }\n};\n\nstatic const ExtensionMap\naCalcExtensionMap[] = {\n { \"csv\", \"Text - txt - csv (StarCalc)\" },\n { \"fods\", \"OpenDocument Spreadsheet Flat XML\" },\n { \"html\", \"HTML (StarCalc)\" },\n { \"ods\", \"calc8\" },\n { \"ots\", \"calc8_template\" },\n { \"pdf\", \"calc_pdf_Export\" },\n { \"xhtml\", \"XHTML Calc File\" },\n { \"xls\", \"MS Excel 97\" },\n { \"xlsx\", \"Calc MS Excel 2007 XML\" },\n { NULL, NULL }\n};\n\nstatic const ExtensionMap\naImpressExtensionMap[] = {\n { \"fodp\", \"OpenDocument Presentation Flat XML\" },\n { \"html\", \"impress_html_Export\" },\n { \"odg\", \"impress8_draw\" },\n { \"odp\", \"impress8\" },\n { \"otp\", \"impress8_template\" },\n { \"pdf\", \"impress_pdf_Export\" },\n { \"potm\", \"Impress MS PowerPoint 2007 XML Template\" },\n { \"pot\", \"MS PowerPoint 97 Vorlage\" },\n { \"pptx\", \"Impress MS PowerPoint 2007 XML\" },\n { \"pps\", \"MS PowerPoint 97 Autoplay\" },\n { \"ppt\", \"MS PowerPoint 97\" },\n { \"svg\", \"impress_svg_Export\" },\n { \"swf\", \"impress_flash_Export\" },\n { \"xhtml\", \"XHTML Impress File\" },\n { NULL, NULL }\n};\n\nextern \"C\" {\n\nSAL_DLLPUBLIC_EXPORT LibreOffice *liblibreoffice_hook(void);\n\nstatic void doc_destroy( LibreOfficeDocument *pThis );\nstatic int doc_saveAs( LibreOfficeDocument *pThis, const char *pUrl, const char *pFormat );\n\nstruct LibLODocument_Impl : public _LibreOfficeDocument\n{\n uno::Reference < css::lang::XComponent > mxComponent;\n\n LibLODocument_Impl( const uno::Reference < css::lang::XComponent > &xComponent )\n : mxComponent( xComponent )\n {\n nSize = sizeof( LibreOffice );\n\n destroy = doc_destroy;\n saveAs = doc_saveAs;\n }\n};\n\nstatic void doc_destroy( LibreOfficeDocument *pThis )\n{\n LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );\n delete pDocument;\n}\n\nstatic void lo_destroy (LibreOffice *pThis);\nstatic int lo_initialize (LibreOffice *pThis,\n const char *pInstallPath);\nstatic LibreOfficeDocument *lo_documentLoad (LibreOffice *pThis,\n const char *pURL);\nstatic char * lo_getError (LibreOffice *pThis);\n\nstruct LibLibreOffice_Impl : public _LibreOffice\n{\n rtl::OUString maLastExceptionMsg;\n\n LibLibreOffice_Impl()\n {\n nSize = sizeof( LibreOfficeDocument );\n\n destroy = lo_destroy;\n initialize = lo_initialize;\n documentLoad = lo_documentLoad;\n getError = lo_getError;\n }\n};\n\n\/\/ Wonder global state ...\nstatic uno::Reference xContext;\nstatic uno::Reference xSFactory;\nstatic uno::Reference xFactory;\n\nstatic OUString getUString( const char *str )\n{\n if( !str )\n return OUString( \"\" );\n return OStringToOUString( OString( str, strlen (str) ),\n RTL_TEXTENCODING_UTF8 );\n}\n\n\/\/ Try to convert a relative URL to an absolute one\nstatic OUString getAbsoluteURL( const char *pURL )\n{\n OUString aURL( getUString( pURL ) );\n OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl;\n\n \/\/ FIXME: this would appear to kill non-file URLs.\n osl_getProcessWorkingDir(&sWorkingDir.pData);\n osl::FileBase::getFileURLFromSystemPath( aURL, sDocPathUrl );\n osl::FileBase::getAbsoluteFileURL(sWorkingDir, sDocPathUrl, sAbsoluteDocUrl);\n\n return sAbsoluteDocUrl;\n}\n\nstatic LibreOfficeDocument *\nlo_documentLoad( LibreOffice *pThis, const char *pURL )\n{\n LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );\n\n OUString aURL = getAbsoluteURL( pURL );\n\n uno::Reference < css::frame::XDesktop2 > xComponentLoader =\n css::frame::Desktop::create(xContext);\n\n pLib->maLastExceptionMsg = \"\";\n try {\n uno::Reference < css::lang::XComponent > xComponent =\n xComponentLoader->loadComponentFromURL(\n aURL, OUString(\"_blank\"), 0,\n uno::Sequence < css::beans::PropertyValue >());\n if( xComponentLoader.is() )\n return new LibLODocument_Impl( xComponent );\n else\n pLib->maLastExceptionMsg = \"unknown load failure\";\n } catch (const uno::Exception &ex) {\n pLib->maLastExceptionMsg = ex.Message;\n }\n return NULL;\n}\n\nstatic int\ndoc_saveAs( LibreOfficeDocument *pThis,\n const char *url, const char *format )\n{\n LibLODocument_Impl *pDocument = static_cast< LibLODocument_Impl *>( pThis );\n\n OUString sFormat = getUString( format );\n\n OUString aURL = getAbsoluteURL( url );\n\n try {\n uno::Reference< frame::XModel > xDocument( pDocument->mxComponent,\n uno::UNO_QUERY_THROW );\n uno::Sequence< beans::PropertyValue > aSeq = xDocument->getArgs();\n\n OUString aDocumentService;\n for( sal_Int32 i = 0; i < aSeq.getLength(); ++i )\n {\n if( aSeq[i].Name == \"DocumentService\" )\n aSeq[i].Value >>= aDocumentService;\n OUString aValue;\n aSeq[i].Value >>= aValue;\n }\n\n if( aDocumentService == \"\")\n {\n gImpl->maLastExceptionMsg = \"Unknown document type\";\n return false;\n }\n const ExtensionMap *pMap;\n\n if( aDocumentService == \"com.sun.star.sheet.SpreadsheetDocument\" )\n pMap = (const ExtensionMap *)aCalcExtensionMap;\n else if( aDocumentService == \"com.sun.star.presentation.PresentationDocument\" )\n pMap = (const ExtensionMap *)aImpressExtensionMap;\n else \/\/ for the sake of argument only writer documents ...\n pMap = (const ExtensionMap *)aWriterExtensionMap;\n\n if( ! format )\n {\n \/\/ sniff from the extension\n sal_Int32 idx = aURL.lastIndexOf( \".\" );\n if( idx > 0 )\n {\n sFormat = aURL.copy( idx + 1 );\n }\n else\n {\n gImpl->maLastExceptionMsg = \"input filename without a suffix\";\n return false;\n }\n }\n\n OUString aFilterName;\n for( sal_Int32 i = 0; pMap[i].extn; i++ )\n {\n if( sFormat.equalsIgnoreAsciiCaseAscii( pMap[i].extn ) )\n {\n aFilterName = getUString( pMap[i].filterName );\n break;\n }\n }\n if( ! aFilterName.getLength() )\n {\n gImpl->maLastExceptionMsg = \"no output filter found for provided suffix\";\n return false;\n }\n\n aSeq.realloc(2);\n aSeq[0].Name = \"Overwrite\";\n aSeq[0].Value <<= sal_True;\n aSeq[1].Name = \"FilterName\";\n aSeq[1].Value <<= aFilterName;\n\n uno::Reference< frame::XStorable > xStorable( pDocument->mxComponent,\n uno::UNO_QUERY_THROW );\n xStorable->storeToURL( aURL, aSeq );\n\n return true;\n } catch (const uno::Exception &ex) {\n gImpl->maLastExceptionMsg = \"exception \" + ex.Message;\n return false;\n }\n}\n\nstatic char *\nlo_getError (LibreOffice *pThis)\n{\n LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );\n OString aStr = rtl::OUStringToOString( pLib->maLastExceptionMsg, RTL_TEXTENCODING_UTF8 );\n char *pMem = (char *) malloc (aStr.getLength() + 1);\n strcpy( pMem, aStr.getStr() );\n return pMem;\n}\n\nstatic void\nforce_c_locale( void )\n{\n \/\/ force locale (and resource files loaded) to en-US\n OUString aLangISO( \"en-US\" );\n LanguageTag aLocale( aLangISO );\n ResMgr::SetDefaultLocale( aLocale );\n SvtSysLocaleOptions aLocalOptions;\n aLocalOptions.SetLocaleConfigString( aLangISO );\n aLocalOptions.SetUILocaleConfigString( aLangISO );\n}\n\nstatic void\naBasicErrorFunc( const OUString &rErr, const OUString &rAction )\n{\n OStringBuffer aErr( \"Unexpected dialog: \" );\n aErr.append( OUStringToOString( rAction, RTL_TEXTENCODING_ASCII_US ) );\n aErr.append( \" Error: \" );\n aErr.append( OUStringToOString( rErr, RTL_TEXTENCODING_ASCII_US ) );\n fprintf( stderr, \"Unexpected basic error dialog '%s'\\n\", aErr.getStr() );\n}\n\nstatic void\ninitialize_uno( const OUString &aAppURL )\n{\n rtl::Bootstrap::setIniFilename( aAppURL + \"\/fundamentalrc\" );\n\n rtl::Bootstrap::set( \"CONFIGURATION_LAYERS\",\n \"xcsxcu:${BRAND_BASE_DIR}\/\" LIBO_SHARE_FOLDER \"\/registry \"\n \"res:${BRAND_BASE_DIR}\/\" LIBO_SHARE_FOLDER \"\/registry \"\n\/\/ \"bundledext:${${BRAND_BASE_DIR}\/\" LIBO_ETC_FOLDER \"\/unorc:BUNDLED_EXTENSIONS_USER}\/registry\/com.sun.star.comp.deployment.configuration.PackageRegistryBackend\/configmgr.ini \" );\n\/\/ \"sharedext:${${BRAND_BASE_DIR}\/\" LIBO_ETC_FOLDER \"\/unorc:SHARED_EXTENSIONS_USER}\/registry\/com.sun.star.comp.deployment.configuration.PackageRegistryBackend\/configmgr.ini \"\n\/\/ \"userext:${${BRAND_BASE_DIR}\/\" LIBO_ETC_FOLDER \"\/unorc:UNO_USER_PACKAGES_CACHE}\/registry\/com.sun.star.comp.deployment.configuration.PackageRegistryBackend\/configmgr.ini \"\n\/\/ \"user:${$BRAND_BASE_DIR\/\" LIBO_ETC_FOLDER \"\/bootstraprc:UserInstallation}\/user\/registrymodifications.xcu\"\n );\n\n xContext = cppu::defaultBootstrap_InitialComponentContext();\n fprintf( stderr, \"Uno initialized %d\\n\", xContext.is() );\n xFactory = xContext->getServiceManager();\n xSFactory = uno::Reference(xFactory, uno::UNO_QUERY_THROW);\n comphelper::setProcessServiceFactory(xSFactory);\n\n \/\/ set UserInstallation to user profile dir in test\/user-template\n\/\/ rtl::Bootstrap aDefaultVars;\n\/\/ aDefaultVars.set(OUString(\"UserInstallation\"), aAppURL + \"..\/registry\" );\n \/\/ configmgr setup ?\n}\n\nstatic int\nlo_initialize( LibreOffice *pThis, const char *app_path )\n{\n (void) pThis;\n\n static bool bInitialized = false;\n if( bInitialized )\n return 1;\n\n if( !app_path )\n return 0;\n\n OUString aAppPath( app_path, strlen( app_path ), RTL_TEXTENCODING_UTF8 );\n OUString aAppURL;\n if( osl::FileBase::getFileURLFromSystemPath( aAppPath, aAppURL ) !=\n osl::FileBase::E_None )\n return 0;\n\n try {\n initialize_uno( aAppURL );\n force_c_locale();\n\n \/\/ Force headless\n rtl::Bootstrap::set( \"SAL_USE_VCLPLUGIN\", \"svp\" );\n InitVCL();\n Application::EnableHeadlessMode(true);\n\n ErrorHandler::RegisterDisplay( aBasicErrorFunc );\n\n fprintf( stderr, \"initialized\\n\" );\n bInitialized = true;\n } catch (css::uno::Exception & e) {\n fprintf( stderr, \"bootstrapping exception '%s'\\n\",\n OUStringToOString( e.Message, RTL_TEXTENCODING_UTF8 ).getStr() );\n }\n return bInitialized;\n}\n\nLibreOffice *liblibreoffice_hook(void)\n{\n if( !gImpl )\n {\n fprintf( stderr, \"create libreoffice object\\n\" );\n gImpl = new LibLibreOffice_Impl();\n }\n return static_cast< LibreOffice *>( gImpl );\n}\n\nstatic void lo_destroy (LibreOffice *pThis)\n{\n LibLibreOffice_Impl *pLib = static_cast< LibLibreOffice_Impl *>( pThis );\n delete pLib;\n gImpl = NULL;\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \"musicmarqueewidget.h\"\n#include \n\nMusicMarqueeWidget::MusicMarqueeWidget(QWidget *parent)\n : QWidget(parent)\n{\n m_offset = 0;\n m_myTimerId = 0;\n}\n\nvoid MusicMarqueeWidget::setText(const QString &newText)\n{\n m_myText = newText.leftJustified(50, ' ');\n update();\n updateGeometry();\n}\n\nQSize MusicMarqueeWidget::sizeHint() const\n{\n return fontMetrics().size(0, text());\n}\n\nvoid MusicMarqueeWidget::paintEvent(QPaintEvent *)\n{\n QPainter painter(this);\n\n int textWidth = fontMetrics().width(text());\n if(textWidth < 1)\n {\n return;\n }\n int x = -m_offset;\n while(x < width())\n {\n painter.drawText(x, 0, textWidth, height(),\n Qt::AlignLeft | Qt::AlignVCenter, text());\n x += textWidth;\n }\n painter.end();\n}\n\nvoid MusicMarqueeWidget::showEvent(QShowEvent *)\n{\n m_myTimerId = startTimer(30);\n}\n\nvoid MusicMarqueeWidget::timerEvent(QTimerEvent *event)\n{\n if(event->timerId() == m_myTimerId)\n {\n ++m_offset;\n if (m_offset >= fontMetrics().width(text()))\n {\n m_offset = 0;\n }\n scroll(-1, 0);\n }\n else\n {\n QWidget::timerEvent(event);\n }\n}\n\nvoid MusicMarqueeWidget::hideEvent(QHideEvent *)\n{\n killTimer(m_myTimerId);\n m_myTimerId = 0;\n}\noptimized marquee widgte size[320187]#include \"musicmarqueewidget.h\"\n#include \n\nMusicMarqueeWidget::MusicMarqueeWidget(QWidget *parent)\n : QWidget(parent)\n{\n m_offset = 0;\n m_myTimerId = 0;\n}\n\nvoid MusicMarqueeWidget::setText(const QString &newText)\n{\n m_myText = newText.leftJustified(fontMetrics().width(newText) >= width()\n ? 45 : 25, ' ');\n update();\n updateGeometry();\n}\n\nQSize MusicMarqueeWidget::sizeHint() const\n{\n return fontMetrics().size(0, text());\n}\n\nvoid MusicMarqueeWidget::paintEvent(QPaintEvent *event)\n{\n QWidget::paintEvent(event);\n QPainter painter(this);\n int textWidth = fontMetrics().width(text());\n if(textWidth < 1)\n {\n return;\n }\n int x = -m_offset;\n while(x < width())\n {\n painter.drawText(x, 0, textWidth, height(),\n Qt::AlignLeft | Qt::AlignVCenter, text());\n x += textWidth;\n }\n painter.end();\n}\n\nvoid MusicMarqueeWidget::showEvent(QShowEvent *event)\n{\n QWidget::showEvent(event);\n m_myTimerId = startTimer(30);\n}\n\nvoid MusicMarqueeWidget::timerEvent(QTimerEvent *event)\n{\n if(event->timerId() == m_myTimerId)\n {\n ++m_offset;\n if (m_offset >= fontMetrics().width(text()))\n {\n m_offset = 0;\n }\n scroll(-1, 0);\n }\n else\n {\n QWidget::timerEvent(event);\n }\n}\n\nvoid MusicMarqueeWidget::hideEvent(QHideEvent *event)\n{\n QWidget::hideEvent(event);\n killTimer(m_myTimerId);\n m_myTimerId = 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n\/\/ https:\/\/infektor.net\/posts\/2017-03-31-range-based-enumerate.html\n\n#include \n#include \n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n namespace _enumerate_internal\n {\n template struct enumerate_iterator\n {\n using iterator = Iterator;\n \/\/using index_type = typename std::iterator_traits::difference_type;\n using reference = typename std::iterator_traits::reference;\n\n inline enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}\n inline enumerate_iterator& operator++() { ++index; ++iter; return *this; }\n inline bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }\n inline std::pair operator*() { return {index, *iter}; }\n\n private:\n index_type index;\n iterator iter;\n };\n\n \/\/ ----------------------------------------------------------------------\n\n template struct enumerate_range\n {\n \/\/ using index_type = typename std::iterator_traits::difference_type;\n using iterator = enumerate_iterator;\n\n inline enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}\n inline iterator begin() const { return iterator(initial, first); }\n inline iterator end() const { return iterator(0, last); }\n\n private:\n Iterator first;\n Iterator last;\n index_type initial;\n };\n\n } \/\/ namespace _enumerate_internal\n\n\/\/ ----------------------------------------------------------------------\n\n template inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)\n {\n return _enumerate_internal::enumerate_range(first, last, initial);\n }\n\n template inline auto enumerate(Container& content, size_t initial = 0)\n {\n using iter_type = decltype(std::begin(content));\n return _enumerate_internal::enumerate_range(std::begin(content), std::end(content), initial);\n }\n\n template inline auto enumerate(const Container& content, size_t initial = 0)\n {\n using iter_type = decltype(std::begin(content));\n return _enumerate_internal::enumerate_range(std::begin(content), std::end(content), initial);\n }\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nminor fix#pragma once\n\n\/\/ https:\/\/infektor.net\/posts\/2017-03-31-range-based-enumerate.html\n\n#include \n#include \n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n namespace _enumerate_internal\n {\n template struct enumerate_iterator\n {\n using iterator = Iterator;\n \/\/using index_type = typename std::iterator_traits::difference_type;\n using reference = typename std::iterator_traits::reference;\n\n enumerate_iterator(index_type aIndex, iterator aIterator) : index(aIndex), iter(aIterator) {}\n enumerate_iterator& operator++() { ++index; ++iter; return *this; }\n bool operator!=(const enumerate_iterator &other) const { return iter != other.iter; }\n std::pair operator*() { return {index, *iter}; }\n\n private:\n index_type index;\n iterator iter;\n };\n\n \/\/ ----------------------------------------------------------------------\n\n template struct enumerate_range\n {\n \/\/ using index_type = typename std::iterator_traits::difference_type;\n using iterator = enumerate_iterator;\n\n enumerate_range(Iterator aFirst, Iterator aLast, index_type aInitial) : first(aFirst), last(aLast), initial(aInitial) {}\n iterator begin() const { return iterator(initial, first); }\n iterator end() const { return iterator(0, last); }\n\n private:\n Iterator first;\n Iterator last;\n index_type initial;\n };\n\n } \/\/ namespace _enumerate_internal\n\n\/\/ ----------------------------------------------------------------------\n\n template inline auto enumerate(Iterator first, Iterator last, index_type initial = 0)\n {\n return _enumerate_internal::enumerate_range(first, last, initial);\n }\n\n template inline auto enumerate(Container& content, size_t initial = 0)\n {\n using iter_type = decltype(std::begin(content));\n return _enumerate_internal::enumerate_range(std::begin(content), std::end(content), initial);\n }\n\n template inline auto enumerate(const Container& content, size_t initial = 0)\n {\n using iter_type = decltype(std::begin(content));\n return _enumerate_internal::enumerate_range(std::begin(content), std::end(content), initial);\n }\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"\/\/ @(#)root\/base:$Id$\n\/\/ Author: Christian Bormann 13\/10\/97\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\/\/ TSystemDirectory \/\/\n\/\/ \/\/\n\/\/ Describes an Operating System directory for the browser. \/\/\n\/\/ \/\/\n\/\/ Author: Christian Bormann 30\/09\/97 \/\/\n\/\/ http:\/\/www.ikf.physik.uni-frankfurt.de\/~bormann\/ \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TSystemDirectory.h\"\n#include \"TSystem.h\"\n#include \"TBrowser.h\"\n#include \"TOrdCollection.h\"\n#include \"TList.h\"\n\n\nClassImp(TSystemDirectory);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a system directory object.\n\nTSystemDirectory::TSystemDirectory()\n{\n fDirsInBrowser = 0;\n fFilesInBrowser = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a system directory object.\n\nTSystemDirectory::TSystemDirectory(const char *dirname, const char *path) :\n TSystemFile(dirname, path)\n{\n fDirsInBrowser = 0;\n fFilesInBrowser = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/copy constructor\n\nTSystemDirectory::TSystemDirectory(const TSystemDirectory& sd) :\n TSystemFile(sd),\n fDirsInBrowser(sd.fDirsInBrowser),\n fFilesInBrowser(sd.fFilesInBrowser)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/assignment operator\n\nTSystemDirectory& TSystemDirectory::operator=(const TSystemDirectory& sd)\n{\n if(this!=&sd) {\n TSystemFile::operator=(sd);\n fDirsInBrowser=sd.fDirsInBrowser;\n fFilesInBrowser=sd.fFilesInBrowser;\n }\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Delete system directory object.\n\nTSystemDirectory::~TSystemDirectory()\n{\n delete fDirsInBrowser;\n delete fFilesInBrowser;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns a TList of TSystemFile objects representing the contents\n\/\/\/ of the directory. It's the responsibility of the user to delete\n\/\/\/ the list (the list owns the contained objects).\n\/\/\/ Returns 0 in case of errors.\n\nTList *TSystemDirectory::GetListOfFiles() const\n{\n void *dir = gSystem->OpenDirectory(GetTitle());\n if (!dir) return 0;\n\n const char *file = 0;\n TList *contents = new TList;\n contents->SetOwner();\n while ((file = gSystem->GetDirEntry(dir))) {\n if (IsItDirectory(file)) {\n TString sdirpath;\n if (file[0] == '.' && file[1] == '\\0')\n sdirpath = GetTitle();\n else if (file[0] == '.' && file[1] == '.' && file[2] == '.')\n sdirpath = gSystem->DirName(GetTitle());\n else {\n sdirpath = GetTitle();\n if (!sdirpath.EndsWith(\"\/\"))\n sdirpath += \"\/\";\n sdirpath += file;\n }\n contents->Add(new TSystemDirectory(file, sdirpath.Data()));\n } else\n contents->Add(new TSystemFile(file, GetTitle()));\n }\n gSystem->FreeDirectory(dir);\n return contents;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a system directory object.\n\nvoid TSystemDirectory::SetDirectory(const char *name)\n{\n SetName(name);\n SetTitle(name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Check if name is a directory.\n\nBool_t TSystemDirectory::IsItDirectory(const char *name) const\n{\n Long64_t size;\n Long_t id, flags, modtime;\n const char *dirfile = GetTitle();\n TString savDir = gSystem->WorkingDirectory();\n\n gSystem->ChangeDirectory(dirfile);\n flags = id = size = modtime = 0;\n gSystem->GetPathInfo(name, &id, &size, &flags, &modtime);\n Int_t isdir = (Int_t)flags & 2;\n\n gSystem->ChangeDirectory(savDir);\n return isdir ? kTRUE : kFALSE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Browse OS system directories.\n\nvoid TSystemDirectory::Browse(TBrowser *b)\n{\n \/\/ Collections to keep track of all browser objects that have been\n \/\/ generated. It's main goal is to prevent the contineous\n \/\/ allocations of new objects with the same names during browsing.\n if (!fDirsInBrowser) fDirsInBrowser = new TOrdCollection;\n if (!fFilesInBrowser) fFilesInBrowser = new TOrdCollection(10);\n\n const char *name = GetTitle();\n TSystemFile *sfile;\n TSystemDirectory *sdir;\n const char *file;\n\n gSystem->ChangeDirectory(name);\n\n if (GetName()[0] == '.' && GetName()[1] == '.')\n SetName(gSystem->BaseName(name));\n\n void *dir = gSystem->OpenDirectory(name);\n\n if (!dir)\n return;\n\n while ((file = gSystem->GetDirEntry(dir))) {\n if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )\n continue;\n if (IsItDirectory(file)) {\n TString sdirpath;\n if (!strcmp(file, \".\"))\n sdirpath = name;\n else if (!strcmp(file, \"..\"))\n sdirpath = gSystem->DirName(name);\n else {\n sdirpath = name;\n if (!sdirpath.EndsWith(\"\/\"))\n sdirpath += \"\/\";\n sdirpath += file;\n }\n if (!(sdir = FindDirObj(sdirpath.Data()))) {\n sdir = new TSystemDirectory(file, sdirpath.Data());\n fDirsInBrowser->Add(sdir);\n }\n b->Add(sdir, file);\n } else {\n if (!(sfile = FindFileObj(file, gSystem->WorkingDirectory()))) {\n sfile = new TSystemFile(file, gSystem->WorkingDirectory());\n fFilesInBrowser->Add(sfile);\n }\n b->Add(sfile, file);\n }\n }\n gSystem->FreeDirectory(dir);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Method that returns system directory object if it\n\/\/\/ exists in list, 0 otherwise.\n\nTSystemDirectory *TSystemDirectory::FindDirObj(const char *name)\n{\n int size = fDirsInBrowser->GetSize();\n for (int i = 0; i < size; i++) {\n TSystemDirectory *obj = (TSystemDirectory *) fDirsInBrowser->At(i);\n if (!strcmp(name, obj->GetTitle()))\n return obj;\n }\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Method that returns system file object if it exists in\n\/\/\/ list, 0 otherwise.\n\nTSystemFile *TSystemDirectory::FindFileObj(const char *name, const char *dir)\n{\n int size = fFilesInBrowser->GetSize();\n for (int i = 0; i < size; i++) {\n TSystemFile *obj = (TSystemFile *) fFilesInBrowser->At(i);\n if (!strcmp(name, obj->GetName()) && !strcmp(dir, obj->GetTitle()))\n return obj;\n }\n return 0;\n}\nDoxygen\/\/ @(#)root\/base:$Id$\n\/\/ Author: Christian Bormann 13\/10\/97\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\/** \\class TSystemDirectory\nDescribes an Operating System directory for the browser.\n*\/\n\n#include \"TSystemDirectory.h\"\n#include \"TSystem.h\"\n#include \"TBrowser.h\"\n#include \"TOrdCollection.h\"\n#include \"TList.h\"\n\n\nClassImp(TSystemDirectory);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a system directory object.\n\nTSystemDirectory::TSystemDirectory()\n{\n fDirsInBrowser = 0;\n fFilesInBrowser = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a system directory object.\n\nTSystemDirectory::TSystemDirectory(const char *dirname, const char *path) :\n TSystemFile(dirname, path)\n{\n fDirsInBrowser = 0;\n fFilesInBrowser = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Copy constructor\n\nTSystemDirectory::TSystemDirectory(const TSystemDirectory& sd) :\n TSystemFile(sd),\n fDirsInBrowser(sd.fDirsInBrowser),\n fFilesInBrowser(sd.fFilesInBrowser)\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Assignment operator\n\nTSystemDirectory& TSystemDirectory::operator=(const TSystemDirectory& sd)\n{\n if(this!=&sd) {\n TSystemFile::operator=(sd);\n fDirsInBrowser=sd.fDirsInBrowser;\n fFilesInBrowser=sd.fFilesInBrowser;\n }\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Delete system directory object.\n\nTSystemDirectory::~TSystemDirectory()\n{\n delete fDirsInBrowser;\n delete fFilesInBrowser;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns a TList of TSystemFile objects representing the contents\n\/\/\/ of the directory. It's the responsibility of the user to delete\n\/\/\/ the list (the list owns the contained objects).\n\/\/\/ Returns 0 in case of errors.\n\nTList *TSystemDirectory::GetListOfFiles() const\n{\n void *dir = gSystem->OpenDirectory(GetTitle());\n if (!dir) return 0;\n\n const char *file = 0;\n TList *contents = new TList;\n contents->SetOwner();\n while ((file = gSystem->GetDirEntry(dir))) {\n if (IsItDirectory(file)) {\n TString sdirpath;\n if (file[0] == '.' && file[1] == '\\0')\n sdirpath = GetTitle();\n else if (file[0] == '.' && file[1] == '.' && file[2] == '.')\n sdirpath = gSystem->DirName(GetTitle());\n else {\n sdirpath = GetTitle();\n if (!sdirpath.EndsWith(\"\/\"))\n sdirpath += \"\/\";\n sdirpath += file;\n }\n contents->Add(new TSystemDirectory(file, sdirpath.Data()));\n } else\n contents->Add(new TSystemFile(file, GetTitle()));\n }\n gSystem->FreeDirectory(dir);\n return contents;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Create a system directory object.\n\nvoid TSystemDirectory::SetDirectory(const char *name)\n{\n SetName(name);\n SetTitle(name);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Check if name is a directory.\n\nBool_t TSystemDirectory::IsItDirectory(const char *name) const\n{\n Long64_t size;\n Long_t id, flags, modtime;\n const char *dirfile = GetTitle();\n TString savDir = gSystem->WorkingDirectory();\n\n gSystem->ChangeDirectory(dirfile);\n flags = id = size = modtime = 0;\n gSystem->GetPathInfo(name, &id, &size, &flags, &modtime);\n Int_t isdir = (Int_t)flags & 2;\n\n gSystem->ChangeDirectory(savDir);\n return isdir ? kTRUE : kFALSE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Browse OS system directories.\n\nvoid TSystemDirectory::Browse(TBrowser *b)\n{\n \/\/ Collections to keep track of all browser objects that have been\n \/\/ generated. It's main goal is to prevent the continuous\n \/\/ allocations of new objects with the same names during browsing.\n if (!fDirsInBrowser) fDirsInBrowser = new TOrdCollection;\n if (!fFilesInBrowser) fFilesInBrowser = new TOrdCollection(10);\n\n const char *name = GetTitle();\n TSystemFile *sfile;\n TSystemDirectory *sdir;\n const char *file;\n\n gSystem->ChangeDirectory(name);\n\n if (GetName()[0] == '.' && GetName()[1] == '.')\n SetName(gSystem->BaseName(name));\n\n void *dir = gSystem->OpenDirectory(name);\n\n if (!dir)\n return;\n\n while ((file = gSystem->GetDirEntry(dir))) {\n if (b->TestBit(TBrowser::kNoHidden) && file[0] == '.' && file[1] != '.' )\n continue;\n if (IsItDirectory(file)) {\n TString sdirpath;\n if (!strcmp(file, \".\"))\n sdirpath = name;\n else if (!strcmp(file, \"..\"))\n sdirpath = gSystem->DirName(name);\n else {\n sdirpath = name;\n if (!sdirpath.EndsWith(\"\/\"))\n sdirpath += \"\/\";\n sdirpath += file;\n }\n if (!(sdir = FindDirObj(sdirpath.Data()))) {\n sdir = new TSystemDirectory(file, sdirpath.Data());\n fDirsInBrowser->Add(sdir);\n }\n b->Add(sdir, file);\n } else {\n if (!(sfile = FindFileObj(file, gSystem->WorkingDirectory()))) {\n sfile = new TSystemFile(file, gSystem->WorkingDirectory());\n fFilesInBrowser->Add(sfile);\n }\n b->Add(sfile, file);\n }\n }\n gSystem->FreeDirectory(dir);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Method that returns system directory object if it\n\/\/\/ exists in list, 0 otherwise.\n\nTSystemDirectory *TSystemDirectory::FindDirObj(const char *name)\n{\n int size = fDirsInBrowser->GetSize();\n for (int i = 0; i < size; i++) {\n TSystemDirectory *obj = (TSystemDirectory *) fDirsInBrowser->At(i);\n if (!strcmp(name, obj->GetTitle()))\n return obj;\n }\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Method that returns system file object if it exists in\n\/\/\/ list, 0 otherwise.\n\nTSystemFile *TSystemDirectory::FindFileObj(const char *name, const char *dir)\n{\n int size = fFilesInBrowser->GetSize();\n for (int i = 0; i < size; i++) {\n TSystemFile *obj = (TSystemFile *) fFilesInBrowser->At(i);\n if (!strcmp(name, obj->GetName()) && !strcmp(dir, obj->GetTitle()))\n return obj;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"pbfParser.h\"\n#include \"platform.h\"\n#include \"tileID.h\"\n\n#include \n#include \n\n#include \"protobuffSrc.h\"\n\nMapboxProtoBuffSrc::MapboxProtoBuffSrc() {\n m_urlTemplate = \"http:\/\/vector.mapzen.com\/osm\/all\/[z]\/[x]\/[y].mapbox\";\n}\n\nstd::shared_ptr MapboxProtoBuffSrc::parse(const MapTile& _tile, std::stringstream& _in) {\n \n std::shared_ptr tileData = std::make_shared();\n \n std::string buffer(std::istreambuf_iterator(_in.rdbuf()), (std::istreambuf_iterator()));\n \n protobuf::message item(buffer.data(), buffer.size());\n \n while(item.next()) {\n if(item.tag == 3) {\n protobuf::message layerMsg = item.getMessage();\n protobuf::message layerItr = layerMsg;\n while (layerItr.next()) {\n if (layerItr.tag == 1) {\n auto layerName = layerItr.string();\n tileData->layers.emplace_back(layerName);\n PbfParser::extractLayer(layerMsg, tileData->layers.back(), _tile);\n } else {\n layerItr.skip();\n }\n }\n } else {\n item.skip();\n }\n }\n return tileData;\n}\nrenamed header inclusion#include \"pbfParser.h\"\n#include \"platform.h\"\n#include \"tileID.h\"\n\n#include \n#include \n\n#include \"protobufSrc.h\"\n\nMapboxProtoBuffSrc::MapboxProtoBuffSrc() {\n m_urlTemplate = \"http:\/\/vector.mapzen.com\/osm\/all\/[z]\/[x]\/[y].mapbox\";\n}\n\nstd::shared_ptr MapboxProtoBuffSrc::parse(const MapTile& _tile, std::stringstream& _in) {\n \n std::shared_ptr tileData = std::make_shared();\n \n std::string buffer(std::istreambuf_iterator(_in.rdbuf()), (std::istreambuf_iterator()));\n \n protobuf::message item(buffer.data(), buffer.size());\n \n while(item.next()) {\n if(item.tag == 3) {\n protobuf::message layerMsg = item.getMessage();\n protobuf::message layerItr = layerMsg;\n while (layerItr.next()) {\n if (layerItr.tag == 1) {\n auto layerName = layerItr.string();\n tileData->layers.emplace_back(layerName);\n PbfParser::extractLayer(layerMsg, tileData->layers.back(), _tile);\n } else {\n layerItr.skip();\n }\n }\n } else {\n item.skip();\n }\n }\n return tileData;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\nnamespace Engine {\n\nstd::unordered_map HgScene::m_entityFactories;\n\nHgScene::HgScene()\n{\n\tauto vBuffer = std::make_shared>();\n\n\tstd::unique_ptr action = std::make_unique(\"ModelMatrix\");\n\tvBuffer->setUseClass(action);\n\n\tm_vBuffer = vBuffer;\n}\n\nHgEntity* HgScene::create_entity(const char* type_str)\n{\n\tauto factory = m_entityFactories.find(type_str);\n\n\tif (factory == m_entityFactories.end()) {\n\t\tfprintf(stderr, \"Unable to find entity type \\\"%s\\\"\\n\", type_str);\n\t\treturn nullptr;\n\t}\n\tfactoryCallback clbk = factory->second;\n\tHgEntity* entity = clbk(this);\n\n\treturn entity;\n}\n\nvoid HgScene::RegisterEntityFactory(const char* str, Engine::factoryCallback clbk)\n{\n\tm_entityFactories[str] = clbk;\n}\n\nvoid HgScene::update(HgTime dtime)\n{\n\tfor (auto& i : m_collections) {\n\t\ti->update(dtime);\n\t}\n\n\tRemoveInvalidEntities();\n}\n\nvoid HgScene::RemoveInvalidEntities()\n{\n\tm_tmpEntities.clear();\n\tif (m_tmpEntities.capacity() < m_entities.size())\n\t{\n\t\tm_tmpEntities.reserve(m_entities.size());\n\t}\n\n\tfor (auto id : m_entities)\n\t{\n\t\tif (EntityIdTable::Manager.exists(id))\n\t\t{\n\t\t\tm_tmpEntities.push_back(id);\n\t\t}\n\t}\n\tstd::swap(m_entities, m_tmpEntities);\n}\n\nstruct {\n\tbool operator()(const EntityRDPair& a, const EntityRDPair& b) const\n\t{\n\t\t\/\/sort to ascending entity id\n\t\tif (a.ptr == b.ptr)\n\t\t{\n\t\t\treturn a.entity < b.entity;\n\t\t}\n\t\treturn a.ptr < b.ptr;\n\t}\n} orderByRenderData;\n\nstruct RdDrawOrder\n{\n\tRdDrawOrder()\n\t\t:drawOrder(0)\n\t{}\n\n\tEntityRDPair rdPair;\n\tint8_t drawOrder;\n\n\tinline bool isSameGroup(const RdDrawOrder& rhs)\n\t{\n\t\treturn (drawOrder == rhs.drawOrder)\n\t\t\t&& (rdPair.ptr == rhs.rdPair.ptr);\n\t}\n};\n\nstruct {\n\tbool operator()(const RdDrawOrder& a, const RdDrawOrder& b) const\n\t{\n\t\tif (a.drawOrder == b.drawOrder)\n\t\t{\n\t\t\t\/\/sort to ascending entity id\n\t\t\tif (a.rdPair.ptr == b.rdPair.ptr)\n\t\t\t{\n\t\t\t\treturn a.rdPair.entity < b.rdPair.entity;\n\t\t\t}\n\t\t\treturn a.rdPair.ptr < b.rdPair.ptr;\n\t\t}\n\t\treturn a.drawOrder < b.drawOrder;\n\t}\n} orderEntitesForDraw;\n\nvoid HgScene::EnqueueForRender(RenderQueue* queue, HgTime dt) {\n\tfor (auto& i : m_collections) {\n\t\ti->EnqueueForRender(queue, dt);\n\t}\n\n\tif (m_entities.empty()) return;\n\n\tauto renderDatas = RenderDataTable::Manager.getRenderDataForEntities(m_entities.data(), m_entities.size());\n\n\tstd::vector list;\n\tlist.reserve(renderDatas.size());\n\n\tfor (auto& rdp : renderDatas)\n\t{\n\t\tRdDrawOrder t;\n\t\tt.rdPair = rdp;\n\t\tt.drawOrder = EntityTable::Singleton.getPtr(rdp.entity)->getDrawOrder();\n\t\tlist.push_back(t);\n\t}\n\n\tif (m_modelMatrices.capacity() < list.size())\n\t{\n\t\tm_modelMatrices.resize(list.size());\n\t}\n\n\tstd::vector< Instancing::InstancingMetaData > instances;\n\n\tm_vBuffer->setDataSource(m_modelMatrices);\n\tm_vBuffer->setNeedsLoadToGPU(true); \/\/entire vector contents needs to be sent to the GPU\n\n\t\/\/sort by draworder, renderdata, entityID\n\tstd::sort(list.begin(), list.end(), orderEntitesForDraw);\n\n\t\/\/group by draworder, renderdata\n\tRdDrawOrder lastRDO;\n\tInstancing::InstancingMetaData imd;\n\tuint32_t matrixOffset = 0;\n\tfor (const auto& t : list)\n\t{\n\t\tif (!lastRDO.isSameGroup(t))\n\t\t{\n\t\t\tif (imd.instanceCount > 0)\n\t\t\t{\n\t\t\t\tinstances.push_back(imd);\n\t\t\t}\n\t\t\timd = Instancing::InstancingMetaData();\n\t\t\timd.byteOffset = sizeof(Instancing::GPUTransformationMatrix) * matrixOffset;\n\t\t\timd.renderData = t.rdPair.ptr;\n\t\t\timd.instanceData = m_vBuffer;\n\t\t}\n\t\tlastRDO = t;\n\t\tauto entity = EntityTable::Singleton.getPtr(t.rdPair.entity);\n\n\t\tconst auto m = entity->computeWorldSpaceMatrix();\n\t\tm.store(m_modelMatrices[matrixOffset].matrix);\n\n\t\timd.instanceCount++;\n\t\tmatrixOffset++;\n\t}\n\n\tif (imd.instanceCount > 0)\n\t{\n\t\tinstances.push_back(imd);\n\t}\n\n\tfor (const auto& i : instances)\n\t{\n\t\tqueue->Enqueue(i);\n\t}\n}\n\n} \/\/Enginerewrite sort for better performance#pragma once\n\n#include \n#include \n\nnamespace Engine {\n\nstd::unordered_map HgScene::m_entityFactories;\n\nHgScene::HgScene()\n{\n\tauto vBuffer = std::make_shared>();\n\n\tstd::unique_ptr action = std::make_unique(\"ModelMatrix\");\n\tvBuffer->setUseClass(action);\n\n\tm_vBuffer = vBuffer;\n}\n\nHgEntity* HgScene::create_entity(const char* type_str)\n{\n\tauto factory = m_entityFactories.find(type_str);\n\n\tif (factory == m_entityFactories.end()) {\n\t\tfprintf(stderr, \"Unable to find entity type \\\"%s\\\"\\n\", type_str);\n\t\treturn nullptr;\n\t}\n\tfactoryCallback clbk = factory->second;\n\tHgEntity* entity = clbk(this);\n\n\treturn entity;\n}\n\nvoid HgScene::RegisterEntityFactory(const char* str, Engine::factoryCallback clbk)\n{\n\tm_entityFactories[str] = clbk;\n}\n\nvoid HgScene::update(HgTime dtime)\n{\n\tfor (auto& i : m_collections) {\n\t\ti->update(dtime);\n\t}\n\n\tRemoveInvalidEntities();\n}\n\nvoid HgScene::RemoveInvalidEntities()\n{\n\tm_tmpEntities.clear();\n\tif (m_tmpEntities.capacity() < m_entities.size())\n\t{\n\t\tm_tmpEntities.reserve(m_entities.size());\n\t}\n\n\tfor (auto id : m_entities)\n\t{\n\t\tif (EntityIdTable::Manager.exists(id))\n\t\t{\n\t\t\tm_tmpEntities.push_back(id);\n\t\t}\n\t}\n\tstd::swap(m_entities, m_tmpEntities);\n}\n\nstruct {\n\tbool operator()(const EntityRDPair& a, const EntityRDPair& b) const\n\t{\n\t\t\/\/sort to ascending entity id\n\t\tif (a.ptr == b.ptr)\n\t\t{\n\t\t\treturn a.entity < b.entity;\n\t\t}\n\t\treturn a.ptr < b.ptr;\n\t}\n} orderByRenderData;\n\nstruct RdDrawOrder\n{\n\tRdDrawOrder()\n\t\t:drawOrder(0)\n\t{}\n\n\tEntityRDPair rdPair;\n\tint8_t drawOrder;\n\n\tinline bool isSameGroup(const RdDrawOrder& rhs)\n\t{\n\t\treturn (drawOrder == rhs.drawOrder)\n\t\t\t&& (rdPair.ptr == rhs.rdPair.ptr);\n\t}\n};\n\nstruct {\n\tbool operator()(const RdDrawOrder& a, const RdDrawOrder& b) const\n\t{\n\t\treturn (a.drawOrder < b.drawOrder) ||\n\t\t((a.drawOrder == b.drawOrder) && (a.rdPair.ptr < b.rdPair.ptr)) ||\n\t\t((a.drawOrder == b.drawOrder) && (a.rdPair.ptr == b.rdPair.ptr) && (a.rdPair.ptr < b.rdPair.ptr));\n\n\t\/\/if (a.drawOrder == b.drawOrder)\n\t\/\/\t{\n\t\/\/\t\t\/\/sort to ascending entity id\n\t\/\/\t\tif (a.rdPair.ptr == b.rdPair.ptr)\n\t\/\/\t\t{\n\t\/\/\t\t\treturn a.rdPair.entity < b.rdPair.entity;\n\t\/\/\t\t}\n\t\/\/\t\treturn a.rdPair.ptr < b.rdPair.ptr;\n\t\/\/\t}\n\t\/\/\treturn a.drawOrder < b.drawOrder;\n\t}\n} orderEntitesForDraw;\n\nvoid HgScene::EnqueueForRender(RenderQueue* queue, HgTime dt) {\n\tfor (auto& i : m_collections) {\n\t\ti->EnqueueForRender(queue, dt);\n\t}\n\n\tif (m_entities.empty()) return;\n\n\tauto renderDatas = RenderDataTable::Manager.getRenderDataForEntities(m_entities.data(), m_entities.size());\n\n\tstd::vector list;\n\tlist.reserve(renderDatas.size());\n\n\tfor (auto& rdp : renderDatas)\n\t{\n\t\tRdDrawOrder t;\n\t\tt.rdPair = rdp;\n\t\tt.drawOrder = EntityTable::Singleton.getPtr(rdp.entity)->getDrawOrder();\n\t\tlist.push_back(t);\n\t}\n\n\tif (m_modelMatrices.capacity() < list.size())\n\t{\n\t\tm_modelMatrices.resize(list.size());\n\t}\n\n\tstd::vector< Instancing::InstancingMetaData > instances;\n\n\tm_vBuffer->setDataSource(m_modelMatrices);\n\tm_vBuffer->setNeedsLoadToGPU(true); \/\/entire vector contents needs to be sent to the GPU\n\n\t\/\/sort by draworder, renderdata, entityID\n\tstd::sort(list.begin(), list.end(), orderEntitesForDraw);\n\n\t\/\/group by draworder, renderdata\n\tRdDrawOrder lastRDO;\n\tInstancing::InstancingMetaData imd;\n\tuint32_t matrixOffset = 0;\n\tfor (const auto& t : list)\n\t{\n\t\tif (!lastRDO.isSameGroup(t))\n\t\t{\n\t\t\tif (imd.instanceCount > 0)\n\t\t\t{\n\t\t\t\tinstances.push_back(imd);\n\t\t\t}\n\t\t\timd = Instancing::InstancingMetaData();\n\t\t\timd.byteOffset = sizeof(Instancing::GPUTransformationMatrix) * matrixOffset;\n\t\t\timd.renderData = t.rdPair.ptr;\n\t\t\timd.instanceData = m_vBuffer;\n\t\t\tlastRDO = t;\n\t\t}\n\t\tauto entity = EntityTable::Singleton.getPtr(t.rdPair.entity);\n\n\t\tconst auto m = entity->computeWorldSpaceMatrix();\n\t\tm.store(m_modelMatrices[matrixOffset].matrix);\n\n\t\timd.instanceCount++;\n\t\tmatrixOffset++;\n\t}\n\n\tif (imd.instanceCount > 0)\n\t{\n\t\tinstances.push_back(imd);\n\t}\n\n\tfor (const auto& i : instances)\n\t{\n\t\tqueue->Enqueue(i);\n\t}\n}\n\n} \/\/Engine<|endoftext|>"} {"text":"\/*\n * Harversine.c\n * Haversine\n *\n * Created by Jaime Rios on 2\/16\/08.\n *\n *\/\n\n#include \"Harversine.h\"\n\n#include \/\/ For PI\n\n\n\/*\n Haversine Formula\n R = earth’s radius (mean radius = 6,371km)\n Δlat = lat2− lat1\n Δlong = long2− long1\n a = sin²(Δlat\/2) + cos(lat1).cos(lat2).sin²(Δlong\/2)\n c = 2.atan2(√a, √(1−a))\n d = R.c\n \n JavaScript Example from http:\/\/www.movable-type.co.uk\/scripts\/latlong.html\n var R = 6371; \/\/ km\n var dLat = (lat2-lat1).toRad();\n var dLon = (lon2-lon1).toRad(); \n lat1 = lat1.toRad(), lat2 = lat2.toRad();\n \n var a = Math.sin(dLat\/2) * Math.sin(dLat\/2) +\n\t\t Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * \n\t\t Math.sin(dLon\/2) * Math.sin(dLon\/2); \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n var d = R * c;\n *\/\nauto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle\n{\n auto radius = Kilometers{ 6371 }; \/\/ Earth's radius\n\n\t\/\/ Get the difference between our two points then convert the difference into radians\n auto latDelta = Convert(latitude2 - latitude1);\n auto lonDelta = Convert(longtitude2 - longtitude1);\n\n latitude1 = Convert(latitude1);\n latitude2 = Convert(latitude2);\n\t\n\tauto a = pow ( sin(latDelta\/2), 2 ) +\n\t\t\t cos(latitude1) * cos(latitude2) *\n\t\t\t pow ( sin(lonDelta\/2), 2 );\n\t\n\tauto c = 2 * atan2( sqrt(a), sqrt( 1 - a ));\n\tauto d = radius * c;\n\t\n\treturn d;\n}\n\n\/\/ Convert our passed value to Radians\nauto Convert( const Angle angle ) -> Radians\n{\n\treturn angle * (M_PI\/180);\n}Spaces versus tabs again :|\/*\n * Harversine.c\n * Haversine\n *\n * Created by Jaime Rios on 2\/16\/08.\n *\n *\/\n\n#include \"Harversine.h\"\n\n#include \/\/ For PI\n\n\n\/*\n Haversine Formula\n R = earth’s radius (mean radius = 6,371km)\n Δlat = lat2− lat1\n Δlong = long2− long1\n a = sin²(Δlat\/2) + cos(lat1).cos(lat2).sin²(Δlong\/2)\n c = 2.atan2(√a, √(1−a))\n d = R.c\n \n JavaScript Example from http:\/\/www.movable-type.co.uk\/scripts\/latlong.html\n var R = 6371; \/\/ km\n var dLat = (lat2-lat1).toRad();\n var dLon = (lon2-lon1).toRad(); \n lat1 = lat1.toRad(), lat2 = lat2.toRad();\n \n var a = Math.sin(dLat\/2) * Math.sin(dLat\/2) +\n\t\t Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * \n\t\t Math.sin(dLon\/2) * Math.sin(dLon\/2); \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n var d = R * c;\n *\/\nauto CalculateDistance( Angle latitude1, Angle longtitude1, Angle latitude2, Angle longtitude2 ) -> Angle\n{\n auto radius = Kilometers{ 6371 }; \/\/ Earth's radius\n\n\t\/\/ Get the difference between our two points then convert the difference into radians\n auto latDelta = Convert(latitude2 - latitude1);\n auto lonDelta = Convert(longtitude2 - longtitude1);\n\n latitude1 = Convert(latitude1);\n latitude2 = Convert(latitude2);\n\t\n auto a = pow ( sin(latDelta\/2), 2 ) +\n cos(latitude1) * cos(latitude2) *\n pow ( sin(lonDelta\/2), 2 );\n\t\n auto c = 2 * atan2( sqrt(a), sqrt( 1 - a ));\n auto d = radius * c;\n\t\n\treturn d;\n}\n\n\/\/ Convert our passed value to Radians\nauto Convert( const Angle angle ) -> Radians\n{\n\treturn angle * (M_PI\/180);\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define pb push_back\n\n#define mp make_pair\n#define f first\n#define s second\n#define ll long long\n\nusing namespace std;\n\n\n\nclass Solver {\n\n vector current_set;\n int N, count_set;\n\n vector> edges;\n vector L;\n map R;\n vector viz;\n set> unique_sets;\n\n public:\n Solver(int _N) {\n \/\/\n N = _N;\n count_set = 0;\n edges.assign(N, vector());\n L.assign(N,0);\n viz.assign(N, 0);\n }\n\n bool intersect(int mask1, int mask2) {\n return (mask1 & mask2);\n }\n\n void to_set(int mask) {\n cout << \"{\";\n vector Ans;\n for (int i = 0; i < N; ++i) {\n if (mask & (1 << i)) {\n Ans.push_back(i + 1);\n }\n }\n for (int i = 0; i < Ans.size() - 1; ++i) {\n cout << Ans[i] << \",\";\n }\n if (Ans.size() > 0) {\n cout << Ans[Ans.size() - 1];\n }\n cout << \"}\";\n }\n\n\n bool pairup(int node) {\n if (viz[node]) {\n return 0;\n }\n viz[node] = 1;\n for (auto vec: edges[node]) {\n if (R.find(vec) == R.end()) {\n L[node] = vec;\n R[vec] = node;\n return 1;\n }\n }\n for (auto vec: edges[node]) {\n if (pairup(R[vec])) {\n L[node] = vec;\n R[vec] = node;\n return 1;\n }\n }\n return 0;\n }\n\n void debug_set(const vector& v) {\n cout << \"**********\\n\";\n for (int i = 0; i < v.size(); ++i) {\n to_set(v[i]);\n cout << \"\\n\";\n }\n }\n bool do_matching(const vector&to_check) {\n \/\/debug_set(to_check);\n \/\/\n int ret = prime_condition(to_check);\n if (ret == 0) {\n return 0;\n }\n for (int i = 0; i < N; ++i) {\n edges[i].clear();\n viz[i] = 0;\n L[i] = -1;\n R.clear();\n }\n for (int i = 0; i < N; ++i) {\n for (int j = 0; j < N; ++j) {\n if (to_check[j] & (1 << i)) {\n edges[i].push_back(j);\n }\n }\n }\n for (int i = 0; i < N; ++i) {\n if (edges[i].size() == 0) {\n return 0;\n }\n }\n int change = 1;\n while(change) {\n change = 0;\n for (int i = 0; i < N; ++i) {\n viz[i] = 0;\n }\n for (int i = 0; i < N; ++i) {\n if (L[i] == -1) {\n change |= pairup(i);\n }\n }\n }\n\n for (int i = 0; i < N; ++i) {\n if (L[i] == -1) {\n cout << \"FAIL ON\\n\";\n cout << \"is prime condition? \" << ret << \"\\n\";\n write_set(L, to_check);\n\n cout << \"graph: \\n\";\n for (int k = 0; k < N; ++k) {\n cerr << k + 1 << \" -> \" ;\n for (auto vec: edges[k]) {\n to_set(to_check[vec]);\n }\n cerr << \"\\n\";\n }\n return 0;\n }\n }\n \/*\n cout << \"set: \" << count_set << \"\\n\";\n write_set(L, to_check);\n *\/\n \/\/cerr << \"MATCHING DONE?\\n\";\n \/*\n vector tmp(to_check);\n sort(tmp.begin(), tmp.end());\n unique_sets.insert(tmp);\n *\/\n return 1;\n }\n\n void generate_all_sets(int k) {\n if (k == N) {\n count_set += do_matching(current_set);\n } else {\n int start = 0;\n if (k != 0) {\n start = current_set[k - 1];\n }\n for (int mask = start + 1; mask < (1 << N); ++mask) {\n bool flag = false;\n for (int i = 0; i < k; ++i) {\n if (!intersect(mask, current_set[i])) {\n flag = true;\n break;\n }\n }\n if (flag) {\n continue;\n }\n current_set.push_back(mask);\n generate_all_sets(k + 1);\n current_set.pop_back();\n }\n }\n }\n\n bool prime_condition(const vector&to_check) {\n for (int i = 0; i < N; ++i) {\n for (int j = 0; j < N; ++j) {\n if (i == j) {\n continue;\n }\n bool can_go = false;\n for (int k = 0; k < N; ++k) {\n if (intersect(to_check[k], 1<& L, const vector&v) {\n for (int i = 0; i < N; ++i) {\n if (L[i] == -1) {\n cout << \"?\";\n } else {\n cout << i + 1;\n }\n cout << \" -> \";\n if (L[i] != -1) {\n to_set(v[L[i]]);\n }\n cout << \"\\n\";\n }\n }\n void checker() {\n generate_all_sets(0);\n cout << \"Found \" << count_set << \" matchings\\n\";\n cout << \"Found \" << unique_sets.size() << \" unique sets\\n\";\n }\n};\nint main() {\n ifstream cin(\"test.in\");\n\n int N; cin >> N;\n N = 4;\n Solver G(N);\n\n G.checker();\n \/\/int res = G.do_matching({127,191,223,239,247,251,253,254,22019,10764,3376,12736,341,405,16808});\n \/\/cout << res << \"\\n\";\n \/\/cout << G.prime_condition({7,6,5});\n return 0;\n}\nlast chance#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#define pb push_back\n\n#define mp make_pair\n#define f first\n#define s second\n#define ll long long\n\nusing namespace std;\n\n\n\nclass Graph {\n public:\n Graph(int _N) {\n N = _N;\n viz.assign(N, 0);\n L.assign(N, -1);\n R.assign(N, -1);\n edges.assign(N, vector());\n edge_mask.assign(N, 0);\n }\n void addEdge(int x, int y) {\n edges[x].push_back(y);\n edge_mask[y] |= (1 << x);\n }\n\n bool pairup(int node) {\n if (viz[node]) {\n return 0;\n }\n viz[node] = 1;\n for (auto vec: edges[node]) {\n if (R[vec] == -1) {\n L[node] = vec;\n R[vec] = node;\n return 1;\n }\n }\n for (auto vec: edges[node]) {\n if (pairup(R[vec])) {\n L[node] = vec;\n R[vec] = node;\n return 1;\n }\n }\n return 0;\n }\n bool maxMatch() {\n int change = 1;\n while(change) {\n change = 0;\n for (int i = 0; i < N; ++i) {\n viz[i] = 0;\n }\n for (int i = 0; i < N; ++i) {\n if (L[i] == -1) {\n change |= pairup(i);\n }\n }\n }\n for (int i = 0; i < N; ++i) {\n if (L[i] == -1) {\n return 0;\n }\n }\n return 1;\n }\n void write() {\n for (int i = 0; i < N; ++i) {\n vector row;\n for (int j = 0; j < N; ++j) {\n if ( edge_mask[i] & (1 << j) ) {\n row.push_back(j);\n }\n }\n if (R[i] != -1) {\n cerr << R[i] << \" -> \";\n } else {\n cerr << \"?\" << \" -> \";\n }\n cerr << \"{\";\n for (int j = 0; j < row.size() - 1; ++j) {\n cerr << row[j] << \",\";\n }\n cerr << *row.rbegin() << \"}\\n\";\n }\n }\n int N;\n vector viz, L, R, edge_mask;\n vector> edges;\n};\n\nclass Solver {\n\n vector current_set;\n int N, count_set;\n set> unique_sets;\n\n public:\n Solver(int _N) {\n N = _N;\n count_set = 0;\n }\n\n bool intersect(int mask1, int mask2) {\n return (mask1 & mask2);\n }\n\n bool do_matching(const vector& to_check) {\n \/\/debug_set(to_check);\n \/\/\n int ret = prime_condition(to_check);\n if (ret == 0) {\n return 0;\n }\n Graph G(N);\n \/\/ prob cache misses?\n for (int i = 0; i < N; ++i) {\n for (int j = 0; j < N; ++j) {\n if (to_check[j] & (1 << i)) {\n G.addEdge(i, j);\n }\n }\n }\n for (int i = 0; i < N; ++i) {\n if (G.edges[i].size() == 0) {\n return 0;\n }\n }\n\n if (!G.maxMatch()) {\n cout << \"FAIL ON\\n\";\n cout << \"is prime condition? \" << ret << \"\\n\";\n G.write();\n return 0;\n }\n \/\/cout << \"set: \" << count_set << \"\\n\";\n \/\/cerr << \"MATCHING DONE?\\n\";\n \/*\n vector tmp(to_check);\n sort(tmp.begin(), tmp.end());\n unique_sets.insert(tmp);\n *\/\n return 1;\n }\n\n void generate_all_sets(int k, vector& current_set) {\n if (k == N) {\n count += do_matching(current_set);\n } else {\n int start = 0;\n if (k != 0) {\n start = current_set[k - 1];\n }\n #pragma omp parallel for\n for (int mask = start + 1; mask < (1 << N); ++mask) {\n bool flag = false;\n for (int i = 0; i < k; ++i) {\n if (!intersect(mask, current_set[i])) {\n flag = true;\n break;\n }\n }\n if (!flag) {\n vector next_set(current_set);\n next_set.push_back(mask);\n generate_all_sets(k + 1, next_set);\n }\n }\n }\n }\n\n bool prime_condition(const vector&to_check) {\n for (int i = 0; i < N; ++i) {\n for (int j = 0; j < N; ++j) {\n if (i == j) {\n continue;\n }\n bool can_go = false;\n for (int k = 0; k < N; ++k) {\n if (intersect(to_check[k], 1<& edges) {\n for (int i = 0; i < edges.size(); ++i) {\n for (int j = 0; j < N; ++j) {\n if (edges[i] & (1 << j)) {\n cout << j + 1 << \" \" ;\n }\n }\n cout << \"\\n\";\n }\n cout << \"\\n\";\n }\n void checker() {\n vector empty_vector;\n generate_all_sets(0, empty_vector);\n cout << \"Found \" << count_set << \" matchings\\n\";\n cout << \"Found \" << unique_sets.size() << \" unique sets\\n\";\n \/*\n for (auto edges: unique_sets) {\n debug_(edges);\n }\n *\/\n }\n};\nint main() {\n ifstream cin(\"test.in\");\n\n int N; cin >> N;\n Solver G(N);\n G.checker();\n\/\/ int res = G.do_matching({35,77,161,53,19,13,102,122});\n \/\/ cout << res << \"\\n\";\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/utils:$Id$\n\/\/ Author: Axel Naumann, 2014-04-07\n\n\/*************************************************************************\n * Copyright (C) 1995-2014, 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\/\/ Provides bindings to TCling (compiled with rtti) from rootcling (compiled\n\/\/ without rtti).\n\n#include \"TCling.h\"\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TClass.h\"\n#include \"TStreamerInfo.h\"\n#include \n#include \"TProtoClass.h\"\n\nstd::string gPCMFilename;\nstd::vector gClassesToStore;\nstd::vector gTypedefsToStore;\nstd::vector gAncestorPCMsNames;\n\nextern \"C\"\nconst char*** TROOT__GetExtraInterpreterArgs() {\n return &TROOT::GetExtraInterpreterArgs();\n}\n\nextern \"C\"\ncling::Interpreter* TCling__GetInterpreter()\n{\n static bool sInitialized = false;\n gROOT; \/\/ trigger initialization\n if (!sInitialized) {\n gCling->SetClassAutoloading(false);\n sInitialized = true;\n }\n return ((TCling*)gCling)->GetInterpreter();\n}\n\nextern \"C\"\nvoid InitializeStreamerInfoROOTFile(const char* filename)\n{\n gPCMFilename = filename;\n}\n\nextern \"C\"\nvoid AddStreamerInfoToROOTFile(const char* normName)\n{\n gClassesToStore.emplace_back(normName);\n}\n\nextern \"C\"\nvoid AddTypedefToROOTFile(const char* tdname)\n{\n gTypedefsToStore.push_back(tdname);\n}\n\nextern \"C\"\nvoid AddAncestorPCMROOTFile(const char* pcmName)\n{\n gAncestorPCMsNames.emplace_back(pcmName);\n}\n\nextern \"C\"\nbool CloseStreamerInfoROOTFile()\n{\n \/\/ Write all persistent TClasses.\n\n \/\/ Avoid plugins.\n TVirtualStreamerInfo::SetFactory(new TStreamerInfo());\n\n TObjArray protoClasses;\n for (const auto normName: gClassesToStore) {\n TClass* cl = TClass::GetClass(normName.c_str(), kTRUE \/*load*\/);\n if (!cl) {\n std::cerr << \"ERROR in CloseStreamerInfoROOTFile(): cannot find class \"\n << normName << '\\n';\n return false;\n }\n \/\/ If the class is not persistent we return success.\n if (cl->GetClassVersion() == 0)\n continue;\n \/\/ If this is a proxied collection then offsets are not needed.\n if (cl->GetCollectionProxy())\n continue;\n cl->Property(); \/\/ Force initialization of the bits and property fields.\n protoClasses.AddLast(new TProtoClass(cl));\n }\n\n TObjArray typedefs;\n for (const auto dtname: gTypedefsToStore) {\n TDataType* dt = (TDataType*)gROOT->GetListOfTypes()->FindObject(dtname.c_str());\n if (!dt) {\n std::cerr << \"ERROR in CloseStreamerInfoROOTFile(): cannot find class \"\n << dtname << '\\n';\n return false;\n }\n if (dt->GetType() == -1) {\n dt->Property(); \/\/ Force initialization of the bits and property fields.\n dt->GetTypeName(); \/\/ Force caching of type name.\n typedefs.AddLast(dt);\n }\n }\n\n \/\/ Don't use TFile::Open(); we don't need plugins.\n TFile dictFile(gPCMFilename.c_str(), \"RECREATE\");\n if (dictFile.IsZombie())\n return false;\n \/\/ Instead of plugins:\n protoClasses.Write(\"__ProtoClasses\", TObject::kSingleKey);\n protoClasses.Delete();\n typedefs.Write(\"__Typedefs\", TObject::kSingleKey);\n\n dictFile.WriteObjectAny(&gAncestorPCMsNames, \"std::vector\", \"__AncestorPCMsNames\");\n\n\n return true;\n}\nMake sure that the list of bases is complete.\/\/ @(#)root\/utils:$Id$\n\/\/ Author: Axel Naumann, 2014-04-07\n\n\/*************************************************************************\n * Copyright (C) 1995-2014, 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\/\/ Provides bindings to TCling (compiled with rtti) from rootcling (compiled\n\/\/ without rtti).\n\n#include \"TCling.h\"\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TClass.h\"\n#include \"TStreamerInfo.h\"\n#include \n#include \"TProtoClass.h\"\n\nstd::string gPCMFilename;\nstd::vector gClassesToStore;\nstd::vector gTypedefsToStore;\nstd::vector gAncestorPCMsNames;\n\nextern \"C\"\nconst char*** TROOT__GetExtraInterpreterArgs() {\n return &TROOT::GetExtraInterpreterArgs();\n}\n\nextern \"C\"\ncling::Interpreter* TCling__GetInterpreter()\n{\n static bool sInitialized = false;\n gROOT; \/\/ trigger initialization\n if (!sInitialized) {\n gCling->SetClassAutoloading(false);\n sInitialized = true;\n }\n return ((TCling*)gCling)->GetInterpreter();\n}\n\nextern \"C\"\nvoid InitializeStreamerInfoROOTFile(const char* filename)\n{\n gPCMFilename = filename;\n}\n\nextern \"C\"\nvoid AddStreamerInfoToROOTFile(const char* normName)\n{\n gClassesToStore.emplace_back(normName);\n}\n\nextern \"C\"\nvoid AddTypedefToROOTFile(const char* tdname)\n{\n gTypedefsToStore.push_back(tdname);\n}\n\nextern \"C\"\nvoid AddAncestorPCMROOTFile(const char* pcmName)\n{\n gAncestorPCMsNames.emplace_back(pcmName);\n}\n\nextern \"C\"\nbool CloseStreamerInfoROOTFile()\n{\n \/\/ Write all persistent TClasses.\n\n \/\/ Avoid plugins.\n TVirtualStreamerInfo::SetFactory(new TStreamerInfo());\n\n TObjArray protoClasses;\n for (const auto normName: gClassesToStore) {\n TClass* cl = TClass::GetClass(normName.c_str(), kTRUE \/*load*\/);\n if (!cl) {\n std::cerr << \"ERROR in CloseStreamerInfoROOTFile(): cannot find class \"\n << normName << '\\n';\n return false;\n }\n \/\/ If the class is not persistent we return success.\n if (cl->GetClassVersion() == 0)\n continue;\n \/\/ If this is a proxied collection then offsets are not needed.\n if (cl->GetCollectionProxy())\n continue;\n cl->Property(); \/\/ Force initialization of the bits and property fields.\n cl->GetListOfBases();\n\n protoClasses.AddLast(new TProtoClass(cl));\n }\n\n TObjArray typedefs;\n for (const auto dtname: gTypedefsToStore) {\n TDataType* dt = (TDataType*)gROOT->GetListOfTypes()->FindObject(dtname.c_str());\n if (!dt) {\n std::cerr << \"ERROR in CloseStreamerInfoROOTFile(): cannot find class \"\n << dtname << '\\n';\n return false;\n }\n if (dt->GetType() == -1) {\n dt->Property(); \/\/ Force initialization of the bits and property fields.\n dt->GetTypeName(); \/\/ Force caching of type name.\n typedefs.AddLast(dt);\n }\n }\n\n \/\/ Don't use TFile::Open(); we don't need plugins.\n TFile dictFile(gPCMFilename.c_str(), \"RECREATE\");\n if (dictFile.IsZombie())\n return false;\n \/\/ Instead of plugins:\n protoClasses.Write(\"__ProtoClasses\", TObject::kSingleKey);\n protoClasses.Delete();\n typedefs.Write(\"__Typedefs\", TObject::kSingleKey);\n\n dictFile.WriteObjectAny(&gAncestorPCMsNames, \"std::vector\", \"__AncestorPCMsNames\");\n\n\n return true;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef DATABASE_HH_\n#define DATABASE_HH_\n\n#include \"core\/sstring.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"net\/byteorder.hh\"\n#include \"utils\/UUID.hh\"\n#include \"db_clock.hh\"\n#include \"gc_clock.hh\"\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 \"types.hh\"\n#include \"tuple.hh\"\n#include \"core\/future.hh\"\n#include \"cql3\/column_specification.hh\"\n#include \n#include \n#include \"schema.hh\"\n\nusing partition_key_type = tuple_type<>;\nusing clustering_key_type = tuple_type<>;\nusing clustering_prefix_type = tuple_prefix;\nusing partition_key = bytes;\nusing clustering_key = bytes;\nusing clustering_prefix = clustering_prefix_type::value_type;\n\nnamespace api {\n\nusing timestamp_type = int64_t;\ntimestamp_type constexpr missing_timestamp = std::numeric_limits::min();\ntimestamp_type constexpr min_timestamp = std::numeric_limits::min() + 1;\ntimestamp_type constexpr max_timestamp = std::numeric_limits::max();\n\n}\n\n\/**\n* Represents deletion operation. Can be commuted with other tombstones via apply() method.\n* Can be empty.\n*\n*\/\nstruct tombstone final {\n api::timestamp_type timestamp;\n gc_clock::time_point ttl;\n\n tombstone(api::timestamp_type timestamp, gc_clock::time_point ttl)\n : timestamp(timestamp)\n , ttl(ttl)\n { }\n\n tombstone()\n : tombstone(api::missing_timestamp, {})\n { }\n\n int compare(const tombstone& t) const {\n if (timestamp < t.timestamp) {\n return -1;\n } else if (timestamp > t.timestamp) {\n return 1;\n } else if (ttl < t.ttl) {\n return -1;\n } else if (ttl > t.ttl) {\n return 1;\n } else {\n return 0;\n }\n }\n\n bool operator<(const tombstone& t) const {\n return compare(t) < 0;\n }\n\n bool operator==(const tombstone& t) const {\n return compare(t) == 0;\n }\n\n operator bool() const {\n return timestamp != api::missing_timestamp;\n }\n\n void apply(const tombstone& t) {\n if (*this < t) {\n *this = t;\n }\n }\n};\n\nusing ttl_opt = std::experimental::optional;\n\nstruct atomic_cell final {\n struct dead {\n gc_clock::time_point ttl;\n };\n struct live {\n ttl_opt ttl;\n bytes value;\n };\n api::timestamp_type timestamp;\n boost::variant value;\n bool is_live() const { return value.which() == 1; }\n \/\/ Call only when is_live() == true\n const live& as_live() const { return boost::get(value); }\n \/\/ Call only when is_live() == false\n const dead& as_dead() const { return boost::get(value); }\n};\n\nusing row = std::map;\n\nstruct deletable_row final {\n tombstone t;\n row cells;\n};\n\nusing row_tombstone_set = std::map;\n\nclass mutation_partition final {\nprivate:\n tombstone _tombstone;\n row _static_row;\n std::map _rows;\n row_tombstone_set _row_tombstones;\npublic:\n mutation_partition(schema_ptr s)\n : _rows(key_compare(s->clustering_key_type))\n , _row_tombstones(serialized_compare(s->clustering_key_prefix_type))\n { }\n\n void apply(tombstone t) {\n _tombstone.apply(t);\n }\n\n void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t) {\n if (prefix.empty()) {\n apply(t);\n } else if (prefix.size() == schema->clustering_key.size()) {\n _rows[serialize_value(*schema->clustering_key_type, prefix)].t.apply(t);\n } else {\n apply_row_tombstone(schema, {serialize_value(*schema->clustering_key_prefix_type, prefix), t});\n }\n }\n\n void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) {\n apply_row_tombstone(schema, {std::move(prefix), std::move(t)});\n }\n\n void apply_row_tombstone(schema_ptr schema, std::pair row_tombstone) {\n auto& prefix = row_tombstone.first;\n auto i = _row_tombstones.lower_bound(prefix);\n if (i == _row_tombstones.end() || !schema->clustering_key_prefix_type->equal(prefix, i->first)\n || row_tombstone.second > i->second) {\n _row_tombstones.insert(i, std::move(row_tombstone));\n }\n }\n\n void apply(schema_ptr schema, mutation_partition&& p);\n\n row& static_row() {\n return _static_row;\n }\n\n row& clustered_row(const clustering_key& key) {\n return _rows[key].cells;\n }\n\n row& clustered_row(clustering_key&& key) {\n return _rows[std::move(key)].cells;\n }\n\n row* find_row(const clustering_key& key) {\n auto i = _rows.find(key);\n if (i == _rows.end()) {\n return nullptr;\n }\n return &i->second.cells;\n }\n};\n\nclass mutation final {\npublic:\n schema_ptr schema;\n partition_key key;\n mutation_partition p;\npublic:\n mutation(partition_key key_, schema_ptr schema_)\n : schema(std::move(schema_))\n , key(std::move(key_))\n , p(schema)\n { }\n\n mutation(mutation&&) = default;\n mutation(const mutation&) = delete;\n\n void set_static_cell(const column_definition& def, boost::any value) {\n p.static_row()[def.id] = std::move(value);\n }\n\n void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, boost::any value) {\n auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix));\n row[def.id] = std::move(value);\n }\n\n void set_clustered_cell(const clustering_key& key, const column_definition& def, boost::any value) {\n auto& row = p.clustered_row(key);\n row[def.id] = std::move(value);\n }\n};\n\nstruct column_family {\n column_family(schema_ptr schema);\n mutation_partition& find_or_create_partition(const bytes& key);\n row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key);\n mutation_partition* find_partition(const bytes& key);\n row* find_row(const bytes& partition_key, const bytes& clustering_key);\n schema_ptr _schema;\n \/\/ partition key -> partition\n std::map partitions;\n void apply(mutation&& m);\n};\n\nclass keyspace {\npublic:\n std::unordered_map column_families;\n static future populate(sstring datadir);\n schema_ptr find_schema(sstring cf_name);\n column_family* find_column_family(sstring cf_name);\n};\n\nclass database {\npublic:\n std::unordered_map keyspaces;\n static future populate(sstring datadir);\n keyspace* find_keyspace(sstring name);\n};\n\n\n#endif \/* DATABASE_HH_ *\/\ndb: Define the rest of comparison operators in tombstone\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef DATABASE_HH_\n#define DATABASE_HH_\n\n#include \"core\/sstring.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"net\/byteorder.hh\"\n#include \"utils\/UUID.hh\"\n#include \"db_clock.hh\"\n#include \"gc_clock.hh\"\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 \"types.hh\"\n#include \"tuple.hh\"\n#include \"core\/future.hh\"\n#include \"cql3\/column_specification.hh\"\n#include \n#include \n#include \"schema.hh\"\n\nusing partition_key_type = tuple_type<>;\nusing clustering_key_type = tuple_type<>;\nusing clustering_prefix_type = tuple_prefix;\nusing partition_key = bytes;\nusing clustering_key = bytes;\nusing clustering_prefix = clustering_prefix_type::value_type;\n\nnamespace api {\n\nusing timestamp_type = int64_t;\ntimestamp_type constexpr missing_timestamp = std::numeric_limits::min();\ntimestamp_type constexpr min_timestamp = std::numeric_limits::min() + 1;\ntimestamp_type constexpr max_timestamp = std::numeric_limits::max();\n\n}\n\n\/**\n* Represents deletion operation. Can be commuted with other tombstones via apply() method.\n* Can be empty.\n*\n*\/\nstruct tombstone final {\n api::timestamp_type timestamp;\n gc_clock::time_point ttl;\n\n tombstone(api::timestamp_type timestamp, gc_clock::time_point ttl)\n : timestamp(timestamp)\n , ttl(ttl)\n { }\n\n tombstone()\n : tombstone(api::missing_timestamp, {})\n { }\n\n int compare(const tombstone& t) const {\n if (timestamp < t.timestamp) {\n return -1;\n } else if (timestamp > t.timestamp) {\n return 1;\n } else if (ttl < t.ttl) {\n return -1;\n } else if (ttl > t.ttl) {\n return 1;\n } else {\n return 0;\n }\n }\n\n bool operator<(const tombstone& t) const {\n return compare(t) < 0;\n }\n\n bool operator<=(const tombstone& t) const {\n return compare(t) <= 0;\n }\n\n bool operator>(const tombstone& t) const {\n return compare(t) > 0;\n }\n\n bool operator>=(const tombstone& t) const {\n return compare(t) >= 0;\n }\n\n bool operator==(const tombstone& t) const {\n return compare(t) == 0;\n }\n\n bool operator!=(const tombstone& t) const {\n return compare(t) != 0;\n }\n\n operator bool() const {\n return timestamp != api::missing_timestamp;\n }\n\n void apply(const tombstone& t) {\n if (*this < t) {\n *this = t;\n }\n }\n};\n\nusing ttl_opt = std::experimental::optional;\n\nstruct atomic_cell final {\n struct dead {\n gc_clock::time_point ttl;\n };\n struct live {\n ttl_opt ttl;\n bytes value;\n };\n api::timestamp_type timestamp;\n boost::variant value;\n bool is_live() const { return value.which() == 1; }\n \/\/ Call only when is_live() == true\n const live& as_live() const { return boost::get(value); }\n \/\/ Call only when is_live() == false\n const dead& as_dead() const { return boost::get(value); }\n};\n\nusing row = std::map;\n\nstruct deletable_row final {\n tombstone t;\n row cells;\n};\n\nusing row_tombstone_set = std::map;\n\nclass mutation_partition final {\nprivate:\n tombstone _tombstone;\n row _static_row;\n std::map _rows;\n row_tombstone_set _row_tombstones;\npublic:\n mutation_partition(schema_ptr s)\n : _rows(key_compare(s->clustering_key_type))\n , _row_tombstones(serialized_compare(s->clustering_key_prefix_type))\n { }\n\n void apply(tombstone t) {\n _tombstone.apply(t);\n }\n\n void apply_delete(schema_ptr schema, const clustering_prefix& prefix, tombstone t) {\n if (prefix.empty()) {\n apply(t);\n } else if (prefix.size() == schema->clustering_key.size()) {\n _rows[serialize_value(*schema->clustering_key_type, prefix)].t.apply(t);\n } else {\n apply_row_tombstone(schema, {serialize_value(*schema->clustering_key_prefix_type, prefix), t});\n }\n }\n\n void apply_row_tombstone(schema_ptr schema, bytes prefix, tombstone t) {\n apply_row_tombstone(schema, {std::move(prefix), std::move(t)});\n }\n\n void apply_row_tombstone(schema_ptr schema, std::pair row_tombstone) {\n auto& prefix = row_tombstone.first;\n auto i = _row_tombstones.lower_bound(prefix);\n if (i == _row_tombstones.end() || !schema->clustering_key_prefix_type->equal(prefix, i->first)\n || row_tombstone.second > i->second) {\n _row_tombstones.insert(i, std::move(row_tombstone));\n }\n }\n\n void apply(schema_ptr schema, mutation_partition&& p);\n\n row& static_row() {\n return _static_row;\n }\n\n row& clustered_row(const clustering_key& key) {\n return _rows[key].cells;\n }\n\n row& clustered_row(clustering_key&& key) {\n return _rows[std::move(key)].cells;\n }\n\n row* find_row(const clustering_key& key) {\n auto i = _rows.find(key);\n if (i == _rows.end()) {\n return nullptr;\n }\n return &i->second.cells;\n }\n};\n\nclass mutation final {\npublic:\n schema_ptr schema;\n partition_key key;\n mutation_partition p;\npublic:\n mutation(partition_key key_, schema_ptr schema_)\n : schema(std::move(schema_))\n , key(std::move(key_))\n , p(schema)\n { }\n\n mutation(mutation&&) = default;\n mutation(const mutation&) = delete;\n\n void set_static_cell(const column_definition& def, boost::any value) {\n p.static_row()[def.id] = std::move(value);\n }\n\n void set_clustered_cell(const clustering_prefix& prefix, const column_definition& def, boost::any value) {\n auto& row = p.clustered_row(serialize_value(*schema->clustering_key_type, prefix));\n row[def.id] = std::move(value);\n }\n\n void set_clustered_cell(const clustering_key& key, const column_definition& def, boost::any value) {\n auto& row = p.clustered_row(key);\n row[def.id] = std::move(value);\n }\n};\n\nstruct column_family {\n column_family(schema_ptr schema);\n mutation_partition& find_or_create_partition(const bytes& key);\n row& find_or_create_row(const bytes& partition_key, const bytes& clustering_key);\n mutation_partition* find_partition(const bytes& key);\n row* find_row(const bytes& partition_key, const bytes& clustering_key);\n schema_ptr _schema;\n \/\/ partition key -> partition\n std::map partitions;\n void apply(mutation&& m);\n};\n\nclass keyspace {\npublic:\n std::unordered_map column_families;\n static future populate(sstring datadir);\n schema_ptr find_schema(sstring cf_name);\n column_family* find_column_family(sstring cf_name);\n};\n\nclass database {\npublic:\n std::unordered_map keyspaces;\n static future populate(sstring datadir);\n keyspace* find_keyspace(sstring name);\n};\n\n\n#endif \/* DATABASE_HH_ *\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \n#include \"TTimestamp.h\"\n\nnamespace tyr { namespace basic {\n\nstatic_assert(sizeof(Timestamp) == sizeof(int64_t), \"Timestamp is same size as int64_t\");\n\nstd::string Timestamp::to_string(void) const {\n char buf[32] = {0};\n int64_t sec = epoch_msec_ \/ kMicroSecondsPerSecond;\n int64_t msec = epoch_msec_ % kMicroSecondsPerSecond;\n snprintf(buf, sizeof(buf) - 1, \"%\" PRId64 \".%06\" PRId64 \"\", sec, msec);\n return buf;\n}\n\nstd::string Timestamp::to_formatted_string(bool show_msec) const {\n char buf[32] = {0};\n time_t sec = static_cast(epoch_msec_ \/ kMicroSecondsPerSecond);\n struct tm tm_time;\n gmtime_r(&sec, &tm_time);\n\n if (show_msec) {\n int msec = static_cast(epoch_msec_ % kMicroSecondsPerSecond);\n snprintf(buf,\n sizeof(buf),\n \"%04d%02d%02d %02d:%02d:%02d.%06d\",\n tm_time.tm_year + 1900,\n tm_time.tm_mon + 1,\n tm_time.tm_mday,\n tm_time.tm_hour,\n tm_time.tm_min,\n tm_time.tm_sec,\n msec);\n }\n else {\n snprintf(buf,\n sizeof(buf),\n \"%04d%02d%02d %02d:%02d:%02d\",\n tm_time.tm_year + 1900,\n tm_time.tm_mon + 1,\n tm_time.tm_mday,\n tm_time.tm_hour,\n tm_time.tm_min,\n tm_time.tm_sec);\n }\n\n return buf;\n}\n\nTimestamp Timestamp::now(void) {\n struct timeval tv;\n gettimeofday(&tv, nullptr);\n int64_t sec = tv.tv_sec;\n return Timestamp(sec * kMicroSecondsPerSecond + tv.tv_usec);\n}\n\nTimestamp Timestamp::invalid(void) {\n return Timestamp();\n}\n\nTimestamp Timestamp::from_unix_time(time_t t) {\n return from_unix_time(t, 0);\n}\n\nTimestamp Timestamp::from_unix_time(time_t t, int msec) {\n return Timestamp(static_cast(t) * kMicroSecondsPerSecond + msec);\n}\n\n}}\nchore(timestamp): updated the implementation of timestamp\/\/ Copyright (c) 2016 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \"TPlatform.h\"\n#include \"TTimestamp.h\"\n\nnamespace tyr { namespace basic {\n\nstatic_assert(sizeof(Timestamp) == sizeof(int64_t), \"Timestamp is same size as int64_t\");\n\nstd::string Timestamp::to_string(void) const {\n char buf[32] = {0};\n int64_t sec = epoch_msec_ \/ kMicroSecondsPerSecond;\n int64_t msec = epoch_msec_ % kMicroSecondsPerSecond;\n snprintf(buf, sizeof(buf) - 1, \"%\" PRId64 \".%06\" PRId64 \"\", sec, msec);\n return buf;\n}\n\nstd::string Timestamp::to_formatted_string(bool show_msec) const {\n char buf[32] = {0};\n time_t time = static_cast(epoch_msec_ \/ kMicroSecondsPerSecond);\n struct tm result;\n gmtime_r(&time, &result);\n\n if (show_msec) {\n int msec = static_cast(epoch_msec_ % kMicroSecondsPerSecond);\n snprintf(buf,\n sizeof(buf),\n \"%04d%02d%02d %02d:%02d:%02d.%06d\",\n result.tm_year + 1900,\n result.tm_mon + 1,\n result.tm_mday,\n result.tm_hour,\n result.tm_min,\n result.tm_sec,\n msec);\n }\n else {\n snprintf(buf,\n sizeof(buf),\n \"%04d%02d%02d %02d:%02d:%02d\",\n result.tm_year + 1900,\n result.tm_mon + 1,\n result.tm_mday,\n result.tm_hour,\n result.tm_min,\n result.tm_sec);\n }\n\n return buf;\n}\n\nTimestamp Timestamp::now(void) {\n struct timeval tv;\n gettimeofday(&tv, nullptr);\n int64_t sec = tv.tv_sec;\n return Timestamp(sec * kMicroSecondsPerSecond + tv.tv_usec);\n}\n\nTimestamp Timestamp::invalid(void) {\n return Timestamp();\n}\n\nTimestamp Timestamp::from_unix_time(time_t t) {\n return from_unix_time(t, 0);\n}\n\nTimestamp Timestamp::from_unix_time(time_t t, int msec) {\n return Timestamp(static_cast(t) * kMicroSecondsPerSecond + msec);\n}\n\n}}\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 \"arrow\/util\/tdigest.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"arrow\/status.h\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nnamespace arrow {\nnamespace internal {\n\nnamespace {\n\n\/\/ a numerically stable lerp is unbelievably complex\n\/\/ but we are *approximating* the quantile, so let's keep it simple\ndouble Lerp(double a, double b, double t) { return a + t * (b - a); }\n\n\/\/ histogram bin\nstruct Centroid {\n double mean;\n double weight; \/\/ # data points in this bin\n\n \/\/ merge with another centroid\n void Merge(const Centroid& centroid) {\n weight += centroid.weight;\n mean += (centroid.mean - mean) * centroid.weight \/ weight;\n }\n};\n\n\/\/ scale function K0: linear function, as baseline\nstruct ScalerK0 {\n explicit ScalerK0(uint32_t delta) : delta_norm(delta \/ 2.0) {}\n\n double K(double q) const { return delta_norm * q; }\n double Q(double k) const { return k \/ delta_norm; }\n\n const double delta_norm;\n};\n\n\/\/ scale function K1\nstruct ScalerK1 {\n explicit ScalerK1(uint32_t delta) : delta_norm(delta \/ (2.0 * M_PI)) {}\n\n double K(double q) const { return delta_norm * std::asin(2 * q - 1); }\n double Q(double k) const { return (std::sin(k \/ delta_norm) + 1) \/ 2; }\n\n const double delta_norm;\n};\n\n\/\/ implements t-digest merging algorithm\ntemplate \nclass TDigestMerger : private T {\n public:\n explicit TDigestMerger(uint32_t delta) : T(delta) { Reset(0, nullptr); }\n\n void Reset(double total_weight, std::vector* tdigest) {\n total_weight_ = total_weight;\n tdigest_ = tdigest;\n if (tdigest_) {\n tdigest_->resize(0);\n }\n weight_so_far_ = 0;\n weight_limit_ = -1; \/\/ trigger first centroid merge\n }\n\n \/\/ merge one centroid from a sorted centroid stream\n void Add(const Centroid& centroid) {\n auto& td = *tdigest_;\n const double weight = weight_so_far_ + centroid.weight;\n if (weight <= weight_limit_) {\n td.back().Merge(centroid);\n } else {\n const double quantile = weight_so_far_ \/ total_weight_;\n const double next_weight_limit = total_weight_ * this->Q(this->K(quantile) + 1);\n \/\/ weight limit should be strictly increasing, until the last centroid\n if (next_weight_limit <= weight_limit_) {\n weight_limit_ = total_weight_;\n } else {\n weight_limit_ = next_weight_limit;\n }\n td.push_back(centroid); \/\/ should never exceed capacity and trigger reallocation\n }\n weight_so_far_ = weight;\n }\n\n \/\/ validate k-size of a tdigest\n Status Validate(const std::vector& tdigest, double total_weight) const {\n double q_prev = 0, k_prev = this->K(0);\n for (size_t i = 0; i < tdigest.size(); ++i) {\n const double q = q_prev + tdigest[i].weight \/ total_weight;\n const double k = this->K(q);\n if (tdigest[i].weight != 1 && (k - k_prev) > 1.001) {\n return Status::Invalid(\"oversized centroid: \", k - k_prev);\n }\n k_prev = k;\n q_prev = q;\n }\n return Status::OK();\n }\n\n private:\n double total_weight_; \/\/ total weight of this tdigest\n double weight_so_far_; \/\/ accumulated weight till current bin\n double weight_limit_; \/\/ max accumulated weight to move to next bin\n std::vector* tdigest_;\n};\n\n} \/\/ namespace\n\nclass TDigest::TDigestImpl {\n public:\n explicit TDigestImpl(uint32_t delta)\n : delta_(delta > 10 ? delta : 10), merger_(delta_) {\n tdigests_[0].reserve(delta_);\n tdigests_[1].reserve(delta_);\n Reset();\n }\n\n void Reset() {\n tdigests_[0].resize(0);\n tdigests_[1].resize(0);\n current_ = 0;\n total_weight_ = 0;\n min_ = std::numeric_limits::max();\n max_ = std::numeric_limits::lowest();\n merger_.Reset(0, nullptr);\n }\n\n Status Validate() const {\n \/\/ check weight, centroid order\n double total_weight = 0, prev_mean = std::numeric_limits::lowest();\n for (const auto& centroid : tdigests_[current_]) {\n if (std::isnan(centroid.mean) || std::isnan(centroid.weight)) {\n return Status::Invalid(\"NAN found in tdigest\");\n }\n if (centroid.mean < prev_mean) {\n return Status::Invalid(\"centroid mean decreases\");\n }\n if (centroid.weight < 1) {\n return Status::Invalid(\"invalid centroid weight\");\n }\n prev_mean = centroid.mean;\n total_weight += centroid.weight;\n }\n if (total_weight != total_weight_) {\n return Status::Invalid(\"tdigest total weight mismatch\");\n }\n \/\/ check if buffer expanded\n if (tdigests_[0].capacity() > delta_ || tdigests_[1].capacity() > delta_) {\n return Status::Invalid(\"oversized tdigest buffer\");\n }\n \/\/ check k-size\n return merger_.Validate(tdigests_[current_], total_weight_);\n }\n\n void Dump() const {\n const auto& td = tdigests_[current_];\n for (size_t i = 0; i < td.size(); ++i) {\n std::cerr << i << \": mean = \" << td[i].mean << \", weight = \" << td[i].weight\n << std::endl;\n }\n std::cerr << \"min = \" << min_ << \", max = \" << max_ << std::endl;\n }\n\n \/\/ merge with other tdigests\n void Merge(const std::vector& tdigest_impls) {\n \/\/ current and end iterator\n using CentroidIter = std::vector::const_iterator;\n using CentroidIterPair = std::pair;\n \/\/ use a min-heap to find next minimal centroid from all tdigests\n auto centroid_gt = [](const CentroidIterPair& lhs, const CentroidIterPair& rhs) {\n return lhs.first->mean > rhs.first->mean;\n };\n using CentroidQueue =\n std::priority_queue,\n decltype(centroid_gt)>;\n\n \/\/ trivial dynamic memory allocated at runtime\n std::vector queue_buffer;\n queue_buffer.reserve(tdigest_impls.size() + 1);\n CentroidQueue queue(std::move(centroid_gt), std::move(queue_buffer));\n\n const auto& this_tdigest = tdigests_[current_];\n if (this_tdigest.size() > 0) {\n queue.emplace(this_tdigest.cbegin(), this_tdigest.cend());\n }\n for (const TDigestImpl* td : tdigest_impls) {\n const auto& other_tdigest = td->tdigests_[td->current_];\n if (other_tdigest.size() > 0) {\n queue.emplace(other_tdigest.cbegin(), other_tdigest.cend());\n total_weight_ += td->total_weight_;\n min_ = std::min(min_, td->min_);\n max_ = std::max(max_, td->max_);\n }\n }\n\n merger_.Reset(total_weight_, &tdigests_[1 - current_]);\n CentroidIter current_iter, end_iter;\n \/\/ do k-way merge till one buffer left\n while (queue.size() > 1) {\n std::tie(current_iter, end_iter) = queue.top();\n merger_.Add(*current_iter);\n queue.pop();\n if (++current_iter != end_iter) {\n queue.emplace(current_iter, end_iter);\n }\n }\n \/\/ merge last buffer\n if (!queue.empty()) {\n std::tie(current_iter, end_iter) = queue.top();\n while (current_iter != end_iter) {\n merger_.Add(*current_iter++);\n }\n }\n merger_.Reset(0, nullptr);\n\n current_ = 1 - current_;\n }\n\n \/\/ merge input data with current tdigest\n void MergeInput(std::vector& input) {\n total_weight_ += input.size();\n\n std::sort(input.begin(), input.end());\n min_ = std::min(min_, input.front());\n max_ = std::max(max_, input.back());\n\n \/\/ pick next minimal centroid from input and tdigest, feed to merger\n merger_.Reset(total_weight_, &tdigests_[1 - current_]);\n const auto& td = tdigests_[current_];\n uint32_t tdigest_index = 0, input_index = 0;\n while (tdigest_index < td.size() && input_index < input.size()) {\n if (td[tdigest_index].mean < input[input_index]) {\n merger_.Add(td[tdigest_index++]);\n } else {\n merger_.Add(Centroid{input[input_index++], 1});\n }\n }\n while (tdigest_index < td.size()) {\n merger_.Add(td[tdigest_index++]);\n }\n while (input_index < input.size()) {\n merger_.Add(Centroid{input[input_index++], 1});\n }\n merger_.Reset(0, nullptr);\n\n input.resize(0);\n current_ = 1 - current_;\n }\n\n double Quantile(double q) const {\n const auto& td = tdigests_[current_];\n\n if (q < 0 || q > 1 || td.size() == 0) {\n return NAN;\n }\n\n const double index = q * total_weight_;\n if (index <= 1) {\n return min_;\n } else if (index >= total_weight_ - 1) {\n return max_;\n }\n\n \/\/ find centroid contains the index\n uint32_t ci = 0;\n double weight_sum = 0;\n for (; ci < td.size(); ++ci) {\n weight_sum += td[ci].weight;\n if (index <= weight_sum) {\n break;\n }\n }\n DCHECK_LT(ci, td.size());\n\n \/\/ deviation of index from the centroid center\n double diff = index + td[ci].weight \/ 2 - weight_sum;\n\n \/\/ index happen to be in a unit weight centroid\n if (td[ci].weight == 1 && std::abs(diff) < 0.5) {\n return td[ci].mean;\n }\n\n \/\/ find adjacent centroids for interpolation\n uint32_t ci_left = ci, ci_right = ci;\n if (diff > 0) {\n if (ci_right == td.size() - 1) {\n \/\/ index larger than center of last bin\n DCHECK_EQ(weight_sum, total_weight_);\n const Centroid* c = &td[ci_right];\n DCHECK_GE(c->weight, 2);\n return Lerp(c->mean, max_, diff \/ (c->weight \/ 2));\n }\n ++ci_right;\n } else {\n if (ci_left == 0) {\n \/\/ index smaller than center of first bin\n const Centroid* c = &td[0];\n DCHECK_GE(c->weight, 2);\n return Lerp(min_, c->mean, index \/ (c->weight \/ 2));\n }\n --ci_left;\n diff += td[ci_left].weight \/ 2 + td[ci_right].weight \/ 2;\n }\n\n \/\/ interpolate from adjacent centroids\n diff \/= (td[ci_left].weight \/ 2 + td[ci_right].weight \/ 2);\n return Lerp(td[ci_left].mean, td[ci_right].mean, diff);\n }\n\n double Mean() const {\n double sum = 0;\n for (const auto& centroid : tdigests_[current_]) {\n sum += centroid.mean * centroid.weight;\n }\n return total_weight_ == 0 ? NAN : sum \/ total_weight_;\n }\n\n double total_weight() const { return total_weight_; }\n\n private:\n \/\/ must be delcared before merger_, see constructor initialization list\n const uint32_t delta_;\n\n TDigestMerger<> merger_;\n double total_weight_;\n double min_, max_;\n\n \/\/ ping-pong buffer holds two tdigests, size = 2 * delta * sizeof(Centroid)\n std::vector tdigests_[2];\n \/\/ index of active tdigest buffer, 0 or 1\n int current_;\n};\n\nTDigest::TDigest(uint32_t delta, uint32_t buffer_size) : impl_(new TDigestImpl(delta)) {\n input_.reserve(buffer_size);\n Reset();\n}\n\nTDigest::~TDigest() = default;\nTDigest::TDigest(TDigest&&) = default;\nTDigest& TDigest::operator=(TDigest&&) = default;\n\nvoid TDigest::Reset() {\n input_.resize(0);\n impl_->Reset();\n}\n\nStatus TDigest::Validate() {\n MergeInput();\n return impl_->Validate();\n}\n\nvoid TDigest::Dump() {\n MergeInput();\n impl_->Dump();\n}\n\nvoid TDigest::Merge(std::vector* tdigests) {\n MergeInput();\n\n std::vector tdigest_impls;\n tdigest_impls.reserve(tdigests->size());\n for (auto& td : *tdigests) {\n td.MergeInput();\n tdigest_impls.push_back(td.impl_.get());\n }\n impl_->Merge(tdigest_impls);\n}\n\ndouble TDigest::Quantile(double q) {\n MergeInput();\n return impl_->Quantile(q);\n}\n\ndouble TDigest::Mean() {\n MergeInput();\n return impl_->Mean();\n}\n\nbool TDigest::is_empty() const {\n return input_.size() == 0 && impl_->total_weight() == 0;\n}\n\nvoid TDigest::MergeInput() {\n if (input_.size() > 0) {\n impl_->MergeInput(input_); \/\/ will mutate input_\n }\n}\n\n} \/\/ namespace internal\n} \/\/ namespace arrow\nARROW-13290: [C++] Add missing include\/\/ 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 \"arrow\/util\/tdigest.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"arrow\/status.h\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nnamespace arrow {\nnamespace internal {\n\nnamespace {\n\n\/\/ a numerically stable lerp is unbelievably complex\n\/\/ but we are *approximating* the quantile, so let's keep it simple\ndouble Lerp(double a, double b, double t) { return a + t * (b - a); }\n\n\/\/ histogram bin\nstruct Centroid {\n double mean;\n double weight; \/\/ # data points in this bin\n\n \/\/ merge with another centroid\n void Merge(const Centroid& centroid) {\n weight += centroid.weight;\n mean += (centroid.mean - mean) * centroid.weight \/ weight;\n }\n};\n\n\/\/ scale function K0: linear function, as baseline\nstruct ScalerK0 {\n explicit ScalerK0(uint32_t delta) : delta_norm(delta \/ 2.0) {}\n\n double K(double q) const { return delta_norm * q; }\n double Q(double k) const { return k \/ delta_norm; }\n\n const double delta_norm;\n};\n\n\/\/ scale function K1\nstruct ScalerK1 {\n explicit ScalerK1(uint32_t delta) : delta_norm(delta \/ (2.0 * M_PI)) {}\n\n double K(double q) const { return delta_norm * std::asin(2 * q - 1); }\n double Q(double k) const { return (std::sin(k \/ delta_norm) + 1) \/ 2; }\n\n const double delta_norm;\n};\n\n\/\/ implements t-digest merging algorithm\ntemplate \nclass TDigestMerger : private T {\n public:\n explicit TDigestMerger(uint32_t delta) : T(delta) { Reset(0, nullptr); }\n\n void Reset(double total_weight, std::vector* tdigest) {\n total_weight_ = total_weight;\n tdigest_ = tdigest;\n if (tdigest_) {\n tdigest_->resize(0);\n }\n weight_so_far_ = 0;\n weight_limit_ = -1; \/\/ trigger first centroid merge\n }\n\n \/\/ merge one centroid from a sorted centroid stream\n void Add(const Centroid& centroid) {\n auto& td = *tdigest_;\n const double weight = weight_so_far_ + centroid.weight;\n if (weight <= weight_limit_) {\n td.back().Merge(centroid);\n } else {\n const double quantile = weight_so_far_ \/ total_weight_;\n const double next_weight_limit = total_weight_ * this->Q(this->K(quantile) + 1);\n \/\/ weight limit should be strictly increasing, until the last centroid\n if (next_weight_limit <= weight_limit_) {\n weight_limit_ = total_weight_;\n } else {\n weight_limit_ = next_weight_limit;\n }\n td.push_back(centroid); \/\/ should never exceed capacity and trigger reallocation\n }\n weight_so_far_ = weight;\n }\n\n \/\/ validate k-size of a tdigest\n Status Validate(const std::vector& tdigest, double total_weight) const {\n double q_prev = 0, k_prev = this->K(0);\n for (size_t i = 0; i < tdigest.size(); ++i) {\n const double q = q_prev + tdigest[i].weight \/ total_weight;\n const double k = this->K(q);\n if (tdigest[i].weight != 1 && (k - k_prev) > 1.001) {\n return Status::Invalid(\"oversized centroid: \", k - k_prev);\n }\n k_prev = k;\n q_prev = q;\n }\n return Status::OK();\n }\n\n private:\n double total_weight_; \/\/ total weight of this tdigest\n double weight_so_far_; \/\/ accumulated weight till current bin\n double weight_limit_; \/\/ max accumulated weight to move to next bin\n std::vector* tdigest_;\n};\n\n} \/\/ namespace\n\nclass TDigest::TDigestImpl {\n public:\n explicit TDigestImpl(uint32_t delta)\n : delta_(delta > 10 ? delta : 10), merger_(delta_) {\n tdigests_[0].reserve(delta_);\n tdigests_[1].reserve(delta_);\n Reset();\n }\n\n void Reset() {\n tdigests_[0].resize(0);\n tdigests_[1].resize(0);\n current_ = 0;\n total_weight_ = 0;\n min_ = std::numeric_limits::max();\n max_ = std::numeric_limits::lowest();\n merger_.Reset(0, nullptr);\n }\n\n Status Validate() const {\n \/\/ check weight, centroid order\n double total_weight = 0, prev_mean = std::numeric_limits::lowest();\n for (const auto& centroid : tdigests_[current_]) {\n if (std::isnan(centroid.mean) || std::isnan(centroid.weight)) {\n return Status::Invalid(\"NAN found in tdigest\");\n }\n if (centroid.mean < prev_mean) {\n return Status::Invalid(\"centroid mean decreases\");\n }\n if (centroid.weight < 1) {\n return Status::Invalid(\"invalid centroid weight\");\n }\n prev_mean = centroid.mean;\n total_weight += centroid.weight;\n }\n if (total_weight != total_weight_) {\n return Status::Invalid(\"tdigest total weight mismatch\");\n }\n \/\/ check if buffer expanded\n if (tdigests_[0].capacity() > delta_ || tdigests_[1].capacity() > delta_) {\n return Status::Invalid(\"oversized tdigest buffer\");\n }\n \/\/ check k-size\n return merger_.Validate(tdigests_[current_], total_weight_);\n }\n\n void Dump() const {\n const auto& td = tdigests_[current_];\n for (size_t i = 0; i < td.size(); ++i) {\n std::cerr << i << \": mean = \" << td[i].mean << \", weight = \" << td[i].weight\n << std::endl;\n }\n std::cerr << \"min = \" << min_ << \", max = \" << max_ << std::endl;\n }\n\n \/\/ merge with other tdigests\n void Merge(const std::vector& tdigest_impls) {\n \/\/ current and end iterator\n using CentroidIter = std::vector::const_iterator;\n using CentroidIterPair = std::pair;\n \/\/ use a min-heap to find next minimal centroid from all tdigests\n auto centroid_gt = [](const CentroidIterPair& lhs, const CentroidIterPair& rhs) {\n return lhs.first->mean > rhs.first->mean;\n };\n using CentroidQueue =\n std::priority_queue,\n decltype(centroid_gt)>;\n\n \/\/ trivial dynamic memory allocated at runtime\n std::vector queue_buffer;\n queue_buffer.reserve(tdigest_impls.size() + 1);\n CentroidQueue queue(std::move(centroid_gt), std::move(queue_buffer));\n\n const auto& this_tdigest = tdigests_[current_];\n if (this_tdigest.size() > 0) {\n queue.emplace(this_tdigest.cbegin(), this_tdigest.cend());\n }\n for (const TDigestImpl* td : tdigest_impls) {\n const auto& other_tdigest = td->tdigests_[td->current_];\n if (other_tdigest.size() > 0) {\n queue.emplace(other_tdigest.cbegin(), other_tdigest.cend());\n total_weight_ += td->total_weight_;\n min_ = std::min(min_, td->min_);\n max_ = std::max(max_, td->max_);\n }\n }\n\n merger_.Reset(total_weight_, &tdigests_[1 - current_]);\n CentroidIter current_iter, end_iter;\n \/\/ do k-way merge till one buffer left\n while (queue.size() > 1) {\n std::tie(current_iter, end_iter) = queue.top();\n merger_.Add(*current_iter);\n queue.pop();\n if (++current_iter != end_iter) {\n queue.emplace(current_iter, end_iter);\n }\n }\n \/\/ merge last buffer\n if (!queue.empty()) {\n std::tie(current_iter, end_iter) = queue.top();\n while (current_iter != end_iter) {\n merger_.Add(*current_iter++);\n }\n }\n merger_.Reset(0, nullptr);\n\n current_ = 1 - current_;\n }\n\n \/\/ merge input data with current tdigest\n void MergeInput(std::vector& input) {\n total_weight_ += input.size();\n\n std::sort(input.begin(), input.end());\n min_ = std::min(min_, input.front());\n max_ = std::max(max_, input.back());\n\n \/\/ pick next minimal centroid from input and tdigest, feed to merger\n merger_.Reset(total_weight_, &tdigests_[1 - current_]);\n const auto& td = tdigests_[current_];\n uint32_t tdigest_index = 0, input_index = 0;\n while (tdigest_index < td.size() && input_index < input.size()) {\n if (td[tdigest_index].mean < input[input_index]) {\n merger_.Add(td[tdigest_index++]);\n } else {\n merger_.Add(Centroid{input[input_index++], 1});\n }\n }\n while (tdigest_index < td.size()) {\n merger_.Add(td[tdigest_index++]);\n }\n while (input_index < input.size()) {\n merger_.Add(Centroid{input[input_index++], 1});\n }\n merger_.Reset(0, nullptr);\n\n input.resize(0);\n current_ = 1 - current_;\n }\n\n double Quantile(double q) const {\n const auto& td = tdigests_[current_];\n\n if (q < 0 || q > 1 || td.size() == 0) {\n return NAN;\n }\n\n const double index = q * total_weight_;\n if (index <= 1) {\n return min_;\n } else if (index >= total_weight_ - 1) {\n return max_;\n }\n\n \/\/ find centroid contains the index\n uint32_t ci = 0;\n double weight_sum = 0;\n for (; ci < td.size(); ++ci) {\n weight_sum += td[ci].weight;\n if (index <= weight_sum) {\n break;\n }\n }\n DCHECK_LT(ci, td.size());\n\n \/\/ deviation of index from the centroid center\n double diff = index + td[ci].weight \/ 2 - weight_sum;\n\n \/\/ index happen to be in a unit weight centroid\n if (td[ci].weight == 1 && std::abs(diff) < 0.5) {\n return td[ci].mean;\n }\n\n \/\/ find adjacent centroids for interpolation\n uint32_t ci_left = ci, ci_right = ci;\n if (diff > 0) {\n if (ci_right == td.size() - 1) {\n \/\/ index larger than center of last bin\n DCHECK_EQ(weight_sum, total_weight_);\n const Centroid* c = &td[ci_right];\n DCHECK_GE(c->weight, 2);\n return Lerp(c->mean, max_, diff \/ (c->weight \/ 2));\n }\n ++ci_right;\n } else {\n if (ci_left == 0) {\n \/\/ index smaller than center of first bin\n const Centroid* c = &td[0];\n DCHECK_GE(c->weight, 2);\n return Lerp(min_, c->mean, index \/ (c->weight \/ 2));\n }\n --ci_left;\n diff += td[ci_left].weight \/ 2 + td[ci_right].weight \/ 2;\n }\n\n \/\/ interpolate from adjacent centroids\n diff \/= (td[ci_left].weight \/ 2 + td[ci_right].weight \/ 2);\n return Lerp(td[ci_left].mean, td[ci_right].mean, diff);\n }\n\n double Mean() const {\n double sum = 0;\n for (const auto& centroid : tdigests_[current_]) {\n sum += centroid.mean * centroid.weight;\n }\n return total_weight_ == 0 ? NAN : sum \/ total_weight_;\n }\n\n double total_weight() const { return total_weight_; }\n\n private:\n \/\/ must be delcared before merger_, see constructor initialization list\n const uint32_t delta_;\n\n TDigestMerger<> merger_;\n double total_weight_;\n double min_, max_;\n\n \/\/ ping-pong buffer holds two tdigests, size = 2 * delta * sizeof(Centroid)\n std::vector tdigests_[2];\n \/\/ index of active tdigest buffer, 0 or 1\n int current_;\n};\n\nTDigest::TDigest(uint32_t delta, uint32_t buffer_size) : impl_(new TDigestImpl(delta)) {\n input_.reserve(buffer_size);\n Reset();\n}\n\nTDigest::~TDigest() = default;\nTDigest::TDigest(TDigest&&) = default;\nTDigest& TDigest::operator=(TDigest&&) = default;\n\nvoid TDigest::Reset() {\n input_.resize(0);\n impl_->Reset();\n}\n\nStatus TDigest::Validate() {\n MergeInput();\n return impl_->Validate();\n}\n\nvoid TDigest::Dump() {\n MergeInput();\n impl_->Dump();\n}\n\nvoid TDigest::Merge(std::vector* tdigests) {\n MergeInput();\n\n std::vector tdigest_impls;\n tdigest_impls.reserve(tdigests->size());\n for (auto& td : *tdigests) {\n td.MergeInput();\n tdigest_impls.push_back(td.impl_.get());\n }\n impl_->Merge(tdigest_impls);\n}\n\ndouble TDigest::Quantile(double q) {\n MergeInput();\n return impl_->Quantile(q);\n}\n\ndouble TDigest::Mean() {\n MergeInput();\n return impl_->Mean();\n}\n\nbool TDigest::is_empty() const {\n return input_.size() == 0 && impl_->total_weight() == 0;\n}\n\nvoid TDigest::MergeInput() {\n if (input_.size() > 0) {\n impl_->MergeInput(input_); \/\/ will mutate input_\n }\n}\n\n} \/\/ namespace internal\n} \/\/ namespace arrow\n<|endoftext|>"} {"text":"#include \"ImagePanel.h\"\r\n\r\n#include \r\n\r\nusing namespace std;\r\n\r\n\r\nwxBitmapPtr ToBitmap( const LinearImage& image )\r\n{\r\n vector< unsigned char > color, alpha;\r\n image.GetSrgb( color, alpha );\r\n return wxBitmapPtr( new wxBitmap( \r\n alpha.empty()\r\n ? wxImage( image.GetWidth(), image.GetHeight(), &color[0], true )\r\n : wxImage( image.GetWidth(), image.GetHeight(), &color[0], &alpha[0], true )\r\n ) );\r\n}\r\n\r\n\r\nvector< wxRect > GetCoverage( const wxRect& viewport, const wxRect& canvas, const wxSize& gridSize )\r\n{\r\n const wxRect clippedViewport( canvas.Intersect( viewport ) );\r\n\r\n vector< wxRect > coverage;\r\n const int top = clippedViewport.GetTop() \/ gridSize.y;\r\n const int bottom = clippedViewport.GetBottom() \/ gridSize.y;\r\n const int left = clippedViewport.GetLeft() \/ gridSize.x;\r\n const int right = clippedViewport.GetRight() \/ gridSize.x;\r\n for( int y = top; y <= bottom; ++y )\r\n {\r\n for( int x = left; x <= right; ++x )\r\n {\r\n const wxRect candidate( x * gridSize.x, y * gridSize.y, gridSize.x, gridSize.y );\r\n const wxRect clipped( canvas.Intersect( candidate ) );\r\n coverage.push_back( clipped );\r\n }\r\n }\r\n return coverage;\r\n}\r\n\r\n\r\ntemplate< typename T >\r\nT clamp( const T& val, const T& minVal, const T& maxVal )\r\n{\r\n if( val < minVal ) return minVal;\r\n if( val > maxVal ) return maxVal;\r\n return val;\r\n}\r\n\r\n\r\nwxPoint ClampPosition( const wxRect& viewport, const wxRect& extent )\r\n{\r\n const wxSize delta( viewport.GetSize() - extent.GetSize() ); \r\n\r\n wxPoint newTopLeft( viewport.GetPosition() );\r\n\r\n if( delta.x < 0 )\r\n {\r\n \/\/ viewport smaller than extent\r\n int minX = extent.GetPosition().x;\r\n int maxX = ( extent.GetPosition().x + extent.GetSize().x ) - viewport.GetSize().x;\r\n newTopLeft.x = clamp( newTopLeft.x, minX, maxX );\r\n }\r\n else\r\n {\r\n \/\/ viewport larger than extent\r\n newTopLeft.x = extent.GetPosition().x - ( delta.x \/ 2 );\r\n }\r\n\r\n if( delta.y < 0 )\r\n {\r\n \/\/ viewport smaller than extent\r\n int minY = extent.GetPosition().y;\r\n int maxY = ( extent.GetPosition().y + extent.GetSize().y ) - viewport.GetSize().y;\r\n newTopLeft.y = clamp( newTopLeft.y, minY, maxY );\r\n }\r\n else\r\n {\r\n \/\/ viewport larger than extent\r\n newTopLeft.y = extent.GetPosition().y - ( delta.y \/ 2 );\r\n }\r\n\r\n return newTopLeft;\r\n}\r\n\r\n\r\nwxBitmapPtr GetScaledSubrect( const LinearImage& src, auto_ptr< Resampler > resamplers[ 4 ], const wxRect& rect )\r\n{\r\n LinearImage dst( rect.GetWidth(), rect.GetHeight(), src.GetNumChannels() == 4 ? true : false, NULL );\r\n\r\n for( size_t c = 0; c < src.GetNumChannels(); ++c )\r\n {\r\n resamplers[ c ]->StartResample\r\n (\r\n rect.x, rect.y,\r\n rect.GetWidth(), rect.GetHeight()\r\n );\r\n }\r\n\r\n size_t dstY = 0;\r\n for( size_t y = 0; y < src.GetHeight(); ++y )\r\n {\r\n for( size_t c = 0; c < src.GetNumChannels(); ++c )\r\n {\r\n resamplers[ c ]->PutLine( src.GetRow( c, y ) );\r\n }\r\n\r\n while( true )\r\n {\r\n bool missedLine = false;\r\n for( size_t c = 0; c < src.GetNumChannels(); ++c )\r\n {\r\n const float* line = resamplers[ c ]->GetLine();\r\n if( NULL == line )\r\n {\r\n missedLine = true;\r\n break;\r\n }\r\n\r\n copy( line, line + dst.GetWidth(), dst.GetRow( c, dstY ) );\r\n }\r\n\r\n if( missedLine )\r\n {\r\n break;\r\n }\r\n\r\n dstY++;\r\n }\r\n }\r\n\r\n return ToBitmap( dst );\r\n}\r\n\r\n\r\nwxImagePanel::wxImagePanel( wxWindow* parent )\r\n : wxWindow( parent, wxID_ANY )\r\n , mPosition( 0, 0 )\r\n , mScale( 1.0 )\r\n{\r\n \/\/ for wxAutoBufferedPaintDC\r\n SetBackgroundStyle( wxBG_STYLE_PAINT );\r\n\r\n SetBackgroundColour( *wxBLACK );\r\n \r\n Bind( wxEVT_SIZE , &wxImagePanel::OnSize , this );\r\n Bind( wxEVT_PAINT , &wxImagePanel::OnPaint , this );\r\n Bind( wxEVT_KEY_DOWN , &wxImagePanel::OnKeyDown , this );\r\n Bind( wxEVT_KEY_UP , &wxImagePanel::OnKeyUp , this );\r\n Bind( wxEVT_LEFT_DOWN , &wxImagePanel::OnButtonDown , this );\r\n Bind( wxEVT_RIGHT_DOWN , &wxImagePanel::OnButtonDown , this );\r\n Bind( wxEVT_MIDDLE_DOWN , &wxImagePanel::OnButtonDown , this );\r\n Bind( wxEVT_MOTION , &wxImagePanel::OnMotion , this );\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnSize( wxSizeEvent& event )\r\n{\r\n mPosition = ClampPosition( mPosition );\r\n\r\n \/\/ invalidate entire panel since we need to redraw everything\r\n Refresh( true );\r\n\r\n \/\/ skip the event so sizers can do their thing\r\n event.Skip();\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnButtonDown( wxMouseEvent& event )\r\n{\r\n if( event.LeftDown() )\r\n {\r\n mLeftPositionStart = mPosition;\r\n mLeftMouseStart = event.GetPosition();\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnMotion( wxMouseEvent& event )\r\n{\r\n if( event.LeftIsDown() && event.Dragging() )\r\n {\r\n wxPoint newPos( mLeftPositionStart - ( event.GetPosition() - mLeftMouseStart ) );\r\n if( newPos != mPosition )\r\n {\r\n ScrollToPosition( newPos );\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnIdle( wxIdleEvent& event )\r\n{\r\n wxPoint newPos( mPosition );\r\n const int step = 1;\r\n if( wxGetKeyState( WXK_LEFT ) ) newPos += step * wxPoint( -1, 0 );\r\n if( wxGetKeyState( WXK_RIGHT ) ) newPos += step * wxPoint( 1, 0 );\r\n if( wxGetKeyState( WXK_UP ) ) newPos += step * wxPoint( 0, -1 );\r\n if( wxGetKeyState( WXK_DOWN ) ) newPos += step * wxPoint( 0, 1 );\r\n\r\n if( newPos == mPosition )\r\n {\r\n Unbind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );\r\n return;\r\n }\r\n\r\n ScrollToPosition( newPos );\r\n\r\n \/\/event.RequestMore( true );\r\n \/\/wxMilliSleep( 1 );\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnKeyDown( wxKeyEvent& event )\r\n{\r\n switch( event.GetKeyCode() )\r\n {\r\n case WXK_LEFT:\r\n case WXK_RIGHT:\r\n case WXK_UP:\r\n case WXK_DOWN:\r\n Bind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );\r\n break;\r\n default:\r\n break;\r\n }\r\n}\r\n\r\n\r\nwxPoint wxImagePanel::ClampPosition( const wxPoint& newPos )\r\n{\r\n if( NULL == mImage )\r\n {\r\n return newPos;\r\n }\r\n\r\n const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );\r\n return ::ClampPosition\r\n (\r\n wxRect( newPos, GetSize() ),\r\n wxRect( wxPoint(0,0), scaledSize )\r\n );\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnKeyUp( wxKeyEvent& event )\r\n{\r\n switch( event.GetKeyCode() )\r\n {\r\n case WXK_ADD:\r\n case WXK_NUMPAD_ADD:\r\n SetScale( mScale * 1.1 );\r\n break;\r\n case WXK_SUBTRACT:\r\n case WXK_NUMPAD_SUBTRACT:\r\n SetScale( mScale \/ 1.1 );\r\n break;\r\n default:\r\n break;\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::ScrollToPosition( const wxPoint& newPos )\r\n{\r\n const wxPoint clamped = ClampPosition( newPos );\r\n wxPoint delta( clamped - mPosition );\r\n ScrollWindow( -delta.x, -delta.y );\r\n mPosition = clamped;\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnPaint( wxPaintEvent& event )\r\n{\r\n wxPaintDC dc(this);\r\n \/\/wxAutoBufferedPaintDC dc( this );\r\n\r\n dc.SetDeviceOrigin( -mPosition.x, -mPosition.y );\r\n\r\n dc.Clear();\r\n\r\n if( NULL == mImage )\r\n {\r\n return;\r\n }\r\n\r\n const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );\r\n const wxRect scaledRect( wxPoint( 0, 0 ), scaledSize );\r\n const wxSize gridSize( TILE_SIZE, TILE_SIZE );\r\n\r\n \/\/ get the set of tiles we need to draw\r\n set< wxRect, wxRectCmp > covered;\r\n for( wxRegionIterator upd( GetUpdateRegion() ); upd.HaveRects(); ++upd )\r\n {\r\n wxRect rect( upd.GetRect() );\r\n rect.SetPosition( rect.GetPosition() + mPosition );\r\n\r\n const vector< wxRect > ret = GetCoverage( rect, scaledRect, gridSize );\r\n covered.insert( ret.begin(), ret.end() );\r\n }\r\n \r\n for( const wxRect& rect : covered )\r\n {\r\n map< wxRect, wxBitmapPtr >::iterator it = mBitmapCache.find( rect );\r\n if( mBitmapCache.end() == it )\r\n {\r\n it = mBitmapCache.insert( make_pair( rect, GetScaledSubrect( *mImage, mResamplers, rect ) ) ).first;\r\n }\r\n\r\n dc.DrawBitmap( *(it->second), rect.GetPosition() );\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::SetImage( const LinearImage* newImage )\r\n{\r\n mImage = newImage;\r\n SetScale( mScale );\r\n mPosition = ClampPosition( mPosition );\r\n}\r\n\r\n\r\nvoid wxImagePanel::SetScale( const double newScale )\r\n{\r\n mScale = newScale;\r\n mBitmapCache.clear();\r\n mPosition = ClampPosition( mPosition );\r\n\r\n \/\/ invalidate entire panel since we need to redraw everything\r\n Refresh( true );\r\n\r\n if( NULL == mImage )\r\n {\r\n return;\r\n }\r\n\r\n \/\/ regenerate resamplers\r\n mContribLists.reset( new Resampler::ContribLists\r\n (\r\n mImage->GetWidth(), mImage->GetHeight(),\r\n mImage->GetWidth() * mScale, mImage->GetHeight() * mScale\r\n ) );\r\n for( size_t i = 0; i < 4; ++i )\r\n {\r\n mResamplers[ i ].reset( new Resampler( *mContribLists ) );\r\n }\r\n}Add fit-to-window and reset zoom controls#include \"ImagePanel.h\"\r\n\r\n#include \r\n\r\nusing namespace std;\r\n\r\n\r\nwxBitmapPtr ToBitmap( const LinearImage& image )\r\n{\r\n vector< unsigned char > color, alpha;\r\n image.GetSrgb( color, alpha );\r\n return wxBitmapPtr( new wxBitmap( \r\n alpha.empty()\r\n ? wxImage( image.GetWidth(), image.GetHeight(), &color[0], true )\r\n : wxImage( image.GetWidth(), image.GetHeight(), &color[0], &alpha[0], true )\r\n ) );\r\n}\r\n\r\n\r\nvector< wxRect > GetCoverage( const wxRect& viewport, const wxRect& canvas, const wxSize& gridSize )\r\n{\r\n const wxRect clippedViewport( canvas.Intersect( viewport ) );\r\n\r\n vector< wxRect > coverage;\r\n const int top = clippedViewport.GetTop() \/ gridSize.y;\r\n const int bottom = clippedViewport.GetBottom() \/ gridSize.y;\r\n const int left = clippedViewport.GetLeft() \/ gridSize.x;\r\n const int right = clippedViewport.GetRight() \/ gridSize.x;\r\n for( int y = top; y <= bottom; ++y )\r\n {\r\n for( int x = left; x <= right; ++x )\r\n {\r\n const wxRect candidate( x * gridSize.x, y * gridSize.y, gridSize.x, gridSize.y );\r\n const wxRect clipped( canvas.Intersect( candidate ) );\r\n coverage.push_back( clipped );\r\n }\r\n }\r\n return coverage;\r\n}\r\n\r\n\r\ntemplate< typename T >\r\nT clamp( const T& val, const T& minVal, const T& maxVal )\r\n{\r\n if( val < minVal ) return minVal;\r\n if( val > maxVal ) return maxVal;\r\n return val;\r\n}\r\n\r\n\r\nwxPoint ClampPosition( const wxRect& viewport, const wxRect& extent )\r\n{\r\n const wxSize delta( viewport.GetSize() - extent.GetSize() ); \r\n\r\n wxPoint newTopLeft( viewport.GetPosition() );\r\n\r\n if( delta.x < 0 )\r\n {\r\n \/\/ viewport smaller than extent\r\n int minX = extent.GetPosition().x;\r\n int maxX = ( extent.GetPosition().x + extent.GetSize().x ) - viewport.GetSize().x;\r\n newTopLeft.x = clamp( newTopLeft.x, minX, maxX );\r\n }\r\n else\r\n {\r\n \/\/ viewport larger than extent\r\n newTopLeft.x = extent.GetPosition().x - ( delta.x \/ 2 );\r\n }\r\n\r\n if( delta.y < 0 )\r\n {\r\n \/\/ viewport smaller than extent\r\n int minY = extent.GetPosition().y;\r\n int maxY = ( extent.GetPosition().y + extent.GetSize().y ) - viewport.GetSize().y;\r\n newTopLeft.y = clamp( newTopLeft.y, minY, maxY );\r\n }\r\n else\r\n {\r\n \/\/ viewport larger than extent\r\n newTopLeft.y = extent.GetPosition().y - ( delta.y \/ 2 );\r\n }\r\n\r\n return newTopLeft;\r\n}\r\n\r\n\r\nwxBitmapPtr GetScaledSubrect( const LinearImage& src, auto_ptr< Resampler > resamplers[ 4 ], const wxRect& rect )\r\n{\r\n LinearImage dst( rect.GetWidth(), rect.GetHeight(), src.GetNumChannels() == 4 ? true : false, NULL );\r\n\r\n for( size_t c = 0; c < src.GetNumChannels(); ++c )\r\n {\r\n resamplers[ c ]->StartResample\r\n (\r\n rect.x, rect.y,\r\n rect.GetWidth(), rect.GetHeight()\r\n );\r\n }\r\n\r\n size_t dstY = 0;\r\n for( size_t y = 0; y < src.GetHeight(); ++y )\r\n {\r\n for( size_t c = 0; c < src.GetNumChannels(); ++c )\r\n {\r\n resamplers[ c ]->PutLine( src.GetRow( c, y ) );\r\n }\r\n\r\n while( true )\r\n {\r\n bool missedLine = false;\r\n for( size_t c = 0; c < src.GetNumChannels(); ++c )\r\n {\r\n const float* line = resamplers[ c ]->GetLine();\r\n if( NULL == line )\r\n {\r\n missedLine = true;\r\n break;\r\n }\r\n\r\n copy( line, line + dst.GetWidth(), dst.GetRow( c, dstY ) );\r\n }\r\n\r\n if( missedLine )\r\n {\r\n break;\r\n }\r\n\r\n dstY++;\r\n }\r\n }\r\n\r\n return ToBitmap( dst );\r\n}\r\n\r\n\r\nwxImagePanel::wxImagePanel( wxWindow* parent )\r\n : wxWindow( parent, wxID_ANY )\r\n , mPosition( 0, 0 )\r\n , mScale( 1.0 )\r\n{\r\n \/\/ for wxAutoBufferedPaintDC\r\n SetBackgroundStyle( wxBG_STYLE_PAINT );\r\n\r\n SetBackgroundColour( *wxBLACK );\r\n \r\n Bind( wxEVT_SIZE , &wxImagePanel::OnSize , this );\r\n Bind( wxEVT_PAINT , &wxImagePanel::OnPaint , this );\r\n Bind( wxEVT_KEY_DOWN , &wxImagePanel::OnKeyDown , this );\r\n Bind( wxEVT_KEY_UP , &wxImagePanel::OnKeyUp , this );\r\n Bind( wxEVT_LEFT_DOWN , &wxImagePanel::OnButtonDown , this );\r\n Bind( wxEVT_RIGHT_DOWN , &wxImagePanel::OnButtonDown , this );\r\n Bind( wxEVT_MIDDLE_DOWN , &wxImagePanel::OnButtonDown , this );\r\n Bind( wxEVT_MOTION , &wxImagePanel::OnMotion , this );\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnSize( wxSizeEvent& event )\r\n{\r\n mPosition = ClampPosition( mPosition );\r\n\r\n \/\/ invalidate entire panel since we need to redraw everything\r\n Refresh( true );\r\n\r\n \/\/ skip the event so sizers can do their thing\r\n event.Skip();\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnButtonDown( wxMouseEvent& event )\r\n{\r\n if( event.LeftDown() )\r\n {\r\n mLeftPositionStart = mPosition;\r\n mLeftMouseStart = event.GetPosition();\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnMotion( wxMouseEvent& event )\r\n{\r\n if( event.LeftIsDown() && event.Dragging() )\r\n {\r\n wxPoint newPos( mLeftPositionStart - ( event.GetPosition() - mLeftMouseStart ) );\r\n if( newPos != mPosition )\r\n {\r\n ScrollToPosition( newPos );\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnIdle( wxIdleEvent& event )\r\n{\r\n wxPoint newPos( mPosition );\r\n const int step = 1;\r\n if( wxGetKeyState( WXK_LEFT ) ) newPos += step * wxPoint( -1, 0 );\r\n if( wxGetKeyState( WXK_RIGHT ) ) newPos += step * wxPoint( 1, 0 );\r\n if( wxGetKeyState( WXK_UP ) ) newPos += step * wxPoint( 0, -1 );\r\n if( wxGetKeyState( WXK_DOWN ) ) newPos += step * wxPoint( 0, 1 );\r\n\r\n if( newPos == mPosition )\r\n {\r\n Unbind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );\r\n return;\r\n }\r\n\r\n ScrollToPosition( newPos );\r\n\r\n \/\/event.RequestMore( true );\r\n \/\/wxMilliSleep( 1 );\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnKeyDown( wxKeyEvent& event )\r\n{\r\n switch( event.GetKeyCode() )\r\n {\r\n case WXK_LEFT:\r\n case WXK_RIGHT:\r\n case WXK_UP:\r\n case WXK_DOWN:\r\n Bind( wxEVT_IDLE, &wxImagePanel::OnIdle, this );\r\n break;\r\n default:\r\n break;\r\n }\r\n}\r\n\r\n\r\nwxPoint wxImagePanel::ClampPosition( const wxPoint& newPos )\r\n{\r\n if( NULL == mImage )\r\n {\r\n return newPos;\r\n }\r\n\r\n const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );\r\n return ::ClampPosition\r\n (\r\n wxRect( newPos, GetSize() ),\r\n wxRect( wxPoint(0,0), scaledSize )\r\n );\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnKeyUp( wxKeyEvent& event )\r\n{\r\n if( NULL == mImage )\r\n {\r\n return;\r\n }\r\n\r\n switch( event.GetKeyCode() )\r\n {\r\n case WXK_ADD:\r\n case WXK_NUMPAD_ADD:\r\n SetScale( mScale * 1.1 );\r\n break;\r\n case WXK_SUBTRACT:\r\n case WXK_NUMPAD_SUBTRACT:\r\n SetScale( mScale \/ 1.1 );\r\n break;\r\n case WXK_NUMPAD_MULTIPLY:\r\n {\r\n const int iMax = max( mImage->GetWidth(), mImage->GetHeight() );\r\n const int wMin = min( GetSize().x, GetSize().y );\r\n SetScale( wMin \/ (double)iMax );\r\n }\r\n break;\r\n case WXK_NUMPAD_DIVIDE:\r\n SetScale( 1.0 );\r\n break;\r\n default:\r\n break;\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::ScrollToPosition( const wxPoint& newPos )\r\n{\r\n const wxPoint clamped = ClampPosition( newPos );\r\n wxPoint delta( clamped - mPosition );\r\n ScrollWindow( -delta.x, -delta.y );\r\n mPosition = clamped;\r\n}\r\n\r\n\r\nvoid wxImagePanel::OnPaint( wxPaintEvent& event )\r\n{\r\n wxPaintDC dc(this);\r\n \/\/wxAutoBufferedPaintDC dc( this );\r\n\r\n dc.SetDeviceOrigin( -mPosition.x, -mPosition.y );\r\n\r\n dc.Clear();\r\n\r\n if( NULL == mImage )\r\n {\r\n return;\r\n }\r\n\r\n const wxSize scaledSize( mImage->GetWidth() * mScale, mImage->GetHeight() * mScale );\r\n const wxRect scaledRect( wxPoint( 0, 0 ), scaledSize );\r\n const wxSize gridSize( TILE_SIZE, TILE_SIZE );\r\n\r\n \/\/ get the set of tiles we need to draw\r\n set< wxRect, wxRectCmp > covered;\r\n for( wxRegionIterator upd( GetUpdateRegion() ); upd.HaveRects(); ++upd )\r\n {\r\n wxRect rect( upd.GetRect() );\r\n rect.SetPosition( rect.GetPosition() + mPosition );\r\n\r\n const vector< wxRect > ret = GetCoverage( rect, scaledRect, gridSize );\r\n covered.insert( ret.begin(), ret.end() );\r\n }\r\n \r\n for( const wxRect& rect : covered )\r\n {\r\n map< wxRect, wxBitmapPtr >::iterator it = mBitmapCache.find( rect );\r\n if( mBitmapCache.end() == it )\r\n {\r\n it = mBitmapCache.insert( make_pair( rect, GetScaledSubrect( *mImage, mResamplers, rect ) ) ).first;\r\n }\r\n\r\n dc.DrawBitmap( *(it->second), rect.GetPosition() );\r\n }\r\n}\r\n\r\n\r\nvoid wxImagePanel::SetImage( const LinearImage* newImage )\r\n{\r\n mImage = newImage;\r\n SetScale( mScale );\r\n mPosition = ClampPosition( mPosition );\r\n}\r\n\r\n\r\nvoid wxImagePanel::SetScale( const double newScale )\r\n{\r\n mScale = newScale;\r\n mBitmapCache.clear();\r\n mPosition = ClampPosition( mPosition );\r\n\r\n \/\/ invalidate entire panel since we need to redraw everything\r\n Refresh( true );\r\n\r\n if( NULL == mImage )\r\n {\r\n return;\r\n }\r\n\r\n \/\/ regenerate resamplers\r\n mContribLists.reset( new Resampler::ContribLists\r\n (\r\n mImage->GetWidth(), mImage->GetHeight(),\r\n mImage->GetWidth() * mScale, mImage->GetHeight() * mScale\r\n ) );\r\n for( size_t i = 0; i < 4; ++i )\r\n {\r\n mResamplers[ i ].reset( new Resampler( *mContribLists ) );\r\n }\r\n}<|endoftext|>"} {"text":"#ifndef __GLYPH_HPP_INCLUDED\n#define __GLYPH_HPP_INCLUDED\n\n#include \"species_or_glyph.hpp\"\n#include \"text3D.hpp\"\n#include \"vector_font.hpp\"\n#include \"render_templates.hpp\"\n#include \"cpp\/ylikuutio\/hierarchy\/hierarchy_templates.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include standard headers\n#include \/\/ std::queue\n#include \/\/ uint32_t etc.\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace model\n{\n class Object;\n\n class Glyph\n {\n public:\n \/\/ constructor.\n Glyph(GlyphStruct glyph_struct);\n\n \/\/ destructor.\n \/\/ glyphs should be destroyed only by destroying the entire `VectorFont`.\n ~Glyph();\n\n \/\/ this method sets a object pointer.\n void set_object_pointer(uint32_t childID, void* parent_pointer);\n\n \/\/ this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.\n uint32_t get_objectID();\n\n glm::vec3 light_position; \/\/ light position.\n\n \/\/ The rest fields are created in the constructor.\n uint32_t image_width;\n uint32_t image_height;\n\n GLuint vertexPosition_modelspaceID;\n GLuint vertexUVID;\n GLuint vertexNormal_modelspaceID;\n\n std::vector vertices; \/\/ vertices of the object.\n std::vector UVs; \/\/ UVs of the object.\n std::vector normals; \/\/ normals of the object.\n\n std::vector indices; \/\/ the deleted vertices will be reused (though it is not required, if there's enough memory).\n std::vector indexed_vertices;\n std::vector indexed_UVs;\n std::vector indexed_normals;\n\n GLuint vertexbuffer;\n GLuint uvbuffer;\n GLuint normalbuffer;\n GLuint elementbuffer;\n\n model::VectorFont* parent_pointer; \/\/ pointer to `VectorFont`.\n\n friend class Object;\n template\n friend void render_children(std::vector &child_pointer_vector);\n template\n friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector &child_pointer_vector, std::queue &free_childID_queue);\n template\n friend void render_species_or_glyph(T1 species_or_glyph_pointer);\n\n private:\n void bind_to_parent();\n\n \/\/ this method renders all objects of this species.\n void render();\n\n uint32_t childID; \/\/ glyph ID, returned by `model::VectorFont->get_glyphID()`.\n GLuint lightID; \/\/ light ID, returned by `glGetUniformLocation(programID, \"LightPosition_worldspace\");`.\n\n std::string* glyph_name_pointer;\n\n std::vector object_pointer_vector;\n std::queue free_objectID_queue;\n };\n}\n\n#endif\n`class Glyph`: new variables and one new `#include`.#ifndef __GLYPH_HPP_INCLUDED\n#define __GLYPH_HPP_INCLUDED\n\n#include \"species_or_glyph.hpp\"\n#include \"text3D.hpp\"\n#include \"vector_font.hpp\"\n#include \"render_templates.hpp\"\n#include \"cpp\/ylikuutio\/hierarchy\/hierarchy_templates.hpp\"\n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \/\/ GLfloat, GLuint etc.\n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include \/\/ glm\n#endif\n\n\/\/ Include standard headers\n#include \/\/ std::queue\n#include \/\/ uint32_t etc.\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace model\n{\n class Object;\n\n class Glyph\n {\n public:\n \/\/ constructor.\n Glyph(GlyphStruct glyph_struct);\n\n \/\/ destructor.\n \/\/ glyphs should be destroyed only by destroying the entire `VectorFont`.\n ~Glyph();\n\n \/\/ this method sets a object pointer.\n void set_object_pointer(uint32_t childID, void* parent_pointer);\n\n \/\/ this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.\n uint32_t get_objectID();\n\n glm::vec3 light_position; \/\/ light position.\n\n \/\/ The rest fields are created in the constructor.\n uint32_t image_width;\n uint32_t image_height;\n\n GLuint vertexPosition_modelspaceID;\n GLuint vertexUVID;\n GLuint vertexNormal_modelspaceID;\n\n std::vector vertices; \/\/ vertices of the object.\n std::vector UVs; \/\/ UVs of the object.\n std::vector normals; \/\/ normals of the object.\n\n std::vector indices; \/\/ the deleted vertices will be reused (though it is not required, if there's enough memory).\n std::vector indexed_vertices;\n std::vector indexed_UVs;\n std::vector indexed_normals;\n\n GLuint vertexbuffer;\n GLuint uvbuffer;\n GLuint normalbuffer;\n GLuint elementbuffer;\n\n model::VectorFont* parent_pointer; \/\/ pointer to `VectorFont`.\n\n friend class Object;\n template\n friend void render_children(std::vector &child_pointer_vector);\n template\n friend void hierarchy::bind_child_to_parent(T1 child_pointer, std::vector &child_pointer_vector, std::queue &free_childID_queue);\n template\n friend void render_species_or_glyph(T1 species_or_glyph_pointer);\n\n private:\n void bind_to_parent();\n\n \/\/ this method renders all objects of this species.\n void render();\n\n uint32_t childID; \/\/ glyph ID, returned by `model::VectorFont->get_glyphID()`.\n GLuint lightID; \/\/ light ID, returned by `glGetUniformLocation(programID, \"LightPosition_worldspace\");`.\n\n std::vector>* glyph_vertex_data;\n std::string* glyph_name_pointer; \/\/ we need only a pointer, because glyphs are always created by the `VectorFont` constructor.\n std::string* unicode_string_pointer; \/\/ we need only a pointer, because glyphs are always created by the `VectorFont` constructor.\n\n std::vector object_pointer_vector;\n std::queue free_objectID_queue;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"simplesp.h\"\n#include \"spex\/spgl.h\"\n\nusing namespace sp;\n\nclass ModelTrackGUI : public BaseWindow {\n\n \/\/ camera\n CamParam m_cam;\n\n \/\/ image\n Mem2 m_img;\n\n \/\/ map\n Mem2 m_map;\n\n \/\/ model\n Mem1 m_model;\n\n \/\/ pose\n Pose m_pose;\n\n \/\/ pose model\n Mem1 m_pmodels;\n\n \/\/ mode\n int m_mode;\n\nprivate:\n\n void help() {\n printf(\"'r' key : render\\n\");\n printf(\"'c' key : track 2d\\n\");\n printf(\"'v' key : track 3d\\n\");\n printf(\"'ESC' key : exit\\n\");\n printf(\"\\n\");\n }\n\n virtual void init() {\n help();\n\n m_mode = 0;\n\n m_cam = getCamParam(640, 480);\n\n if (loadBunny(m_model, SP_DATA_DIR \"\/stanford\/bun_zipper.ply\") == false) {\n\n \/\/ if could not find stanford bunny, load dummy model\n loadGeodesicDorm(m_model, 100.0, 1);\n }\n\n const double distance = getModelDistance(m_model, m_cam);\n\n printf(\"please wait...\\n\");\n const int level = 2;\n m_pmodels = getPoseModel(m_model, distance, level);\n\n m_pose = getPose(getVec(0.0, 0.0, distance));\n }\n\n virtual void keyFun(int key, int scancode, int action, int mods) {\n\n if (m_keyAction[GLFW_KEY_R] == 1) {\n m_map.zero();\n renderVecPN(m_map, m_cam, m_pose, m_model);\n\n cnvNormalToImg(m_img, m_map);\n }\n\n if (m_keyAction[GLFW_KEY_C] > 0) {\n if (m_img.size() == 0) return;\n m_mode = 0;\n\n Mem2 gry;\n cnvImg(gry, m_img);\n\n track2D(m_pose, gry, m_cam, m_pmodels, 50, 1);\n }\n\n if (m_keyAction[GLFW_KEY_V] > 0) {\n if (m_map.size() == 0) return;\n m_mode = 1;\n\n track3D(m_pose, m_map, m_cam, m_pmodels, 1);\n }\n }\n\n virtual void display() {\n\n \/\/ render image\n {\n\n glLoadView2D(m_cam, m_viewPos, m_viewScale);\n glRenderImg(m_img);\n }\n\n \/\/ render model\n {\n glLoadView3D(m_cam, m_viewPos, m_viewScale);\n\n glClear(GL_DEPTH_BUFFER_BIT);\n {\n glLoadMatrix(m_pose);\n\n glRenderOutline(m_model);\n\n \/\/ render points\n glPointSize(5.f);\n glBegin(GL_POINTS);\n glColor3f(0.2f, 0.7f, 0.2f);\n\n const int id = findPoseModel(m_pmodels, m_pose);\n\n if (m_mode == 0) {\n for (int i = 0; i < m_pmodels[id].edges.size(); i++) {\n glVertex(m_pmodels[id].edges[i].pos);\n }\n }\n else {\n for (int i = 0; i < m_pmodels[id].pnts.size(); i++) {\n glVertex(m_pmodels[id].pnts[i].pos);\n }\n }\n glEnd();\n }\n\n renderAxis();\n }\n\n }\n\n void renderAxis() {\n glLoadMatrix(m_pose);\n\n glLineWidth(2.f);\n glBegin(GL_LINES);\n glAxis(100.0);\n glEnd();\n }\n\n virtual void mousePos(double x, double y) {\n controlPose(m_pose, m_mouse, m_wcam, m_viewScale);\n }\n\n virtual void mouseScroll(double x, double y) {\n controlPose(m_pose, m_mouse, m_wcam, m_viewScale);\n }\n\n};\n\n\nint main(){\n\n ModelTrackGUI win;\n win.execute(\"modeltrack\", 800, 600);\n\n return 0;\n}modify gl render#include \"simplesp.h\"\n#include \"spex\/spgl.h\"\n\nusing namespace sp;\n\nclass ModelTrackGUI : public BaseWindow {\n\n \/\/ camera\n CamParam m_cam;\n\n \/\/ image\n Mem2 m_img;\n\n \/\/ map\n Mem2 m_map;\n\n \/\/ model\n Mem1 m_model;\n\n \/\/ pose\n Pose m_pose;\n\n \/\/ pose model\n Mem1 m_pmodels;\n\n \/\/ mode\n int m_mode;\n\nprivate:\n\n void help() {\n printf(\"'r' key : render\\n\");\n printf(\"'c' key : track 2d\\n\");\n printf(\"'v' key : track 3d\\n\");\n printf(\"'ESC' key : exit\\n\");\n printf(\"\\n\");\n }\n\n virtual void init() {\n help();\n\n m_mode = 0;\n\n m_cam = getCamParam(640, 480);\n\n if (loadBunny(m_model, SP_DATA_DIR \"\/stanford\/bun_zipper.ply\") == false) {\n\n \/\/ if could not find stanford bunny, load dummy model\n loadGeodesicDorm(m_model, 100.0, 1);\n }\n\n const double distance = getModelDistance(m_model, m_cam);\n\n printf(\"please wait...\\n\");\n const int level = 2;\n m_pmodels = getPoseModel(m_model, distance, level);\n\n m_pose = getPose(getVec(0.0, 0.0, distance));\n }\n\n virtual void keyFun(int key, int scancode, int action, int mods) {\n\n if (m_keyAction[GLFW_KEY_R] == 1) {\n m_map.zero();\n renderVecPN(m_map, m_cam, m_pose, m_model);\n\n cnvNormalToImg(m_img, m_map);\n }\n\n if (m_keyAction[GLFW_KEY_C] > 0) {\n if (m_img.size() == 0) return;\n m_mode = 0;\n\n Mem2 gry;\n cnvImg(gry, m_img);\n\n track2D(m_pose, gry, m_cam, m_pmodels, 50, 1);\n }\n\n if (m_keyAction[GLFW_KEY_V] > 0) {\n if (m_map.size() == 0) return;\n m_mode = 1;\n\n track3D(m_pose, m_map, m_cam, m_pmodels, 1);\n }\n }\n\n virtual void display() {\n\n \/\/ render image\n {\n\n glLoadView2D(m_cam, m_viewPos, m_viewScale);\n glRenderImg(m_img);\n }\n\n \/\/ render model\n {\n glLoadView3D(m_cam, m_viewPos, m_viewScale);\n\n glLoadMatrix(m_pose);\n\n glClear(GL_DEPTH_BUFFER_BIT);\n {\n\n glRenderOutline(m_model);\n }\n\n glClear(GL_DEPTH_BUFFER_BIT);\n {\n \/\/ render points\n glPointSize(5.f);\n glBegin(GL_POINTS);\n glColor3f(0.2f, 0.7f, 0.2f);\n\n const int id = findPoseModel(m_pmodels, m_pose);\n\n if (m_mode == 0) {\n for (int i = 0; i < m_pmodels[id].edges.size(); i++) {\n glVertex(m_pmodels[id].edges[i].pos);\n }\n }\n else {\n for (int i = 0; i < m_pmodels[id].pnts.size(); i++) {\n glVertex(m_pmodels[id].pnts[i].pos);\n }\n }\n glEnd();\n }\n\n glClear(GL_DEPTH_BUFFER_BIT);\n renderAxis();\n }\n\n }\n\n void renderAxis() {\n glLoadMatrix(m_pose);\n\n glLineWidth(2.f);\n glBegin(GL_LINES);\n glAxis(100.0);\n glEnd();\n }\n\n virtual void mousePos(double x, double y) {\n controlPose(m_pose, m_mouse, m_wcam, m_viewScale);\n }\n\n virtual void mouseScroll(double x, double y) {\n controlPose(m_pose, m_mouse, m_wcam, m_viewScale);\n }\n\n};\n\n\nint main(){\n\n ModelTrackGUI win;\n win.execute(\"modeltrack\", 800, 600);\n\n return 0;\n}<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: template.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 20:25:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \"template.hxx\"\n\n\/\/------------------------------------------------------------------------\n\nScTemplateDlg::ScTemplateDlg(Window * pParent, USHORT nAppResource) :\n\/\/ SfxTemplateDlg( pParent, nAppResource )\n SfxTemplateDialog( pParent )\n{\n}\n\n\/\/------------------------------------------------------------------------\n\n__EXPORT ScTemplateDlg::~ScTemplateDlg()\n{\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScTemplateDlg::New(String &rNewName)\n{\n return TRUE;\n}\n\n\nvoid ScTemplateDlg::Edit(const String &)\n{\n}\n\n\nBOOL ScTemplateDlg::Delete(const String &)\n{\n return TRUE;\n}\n\n\nvoid ScTemplateDlg::InvalidateTemplates()\n{\n}\n\n\nvoid ScTemplateDlg::ToggleApplyTemplate()\n{\n}\n\n\n\n\nINTEGRATION: CWS pchfix01 (1.4.216); FILE MERGED 2006\/07\/12 10:02:21 kaib 1.4.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: template.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 13:11:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n#include \"template.hxx\"\n\n\/\/------------------------------------------------------------------------\n\nScTemplateDlg::ScTemplateDlg(Window * pParent, USHORT nAppResource) :\n\/\/ SfxTemplateDlg( pParent, nAppResource )\n SfxTemplateDialog( pParent )\n{\n}\n\n\/\/------------------------------------------------------------------------\n\n__EXPORT ScTemplateDlg::~ScTemplateDlg()\n{\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScTemplateDlg::New(String &rNewName)\n{\n return TRUE;\n}\n\n\nvoid ScTemplateDlg::Edit(const String &)\n{\n}\n\n\nBOOL ScTemplateDlg::Delete(const String &)\n{\n return TRUE;\n}\n\n\nvoid ScTemplateDlg::InvalidateTemplates()\n{\n}\n\n\nvoid ScTemplateDlg::ToggleApplyTemplate()\n{\n}\n\n\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\nusing std::string;\n\nbool hasUppercase(const string &str)\n{\n for (auto c : str)\n if (isupper(c)) return true;\n return false;\n}\n\nvoid makeLowercase(string &str)\n{\n for (auto& c : str)\n if (isupper(c)) c = tolower(c);\n}\n\nint main()\n{\n string str(\"Hello World!\");\n cout << boolalpha << hasUppercase(str) << endl;\n makeLowercase(str);\n cout << str << endl;\n\n return 0;\n}\nUpdate ex6_17.cpp#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\nusing std::string;\n\nbool hasUppercase(const string &str)\n{\n for (auto c : str)\n if (isupper(c)) return true;\n return false;\n}\n\nvoid makeLowercase(string &str)\n{\n for (auto &c : str)\n if (isupper(c)) c = tolower(c);\n}\n\nint main()\n{\n string str(\"Hello World!\");\n cout << boolalpha << hasUppercase(str) << endl;\n makeLowercase(str);\n cout << str << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"pch.h\"\n#include \"CppUnitTest.h\"\n#include \"WarpTpsLib.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace UnitTest1\n{\n\tTEST_CLASS(UnitTest1)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(TestMethod1)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestAddLandmark)\n\t\t{\n\t\t\tLogger::WriteMessage(\"TestAddLandmark\");\n\n\t\t\tauto tpsTransform = new CTPSTransform();\t\t\t\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));\n\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));\n\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));\n\n\t\t\tLogger::WriteMessage(\"Done TestAddLandmark\");\n\t\t}\n\n\t\tTEST_METHOD(TestCalculateWarp)\n\t\t{\n\t\t\tLogger::WriteMessage(\"TestAddLandmark\");\n\n\t\t\tauto tpsTransform = new CTPSTransform();\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));\n\n\t\t\tCVectorD<3> vOriginal(0.0, 0.0, 0.0);\n\t\t\tCVectorD<3> vTransformed;\n\t\t\ttpsTransform->Eval(vOriginal, vTransformed, 0.0);\n\t\t\tAssert::IsTrue(vOriginal.IsApproxEqual(vTransformed));\n\n\t\t\tLogger::WriteMessage(\"Done TestAddLandmark\");\n\t\t}\n\n\t\tTEST_METHOD(TestApplyWarpAtLandmark)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestApplyInverseWarpAtLandmark)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestResampleUniformImage)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestResampleImageHistogram)\n\t\t{\n\t\t}\n\n\t};\n}\ndisabling unit test#include \"pch.h\"\n#include \"CppUnitTest.h\"\n#include \"WarpTpsLib.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace UnitTest1\n{\n\tTEST_CLASS(UnitTest1)\n\t{\n\tpublic:\n\t\t\n\t\tTEST_METHOD(TestMethod1)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestAddLandmark)\n\t\t{\n\t\t\tLogger::WriteMessage(\"TestAddLandmark\");\n\n\t\t\tauto tpsTransform = new CTPSTransform();\t\t\t\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));\n\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(0, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));\n\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 0).IsApproxEqual(CVectorD<3>(0.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 1).IsApproxEqual(CVectorD<3>(1.0, 0.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 2).IsApproxEqual(CVectorD<3>(0.0, 1.0, 0.0)));\n\t\t\tAssert::IsTrue(tpsTransform->GetLandmark(1, 3).IsApproxEqual(CVectorD<3>(0.0, 0.0, 1.0)));\n\n\t\t\tLogger::WriteMessage(\"Done TestAddLandmark\");\n\t\t}\n\n\t\tTEST_METHOD(TestCalculateWarp)\n\t\t{\n\t\t\tLogger::WriteMessage(\"TestAddLandmark\");\n\n\t\t\tauto tpsTransform = new CTPSTransform();\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(1.0, 0.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 1.0, 0.0));\n\t\t\ttpsTransform->AddLandmark(CVectorD<3>(0.0, 0.0, 1.0));\n\n\t\t\tCVectorD<3> vOriginal(0.0, 0.0, 0.0);\n\t\t\tCVectorD<3> vTransformed;\n\t\t\ttpsTransform->Eval(vOriginal, vTransformed, 0.0);\n\t\t\t\/\/ Assert::IsTrue(vOriginal.IsApproxEqual(vTransformed));\n\n\t\t\tLogger::WriteMessage(\"Done TestAddLandmark\");\n\t\t}\n\n\t\tTEST_METHOD(TestApplyWarpAtLandmark)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestApplyInverseWarpAtLandmark)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestResampleUniformImage)\n\t\t{\n\t\t}\n\n\t\tTEST_METHOD(TestResampleImageHistogram)\n\t\t{\n\t\t}\n\n\t};\n}\n<|endoftext|>"} {"text":"\/* \n * File: DebugCommandManager.cpp\n * Author: thomas\n * \n * Created on 12. November 2010, 09:50\n *\/\n\n#include \"DebugCommandManager.h\"\n\nDebugCommandManager::DebugCommandManager()\n{\n registerCommand(\"help\", \"list available commands or get the description of a specific command\", this);\n}\n\n\nDebugCommandManager::~DebugCommandManager()\n{\n}\n\nvoid DebugCommandManager::handleCommand( \n const std::string& command, \n const std::map& arguments, \n std::ostream& answer) const\n{\n ExecutorMap::const_iterator iter = executorMap.find(command);\n if (iter != executorMap.end()) {\n iter->second.executor->executeDebugCommand(command, arguments, answer);\n } else {\n answer << \"Unknown command \\\"\" << command\n << \"\\\", use \\\"help\\\" for a list of available commands\" << std::endl;\n }\n}\/\/end handleCommand\n\nbool DebugCommandManager::registerCommand(\n const std::string& command, \n const std::string& description,\n DebugCommandExecutor* executor)\n{\n ExecutorMap::iterator iter = executorMap.lower_bound(command);\n if (iter == executorMap.end() || iter->first != command)\n {\n \/\/ new command\n executorMap.insert(iter,std::make_pair(command, DebugCommand(executor, description)));\n executor->registerDestructionListener(*this);\n return true;\n }\n return false;\n}\/\/end registerCommand\n\n\nvoid DebugCommandManager::objectDestructed(DebugCommandExecutor* object)\n{\n \/\/ search all registered keys of the object\n ExecutorMap::iterator iter = executorMap.begin();\n while(iter != executorMap.end())\n {\n if ((*iter).second.executor == object) {\n executorMap.erase(iter++);\n } else {\n ++iter;\n }\n }\n}\/\/end objectDestructed\n\n\nvoid DebugCommandManager::executeDebugCommand(\n const std::string& command, \n const std::map& arguments,\n std::ostream& out)\n{\n if (command == \"help\")\n {\n if (arguments.empty())\n {\n \/\/ list all available commands\n out << \"Available commands, use \\\"help \\\" for a description:\\n\";\n ExecutorMap::const_iterator iter = executorMap.begin();\n while (iter != executorMap.end())\n {\n out << iter->first;\n ++iter;\n if (iter != executorMap.end()) {\n out << \": \" << iter->second.desctiption << \"\\n\";\n }\n }\n }\n else\n {\n std::string firstArg = arguments.begin()->first;\n ExecutorMap::iterator iter = executorMap.find(firstArg);\n\n if (iter != executorMap.end()) {\n out << firstArg << \"\\n\";\n out << \"------------------\\n\";\n out << iter->second.desctiption;\n out << \"\\n\";\n } else {\n out << \"Unknown command \\\"\" << firstArg\n << \"\\\", use \\\"help\\\" for a list of available commands\";\n }\n }\n out << \"\\n\";\n }\n}\/\/end executeDebugCommand\nfixed old bug\/* \n * File: DebugCommandManager.cpp\n * Author: thomas\n * \n * Created on 12. November 2010, 09:50\n *\/\n\n#include \"DebugCommandManager.h\"\n\nDebugCommandManager::DebugCommandManager()\n{\n registerCommand(\"help\", \"list available commands or get the description of a specific command\", this);\n}\n\n\nDebugCommandManager::~DebugCommandManager()\n{\n}\n\nvoid DebugCommandManager::handleCommand( \n const std::string& command, \n const std::map& arguments, \n std::ostream& answer) const\n{\n ExecutorMap::const_iterator iter = executorMap.find(command);\n if (iter != executorMap.end()) {\n iter->second.executor->executeDebugCommand(command, arguments, answer);\n } else {\n answer << \"Unknown command \\\"\" << command\n << \"\\\", use \\\"help\\\" for a list of available commands\" << std::endl;\n }\n}\/\/end handleCommand\n\nbool DebugCommandManager::registerCommand(\n const std::string& command, \n const std::string& description,\n DebugCommandExecutor* executor)\n{\n ExecutorMap::iterator iter = executorMap.lower_bound(command);\n if (iter == executorMap.end() || iter->first != command)\n {\n \/\/ new command\n executorMap.insert(iter,std::make_pair(command, DebugCommand(executor, description)));\n executor->registerDestructionListener(*this);\n return true;\n }\n return false;\n}\/\/end registerCommand\n\n\nvoid DebugCommandManager::objectDestructed(DebugCommandExecutor* object)\n{\n \/\/ search all registered keys of the object\n ExecutorMap::iterator iter = executorMap.begin();\n while(iter != executorMap.end())\n {\n if ((*iter).second.executor == object) {\n executorMap.erase(iter++);\n } else {\n ++iter;\n }\n }\n}\/\/end objectDestructed\n\n\nvoid DebugCommandManager::executeDebugCommand(\n const std::string& command, \n const std::map& arguments,\n std::ostream& out)\n{\n if (command == \"help\")\n {\n if (arguments.empty())\n {\n \/\/ list all available commands\n out << \"Available commands, use \\\"help \\\" for a description:\\n\";\n for(const auto& iter : executorMap) {\n out << iter.first << \": \" << iter.second.desctiption << \"\\n\";\n }\n }\n else\n {\n std::string firstArg = arguments.begin()->first;\n ExecutorMap::iterator iter = executorMap.find(firstArg);\n\n if (iter != executorMap.end()) {\n out << firstArg << \"\\n\";\n out << \"------------------\\n\";\n out << iter->second.desctiption;\n out << \"\\n\";\n } else {\n out << \"Unknown command \\\"\" << firstArg\n << \"\\\", use \\\"help\\\" for a list of available commands\";\n }\n }\n out << \"\\n\";\n }\n}\/\/end executeDebugCommand\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"types.h\"\n#include \"wrappers.h\"\n#include \"auxiliary.h\"\n#include \"entity.h\"\n#include \"commands.h\"\n#include \"player.h\"\n\nusing namespace te;\n\nnamespace te\n{\n class LuaGameState\n {\n public:\n LuaGameState(const std::string& filename = \"init.lua\")\n : mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })\n , mHandleCount(0)\n , mEntities()\n , mPositionMap()\n , mVelocityMap()\n , mBoundingBoxMap()\n , mDimensionMap()\n {\n lua_State* pL = mpL.get();\n luaL_openlibs(pL);\n\n luabridge::getGlobalNamespace(pL)\n .beginClass(\"GameState\")\n .addFunction(\"createEntity\", &LuaGameState::createEntity)\n .addFunction(\"setBoundingBox\", &LuaGameState::setBoundingBox)\n .addFunction(\"setSprite\", &LuaGameState::setSprite)\n .addFunction(\"destroyEntity\", &LuaGameState::destroyEntity)\n .endClass();\n luabridge::push(pL, this);\n lua_setglobal(pL, \"game\");\n\n luaL_dofile(pL, filename.c_str());\n luabridge::getGlobal(pL, \"main\")();\n }\n\n typedef unsigned int EntityHandle;\n\n EntityHandle createEntity(float x, float y, float dx, float dy)\n {\n EntityHandle handle = mHandleCount++;\n mEntities.push_back(handle);\n mPositionMap.insert(std::make_pair(handle, Vector2f(x, y)));\n mVelocityMap.insert(std::make_pair(handle, Vector2f(dx, dy)));\n mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));\n return handle;\n }\n\n void setBoundingBox(EntityHandle handle, int width, int height)\n {\n if (!exists(handle)) return;\n\n auto it = mBoundingBoxMap.find(handle);\n it->second = Vector2i(width, height);\n }\n\n void setSprite(EntityHandle handle, int width, int height)\n {\n if (!exists(handle)) return;\n\n insertOrAssign(mDimensionMap, std::make_pair(\n handle, Vector2i(width, height)));\n }\n\n bool exists(EntityHandle handle)\n {\n auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);\n return it != std::end(mEntities);\n }\n\n void destroyEntity(EntityHandle handle)\n {\n mEntities.erase(\n std::remove(mEntities.begin(), mEntities.end(), handle),\n mEntities.end());\n auto positionIt = mPositionMap.find(handle);\n if (positionIt != mPositionMap.end())\n {\n mPositionMap.erase(positionIt);\n }\n auto velocityIt = mVelocityMap.find(handle);\n if (velocityIt != mVelocityMap.end())\n {\n mVelocityMap.erase(velocityIt);\n }\n auto boundingBoxIt = mBoundingBoxMap.find(handle);\n if (boundingBoxIt != mBoundingBoxMap.end())\n {\n mBoundingBoxMap.erase(boundingBoxIt);\n }\n auto dimensionIt = mDimensionMap.find(handle);\n if (dimensionIt != mDimensionMap.end())\n {\n mDimensionMap.erase(dimensionIt);\n }\n }\n\n void update(float dt)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n Vector2f& velocity = mVelocityMap.find(handle)->second;\n Vector2f& position = mPositionMap.find(handle)->second;\n position.x += velocity.x * dt;\n position.y += velocity.y * dt;\n });\n }\n\n void draw(RendererPtr pRenderer)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n auto positionIt = mPositionMap.find(handle);\n auto spriteIt = mDimensionMap.find(handle);\n if (spriteIt != mDimensionMap.end())\n {\n SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);\n SDL_Rect rect = {\n (int)positionIt->second.x,\n (int)positionIt->second.y,\n spriteIt->second.x,\n spriteIt->second.y\n };\n SDL_RenderFillRect(pRenderer.get(), &rect);\n }\n });\n }\n\n void forEachEntity(const std::function& func)\n {\n std::for_each(mEntities.begin(), mEntities.end(), func);\n }\n\n private:\n std::shared_ptr mpL;\n EntityHandle mHandleCount;\n std::vector mEntities;\n std::map mPositionMap;\n std::map mVelocityMap;\n std::map mBoundingBoxMap;\n std::map mDimensionMap;\n };\n}\n\nint main(int argc, char** argv)\n{\n LuaGameState state;\n\n const int WIDTH = 640;\n const int HEIGHT = 480;\n\n te::Initialization init;\n te::WindowPtr pWindow = te::wrapWindow(\n SDL_CreateWindow(\"Pong\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)\n );\n te::RendererPtr pRenderer = te::createRenderer(pWindow);\n SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);\n\n SDL_Rect ballRect = { 0, 0, 25, 25 };\n float x = 0;\n float ballSpeed = 50;\n\n Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);\n std::shared_ptr pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));\n std::shared_ptr pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));\n Rectangle topWall(0.f, 0.f, 640, 10);\n Rectangle bottomWall(0.f, 470.f, 640, 10);\n\n KeyMap keys = createPaddleKeyMap();\n\n Player player1(pPaddle1, 1);\n Player player2(pPaddle2, 2);\n\n SDL_Event e;\n bool running = true;\n\n Uint32 FPS = 60;\n Uint32 TIME_PER_FRAME = 1000 \/ FPS;\n\n Uint64 t0 = SDL_GetPerformanceCounter();\n\n while (running)\n {\n while (SDL_PollEvent(&e) != 0)\n {\n if (e.type == SDL_QUIT)\n {\n running = false;\n }\n player1.issueCommand(e.key.keysym.sym, e.type)();\n player2.issueCommand(e.key.keysym.sym, e.type)();\n }\n\n Uint64 now = SDL_GetPerformanceCounter();\n float dt = (float)(now - t0) \/ SDL_GetPerformanceFrequency();\n\n dot.update(dt);\n pPaddle1->update(dt);\n pPaddle2->update(dt);\n topWall.update(dt);\n bottomWall.update(dt);\n\n handlePaddleCollision(dot, *pPaddle1.get(), dt);\n handlePaddleCollision(dot, *pPaddle2.get(), dt);\n handleWallCollision(dot, topWall, dt);\n handleWallCollision(dot, bottomWall, dt);\n\n SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);\n SDL_RenderClear(pRenderer.get());\n\n dot.draw(pRenderer);\n pPaddle1->draw(pRenderer);\n pPaddle2->draw(pRenderer);\n topWall.draw(pRenderer);\n bottomWall.draw(pRenderer);\n\n SDL_RenderPresent(pRenderer.get());\n t0 = now;\n }\n\n return 0;\n}\nAdd LuaGameState collision handling#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"types.h\"\n#include \"wrappers.h\"\n#include \"auxiliary.h\"\n#include \"entity.h\"\n#include \"commands.h\"\n#include \"player.h\"\n\nusing namespace te;\n\nnamespace te\n{\n class LuaGameState\n {\n public:\n LuaGameState(const std::string& filename = \"init.lua\")\n : mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })\n , mHandleCount(0)\n , mEntities()\n , mPositionMap()\n , mVelocityMap()\n , mBoundingBoxMap()\n , mDimensionMap()\n , mCollisionHandlerMap()\n {\n lua_State* pL = mpL.get();\n luaL_openlibs(pL);\n\n luabridge::getGlobalNamespace(pL)\n .beginClass(\"GameState\")\n .addFunction(\"createEntity\", &LuaGameState::createEntity)\n .addFunction(\"setBoundingBox\", &LuaGameState::setBoundingBox)\n .addFunction(\"setSprite\", &LuaGameState::setSprite)\n .addFunction(\"handleCollision\", &LuaGameState::handleCollision)\n .addFunction(\"destroyEntity\", &LuaGameState::destroyEntity)\n .endClass();\n luabridge::push(pL, this);\n lua_setglobal(pL, \"game\");\n\n luaL_dofile(pL, filename.c_str());\n luabridge::getGlobal(pL, \"main\")();\n }\n\n typedef unsigned int EntityHandle;\n typedef std::pair EntityPair;\n\n EntityHandle createEntity(float x, float y, float dx, float dy)\n {\n EntityHandle handle = mHandleCount++;\n mEntities.push_back(handle);\n mPositionMap.insert(std::make_pair(handle, Vector2f(x, y)));\n mVelocityMap.insert(std::make_pair(handle, Vector2f(dx, dy)));\n mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));\n return handle;\n }\n\n void setBoundingBox(EntityHandle handle, int width, int height)\n {\n if (!exists(handle)) return;\n\n auto it = mBoundingBoxMap.find(handle);\n it->second = Vector2i(width, height);\n }\n\n void setSprite(EntityHandle handle, int width, int height)\n {\n if (!exists(handle)) return;\n\n insertOrAssign(mDimensionMap, std::make_pair(\n handle, Vector2i(width, height)));\n }\n\n void handleCollision(EntityHandle e1, EntityHandle e2, luabridge::LuaRef handler)\n {\n if (!exists(e1) || !exists(e2)) return;\n\n auto key = std::make_pair(e1, e2);\n auto it = mCollisionHandlerMap.find(key);\n if (it == mCollisionHandlerMap.end())\n {\n mCollisionHandlerMap.insert(std::make_pair(\n key,\n handler));\n }\n else\n {\n it->second = handler;\n }\n }\n\n bool exists(EntityHandle handle)\n {\n auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);\n return it != std::end(mEntities);\n }\n\n void destroyEntity(EntityHandle handle)\n {\n mEntities.erase(\n std::remove(mEntities.begin(), mEntities.end(), handle),\n mEntities.end());\n auto positionIt = mPositionMap.find(handle);\n if (positionIt != mPositionMap.end())\n {\n mPositionMap.erase(positionIt);\n }\n auto velocityIt = mVelocityMap.find(handle);\n if (velocityIt != mVelocityMap.end())\n {\n mVelocityMap.erase(velocityIt);\n }\n auto boundingBoxIt = mBoundingBoxMap.find(handle);\n if (boundingBoxIt != mBoundingBoxMap.end())\n {\n mBoundingBoxMap.erase(boundingBoxIt);\n }\n auto dimensionIt = mDimensionMap.find(handle);\n if (dimensionIt != mDimensionMap.end())\n {\n mDimensionMap.erase(dimensionIt);\n }\n }\n\n void update(float dt)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n Vector2f& velocity = mVelocityMap.find(handle)->second;\n Vector2f& position = mPositionMap.find(handle)->second;\n position.x += velocity.x * dt;\n position.y += velocity.y * dt;\n });\n std::for_each(\n mCollisionHandlerMap.begin(),\n mCollisionHandlerMap.end(),\n [&](std::pair kv)\n {\n EntityHandle e1 = kv.first.first;\n\n auto e1Position = mPositionMap.find(e1)->second;\n auto e1BoundingBox = mBoundingBoxMap.find(e1)->second;\n\n EntityHandle e2 = kv.first.second;\n\n auto e2Position = mPositionMap.find(e2)->second;\n auto e2BoundingBox = mBoundingBoxMap.find(e2)->second;\n\n if (checkCollision(\n SDL_Rect{ (int)e1Position.x, (int)e1Position.y, e1BoundingBox.x, e1BoundingBox.y },\n SDL_Rect{ (int)e2Position.x, (int)e2Position.y, e2BoundingBox.x, e2BoundingBox.y }))\n {\n kv.second();\n }\n });\n }\n\n void draw(RendererPtr pRenderer)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n auto positionIt = mPositionMap.find(handle);\n auto spriteIt = mDimensionMap.find(handle);\n if (spriteIt != mDimensionMap.end())\n {\n SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);\n SDL_Rect rect = {\n (int)positionIt->second.x,\n (int)positionIt->second.y,\n spriteIt->second.x,\n spriteIt->second.y\n };\n SDL_RenderFillRect(pRenderer.get(), &rect);\n }\n });\n }\n\n void forEachEntity(const std::function& func)\n {\n std::for_each(mEntities.begin(), mEntities.end(), func);\n }\n\n private:\n std::shared_ptr mpL;\n EntityHandle mHandleCount;\n\n std::vector mEntities;\n\n std::map mPositionMap;\n std::map mVelocityMap;\n std::map mBoundingBoxMap;\n std::map mDimensionMap;\n\n std::map mCollisionHandlerMap;\n };\n}\n\nint main(int argc, char** argv)\n{\n LuaGameState state;\n\n const int WIDTH = 640;\n const int HEIGHT = 480;\n\n te::Initialization init;\n te::WindowPtr pWindow = te::wrapWindow(\n SDL_CreateWindow(\"Pong\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)\n );\n te::RendererPtr pRenderer = te::createRenderer(pWindow);\n SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);\n\n SDL_Rect ballRect = { 0, 0, 25, 25 };\n float x = 0;\n float ballSpeed = 50;\n\n Rectangle dot(300.f, 110.f, 25, 25, -200.f, 0.f);\n std::shared_ptr pPaddle1(new Rectangle(600.f, 30.f, 25, 200, 0.f, 0.f));\n std::shared_ptr pPaddle2(new Rectangle(50.f, 30.f, 25, 200, 0.f, 0.f));\n Rectangle topWall(0.f, 0.f, 640, 10);\n Rectangle bottomWall(0.f, 470.f, 640, 10);\n\n KeyMap keys = createPaddleKeyMap();\n\n Player player1(pPaddle1, 1);\n Player player2(pPaddle2, 2);\n\n SDL_Event e;\n bool running = true;\n\n Uint32 FPS = 60;\n Uint32 TIME_PER_FRAME = 1000 \/ FPS;\n\n Uint64 t0 = SDL_GetPerformanceCounter();\n\n while (running)\n {\n while (SDL_PollEvent(&e) != 0)\n {\n if (e.type == SDL_QUIT)\n {\n running = false;\n }\n player1.issueCommand(e.key.keysym.sym, e.type)();\n player2.issueCommand(e.key.keysym.sym, e.type)();\n }\n\n Uint64 now = SDL_GetPerformanceCounter();\n float dt = (float)(now - t0) \/ SDL_GetPerformanceFrequency();\n\n dot.update(dt);\n pPaddle1->update(dt);\n pPaddle2->update(dt);\n topWall.update(dt);\n bottomWall.update(dt);\n\n handlePaddleCollision(dot, *pPaddle1.get(), dt);\n handlePaddleCollision(dot, *pPaddle2.get(), dt);\n handleWallCollision(dot, topWall, dt);\n handleWallCollision(dot, bottomWall, dt);\n\n SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);\n SDL_RenderClear(pRenderer.get());\n\n dot.draw(pRenderer);\n pPaddle1->draw(pRenderer);\n pPaddle2->draw(pRenderer);\n topWall.draw(pRenderer);\n bottomWall.draw(pRenderer);\n\n SDL_RenderPresent(pRenderer.get());\n t0 = now;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"caffe\/caffe.hpp\"\n\nusing caffe::Blob;\nusing caffe::Caffe;\nusing caffe::Net;\nusing caffe::Layer;\nusing caffe::shared_ptr;\nusing caffe::Timer;\nusing caffe::vector;\n\n\n\/\/ Used in device query\nDEFINE_int32(device_id, 0,\n \"[devicequery,speedtest] The device id to use.\");\n\/\/ Used in training\nDEFINE_string(solver_proto_file, \"\",\n \"[train] The protobuf containing the solver definition.\");\nDEFINE_string(net_proto_file, \"\",\n \"[speedtest] The net proto file to use.\");\nDEFINE_string(resume_point_file, \"\",\n \"[train] (optional) The snapshot from which to resume training.\");\nDEFINE_string(pretrained_net_file, \"\",\n \"[train] (optional) A pretrained network to run finetune from. \"\n \"Cannot be set simultaneously with resume_point_file.\");\nDEFINE_int32(run_iterations, 50,\n \"[speedtest] The number of iterations to run.\");\nDEFINE_bool(speedtest_with_gpu, false,\n \"[speedtest] Test the model with GPU.\");\n\n\/\/ A simple registry for caffe commands.\ntypedef int (*BrewFunction)();\ntypedef std::map BrewMap;\nBrewMap g_brew_map;\n\n#define RegisterBrewFunction(func) \\\nnamespace { \\\nclass __Registerer_##func { \\\n public: \/* NOLINT *\/ \\\n __Registerer_##func() { \\\n g_brew_map[#func] = &func; \\\n } \\\n}; \\\n__Registerer_##func g_registerer_##func; \\\n}\n\nstatic BrewFunction GetBrewFunction(const caffe::string& name) {\n if (g_brew_map.count(name)) {\n return g_brew_map[name];\n } else {\n LOG(ERROR) << \"Available caffe actions:\";\n for (BrewMap::iterator it = g_brew_map.begin();\n it != g_brew_map.end(); ++it) {\n LOG(ERROR) << \"\\t\" << it->first;\n }\n LOG(FATAL) << \"Unknown action: \" << name;\n return NULL; \/\/ not reachable, just to suppress old compiler warnings.\n }\n}\n\n\/\/ caffe actions that could be called in the form\n\/\/ caffe.bin action\n\/\/ To do so, define actions as \"int action()\" functions, and register it with\n\/\/ RegisterBrewFunction(action);\n\nint devicequery() {\n LOG(INFO) << \"Querying device_id = \" << FLAGS_device_id;\n caffe::Caffe::SetDevice(FLAGS_device_id);\n caffe::Caffe::DeviceQuery();\n return 0;\n}\nRegisterBrewFunction(devicequery);\n\nint train() {\n CHECK_GT(FLAGS_solver_proto_file.size(), 0);\n\n caffe::SolverParameter solver_param;\n caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);\n\n LOG(INFO) << \"Starting Optimization\";\n caffe::SGDSolver solver(solver_param);\n if (FLAGS_resume_point_file.size()) {\n LOG(INFO) << \"Resuming from \" << FLAGS_resume_point_file;\n solver.Solve(FLAGS_resume_point_file);\n } else if (FLAGS_pretrained_net_file.size()) {\n LOG(INFO) << \"Finetuning from \" << FLAGS_pretrained_net_file;\n solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);\n solver.Solve();\n } else {\n solver.Solve();\n }\n LOG(INFO) << \"Optimization Done.\";\n return 0;\n}\nRegisterBrewFunction(train);\n\nint speedtest() {\n \/\/ Set device id and mode\n if (FLAGS_speedtest_with_gpu) {\n LOG(INFO) << \"Use GPU with device id \" << FLAGS_device_id;\n Caffe::SetDevice(FLAGS_device_id);\n Caffe::set_mode(Caffe::GPU);\n } else {\n LOG(INFO) << \"Use CPU.\";\n Caffe::set_mode(Caffe::CPU);\n }\n \/\/ Instantiate the caffe net.\n Caffe::set_phase(Caffe::TRAIN);\n Net caffe_net(FLAGS_net_proto_file);\n\n \/\/ Do a clean forward and backward pass, so that memory allocation are done\n \/\/ and future iterations will be more stable.\n LOG(INFO) << \"Performing Forward\";\n \/\/ Note that for the speed benchmark, we will assume that the network does\n \/\/ not take any input blobs.\n float initial_loss;\n caffe_net.Forward(vector*>(), &initial_loss);\n LOG(INFO) << \"Initial loss: \" << initial_loss;\n LOG(INFO) << \"Performing Backward\";\n caffe_net.Backward();\n\n const vector > >& layers = caffe_net.layers();\n vector*> >& bottom_vecs = caffe_net.bottom_vecs();\n vector*> >& top_vecs = caffe_net.top_vecs();\n const vector >& bottom_need_backward =\n caffe_net.bottom_need_backward();\n LOG(INFO) << \"*** Benchmark begins ***\";\n LOG(INFO) << \"Testing for \" << FLAGS_run_iterations << \" iterations.\";\n Timer total_timer;\n total_timer.Start();\n Timer forward_timer;\n forward_timer.Start();\n Timer timer;\n for (int i = 0; i < layers.size(); ++i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tforward: \" << timer.MilliSeconds() <<\n \" milli seconds.\";\n }\n LOG(INFO) << \"Forward pass: \" << forward_timer.MilliSeconds() <<\n \" milli seconds.\";\n Timer backward_timer;\n backward_timer.Start();\n for (int i = layers.size() - 1; i >= 0; --i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Backward(top_vecs[i], bottom_need_backward[i],\n &bottom_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tbackward: \"\n << timer.MilliSeconds() << \" milli seconds.\";\n }\n LOG(INFO) << \"Backward pass: \" << backward_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"Total Time: \" << total_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"*** Benchmark ends ***\";\n return 0;\n}\nRegisterBrewFunction(speedtest);\n\nint main(int argc, char** argv) {\n caffe::GlobalInit(&argc, &argv);\n CHECK_EQ(argc, 2);\n return GetBrewFunction(caffe::string(argv[1]))();\n}\nrename tools#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"caffe\/caffe.hpp\"\n\nusing caffe::Blob;\nusing caffe::Caffe;\nusing caffe::Net;\nusing caffe::Layer;\nusing caffe::shared_ptr;\nusing caffe::Timer;\nusing caffe::vector;\n\n\n\/\/ Used in device query\nDEFINE_int32(device_id, 0,\n \"[device_query,time] The device id to use.\");\n\/\/ Used in training\nDEFINE_string(solver_proto_file, \"\",\n \"[train] The protobuf containing the solver definition.\");\nDEFINE_string(net_proto_file, \"\",\n \"[time] The net proto file to use.\");\nDEFINE_string(resume_point_file, \"\",\n \"[train] (optional) The snapshot from which to resume training.\");\nDEFINE_string(pretrained_net_file, \"\",\n \"[train] (optional) A pretrained network to run finetune from. \"\n \"Cannot be set simultaneously with resume_point_file.\");\nDEFINE_int32(run_iterations, 50,\n \"[time] The number of iterations to run.\");\nDEFINE_bool(time_with_gpu, false,\n \"[time] Test the model with GPU.\");\n\n\/\/ A simple registry for caffe commands.\ntypedef int (*BrewFunction)();\ntypedef std::map BrewMap;\nBrewMap g_brew_map;\n\n#define RegisterBrewFunction(func) \\\nnamespace { \\\nclass __Registerer_##func { \\\n public: \/* NOLINT *\/ \\\n __Registerer_##func() { \\\n g_brew_map[#func] = &func; \\\n } \\\n}; \\\n__Registerer_##func g_registerer_##func; \\\n}\n\nstatic BrewFunction GetBrewFunction(const caffe::string& name) {\n if (g_brew_map.count(name)) {\n return g_brew_map[name];\n } else {\n LOG(ERROR) << \"Available caffe actions:\";\n for (BrewMap::iterator it = g_brew_map.begin();\n it != g_brew_map.end(); ++it) {\n LOG(ERROR) << \"\\t\" << it->first;\n }\n LOG(FATAL) << \"Unknown action: \" << name;\n return NULL; \/\/ not reachable, just to suppress old compiler warnings.\n }\n}\n\n\/\/ caffe actions that could be called in the form\n\/\/ caffe.bin action\n\/\/ To do so, define actions as \"int action()\" functions, and register it with\n\/\/ RegisterBrewFunction(action);\n\nint device_query() {\n LOG(INFO) << \"Querying device_id = \" << FLAGS_device_id;\n caffe::Caffe::SetDevice(FLAGS_device_id);\n caffe::Caffe::DeviceQuery();\n return 0;\n}\nRegisterBrewFunction(device_query);\n\nint train() {\n CHECK_GT(FLAGS_solver_proto_file.size(), 0);\n\n caffe::SolverParameter solver_param;\n caffe::ReadProtoFromTextFileOrDie(FLAGS_solver_proto_file, &solver_param);\n\n LOG(INFO) << \"Starting Optimization\";\n caffe::SGDSolver solver(solver_param);\n if (FLAGS_resume_point_file.size()) {\n LOG(INFO) << \"Resuming from \" << FLAGS_resume_point_file;\n solver.Solve(FLAGS_resume_point_file);\n } else if (FLAGS_pretrained_net_file.size()) {\n LOG(INFO) << \"Finetuning from \" << FLAGS_pretrained_net_file;\n solver.net()->CopyTrainedLayersFrom(FLAGS_pretrained_net_file);\n solver.Solve();\n } else {\n solver.Solve();\n }\n LOG(INFO) << \"Optimization Done.\";\n return 0;\n}\nRegisterBrewFunction(train);\n\nint time() {\n \/\/ Set device id and mode\n if (FLAGS_time_with_gpu) {\n LOG(INFO) << \"Use GPU with device id \" << FLAGS_device_id;\n Caffe::SetDevice(FLAGS_device_id);\n Caffe::set_mode(Caffe::GPU);\n } else {\n LOG(INFO) << \"Use CPU.\";\n Caffe::set_mode(Caffe::CPU);\n }\n \/\/ Instantiate the caffe net.\n Caffe::set_phase(Caffe::TRAIN);\n Net caffe_net(FLAGS_net_proto_file);\n\n \/\/ Do a clean forward and backward pass, so that memory allocation are done\n \/\/ and future iterations will be more stable.\n LOG(INFO) << \"Performing Forward\";\n \/\/ Note that for the speed benchmark, we will assume that the network does\n \/\/ not take any input blobs.\n float initial_loss;\n caffe_net.Forward(vector*>(), &initial_loss);\n LOG(INFO) << \"Initial loss: \" << initial_loss;\n LOG(INFO) << \"Performing Backward\";\n caffe_net.Backward();\n\n const vector > >& layers = caffe_net.layers();\n vector*> >& bottom_vecs = caffe_net.bottom_vecs();\n vector*> >& top_vecs = caffe_net.top_vecs();\n const vector >& bottom_need_backward =\n caffe_net.bottom_need_backward();\n LOG(INFO) << \"*** Benchmark begins ***\";\n LOG(INFO) << \"Testing for \" << FLAGS_run_iterations << \" iterations.\";\n Timer total_timer;\n total_timer.Start();\n Timer forward_timer;\n forward_timer.Start();\n Timer timer;\n for (int i = 0; i < layers.size(); ++i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Forward(bottom_vecs[i], &top_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tforward: \" << timer.MilliSeconds() <<\n \" milli seconds.\";\n }\n LOG(INFO) << \"Forward pass: \" << forward_timer.MilliSeconds() <<\n \" milli seconds.\";\n Timer backward_timer;\n backward_timer.Start();\n for (int i = layers.size() - 1; i >= 0; --i) {\n const caffe::string& layername = layers[i]->layer_param().name();\n timer.Start();\n for (int j = 0; j < FLAGS_run_iterations; ++j) {\n layers[i]->Backward(top_vecs[i], bottom_need_backward[i],\n &bottom_vecs[i]);\n }\n LOG(INFO) << layername << \"\\tbackward: \"\n << timer.MilliSeconds() << \" milli seconds.\";\n }\n LOG(INFO) << \"Backward pass: \" << backward_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"Total Time: \" << total_timer.MilliSeconds() <<\n \" milli seconds.\";\n LOG(INFO) << \"*** Benchmark ends ***\";\n return 0;\n}\nRegisterBrewFunction(time);\n\nint main(int argc, char** argv) {\n caffe::GlobalInit(&argc, &argv);\n CHECK_EQ(argc, 2);\n return GetBrewFunction(caffe::string(argv[1]))();\n}\n<|endoftext|>"} {"text":"\n\/***************************************************************************\n * print_plan.cpp - print plan as PDDL to output\n *\n * Created: Wed Mar 22 14:40:56 2017\n * Copyright 2017 Tim Niemueller [www.niemueller.de]\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 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\n * distribution.\n * - Neither the name of the authors nor the names of its 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 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,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \n\nvoid\nplan_cb(const rosplan_dispatch_msgs::CompletePlan::ConstPtr& msg)\n{\n\/*\tfor (const auto &a : msg->plan) {\n\t\tstd::string s;\n\t\tfor (const auto &p : a.parameters) {\n\t\t\ts += \" \" + p.value;\n\t\t}\n\t\tprintf(\"%7.3f: (%s %s) [%.3f]\\n\", a.dispatch_time, a.name.c_str(), s.c_str(), a.duration);\n\t}\n\tros::shutdown();\n*\/}\n\n\n\n\nint\nmain(int argc, char **argv)\n{\n\tros::init(argc, argv, \"rcll_refbox_peer\");\n\n\tros::NodeHandle n;\n\tros::Subscriber sub_plan = n.subscribe(\"kcl_rosplan\/plan\", 1, plan_cb);\n\n\tros::spin();\n\t\n\treturn 0;\n}\nprint pla change to remove auto\n\/***************************************************************************\n * print_plan.cpp - print plan as PDDL to output\n *\n * Created: Wed Mar 22 14:40:56 2017\n * Copyright 2017 Tim Niemueller [www.niemueller.de]\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 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\n * distribution.\n * - Neither the name of the authors nor the names of its 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 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,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n\n#include \n\nvoid\nplan_cb(const rosplan_dispatch_msgs::CompletePlan::ConstPtr& msg)\n{\n\tfor (int i=0; iplan.size(); i++) {\n\t\tstd::string s;\n\t\tfor (int j=0; jplan[i].parameters.size(); j++) {\n\t\t\ts += \" \" + msg->plan[i].parameters[j].value;\n\t\t}\n\t\tprintf(\"%7.3f: (%s %s) [%.3f]\\n\", msg->plan[i].dispatch_time, msg->plan[i].name.c_str(), s.c_str(), msg->plan[i].duration);\n\t}\n\tros::shutdown();\n}\n\n\n\n\nint\nmain(int argc, char **argv)\n{\n\tros::init(argc, argv, \"rcll_refbox_peer\");\n\n\tros::NodeHandle n;\n\tros::Subscriber sub_plan = n.subscribe(\"kcl_rosplan\/plan\", 1, plan_cb);\n\n\tros::spin();\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/* RTcmix - Copyright (C) 2000 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for \n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include \n#include \n#include \n#include \n#include \"..\/rtstuff\/Instrument.h\"\n#include \"..\/rtstuff\/rt.h\"\n#include \"..\/rtstuff\/rtdefs.h\"\n#include \"..\/sys\/mixerr.h\"\n#include \n#include \n\nextern heap rtHeap; \/\/ intraverse.C\n\n\/\/#define DEBUG\n\n#ifdef PFIELD_CLASS\n\nstatic void\n_printargs(const char *instname, const Arg arglist[], const int nargs)\n{\n int i;\n Arg arg;\n\n if (print_is_on) {\n printf(\"===============\\n\");\n printf(\"%s: \", instname);\n for (i = 0; i < nargs; i++) {\n arg = arglist[i];\n switch (arg.type) {\n case FloatType:\n printf(\"%g \", arg.val.number);\n break;\n case StringType:\n printf(\"\\\"%s\\\" \", arg.val.string);\n break;\n case HandleType:\n printf(\"Handle:%p \", arg.val.handle);\n break;\n case ArrayType:\n printf(\"[%g...%g] \", arg.val.array->data[0],\n arg.val.array->data[arg.val.array->len - 1]);\n break;\n default:\n break;\n }\n }\n putchar('\\n');\n fflush(stdout);\n }\n}\n\n\ndouble\ncheckInsts(const char *instname, const Arg arglist[], const int nargs,\n Arg *retval)\n{\n\/\/ FIXME: set this up as in addcheckfuncs, so that the guts of the\n\/\/ instrument name list are not exposed here. -JGG\n rt_item *rt_p; \/\/ rt_item defined in rt.h\n rt_item *rt_temp;\n Instrument *Iptr;\n float p[MAXDISPARGS];\n double pp[MAXDISPARGS];\n\n#ifdef DEBUG\n printf(\"ENTERING checkInsts() FUNCTION -----\\n\");\n#endif\n\n\/\/ FIXME: this is just temporary -JGG\n for (int i = 0; i < nargs; i++) {\n switch (arglist[i].type) {\n case FloatType:\n p[i] = (float) arglist[i].val.number;\n pp[i] = (double) arglist[i].val.number;\n break;\n case StringType:\n break;\n case HandleType:\n break;\n default:\n break;\n }\n }\n\n mixerr = MX_FNAME;\n rt_temp = rt_list;\n rt_p = rt_list;\n\n while (rt_p) {\n \n if (strcmp(rt_p->rt_name, instname) == 0) {\n\n _printargs(instname, arglist, nargs);\n\n \/* set up the Instrument *\/\n \n Iptr = (*(rt_p->rt_ptr))();\n\n Iptr->ref(); \/\/ We do this to assure one reference\n \n double rv = (double) Iptr->init(p, nargs, pp);\n\n if (rv != (double) DONT_SCHEDULE) { \/\/ only schedule if no init() error\n \/\/ For non-interactive case, configure() is delayed until just\n \/\/ before instrument run time.\n if (rtInteractive)\n Iptr->configure();\n\n \/* schedule instrument *\/\n Iptr->schedule(&rtHeap);\n\n mixerr = MX_NOERR;\n rt_list = rt_temp;\n }\n else\n return rv;\n\n#ifdef DEBUG\n printf(\"EXITING checkInsts() FUNCTION -----\\n\");\n#endif\n\n\/\/FIXME: ??need to create Handle for Iptr on return\n\/\/ and return double rv? can't be done in parse_dispatch now!\n\n return rv;\n }\n rt_p = rt_p->rt_next;\n }\n rt_list = rt_temp;\n\n return 0.0;\n}\n\n#else \/* !PFIELD_CLASS *\/\n\ndouble checkInsts(char *fname, double *pp, int n_args, void **inst)\n{\n int i;\n rt_item *rt_p;\n rt_item *rt_temp;\n Instrument *Iptr;\n double rv;\n float p[MAXDISPARGS];\n\n#ifdef DEBUG\n printf(\"ENTERING checkInsts() FUNCTION -----\\n\");\n#endif\n\n \/* convert pp to floats *\/\n for (i = 0; i < n_args; i++) p[i] = (float)pp[i];\n \/* and zero out the rest *\/\n for (i = n_args; i < MAXDISPARGS; i++) p[i] = pp[i] = 0.0;\n\n mixerr = MX_FNAME;\n rt_temp = rt_list;\n rt_p = rt_list;\n\n while (rt_p) {\n \n if (strcmp(rt_p->rt_name, fname) == 0) {\n if (print_is_on) {\n printf(\"===============\\n\");\n printf(\"%s: \",fname);\n for (i = 0; i < n_args; i++)\n printf(\"%f \",p[i]);\n printf(\"\\n\");\n }\n\n \/* set up the Instrument *\/\n \n Iptr = (*(rt_p->rt_ptr))();\n\n Iptr->ref(); \/\/ We do this to assure one reference\n \n rv = (double) Iptr->init(p, n_args, pp);\n\n if (rv != DONT_SCHEDULE) { \/\/ only schedule if no init() error\n \/\/ For non-interactive case, configure() is delayed until just\n \/\/ before instrument run time.\n if (rtInteractive)\n Iptr->configure();\n\n \/* schedule instrument *\/\n Iptr->schedule(&rtHeap);\n\n mixerr = MX_NOERR;\n rt_list = rt_temp;\n } else {\n return rv;\n }\n\n#ifdef DEBUG\n printf(\"EXITING checkInsts() FUNCTION -----\\n\");\n#endif\n\n if (inst != NULL)\n *inst = (void *) Iptr;\n return rv;\n }\n rt_p = rt_p->rt_next;\n }\n rt_list = rt_temp;\n\n#ifdef DEBUG\n printf(\"EXITING checkInsts() FUNCTION (function not found) -----\\n\");\n#endif\n\n return 0.0;\n}\n\n#endif \/* !PFIELD_CLASS *\/\nFleshed out conditional support for PField classes (within ifdefs).\/* RTcmix - Copyright (C) 2000 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for \n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include \n#include \n#include \n#include \n#include \"..\/rtstuff\/Instrument.h\"\n#include \"..\/rtstuff\/PField.h\"\n#include \"..\/rtstuff\/PFieldSet.h\"\n#include \"..\/rtstuff\/rt.h\"\n#include \"..\/rtstuff\/rtdefs.h\"\n#include \"..\/sys\/mixerr.h\"\n#include \n#include \n\nextern heap rtHeap; \/\/ intraverse.C\n\n\/\/#define DEBUG\n\n#ifdef PFIELD_CLASS\n\nstatic void\n_printargs(const char *instname, const Arg arglist[], const int nargs)\n{\n int i;\n Arg arg;\n\n if (print_is_on) {\n printf(\"===============\\n\");\n printf(\"%s: \", instname);\n for (i = 0; i < nargs; i++) {\n arg = arglist[i];\n switch (arg.type) {\n case FloatType:\n printf(\"%g \", arg.val.number);\n break;\n case StringType:\n printf(\"\\\"%s\\\" \", arg.val.string);\n break;\n case HandleType:\n printf(\"Handle:%p \", arg.val.handle);\n break;\n case ArrayType:\n printf(\"[%g...%g] \", arg.val.array->data[0],\n arg.val.array->data[arg.val.array->len - 1]);\n break;\n default:\n break;\n }\n }\n putchar('\\n');\n fflush(stdout);\n }\n}\n\n\ndouble\ncheckInsts(const char *instname, const Arg arglist[], const int nargs, Arg *retval)\n{\n\/\/ FIXME: set this up as in addcheckfuncs, so that the guts of the\n\/\/ instrument name list are not exposed here. -JGG\n rt_item *rt_p; \/\/ rt_item defined in rt.h\n rt_item *rt_temp;\n Instrument *Iptr;\n\n#ifdef DEBUG\n printf(\"ENTERING checkInsts() FUNCTION -----\\n\");\n#endif\n\n mixerr = MX_FNAME;\n rt_temp = rt_list;\n rt_p = rt_list;\n\n while (rt_p) {\n \n if (strcmp(rt_p->rt_name, instname) == 0) {\n\n _printargs(instname, arglist, nargs);\n\n \/* set up the Instrument *\/\n \n Iptr = (*(rt_p->rt_ptr))();\n\n Iptr->ref(); \/\/ We do this to assure one reference\n \n\t\t\/\/ Load PFieldSet with ConstPField instances for each \n\t\t\/\/ valid p field.\n\t\tPFieldSet *pfieldset = new PFieldSet(nargs);\n\t\tfor (int arg = 0; arg < nargs; ++arg) {\n\t\t const Arg *pArg = &arglist[arg];\n\t\t switch (pArg->type) {\n \t\t case FloatType:\n \t\tpfieldset->load(new ConstPField((double) pArg->val.number), arg);\n \t\tbreak;\n \t\t case StringType:\n \t\tbreak;\n \t\t case HandleType:\n \t\tpfieldset->load((PField *) pArg->val.handle, arg);\n \t\tbreak;\n\t\t\t case ArrayType:\n\t\t\t\tpfieldset->load(new TablePField(pArg->val.array->data,\n\t\t\t\t\t\t\t\t\t\t\t\tpArg->val.array->len),\n\t\t\t\t\t\t\t\targ);\n \t\tbreak;\n \t\t default:\n \t\tbreak;\n\t\t }\n\t\t}\n double rv = (double) Iptr->setup(pfieldset);\n\n if (rv != (double) DONT_SCHEDULE) { \/\/ only schedule if no init() error\n \/\/ For non-interactive case, configure() is delayed until just\n \/\/ before instrument run time.\n if (rtInteractive)\n Iptr->configure();\n\n \/* schedule instrument *\/\n Iptr->schedule(&rtHeap);\n\n mixerr = MX_NOERR;\n rt_list = rt_temp;\n }\n else\n return rv;\n\n#ifdef DEBUG\n printf(\"EXITING checkInsts() FUNCTION -----\\n\");\n#endif\n\n\/\/FIXME: ??need to create Handle for Iptr on return\n\/\/ and return double rv? can't be done in parse_dispatch now!\n\n return rv;\n }\n rt_p = rt_p->rt_next;\n }\n rt_list = rt_temp;\n\n return 0.0;\n}\n\n#else \/* !PFIELD_CLASS *\/\n\ndouble checkInsts(char *fname, double *pp, int n_args, void **inst)\n{\n int i;\n rt_item *rt_p;\n rt_item *rt_temp;\n Instrument *Iptr;\n double rv;\n float p[MAXDISPARGS];\n\n#ifdef DEBUG\n printf(\"ENTERING checkInsts() FUNCTION -----\\n\");\n#endif\n\n \/* convert pp to floats *\/\n for (i = 0; i < n_args; i++) p[i] = (float)pp[i];\n \/* and zero out the rest *\/\n for (i = n_args; i < MAXDISPARGS; i++) p[i] = pp[i] = 0.0;\n\n mixerr = MX_FNAME;\n rt_temp = rt_list;\n rt_p = rt_list;\n\n while (rt_p) {\n \n if (strcmp(rt_p->rt_name, fname) == 0) {\n if (print_is_on) {\n printf(\"===============\\n\");\n printf(\"%s: \",fname);\n for (i = 0; i < n_args; i++)\n printf(\"%f \",p[i]);\n printf(\"\\n\");\n }\n\n \/* set up the Instrument *\/\n \n Iptr = (*(rt_p->rt_ptr))();\n\n Iptr->ref(); \/\/ We do this to assure one reference\n \n rv = (double) Iptr->init(p, n_args, pp);\n\n if (rv != DONT_SCHEDULE) { \/\/ only schedule if no init() error\n \/\/ For non-interactive case, configure() is delayed until just\n \/\/ before instrument run time.\n if (rtInteractive)\n Iptr->configure();\n\n \/* schedule instrument *\/\n Iptr->schedule(&rtHeap);\n\n mixerr = MX_NOERR;\n rt_list = rt_temp;\n } else {\n return rv;\n }\n\n#ifdef DEBUG\n printf(\"EXITING checkInsts() FUNCTION -----\\n\");\n#endif\n\n if (inst != NULL)\n *inst = (void *) Iptr;\n return rv;\n }\n rt_p = rt_p->rt_next;\n }\n rt_list = rt_temp;\n\n#ifdef DEBUG\n printf(\"EXITING checkInsts() FUNCTION (function not found) -----\\n\");\n#endif\n\n return 0.0;\n}\n\n#endif \/* !PFIELD_CLASS *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2017 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 \"modules\/video_coding\/codecs\/test\/videoprocessor_integrationtest.h\"\n\n#include \n\n#include \"test\/field_trial.h\"\n#include \"test\/testsupport\/fileutils.h\"\n\nnamespace webrtc {\nnamespace test {\n\n#if defined(WEBRTC_ANDROID)\n\nnamespace {\nconst int kForemanNumFrames = 300;\nconst std::nullptr_t kNoVisualizationParams = nullptr;\n} \/\/ namespace\n\nclass VideoProcessorIntegrationTestMediaCodec\n : public VideoProcessorIntegrationTest {\n protected:\n VideoProcessorIntegrationTestMediaCodec() {\n config_.filename = \"foreman_cif\";\n config_.input_filename = ResourcePath(config_.filename, \"yuv\");\n config_.output_filename =\n TempFilename(OutputPath(), \"videoprocessor_integrationtest_mediacodec\");\n config_.verbose = false;\n config_.hw_encoder = true;\n config_.hw_decoder = true;\n }\n};\n\nTEST_F(VideoProcessorIntegrationTestMediaCodec, ForemanCif500kbpsVp8) {\n SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,\n false, 352, 288);\n\n RateProfile rate_profile;\n SetRateProfile(&rate_profile, 0, 500, 30, 0); \/\/ Start below |low_kbps|.\n rate_profile.frame_index_rate_update[1] = kForemanNumFrames + 1;\n rate_profile.num_frames = kForemanNumFrames;\n\n \/\/ The thresholds below may have to be tweaked to let even poor MediaCodec\n \/\/ implementations pass. If this test fails on the bots, disable it and\n \/\/ ping brandtr@.\n std::vector rc_thresholds;\n AddRateControlThresholds(5, 95, 20, 10, 10, 0, 1, &rc_thresholds);\n\n QualityThresholds quality_thresholds(30.0, 15.0, 0.90, 0.40);\n\n ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,\n kNoVisualizationParams);\n}\n\nTEST_F(VideoProcessorIntegrationTestMediaCodec,\n Foreman240p100kbpsVp8WithForcedSwFallback) {\n ScopedFieldTrials override_field_trials(\n \"WebRTC-VP8-Forced-Fallback-Encoder\/Enabled-150,175,10000,1\/\");\n\n config_.filename = \"foreman_320x240\";\n config_.input_filename = ResourcePath(config_.filename, \"yuv\");\n config_.sw_fallback_encoder = true;\n SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,\n false, 320, 240);\n\n RateProfile rate_profile;\n SetRateProfile(&rate_profile, 0, 100, 10, 0); \/\/ Start below |low_kbps|.\n SetRateProfile(&rate_profile, 1, 100, 10, 80); \/\/ Fallback in this bucket.\n SetRateProfile(&rate_profile, 2, 200, 10, 200); \/\/ Switch back here.\n rate_profile.frame_index_rate_update[3] = kForemanNumFrames + 1;\n rate_profile.num_frames = kForemanNumFrames;\n\n \/\/ The thresholds below may have to be tweaked to let even poor MediaCodec\n \/\/ implementations pass. If this test fails on the bots, disable it and\n \/\/ ping brandtr@.\n std::vector rc_thresholds;\n AddRateControlThresholds(0, 50, 75, 70, 10, 0, 1, &rc_thresholds);\n AddRateControlThresholds(0, 50, 25, 12, 60, 0, 1, &rc_thresholds);\n AddRateControlThresholds(0, 65, 15, 5, 5, 0, 1, &rc_thresholds);\n\n QualityThresholds quality_thresholds(33.0, 30.0, 0.90, 0.85);\n\n ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,\n kNoVisualizationParams);\n}\n\n#endif \/\/ defined(WEBRTC_ANDROID)\n\n} \/\/ namespace test\n} \/\/ namespace webrtc\nDisable flaky test VideoProcessorIntegrationTestMediaCodec.ForemanCif500kbpsVp8.\/*\n * Copyright (c) 2017 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 \"modules\/video_coding\/codecs\/test\/videoprocessor_integrationtest.h\"\n\n#include \n\n#include \"test\/field_trial.h\"\n#include \"test\/testsupport\/fileutils.h\"\n\nnamespace webrtc {\nnamespace test {\n\n#if defined(WEBRTC_ANDROID)\n\nnamespace {\nconst int kForemanNumFrames = 300;\nconst std::nullptr_t kNoVisualizationParams = nullptr;\n} \/\/ namespace\n\nclass VideoProcessorIntegrationTestMediaCodec\n : public VideoProcessorIntegrationTest {\n protected:\n VideoProcessorIntegrationTestMediaCodec() {\n config_.filename = \"foreman_cif\";\n config_.input_filename = ResourcePath(config_.filename, \"yuv\");\n config_.output_filename =\n TempFilename(OutputPath(), \"videoprocessor_integrationtest_mediacodec\");\n config_.verbose = false;\n config_.hw_encoder = true;\n config_.hw_decoder = true;\n }\n};\n\nTEST_F(VideoProcessorIntegrationTestMediaCodec, DISABLED_ForemanCif500kbpsVp8) {\n SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,\n false, 352, 288);\n\n RateProfile rate_profile;\n SetRateProfile(&rate_profile, 0, 500, 30, 0); \/\/ Start below |low_kbps|.\n rate_profile.frame_index_rate_update[1] = kForemanNumFrames + 1;\n rate_profile.num_frames = kForemanNumFrames;\n\n \/\/ The thresholds below may have to be tweaked to let even poor MediaCodec\n \/\/ implementations pass. If this test fails on the bots, disable it and\n \/\/ ping brandtr@.\n std::vector rc_thresholds;\n AddRateControlThresholds(5, 95, 20, 10, 10, 0, 1, &rc_thresholds);\n\n QualityThresholds quality_thresholds(30.0, 15.0, 0.90, 0.40);\n\n ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,\n kNoVisualizationParams);\n}\n\nTEST_F(VideoProcessorIntegrationTestMediaCodec,\n Foreman240p100kbpsVp8WithForcedSwFallback) {\n ScopedFieldTrials override_field_trials(\n \"WebRTC-VP8-Forced-Fallback-Encoder\/Enabled-150,175,10000,1\/\");\n\n config_.filename = \"foreman_320x240\";\n config_.input_filename = ResourcePath(config_.filename, \"yuv\");\n config_.sw_fallback_encoder = true;\n SetCodecSettings(&config_, kVideoCodecVP8, 1, false, false, false, false,\n false, 320, 240);\n\n RateProfile rate_profile;\n SetRateProfile(&rate_profile, 0, 100, 10, 0); \/\/ Start below |low_kbps|.\n SetRateProfile(&rate_profile, 1, 100, 10, 80); \/\/ Fallback in this bucket.\n SetRateProfile(&rate_profile, 2, 200, 10, 200); \/\/ Switch back here.\n rate_profile.frame_index_rate_update[3] = kForemanNumFrames + 1;\n rate_profile.num_frames = kForemanNumFrames;\n\n \/\/ The thresholds below may have to be tweaked to let even poor MediaCodec\n \/\/ implementations pass. If this test fails on the bots, disable it and\n \/\/ ping brandtr@.\n std::vector rc_thresholds;\n AddRateControlThresholds(0, 50, 75, 70, 10, 0, 1, &rc_thresholds);\n AddRateControlThresholds(0, 50, 25, 12, 60, 0, 1, &rc_thresholds);\n AddRateControlThresholds(0, 65, 15, 5, 5, 0, 1, &rc_thresholds);\n\n QualityThresholds quality_thresholds(33.0, 30.0, 0.90, 0.85);\n\n ProcessFramesAndMaybeVerify(rate_profile, &rc_thresholds, &quality_thresholds,\n kNoVisualizationParams);\n}\n\n#endif \/\/ defined(WEBRTC_ANDROID)\n\n} \/\/ namespace test\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/*********************************************************************\n* Software License Agreement (BSD License)\n*\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: Ioan Sucan *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace kinematics_plugin_loader\n{\n\nconst double KinematicsPluginLoader::DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION = 0.1;\n\nclass KinematicsPluginLoader::KinematicsLoaderImpl\n{\npublic:\n KinematicsLoaderImpl(const std::string &robot_description,\n const std::map > &possible_kinematics_solvers, \n const std::map > &search_res,\n const std::map &ik_links) :\n robot_description_(robot_description),\n possible_kinematics_solvers_(possible_kinematics_solvers),\n search_res_(search_res),\n ik_links_(ik_links)\n {\n try\n {\n kinematics_loader_.reset(new pluginlib::ClassLoader(\"moveit_core\", \"kinematics::KinematicsBase\"));\n }\n catch(pluginlib::PluginlibException& e)\n {\n ROS_ERROR(\"Unable to construct kinematics loader. Error: %s\", e.what());\n }\n }\n \n boost::shared_ptr allocKinematicsSolver(const robot_model::JointModelGroup *jmg)\n {\n boost::shared_ptr result;\n if (!jmg)\n {\n ROS_ERROR(\"Specified group is NULL. Cannot allocate kinematics solver.\");\n return result;\n }\n \n ROS_DEBUG(\"Received request to allocate kinematics solver for group '%s'\", jmg->getName().c_str());\n \n if (kinematics_loader_ && jmg)\n {\n std::map >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());\n if (it != possible_kinematics_solvers_.end())\n {\n \/\/ just to be sure, do not call the same pluginlib instance allocation function in parallel\n boost::mutex::scoped_lock slock(lock_);\n \n for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)\n {\n try\n {\n result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));\n if (result)\n {\n const std::vector &links = jmg->getLinkModels();\n if (!links.empty())\n {\n const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?\n links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel()->getModelFrame();\n std::map::const_iterator ik_it = ik_links_.find(jmg->getName());\n const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();\n double search_res = search_res_.find(jmg->getName())->second[i]; \/\/ we know this exists, by construction\n if (!result->initialize(robot_description_, jmg->getName(), base, tip, search_res))\n {\n ROS_ERROR(\"Kinematics solver of type '%s' could not be initialized for group '%s'\", it->second[i].c_str(), jmg->getName().c_str());\n result.reset();\n }\n else\n ROS_DEBUG(\"Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p\",\n it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());\n }\n else\n ROS_ERROR(\"No links specified for group '%s'\", jmg->getName().c_str());\n }\n }\n catch (pluginlib::PluginlibException& e)\n {\n ROS_ERROR(\"The kinematics plugin (%s) failed to load. Error: %s\", it->first.c_str(), e.what());\n }\n }\n }\n else\n ROS_DEBUG(\"No kinematics solver available for this group\");\n }\n \n if (!result)\n ROS_DEBUG(\"No usable kinematics solver was found for this group\");\n return result;\n }\n\n boost::shared_ptr allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)\n {\n {\n boost::mutex::scoped_lock slock(lock_);\n const std::vector > &vi = instances_[jmg];\n for (std::size_t i = 0 ; i < vi.size() ; ++i)\n if (vi[i].unique())\n {\n ROS_DEBUG(\"Reusing cached kinematics solver for group '%s'\", jmg->getName().c_str());\n return vi[i]; \/\/ this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called \n }\n }\n \n boost::shared_ptr res = allocKinematicsSolver(jmg);\n \n {\n boost::mutex::scoped_lock slock(lock_);\n instances_[jmg].push_back(res);\n return res;\n }\n }\n \n void status() const\n {\n for (std::map >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)\n for (std::size_t i = 0 ; i < it->second.size() ; ++i)\n ROS_INFO(\"Solver for group '%s': '%s' (search resolution = %lf)\", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);\n }\n \nprivate:\n\n std::string robot_description_;\n std::map > possible_kinematics_solvers_;\n std::map > search_res_;\n std::map ik_links_;\n boost::shared_ptr > kinematics_loader_;\n std::map > > instances_;\n boost::mutex lock_;\n};\n\n}\n\nvoid kinematics_plugin_loader::KinematicsPluginLoader::status() const\n{\n if (loader_)\n loader_->status();\n else\n ROS_INFO(\"Loader function was never required\");\n}\n\nrobot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()\n{ \n moveit::Profiler::ScopedStart prof_start;\n moveit::Profiler::ScopedBlock prof_block(\"KinematicsPluginLoader::getLoaderFunction\");\n\n if (loader_)\n return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);\n\n rdf_loader::RDFLoader rml(robot_description_);\n robot_description_ = rml.getRobotDescription();\n return getLoaderFunction(rml.getSRDF());\n}\n\nrobot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr &srdf_model)\n{ \n moveit::Profiler::ScopedStart prof_start;\n moveit::Profiler::ScopedBlock prof_block(\"KinematicsPluginLoader::getLoaderFunction(SRDF)\");\n\n if (!loader_)\n {\n ROS_DEBUG(\"Configuring kinematics solvers\");\n groups_.clear();\n\n std::map > possible_kinematics_solvers;\n std::map > search_res;\n std::map ik_links;\n\n if (srdf_model)\n {\n const std::vector &known_groups = srdf_model->getGroups();\n if (default_search_resolution_ <= std::numeric_limits::epsilon())\n default_search_resolution_ = DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION;\n \n if (default_solver_plugin_.empty())\n {\n ROS_DEBUG(\"Loading settings for kinematics solvers from the ROS param server ...\");\n\n \/\/ read data using ROS params\n ros::NodeHandle nh(\"~\");\n \n \/\/ read the list of plugin names for possible kinematics solvers\n for (std::size_t i = 0 ; i < known_groups.size() ; ++i)\n {\n ROS_DEBUG(\"Looking for param %s \", (known_groups[i].name_ + \"\/kinematics_solver\").c_str());\n std::string ksolver_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver\", ksolver_param_name))\n {\n ROS_DEBUG(\"Found param %s \", ksolver_param_name.c_str());\n std::string ksolver; \n if (nh.getParam(ksolver_param_name, ksolver))\n {\n std::stringstream ss(ksolver);\n bool first = true;\n while (ss.good() && !ss.eof())\n {\n if (first)\n {\n first = false;\n groups_.push_back(known_groups[i].name_);\n }\n std::string solver; ss >> solver >> std::ws;\n possible_kinematics_solvers[known_groups[i].name_].push_back(solver);\n ROS_DEBUG(\"Using kinematics solver '%s' for group '%s'.\", solver.c_str(), known_groups[i].name_.c_str());\n }\n }\n }\n \n std::string ksolver_timeout_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_timeout\", ksolver_timeout_param_name))\n {\n double ksolver_timeout;\n if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))\n ik_timeout_[known_groups[i].name_] = ksolver_timeout;\n else\n {\/\/ just in case this is an int\n int ksolver_timeout_i;\n if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))\n ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;\n }\n }\n \n std::string ksolver_attempts_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_attempts\", ksolver_attempts_param_name))\n {\n int ksolver_attempts;\n if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))\n ik_attempts_[known_groups[i].name_] = ksolver_attempts;\n }\n \n std::string ksolver_res_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_search_resolution\", ksolver_res_param_name))\n {\n std::string ksolver_res;\n if (nh.getParam(ksolver_res_param_name, ksolver_res))\n {\n std::stringstream ss(ksolver_res);\n while (ss.good() && !ss.eof())\n {\n double res; ss >> res >> std::ws;\n search_res[known_groups[i].name_].push_back(res);\n }\n }\n else\n { \/\/ handle the case this param is just one value and parsed as a double \n double res;\n if (nh.getParam(ksolver_res_param_name, res))\n search_res[known_groups[i].name_].push_back(res);\n else\n {\n int res_i;\n if (nh.getParam(ksolver_res_param_name, res_i))\n search_res[known_groups[i].name_].push_back(res_i);\n }\n }\n }\n \n std::string ksolver_ik_link_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_ik_link\", ksolver_ik_link_param_name))\n {\n std::string ksolver_ik_link;\n if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))\n ik_links[known_groups[i].name_] = ksolver_ik_link;\n }\n \n \/\/ make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)\n while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())\n search_res[known_groups[i].name_].push_back(default_search_resolution_);\n }\n }\n else\n { \n ROS_DEBUG(\"Using specified default settings for kinematics solvers ...\");\n for (std::size_t i = 0 ; i < known_groups.size() ; ++i)\n {\n possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);\n search_res[known_groups[i].name_].resize(1, default_search_resolution_);\n ik_timeout_[known_groups[i].name_] = default_solver_timeout_;\n ik_attempts_[known_groups[i].name_] = default_ik_attempts_;\n groups_.push_back(known_groups[i].name_);\n }\n }\n }\n \n loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));\n }\n \n return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);\n}\nAdded debug info to remind user to load kinematics.yaml\/*********************************************************************\n* Software License Agreement (BSD License)\n*\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: Ioan Sucan *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace kinematics_plugin_loader\n{\n\nconst double KinematicsPluginLoader::DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION = 0.1;\n\nclass KinematicsPluginLoader::KinematicsLoaderImpl\n{\npublic:\n KinematicsLoaderImpl(const std::string &robot_description,\n const std::map > &possible_kinematics_solvers, \n const std::map > &search_res,\n const std::map &ik_links) :\n robot_description_(robot_description),\n possible_kinematics_solvers_(possible_kinematics_solvers),\n search_res_(search_res),\n ik_links_(ik_links)\n {\n try\n {\n kinematics_loader_.reset(new pluginlib::ClassLoader(\"moveit_core\", \"kinematics::KinematicsBase\"));\n }\n catch(pluginlib::PluginlibException& e)\n {\n ROS_ERROR(\"Unable to construct kinematics loader. Error: %s\", e.what());\n }\n }\n \n boost::shared_ptr allocKinematicsSolver(const robot_model::JointModelGroup *jmg)\n {\n boost::shared_ptr result;\n if (!jmg)\n {\n ROS_ERROR(\"Specified group is NULL. Cannot allocate kinematics solver.\");\n return result;\n }\n \n ROS_DEBUG(\"Received request to allocate kinematics solver for group '%s'\", jmg->getName().c_str());\n \n if (kinematics_loader_ && jmg)\n {\n std::map >::const_iterator it = possible_kinematics_solvers_.find(jmg->getName());\n if (it != possible_kinematics_solvers_.end())\n {\n \/\/ just to be sure, do not call the same pluginlib instance allocation function in parallel\n boost::mutex::scoped_lock slock(lock_);\n \n for (std::size_t i = 0 ; !result && i < it->second.size() ; ++i)\n {\n try\n {\n result.reset(kinematics_loader_->createUnmanagedInstance(it->second[i]));\n if (result)\n {\n const std::vector &links = jmg->getLinkModels();\n if (!links.empty())\n {\n const std::string &base = links.front()->getParentJointModel()->getParentLinkModel() ?\n links.front()->getParentJointModel()->getParentLinkModel()->getName() : jmg->getParentModel()->getModelFrame();\n std::map::const_iterator ik_it = ik_links_.find(jmg->getName());\n const std::string &tip = ik_it != ik_links_.end() ? ik_it->second : links.back()->getName();\n double search_res = search_res_.find(jmg->getName())->second[i]; \/\/ we know this exists, by construction\n if (!result->initialize(robot_description_, jmg->getName(), base, tip, search_res))\n {\n ROS_ERROR(\"Kinematics solver of type '%s' could not be initialized for group '%s'\", it->second[i].c_str(), jmg->getName().c_str());\n result.reset();\n }\n else\n ROS_DEBUG(\"Successfully allocated and initialized a kinematics solver of type '%s' with search resolution %lf for group '%s' at address %p\",\n it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());\n }\n else\n ROS_ERROR(\"No links specified for group '%s'\", jmg->getName().c_str());\n }\n }\n catch (pluginlib::PluginlibException& e)\n {\n ROS_ERROR(\"The kinematics plugin (%s) failed to load. Error: %s\", it->first.c_str(), e.what());\n }\n }\n }\n else\n ROS_DEBUG(\"No kinematics solver available for this group\");\n }\n \n if (!result)\n {\n ROS_DEBUG(\"No usable kinematics solver was found for this group.\");\n ROS_DEBUG(\"Did you load kinematics.yaml into your node's namespace?\");\n }\n return result;\n }\n\n boost::shared_ptr allocKinematicsSolverWithCache(const robot_model::JointModelGroup *jmg)\n {\n {\n boost::mutex::scoped_lock slock(lock_);\n const std::vector > &vi = instances_[jmg];\n for (std::size_t i = 0 ; i < vi.size() ; ++i)\n if (vi[i].unique())\n {\n ROS_DEBUG(\"Reusing cached kinematics solver for group '%s'\", jmg->getName().c_str());\n return vi[i]; \/\/ this is safe since the shared_ptr is copied on stack BEFORE the destructors in scope get called \n }\n }\n \n boost::shared_ptr res = allocKinematicsSolver(jmg);\n \n {\n boost::mutex::scoped_lock slock(lock_);\n instances_[jmg].push_back(res);\n return res;\n }\n }\n \n void status() const\n {\n for (std::map >::const_iterator it = possible_kinematics_solvers_.begin() ; it != possible_kinematics_solvers_.end() ; ++it)\n for (std::size_t i = 0 ; i < it->second.size() ; ++i)\n ROS_INFO(\"Solver for group '%s': '%s' (search resolution = %lf)\", it->first.c_str(), it->second[i].c_str(), search_res_.at(it->first)[i]);\n }\n \nprivate:\n\n std::string robot_description_;\n std::map > possible_kinematics_solvers_;\n std::map > search_res_;\n std::map ik_links_;\n boost::shared_ptr > kinematics_loader_;\n std::map > > instances_;\n boost::mutex lock_;\n};\n\n}\n\nvoid kinematics_plugin_loader::KinematicsPluginLoader::status() const\n{\n if (loader_)\n loader_->status();\n else\n ROS_INFO(\"Loader function was never required\");\n}\n\nrobot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction()\n{ \n moveit::Profiler::ScopedStart prof_start;\n moveit::Profiler::ScopedBlock prof_block(\"KinematicsPluginLoader::getLoaderFunction\");\n\n if (loader_)\n return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);\n\n rdf_loader::RDFLoader rml(robot_description_);\n robot_description_ = rml.getRobotDescription();\n return getLoaderFunction(rml.getSRDF());\n}\n\nrobot_model::SolverAllocatorFn kinematics_plugin_loader::KinematicsPluginLoader::getLoaderFunction(const boost::shared_ptr &srdf_model)\n{ \n moveit::Profiler::ScopedStart prof_start;\n moveit::Profiler::ScopedBlock prof_block(\"KinematicsPluginLoader::getLoaderFunction(SRDF)\");\n\n if (!loader_)\n {\n ROS_DEBUG(\"Configuring kinematics solvers\");\n groups_.clear();\n\n std::map > possible_kinematics_solvers;\n std::map > search_res;\n std::map ik_links;\n\n if (srdf_model)\n {\n const std::vector &known_groups = srdf_model->getGroups();\n if (default_search_resolution_ <= std::numeric_limits::epsilon())\n default_search_resolution_ = DEFAULT_KINEMATICS_SOLVER_SEARCH_RESOLUTION;\n \n if (default_solver_plugin_.empty())\n {\n ROS_DEBUG(\"Loading settings for kinematics solvers from the ROS param server ...\");\n\n \/\/ read data using ROS params\n ros::NodeHandle nh(\"~\");\n \n \/\/ read the list of plugin names for possible kinematics solvers\n for (std::size_t i = 0 ; i < known_groups.size() ; ++i)\n {\n ROS_DEBUG(\"Looking for param %s \", (known_groups[i].name_ + \"\/kinematics_solver\").c_str());\n std::string ksolver_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver\", ksolver_param_name))\n {\n ROS_DEBUG(\"Found param %s \", ksolver_param_name.c_str());\n std::string ksolver; \n if (nh.getParam(ksolver_param_name, ksolver))\n {\n std::stringstream ss(ksolver);\n bool first = true;\n while (ss.good() && !ss.eof())\n {\n if (first)\n {\n first = false;\n groups_.push_back(known_groups[i].name_);\n }\n std::string solver; ss >> solver >> std::ws;\n possible_kinematics_solvers[known_groups[i].name_].push_back(solver);\n ROS_DEBUG(\"Using kinematics solver '%s' for group '%s'.\", solver.c_str(), known_groups[i].name_.c_str());\n }\n }\n }\n \n std::string ksolver_timeout_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_timeout\", ksolver_timeout_param_name))\n {\n double ksolver_timeout;\n if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout))\n ik_timeout_[known_groups[i].name_] = ksolver_timeout;\n else\n {\/\/ just in case this is an int\n int ksolver_timeout_i;\n if (nh.getParam(ksolver_timeout_param_name, ksolver_timeout_i))\n ik_timeout_[known_groups[i].name_] = ksolver_timeout_i;\n }\n }\n \n std::string ksolver_attempts_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_attempts\", ksolver_attempts_param_name))\n {\n int ksolver_attempts;\n if (nh.getParam(ksolver_attempts_param_name, ksolver_attempts))\n ik_attempts_[known_groups[i].name_] = ksolver_attempts;\n }\n \n std::string ksolver_res_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_search_resolution\", ksolver_res_param_name))\n {\n std::string ksolver_res;\n if (nh.getParam(ksolver_res_param_name, ksolver_res))\n {\n std::stringstream ss(ksolver_res);\n while (ss.good() && !ss.eof())\n {\n double res; ss >> res >> std::ws;\n search_res[known_groups[i].name_].push_back(res);\n }\n }\n else\n { \/\/ handle the case this param is just one value and parsed as a double \n double res;\n if (nh.getParam(ksolver_res_param_name, res))\n search_res[known_groups[i].name_].push_back(res);\n else\n {\n int res_i;\n if (nh.getParam(ksolver_res_param_name, res_i))\n search_res[known_groups[i].name_].push_back(res_i);\n }\n }\n }\n \n std::string ksolver_ik_link_param_name;\n if (nh.searchParam(known_groups[i].name_ + \"\/kinematics_solver_ik_link\", ksolver_ik_link_param_name))\n {\n std::string ksolver_ik_link;\n if (nh.getParam(ksolver_ik_link_param_name, ksolver_ik_link))\n ik_links[known_groups[i].name_] = ksolver_ik_link;\n }\n \n \/\/ make sure there is a default resolution at least specified for every solver (in case it was not specified on the param server)\n while (search_res[known_groups[i].name_].size() < possible_kinematics_solvers[known_groups[i].name_].size())\n search_res[known_groups[i].name_].push_back(default_search_resolution_);\n }\n }\n else\n { \n ROS_DEBUG(\"Using specified default settings for kinematics solvers ...\");\n for (std::size_t i = 0 ; i < known_groups.size() ; ++i)\n {\n possible_kinematics_solvers[known_groups[i].name_].resize(1, default_solver_plugin_);\n search_res[known_groups[i].name_].resize(1, default_search_resolution_);\n ik_timeout_[known_groups[i].name_] = default_solver_timeout_;\n ik_attempts_[known_groups[i].name_] = default_ik_attempts_;\n groups_.push_back(known_groups[i].name_);\n }\n }\n }\n \n loader_.reset(new KinematicsLoaderImpl(robot_description_, possible_kinematics_solvers, search_res, ik_links));\n }\n \n return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * 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 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 this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"Directory.h\"\n#include \"utils\/Charsets.h\"\n#include \"utils\/Filename.h\"\n#include \"utils\/Url.h\"\n#include \"utils\/Directory.h\"\n#include \"medialibrary\/filesystem\/IFileSystemFactory.h\"\n#include \"File.h\"\n#include \"logging\/Logger.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace medialibrary\n{\n\nnamespace fs\n{\n\nDirectory::Directory( const std::string& mrl , fs::IFileSystemFactory& fsFactory )\n : CommonDirectory( fsFactory )\n{\n m_path = utils::file::toFolderPath(\n utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ) );\n assert( *m_path.crbegin() == '\/' || *m_path.crbegin() == '\\\\' );\n m_mrl = utils::file::toMrl( m_path );\n}\n\nconst std::string& Directory::mrl() const\n{\n return m_mrl;\n}\n\nvoid Directory::read() const\n{\n#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)\n WIN32_FIND_DATA f;\n auto pattern = m_path + '*';\n auto wpattern = charset::ToWide( pattern.c_str() );\n auto h = FindFirstFile( wpattern.get(), &f );\n if ( h == INVALID_HANDLE_VALUE )\n {\n LOG_ERROR( \"Failed to browse \", m_path );\n throw std::system_error( GetLastError(), std::generic_category(), \"Failed to browse through directory\" );\n }\n do\n {\n auto file = charset::FromWide( f.cFileName );\n if ( file[0] == '.' && strcasecmp( file.get(), \".nomedia\" ) )\n continue;\n auto fullpath = m_path + file.get();\n try\n {\n if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )\n m_dirs.emplace_back( m_fsFactory.createDirectory(\n m_mrl + utils::url::encode( file.get() ) ) );\n else\n m_files.emplace_back( std::make_shared( fullpath ) );\n }\n catch ( const std::system_error& ex )\n {\n LOG_WARN( \"Failed to access a listed file\/dir: \", ex.what() ,\n \". Ignoring this entry.\" );\n }\n } while ( FindNextFile( h, &f ) != 0 );\n FindClose( h );\n#else\n \/\/ We must remove the trailing \/\n \/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa363858(v=vs.85).aspx\n \/\/ «Do not use a trailing backslash (\\), which indicates the root directory of a drive»\n auto tmpPath = path.substr( 0, m_path.length() - 1 );\n auto wpath = charset::ToWide( tmpPath.c_str() );\n\n CREATEFILE2_EXTENDED_PARAMETERS params{};\n params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;\n auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms );\n if ( handle == INVALID_HANDLE_VALUE )\n {\n LOG_ERROR( \"Failed to open directory \", m_path );\n throw std::system_error( GetLastError(), std::generic_category(), \"Failed to open directory\" );\n }\n\n std::unique_ptr::type,\n decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );\n\n \/\/ Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate\n size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;\n std::unique_ptr dirInfo(\n reinterpret_cast( malloc( buffSize ) ),\n [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );\n if ( dirInfo == nullptr )\n throw std::bad_alloc();\n\n while ( true )\n {\n auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );\n if ( h == 0 )\n {\n auto error = GetLastError();\n if ( error == ERROR_FILE_NOT_FOUND )\n break;\n else if ( error == ERROR_MORE_DATA )\n {\n buffSize *= 2;\n dirInfo.reset( reinterpret_cast( malloc( buffSize ) ) );\n if ( dirInfo == nullptr )\n throw std::bad_alloc();\n continue;\n }\n LOG_ERROR( \"Failed to browse \", m_path, \". GetLastError(): \", GetLastError() );\n throw std::system_error( GetLastError(), std::generic_category(), \"Failed to browse through directory\" );\n }\n\n auto file = charset::FromWide( dirInfo->FileName );\n if ( file[0] == '.' && strcasecmp( file.get(), \".nomedia\" ) )\n continue;\n try\n {\n if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )\n m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) );\n else\n m_files.emplace_back( std::make_shared( m_path + file.get()) );\n }\n catch ( const std::system_error& ex )\n {\n LOG_WARN( \"Failed to access a listed file\/dir: \", ex.what() ,\n \". Ignoring this entry.\" );\n }\n }\n#endif\n}\n\n}\n\n}\nfix typo when compiling for Windows Store\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * 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 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 this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#if HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"Directory.h\"\n#include \"utils\/Charsets.h\"\n#include \"utils\/Filename.h\"\n#include \"utils\/Url.h\"\n#include \"utils\/Directory.h\"\n#include \"medialibrary\/filesystem\/IFileSystemFactory.h\"\n#include \"File.h\"\n#include \"logging\/Logger.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace medialibrary\n{\n\nnamespace fs\n{\n\nDirectory::Directory( const std::string& mrl , fs::IFileSystemFactory& fsFactory )\n : CommonDirectory( fsFactory )\n{\n m_path = utils::file::toFolderPath(\n utils::fs::toAbsolute( utils::file::toLocalPath( mrl ) ) );\n assert( *m_path.crbegin() == '\/' || *m_path.crbegin() == '\\\\' );\n m_mrl = utils::file::toMrl( m_path );\n}\n\nconst std::string& Directory::mrl() const\n{\n return m_mrl;\n}\n\nvoid Directory::read() const\n{\n#if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP)\n WIN32_FIND_DATA f;\n auto pattern = m_path + '*';\n auto wpattern = charset::ToWide( pattern.c_str() );\n auto h = FindFirstFile( wpattern.get(), &f );\n if ( h == INVALID_HANDLE_VALUE )\n {\n LOG_ERROR( \"Failed to browse \", m_path );\n throw std::system_error( GetLastError(), std::generic_category(), \"Failed to browse through directory\" );\n }\n do\n {\n auto file = charset::FromWide( f.cFileName );\n if ( file[0] == '.' && strcasecmp( file.get(), \".nomedia\" ) )\n continue;\n auto fullpath = m_path + file.get();\n try\n {\n if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )\n m_dirs.emplace_back( m_fsFactory.createDirectory(\n m_mrl + utils::url::encode( file.get() ) ) );\n else\n m_files.emplace_back( std::make_shared( fullpath ) );\n }\n catch ( const std::system_error& ex )\n {\n LOG_WARN( \"Failed to access a listed file\/dir: \", ex.what() ,\n \". Ignoring this entry.\" );\n }\n } while ( FindNextFile( h, &f ) != 0 );\n FindClose( h );\n#else\n \/\/ We must remove the trailing \/\n \/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa363858(v=vs.85).aspx\n \/\/ «Do not use a trailing backslash (\\), which indicates the root directory of a drive»\n auto tmpPath = m_path.substr( 0, m_path.length() - 1 );\n auto wpath = charset::ToWide( tmpPath.c_str() );\n\n CREATEFILE2_EXTENDED_PARAMETERS params{};\n params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS;\n auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms );\n if ( handle == INVALID_HANDLE_VALUE )\n {\n LOG_ERROR( \"Failed to open directory \", m_path );\n throw std::system_error( GetLastError(), std::generic_category(), \"Failed to open directory\" );\n }\n\n std::unique_ptr::type,\n decltype(&CloseHandle)> handlePtr( handle, &CloseHandle );\n\n \/\/ Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate\n size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32;\n std::unique_ptr dirInfo(\n reinterpret_cast( malloc( buffSize ) ),\n [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } );\n if ( dirInfo == nullptr )\n throw std::bad_alloc();\n\n while ( true )\n {\n auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize );\n if ( h == 0 )\n {\n auto error = GetLastError();\n if ( error == ERROR_FILE_NOT_FOUND )\n break;\n else if ( error == ERROR_MORE_DATA )\n {\n buffSize *= 2;\n dirInfo.reset( reinterpret_cast( malloc( buffSize ) ) );\n if ( dirInfo == nullptr )\n throw std::bad_alloc();\n continue;\n }\n LOG_ERROR( \"Failed to browse \", m_path, \". GetLastError(): \", GetLastError() );\n throw std::system_error( GetLastError(), std::generic_category(), \"Failed to browse through directory\" );\n }\n\n auto file = charset::FromWide( dirInfo->FileName );\n if ( file[0] == '.' && strcasecmp( file.get(), \".nomedia\" ) )\n continue;\n try\n {\n if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 )\n m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) );\n else\n m_files.emplace_back( std::make_shared( m_path + file.get()) );\n }\n catch ( const std::system_error& ex )\n {\n LOG_WARN( \"Failed to access a listed file\/dir: \", ex.what() ,\n \". Ignoring this entry.\" );\n }\n }\n#endif\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"\/************************************************************\nCOSC 501\nElliott Plack\n19 NOV 2013 Due 25 NOV 2013\nProblem: Create a 1-dimensional array with n elements; get\n\tthe size of the array as user input (validate!), max size\n\tshould be 10 (declared as class constant). Perform a\n\tvariety of functions with the array.\nAlgorithm: Get array size from user, validate, get values,\n\tperform functions.\n************************************************************\/\n#include \nusing namespace std;\n\n\/\/ various array handling functions\nfloat average(float numbers[]);\nvoid even(float numbers[]);\nvoid odd(float numbers[]);\nfloat evenSum(float numbers[]);\nfloat oddSum(float numbers[]);\n\nint main()\n{\n\t\/\/ redo with arrays\n\t\/\/ copy back in commit c864814b032eff90c493701556f869aff79629d4\n\t\/\/https:\/\/github.com\/talllguy\/Lab12\/blob\/c864814b032eff90c493701556f869aff79629d4\/Lab12array.cpp\n\n\tint arraySize = 0; \/\/ size of the array\n\tconst int maxArraySize = 10; \/\/ max size of the array\n\tfloat averageNum(0), evenSumNum(0), oddSumNum(0); \/\/ variables that returns will be stored in\n \n\tcout << \"This program does a number of calculations on an array.\\n\"\n\t\t<< \"Enter the size of the array up to 10.\\n\";\n\twhile (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) \/\/ validate\n\t{\n\t\tcin.clear(); \/\/ Clear the error flags \n\t\tcin.ignore(100, '\\n'); \/\/ Remove unwanted characters from buffer \n\t\tcout << \"\\aEnter a positive integer, less than 10: \"; \/\/ Re-issue the prompt \n\t}\n\t\/\/ test:\n\tcout << arraySize;\n\n\tfloat *numbers;\n\tnumbers = new float[arraySize]; \/\/ declare numbers array with 'elements' (n) positions\n\t\n\tfor (int i = 0; i < arraySize; i++) \/\/ loop to fill array\n\t{\n\t\tcout << \"Position \" << (i + 1) << \": \"; \/\/ display the iterator + 1 since it begins as 0\n\t\twhile ((!(cin >> numbers[i]))) \/\/detects errors in input\n\t\t{\n\t\t\tcin.clear(); \/\/ Clear the error flags\n\t\t\tcin.ignore(100, '\\n'); \/\/ Remove unwanted characters from buffer\n\t\t\tcout << \"\\aInput Error. Please enter a number only.\\n\" \/\/ if error, sound the alarm\n\t\t\t\t<< \"Position \" << (i + 1) << \": \";\n\t\t}\n\t}\n\n\tcout << \"\\nExcellent. Your inputs are:\\n\";\n\tcout << \"| \"; \/\/ first separator for clarity\n\tfor (int i = 0; i < arraySize; i++) \/\/ test loop to output variables in positions\n\t{\n\t\tcout << numbers[i] << \" | \"; \/\/ put formatted separator in\n\t}\n\n\treturn 0;\n}removed test\/************************************************************\nCOSC 501\nElliott Plack\n19 NOV 2013 Due 25 NOV 2013\nProblem: Create a 1-dimensional array with n elements; get\n\tthe size of the array as user input (validate!), max size\n\tshould be 10 (declared as class constant). Perform a\n\tvariety of functions with the array.\nAlgorithm: Get array size from user, validate, get values,\n\tperform functions.\n************************************************************\/\n#include \nusing namespace std;\n\n\/\/ various array handling functions\nfloat average(float numbers[]);\nvoid even(float numbers[]);\nvoid odd(float numbers[]);\nfloat evenSum(float numbers[]);\nfloat oddSum(float numbers[]);\n\nint main()\n{\n\t\/\/ redo with arrays\n\t\/\/ copy back in commit c864814b032eff90c493701556f869aff79629d4\n\t\/\/https:\/\/github.com\/talllguy\/Lab12\/blob\/c864814b032eff90c493701556f869aff79629d4\/Lab12array.cpp\n\n\tint arraySize = 0; \/\/ size of the array\n\tconst int maxArraySize = 10; \/\/ max size of the array\n\tfloat averageNum(0), evenSumNum(0), oddSumNum(0); \/\/ variables that returns will be stored in\n \n\tcout << \"This program does a number of calculations on an array.\\n\"\n\t\t<< \"Enter the size of the array up to 10.\\n\";\n\twhile (!(cin >> arraySize) || arraySize < 1 || arraySize > maxArraySize) \/\/ validate\n\t{\n\t\tcin.clear(); \/\/ Clear the error flags \n\t\tcin.ignore(100, '\\n'); \/\/ Remove unwanted characters from buffer \n\t\tcout << \"\\aEnter a positive integer, less than 10: \"; \/\/ Re-issue the prompt \n\t}\n\n\tfloat *numbers;\n\tnumbers = new float[arraySize]; \/\/ declare numbers array with 'elements' (n) positions\n\t\n\tfor (int i = 0; i < arraySize; i++) \/\/ loop to fill array\n\t{\n\t\tcout << \"Position \" << (i + 1) << \": \"; \/\/ display the iterator + 1 since it begins as 0\n\t\twhile ((!(cin >> numbers[i]))) \/\/detects errors in input\n\t\t{\n\t\t\tcin.clear(); \/\/ Clear the error flags\n\t\t\tcin.ignore(100, '\\n'); \/\/ Remove unwanted characters from buffer\n\t\t\tcout << \"\\aInput Error. Please enter a number only.\\n\" \/\/ if error, sound the alarm\n\t\t\t\t<< \"Position \" << (i + 1) << \": \";\n\t\t}\n\t}\n\n\tcout << \"\\nExcellent. Your inputs are:\\n\";\n\tcout << \"| \"; \/\/ first separator for clarity\n\tfor (int i = 0; i < arraySize; i++) \/\/ test loop to output variables in positions\n\t{\n\t\tcout << numbers[i] << \" | \"; \/\/ put formatted separator in\n\t}\n\n\treturn 0;\n}<|endoftext|>"} {"text":"\/*\n * Copyright © 2010 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_constant_variable.cpp\n *\n * Marks variables assigned a single constant value over the course\n * of the program as constant.\n *\n * The goal here is to trigger further constant folding and then dead\n * code elimination. This is common with vector\/matrix constructors\n * and calls to builtin functions.\n *\/\n\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"ir_optimization.h\"\n#include \"glsl_types.h\"\n\nnamespace {\n\nstruct assignment_entry {\n exec_node link;\n int assignment_count;\n ir_variable *var;\n ir_constant *constval;\n bool our_scope;\n};\n\nclass ir_constant_variable_visitor : public ir_hierarchical_visitor {\npublic:\n virtual ir_visitor_status visit_enter(ir_dereference_variable *);\n virtual ir_visitor_status visit(ir_variable *);\n virtual ir_visitor_status visit_enter(ir_assignment *);\n virtual ir_visitor_status visit_enter(ir_call *);\n\n exec_list list;\n};\n\n} \/* unnamed namespace *\/\n\nstatic struct assignment_entry *\nget_assignment_entry(ir_variable *var, exec_list *list)\n{\n struct assignment_entry *entry;\n\n foreach_list_typed(struct assignment_entry, entry, link, list) {\n if (entry->var == var)\n\t return entry;\n }\n\n entry = (struct assignment_entry *)calloc(1, sizeof(*entry));\n entry->var = var;\n list->push_head(&entry->link);\n return entry;\n}\n\nir_visitor_status\nir_constant_variable_visitor::visit(ir_variable *ir)\n{\n struct assignment_entry *entry = get_assignment_entry(ir, &this->list);\n entry->our_scope = true;\n return visit_continue;\n}\n\n\/* Skip derefs of variables so that we can detect declarations. *\/\nir_visitor_status\nir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)\n{\n (void)ir;\n return visit_continue_with_parent;\n}\n\nir_visitor_status\nir_constant_variable_visitor::visit_enter(ir_assignment *ir)\n{\n ir_constant *constval;\n struct assignment_entry *entry;\n\n entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);\n assert(entry);\n entry->assignment_count++;\n\n \/* If it's already constant, don't do the work. *\/\n if (entry->var->constant_value)\n return visit_continue;\n\n \/* OK, now find if we actually have all the right conditions for\n * this to be a constant value assigned to the var.\n *\/\n if (ir->condition)\n return visit_continue;\n\n ir_variable *var = ir->whole_variable_written();\n if (!var)\n return visit_continue;\n\n constval = ir->rhs->constant_expression_value();\n if (!constval)\n return visit_continue;\n\n \/* Mark this entry as having a constant assignment (if the\n * assignment count doesn't go >1). do_constant_variable will fix\n * up the variable with the constant value later.\n *\/\n entry->constval = constval;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_constant_variable_visitor::visit_enter(ir_call *ir)\n{\n \/* Mark any out parameters as assigned to *\/\n exec_list_iterator sig_iter = ir->callee->parameters.iterator();\n foreach_iter(exec_list_iterator, iter, *ir) {\n ir_rvalue *param_rval = (ir_rvalue *)iter.get();\n ir_variable *param = (ir_variable *)sig_iter.get();\n\n if (param->mode == ir_var_out ||\n\t param->mode == ir_var_inout) {\n\t ir_variable *var = param_rval->variable_referenced();\n\t struct assignment_entry *entry;\n\n\t assert(var);\n\t entry = get_assignment_entry(var, &this->list);\n\t entry->assignment_count++;\n }\n sig_iter.next();\n }\n\n \/* Mark the return storage as having been assigned to *\/\n if (ir->return_deref != NULL) {\n ir_variable *var = ir->return_deref->variable_referenced();\n struct assignment_entry *entry;\n\n assert(var);\n entry = get_assignment_entry(var, &this->list);\n entry->assignment_count++;\n }\n\n return visit_continue;\n}\n\n\/**\n * Does a copy propagation pass on the code present in the instruction stream.\n *\/\nbool\ndo_constant_variable(exec_list *instructions)\n{\n bool progress = false;\n ir_constant_variable_visitor v;\n\n v.run(instructions);\n\n while (!v.list.is_empty()) {\n\n struct assignment_entry *entry;\n entry = exec_node_data(struct assignment_entry, v.list.head, link);\n\n if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {\n\t entry->var->constant_value = entry->constval;\n\t progress = true;\n }\n entry->link.remove();\n free(entry);\n }\n\n return progress;\n}\n\nbool\ndo_constant_variable_unlinked(exec_list *instructions)\n{\n bool progress = false;\n\n foreach_iter(exec_list_iterator, iter, *instructions) {\n ir_instruction *ir = (ir_instruction *)iter.get();\n ir_function *f = ir->as_function();\n if (f) {\n\t foreach_iter(exec_list_iterator, sigiter, *f) {\n\t ir_function_signature *sig =\n\t (ir_function_signature *) sigiter.get();\n\t if (do_constant_variable(&sig->body))\n\t progress = true;\n\t }\n }\n }\n\n return progress;\n}\nfix too eager constant variable optimization v2; mark function input parameters as being assigned to\/*\n * Copyright © 2010 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_constant_variable.cpp\n *\n * Marks variables assigned a single constant value over the course\n * of the program as constant.\n *\n * The goal here is to trigger further constant folding and then dead\n * code elimination. This is common with vector\/matrix constructors\n * and calls to builtin functions.\n *\/\n\n#include \"ir.h\"\n#include \"ir_visitor.h\"\n#include \"ir_optimization.h\"\n#include \"glsl_types.h\"\n\nnamespace {\n\nstruct assignment_entry {\n exec_node link;\n int assignment_count;\n ir_variable *var;\n ir_constant *constval;\n bool our_scope;\n};\n\nclass ir_constant_variable_visitor : public ir_hierarchical_visitor {\npublic:\n virtual ir_visitor_status visit_enter(ir_dereference_variable *);\n virtual ir_visitor_status visit(ir_variable *);\n virtual ir_visitor_status visit_enter(ir_assignment *);\n virtual ir_visitor_status visit_enter(ir_call *);\n virtual ir_visitor_status visit_enter(ir_function_signature *);\n\n exec_list list;\n};\n\n} \/* unnamed namespace *\/\n\nstatic struct assignment_entry *\nget_assignment_entry(ir_variable *var, exec_list *list)\n{\n struct assignment_entry *entry;\n\n foreach_list_typed(struct assignment_entry, entry, link, list) {\n if (entry->var == var)\n\t return entry;\n }\n\n entry = (struct assignment_entry *)calloc(1, sizeof(*entry));\n entry->var = var;\n list->push_head(&entry->link);\n return entry;\n}\n\nir_visitor_status\nir_constant_variable_visitor::visit(ir_variable *ir)\n{\n struct assignment_entry *entry = get_assignment_entry(ir, &this->list);\n entry->our_scope = true;\n return visit_continue;\n}\n\n\/* Skip derefs of variables so that we can detect declarations. *\/\nir_visitor_status\nir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)\n{\n (void)ir;\n return visit_continue_with_parent;\n}\n\nir_visitor_status\nir_constant_variable_visitor::visit_enter(ir_assignment *ir)\n{\n ir_constant *constval;\n struct assignment_entry *entry;\n\n entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);\n assert(entry);\n entry->assignment_count++;\n\n \/* If it's already constant, don't do the work. *\/\n if (entry->var->constant_value)\n return visit_continue;\n\n \/* OK, now find if we actually have all the right conditions for\n * this to be a constant value assigned to the var.\n *\/\n if (ir->condition)\n return visit_continue;\n\n ir_variable *var = ir->whole_variable_written();\n if (!var)\n return visit_continue;\n\n constval = ir->rhs->constant_expression_value();\n if (!constval)\n return visit_continue;\n\n \/* Mark this entry as having a constant assignment (if the\n * assignment count doesn't go >1). do_constant_variable will fix\n * up the variable with the constant value later.\n *\/\n entry->constval = constval;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_constant_variable_visitor::visit_enter(ir_call *ir)\n{\n \/* Mark any out parameters as assigned to *\/\n exec_list_iterator sig_iter = ir->callee->parameters.iterator();\n foreach_iter(exec_list_iterator, iter, *ir) {\n ir_rvalue *param_rval = (ir_rvalue *)iter.get();\n ir_variable *param = (ir_variable *)sig_iter.get();\n\n if (param->mode == ir_var_out ||\n\t param->mode == ir_var_inout) {\n\t ir_variable *var = param_rval->variable_referenced();\n\t struct assignment_entry *entry;\n\n\t assert(var);\n\t entry = get_assignment_entry(var, &this->list);\n\t entry->assignment_count++;\n }\n sig_iter.next();\n }\n\n \/* Mark the return storage as having been assigned to *\/\n if (ir->return_deref != NULL) {\n ir_variable *var = ir->return_deref->variable_referenced();\n struct assignment_entry *entry;\n\n assert(var);\n entry = get_assignment_entry(var, &this->list);\n entry->assignment_count++;\n }\n\n return visit_continue;\n}\n\nir_visitor_status\nir_constant_variable_visitor::visit_enter(ir_function_signature *ir)\n{\n \/* Mark any in parameters as assigned to *\/\n foreach_iter(exec_list_iterator, iter, ir->parameters) {\n ir_variable *var = (ir_variable *)iter.get();\n if (var->mode == ir_var_in || var->mode == ir_var_const_in || var->mode == ir_var_inout) {\n struct assignment_entry *entry;\n entry = get_assignment_entry(var, &this->list);\n entry->assignment_count++;\n }\n }\n visit_list_elements(this, &ir->body);\n return visit_continue_with_parent;\n}\n\n\n\/**\n * Does a copy propagation pass on the code present in the instruction stream.\n *\/\nbool\ndo_constant_variable(exec_list *instructions)\n{\n bool progress = false;\n ir_constant_variable_visitor v;\n\n v.run(instructions);\n\n while (!v.list.is_empty()) {\n\n struct assignment_entry *entry;\n entry = exec_node_data(struct assignment_entry, v.list.head, link);\n\n if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {\n\t entry->var->constant_value = entry->constval;\n\t progress = true;\n }\n entry->link.remove();\n free(entry);\n }\n\n return progress;\n}\n\nbool\ndo_constant_variable_unlinked(exec_list *instructions)\n{\n bool progress = false;\n\n foreach_iter(exec_list_iterator, iter, *instructions) {\n ir_instruction *ir = (ir_instruction *)iter.get();\n ir_function *f = ir->as_function();\n if (f) {\n\t foreach_iter(exec_list_iterator, sigiter, *f) {\n\t ir_function_signature *sig =\n\t (ir_function_signature *) sigiter.get();\n\t if (do_constant_variable(&sig->body))\n\t progress = true;\n\t }\n }\n }\n\n return progress;\n}\n<|endoftext|>"} {"text":"\/* conduitConfigDialog.cc KPilot\n**\n** Copyright (C) 2004 by Dan Pilone\n** Written 2004 by Reinhold Kainhofer\n**\n** This file defines a .ui-based configuration dialog for conduits.\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** 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 in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n** MA 02111-1307, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\nstatic const char *conduitconfigdialog_id =\n\t\"$Id$\";\n\n\/\/#include \"options.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kpilotConfig.h\"\n#include \"options.h\"\n\n#include \"kpilotConfigWizard_base1.h\"\n#include \"kpilotConfigWizard_base2.h\"\n#include \"kpilotConfigWizard_base3.h\"\n\n#include \"kpilotConfigWizard.moc\"\n#include \"kpilotProbeDialog.h\"\n\n\nConfigWizard::ConfigWizard(QWidget *parent, const char *n) :\n\tKWizard(parent, n)\n{\n\tpage1=new ConfigWizard_base1(this);\n\taddPage( page1, i18n(\"Select connection type\") );\n\tpage2=new ConfigWizard_base2(this);\n\taddPage( page2, i18n(\"Pilot info\") );\n\tpage3=new ConfigWizard_base3(this);\n\taddPage( page3, i18n(\"Application to sync with\") );\n\tsetFinishEnabled( page3, true );\n\t\n\tconnect( page2->fProbeButton, SIGNAL( pressed() ),\n\t\tthis, SLOT( probeHandheld() ) );\n\t\t\n\tKPilotSettings::self()->readConfig();\n\tpage2->fUserName->setText( KPilotSettings::userName() );\n\tpage2->fDeviceName->setText( KPilotSettings::pilotDevice() );\n\tpage2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() );\n}\n\nConfigWizard::~ConfigWizard()\n{\n}\n\nvoid ConfigWizard::accept()\n{\n\tFUNCTIONSETUP;\n\tQString username( page2->fUserName->text() );\n\tQString devicename( page2->fDeviceName->text() );\n\/\/\tint devicetype( page1->fConnectionType->selectedId() );\n\tenum eSyncApp {\n\t\teAppKDE=0,\n\t\teAppKontact,\n\t\teAppEvolution\n\t} app;\n\tapp=(eSyncApp)( page3->fAppType->selectedId() );\n\tbool keepPermanently( page2->fPilotRunningPermanently->isChecked() );\n#ifdef DEBUG\n\tDEBUGCONDUIT<writeConfig();\n\tQDialog::accept();\n}\n\n\/\/ Devices to probe:\n\/\/ Linux: \/dev\/pilot (symlink), \/dev\/ttyS* (serial + irda), \/dev\/tts\/[012345...] (with devfs), \n\/\/ \/dev\/ttyUSB*, \/dev\/usb\/tts\/[012345...]\n\/\/ *BSD: \/dev\/pilot, \/dev\/cuaa[01] (serial), \/dev\/ucom* (usb)\n\nvoid ConfigWizard::probeHandheld()\n{\n\tProbeDialog *probeDialog = new ProbeDialog( this );\n\tif ( probeDialog->exec() && probeDialog->detected() ) {\n\t\tpage2->fUserName->setText( probeDialog->userName() );\n\t\tpage2->fDeviceName->setText( probeDialog->device() );\n\t}\n\tKPILOT_DELETE(probeDialog);\n}\n\n\/* conduitConfigDialog.cc KPilot\n**\n** Copyright (C) 2004 by Dan Pilone\n** Written 2004 by Reinhold Kainhofer\n**\n** This file defines a .ui-based configuration dialog for conduits.\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** 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 in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n** MA 02111-1307, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\nstatic const char *conduitconfigdialog_id =\n\t\"$Id$\";\n\n\/\/#include \"options.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kpilotConfig.h\"\n#include \"options.h\"\n\n#include \"kpilotConfigWizard_base1.h\"\n#include \"kpilotConfigWizard_base2.h\"\n#include \"kpilotConfigWizard_base3.h\"\n\n#include \"kpilotConfigWizard.moc\"\n#include \"kpilotProbeDialog.h\"\n\n\nConfigWizard::ConfigWizard(QWidget *parent, const char *n) :\n\tKWizard(parent, n)\n{\n\tpage1=new ConfigWizard_base1(this);\n\taddPage( page1, i18n(\"Select connection type\") );\n\tpage2=new ConfigWizard_base2(this);\n\taddPage( page2, i18n(\"Pilot info\") );\n\tpage3=new ConfigWizard_base3(this);\n\taddPage( page3, i18n(\"Application to sync with\") );\n\tsetFinishEnabled( page3, true );\n\t\n\tconnect( page2->fProbeButton, SIGNAL( pressed() ),\n\t\tthis, SLOT( probeHandheld() ) );\n\t\t\n\tKPilotSettings::self()->readConfig();\n\tpage2->fUserName->setText( KPilotSettings::userName() );\n\tpage2->fDeviceName->setText( KPilotSettings::pilotDevice() );\n\tpage2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() );\n}\n\nConfigWizard::~ConfigWizard()\n{\n}\n\nvoid ConfigWizard::accept()\n{\n\tFUNCTIONSETUP;\n\tQString username( page2->fUserName->text() );\n\tQString devicename( page2->fDeviceName->text() );\n\/\/\tint devicetype( page1->fConnectionType->selectedId() );\n\tenum eSyncApp {\n\t\teAppKDE=0,\n\t\teAppKontact,\n\t\teAppEvolution\n\t} app;\n\tapp=(eSyncApp)( page3->fAppType->selectedId() );\n\tbool keepPermanently( page2->fPilotRunningPermanently->isChecked() );\n#ifdef DEBUG\n\tDEBUGCONDUIT<writeConfig();\n\tQDialog::accept();\n}\n\n\/\/ Devices to probe:\n\/\/ Linux: \/dev\/pilot (symlink), \/dev\/ttyS* (serial + irda), \/dev\/tts\/[012345...] (with devfs), \n\/\/ \/dev\/ttyUSB*, \/dev\/usb\/tts\/[012345...]\n\/\/ *BSD: \/dev\/pilot, \/dev\/cuaa[01] (serial), \/dev\/ucom* (usb)\n\nvoid ConfigWizard::probeHandheld()\n{\n\tProbeDialog *probeDialog = new ProbeDialog( this );\n\tif ( probeDialog->exec() && probeDialog->detected() ) {\n\t\tpage2->fUserName->setText( probeDialog->userName() );\n\t\tpage2->fDeviceName->setText( probeDialog->device() );\n\t}\n\tKPILOT_DELETE(probeDialog);\n}\n\n<|endoftext|>"} {"text":"\/* libwpd\n * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)\n * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)\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 * 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 Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n *\n * For further information visit http:\/\/libwpd.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by \n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n\n#include \"WP3FileStructure.h\"\n#include \"WP3VariableLengthGroup.h\"\n#include \"WP3UnsupportedVariableLengthGroup.h\"\n#include \"WP3EndOfLinePageGroup.h\"\n#include \"WP3MiscellaneousGroup.h\"\n#include \"WP3PageFormatGroup.h\"\n#include \"WP3FontGroup.h\"\n#include \"WP3DefinitionGroup.h\"\n#include \"WP3DisplayGroup.h\"\n#include \"WP3HeaderFooterGroup.h\"\n#include \"WP3FootnoteEndnoteGroup.h\"\n#include \"WP3TablesGroup.h\"\n#include \"libwpd_internal.h\"\n\nWP3VariableLengthGroup::WP3VariableLengthGroup()\n{\n}\n\nWP3VariableLengthGroup * WP3VariableLengthGroup::constructVariableLengthGroup(WPXInputStream *input, uint8_t group)\n{\n\tswitch (group)\n\t{\n\t\tcase WP3_PAGE_FORMAT_GROUP:\n\t\t\treturn new WP3PageFormatGroup(input);\n\t\tcase WP3_END_OF_LINE_PAGE_GROUP:\n\t\t\treturn new WP3EndOfLinePageGroup(input);\n\t\tcase WP3_MISCELLANEOUS_GROUP:\n\t\t\treturn new WP3MiscellaneousGroup(input);\n\t\tcase WP3_TABLES_GROUP:\n\t\t\treturn new WP3TablesGroup(input);\n\t\tcase WP3_FONT_GROUP:\n\t\t\treturn new WP3FontGroup(input);\n\t\tcase WP3_DEFINITION_GROUP:\n\t\t\treturn new WP3DefinitionGroup(input);\n\t\tcase WP3_HEADER_FOOTER_GROUP:\n\t\t\treturn new WP3HeaderFooterGroup(input);\n\t\tcase WP3_FOOTNOTE_ENDNOTE_GROUP:\n\t\t\treturn new WP3FootnoteEndnoteGroup(input);\n\t\tcase WP3_DISPLAY_GROUP:\n\t\t\treturn new WP3DisplayGroup(input);\n\t\tdefault:\n\t\t\t\/\/ this is an unhandled group, just skip it\n\t\t\treturn new WP3UnsupportedVariableLengthGroup(input);\n\t}\n}\n\nbool WP3VariableLengthGroup::isGroupConsistent(WPXInputStream *input, const uint8_t group)\n{\n\tuint32_t startPosition = input->tell();\n\n\ttry\n\t{\n\t\tuint8_t subGroup = readU8(input);\n\t\tuint16_t size = readU16(input, true);\n\n\t\tif (input->seek((startPosition + size - 1 - input->tell()), WPX_SEEK_CUR) || input->atEOS())\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\tif (size != readU16(input, true))\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\tif (subGroup != readU8(input))\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\tif (group != readU8(input))\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\treturn true;\n\t}\n\tcatch(...)\n\t{\n\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\treturn false;\n\t}\n}\n\nvoid WP3VariableLengthGroup::_read(WPXInputStream *input)\n{\n\tuint32_t startPosition = input->tell();\n\n\tWPD_DEBUG_MSG((\"WordPerfect: handling a variable length group\\n\"));\t\n\t\n\tm_subGroup = readU8(input);\n\tm_size = readU16(input, true) + 4; \/\/ the length is the number of data bytes minus 4 (ie. the function codes)\n\t\n\tWPD_DEBUG_MSG((\"WordPerfect: Read variable group header (start_position: %i, sub_group: 0x%x, size: %i)\\n\", startPosition, m_subGroup, m_size));\n\t\n\t_readContents(input);\n\t\n\tinput->seek((startPosition + m_size - 5 - input->tell()), WPX_SEEK_CUR);\n\n\tif (m_size != (readU16(input, true) + 4))\n\t{\n\t\tWPD_DEBUG_MSG((\"WordPerfect: Possible corruption detected. Bailing out!\\n\"));\n\t\tthrow FileException();\n\t}\n\tif (m_subGroup != readU8(input))\n\t{\n\t\tWPD_DEBUG_MSG((\"WordPerfect: Possible corruption detected. Bailing out!\\n\"));\n\t\tthrow FileException();\n\t}\n\t\n\tinput->seek((startPosition + m_size - 1 - input->tell()), WPX_SEEK_CUR);\n\n}\nAdding a missing const\/* libwpd\n * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)\n * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)\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 * 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 Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n *\n * For further information visit http:\/\/libwpd.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by \n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n\n#include \"WP3FileStructure.h\"\n#include \"WP3VariableLengthGroup.h\"\n#include \"WP3UnsupportedVariableLengthGroup.h\"\n#include \"WP3EndOfLinePageGroup.h\"\n#include \"WP3MiscellaneousGroup.h\"\n#include \"WP3PageFormatGroup.h\"\n#include \"WP3FontGroup.h\"\n#include \"WP3DefinitionGroup.h\"\n#include \"WP3DisplayGroup.h\"\n#include \"WP3HeaderFooterGroup.h\"\n#include \"WP3FootnoteEndnoteGroup.h\"\n#include \"WP3TablesGroup.h\"\n#include \"libwpd_internal.h\"\n\nWP3VariableLengthGroup::WP3VariableLengthGroup()\n{\n}\n\nWP3VariableLengthGroup * WP3VariableLengthGroup::constructVariableLengthGroup(WPXInputStream *input, const uint8_t group)\n{\n\tswitch (group)\n\t{\n\t\tcase WP3_PAGE_FORMAT_GROUP:\n\t\t\treturn new WP3PageFormatGroup(input);\n\t\tcase WP3_END_OF_LINE_PAGE_GROUP:\n\t\t\treturn new WP3EndOfLinePageGroup(input);\n\t\tcase WP3_MISCELLANEOUS_GROUP:\n\t\t\treturn new WP3MiscellaneousGroup(input);\n\t\tcase WP3_TABLES_GROUP:\n\t\t\treturn new WP3TablesGroup(input);\n\t\tcase WP3_FONT_GROUP:\n\t\t\treturn new WP3FontGroup(input);\n\t\tcase WP3_DEFINITION_GROUP:\n\t\t\treturn new WP3DefinitionGroup(input);\n\t\tcase WP3_HEADER_FOOTER_GROUP:\n\t\t\treturn new WP3HeaderFooterGroup(input);\n\t\tcase WP3_FOOTNOTE_ENDNOTE_GROUP:\n\t\t\treturn new WP3FootnoteEndnoteGroup(input);\n\t\tcase WP3_DISPLAY_GROUP:\n\t\t\treturn new WP3DisplayGroup(input);\n\t\tdefault:\n\t\t\t\/\/ this is an unhandled group, just skip it\n\t\t\treturn new WP3UnsupportedVariableLengthGroup(input);\n\t}\n}\n\nbool WP3VariableLengthGroup::isGroupConsistent(WPXInputStream *input, const uint8_t group)\n{\n\tuint32_t startPosition = input->tell();\n\n\ttry\n\t{\n\t\tuint8_t subGroup = readU8(input);\n\t\tuint16_t size = readU16(input, true);\n\n\t\tif (input->seek((startPosition + size - 1 - input->tell()), WPX_SEEK_CUR) || input->atEOS())\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\tif (size != readU16(input, true))\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\tif (subGroup != readU8(input))\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\tif (group != readU8(input))\n\t\t{\n\t\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\treturn true;\n\t}\n\tcatch(...)\n\t{\n\t\tinput->seek(startPosition, WPX_SEEK_SET);\n\t\treturn false;\n\t}\n}\n\nvoid WP3VariableLengthGroup::_read(WPXInputStream *input)\n{\n\tuint32_t startPosition = input->tell();\n\n\tWPD_DEBUG_MSG((\"WordPerfect: handling a variable length group\\n\"));\t\n\t\n\tm_subGroup = readU8(input);\n\tm_size = readU16(input, true) + 4; \/\/ the length is the number of data bytes minus 4 (ie. the function codes)\n\t\n\tWPD_DEBUG_MSG((\"WordPerfect: Read variable group header (start_position: %i, sub_group: 0x%x, size: %i)\\n\", startPosition, m_subGroup, m_size));\n\t\n\t_readContents(input);\n\t\n\tinput->seek((startPosition + m_size - 5 - input->tell()), WPX_SEEK_CUR);\n\n\tif (m_size != (readU16(input, true) + 4))\n\t{\n\t\tWPD_DEBUG_MSG((\"WordPerfect: Possible corruption detected. Bailing out!\\n\"));\n\t\tthrow FileException();\n\t}\n\tif (m_subGroup != readU8(input))\n\t{\n\t\tWPD_DEBUG_MSG((\"WordPerfect: Possible corruption detected. Bailing out!\\n\"));\n\t\tthrow FileException();\n\t}\n\t\n\tinput->seek((startPosition + m_size - 1 - input->tell()), WPX_SEEK_CUR);\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2009-2013 The VOTCA Development Team (http:\/\/www.votca.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\n#include \n#include \n#include \n#include \n#include \"pdbreader.h\"\n\nnamespace votca { namespace csg {\n using namespace boost;\nusing namespace std;\n\nbool PDBReader::ReadTopology(string file, Topology &top)\n{\n _topology = true;\n top.Cleanup();\n\n _fl.open(file.c_str());\n if(!_fl.is_open())\n throw std::ios_base::failure(\"Error on open topology file: \" + file);\n\n NextFrame(top);\n\n _fl.close();\n\n return true;\n}\n\nbool PDBReader::Open(const string &file)\n{\n _fl.open(file.c_str());\n if(!_fl.is_open())\n throw std::ios_base::failure(\"Error on open trajectory file: \" + file);\n return true;\n}\n\nvoid PDBReader::Close()\n{\n _fl.close();\n}\n\nbool PDBReader::FirstFrame(Topology &top)\n{\n _topology = false;\n NextFrame(top);\n return true;\n}\n\nbool PDBReader::NextFrame(Topology &top)\n{\n string line;\n int i = 0 ;\n while ( std::getline(_fl, line) ){\n if( wildcmp(\"CRYST1*\",line.c_str())){\n\t string a, b, c, alpha, beta, gamma;\n\t try {\n \/\/1 - 6 Record name \"CRYST1\"\n\t a=string(line,(7-1),9); \/\/7 - 15 Real(9.3) a (Angstroms)\n\t b=string(line,(16-1),9); \/\/16 - 24 Real(9.3) b (Angstroms)\n\t c=string(line,(25-1),9); \/\/25 - 33 Real(9.3) c (Angstroms)\n\t alpha=string(line,(34-1),7); \/\/34 - 40 Real(7.2) alpha (degrees)\n beta=string(line,(41-1),7); \/\/41 - 47 Real(7.2) beta (degrees)\n\t gamma=string(line,(48-1),7); \/\/48 - 54 Real(7.2) gamma (degrees)\n \/\/56 - 66 LString Space group\n\t \/\/67 - 70 Integer Z value\n\t } catch (std::out_of_range& err) {\n\t throw std::runtime_error(\"Misformated pdb file in CRYST1 line\");\n\t }\n\t boost::algorithm::trim(a);\n\t boost::algorithm::trim(b);\n\t boost::algorithm::trim(c);\n\t boost::algorithm::trim(alpha);\n\t boost::algorithm::trim(beta);\n\t boost::algorithm::trim(gamma);\n\t if ((!wildcmp(\"90*\",alpha.c_str()))||(!wildcmp(\"90*\",alpha.c_str()))||(!wildcmp(\"90*\",alpha.c_str()))){\n\t throw std::runtime_error(\"Non cubical box in pdb file not implemented, yet!\");\n }\n\t top.setBox(matrix(vec(boost::lexical_cast(a), 0, 0),\n\t vec(0, boost::lexical_cast(b), 0), \n\t\t\t vec(0, 0, boost::lexical_cast(c))));\n\n\t}\n if( wildcmp(\"ATOM*\",line.c_str()) || wildcmp(\"HETATM*\",line.c_str())){\n \n \/\/ according to PDB format\n\t string x,y,z, resNum, resName, atName;\n try {\n\t \/* Some pdb don't include all this, read only what we realy need*\/\n\t \/* leave this here in case we need more later*\/\n \/\/string recType (line,( 1-1),6); \/\/ str, \"ATOM\", \"HETATM\"\n \/\/string atNum (line,( 7-1),6); \/\/ int, Atom serial number\n atName=string(line,(13-1),4); \/\/ str, Atom name\n \/\/string atAltLoc (line,(17-1),1); \/\/ char, Alternate location indicator\n resName=string(line,(18-1),3); \/\/ str, Residue name\n \/\/string chainID (line,(22-1),1); \/\/ char, Chain identifier\n resNum=string(line,(23-1),4); \/\/ int, Residue sequence number\n \/\/string atICode (line,(27-1),1); \/\/ char, Code for insertion of res\n x=string(line,(31-1),8); \/\/ float 8.3 ,x\n y=string(line,(39-1),8); \/\/ float 8.3 ,y\n z=string(line,(47-1),8); \/\/ float 8.3 ,z\n \/\/string atOccup (line,(55-1),6); \/\/ float 6.2, Occupancy\n \/\/string atTFactor (line,(61-1),6); \/\/ float 6.2, Temperature factor\n \/\/string segID (line,(73-1),4); \/\/ str, Segment identifier\n \/\/string atElement (line,(77-1),2); \/\/ str, Element symbol\n \/\/string atCharge (line,(79-1),2); \/\/ str, Charge on the atom\n\n\t } catch (std::out_of_range& err) {\n\t throw std::runtime_error(\"Misformated pdb file in atom line # \"+ boost::lexical_cast(i));\n\t }\n boost::algorithm::trim(atName);\n boost::algorithm::trim(resName);\n boost::algorithm::trim(resNum);\n boost::algorithm::trim(x);\n boost::algorithm::trim(y);\n boost::algorithm::trim(z);\n\n\t i++;\n if(!_topology && i > top.BeadCount())\n throw std::runtime_error(\"number of beads in topology and trajectory differ\");\n\n Bead *b;\n if(_topology){\n\t int resnr;\n\t try {\n\t\tresnr = boost::lexical_cast(resNum);\n\t } catch(bad_lexical_cast &) {\n\t throw std::runtime_error(\"Cannot convert resNum='\"+ resNum+\"' to int, that usallly means: misformated pdb file\");\n\t }\n if (resnr < 1)\n throw std::runtime_error(\"Misformated pdb file, resnr has to be > 0\");\n\t \/\/TODO: fix the case that resnr is not in ascending order\n if(resnr > top.ResidueCount()) {\n while ((resnr-1)>top.ResidueCount()){ \/\/pdb resnr should start with 1 but accept sloppy files\n\t top.CreateResidue(\"DUMMY\"); \/\/ create dummy residue, hopefully it will never show\n\t cout << \"Warning: residue numbers not continous, create DUMMY residue with nr \" << top.ResidueCount() << endl;\n\t\t}\n top.CreateResidue(resName);\n\t }\n \/\/this is not correct, but still better than no type at all!\n\t BeadType *type = top.GetOrCreateBeadType(atName);\n \n\t \/\/ res -1 as internal number starts with 0\n\t b = top.CreateBead(1, atName, type, resnr-1, 1., 0.);\n\t } else {\n b = top.getBead(i-1);\n\t }\n \/\/ convert to nm from A\n b->setPos(vec(\n boost::lexical_cast(x)\/10.0,\n boost::lexical_cast(y)\/10.0,\n boost::lexical_cast(z)\/10.0\n ));\n\n\t}\n\n if (( line == \"ENDMDL\" ) || ( line == \"END\" ) || ( _fl.eof())){\n break;\n\t}\n }\n\n if(!_topology && (i>0) && i != top.BeadCount())\n throw std::runtime_error(\"number of beads in topology and trajectory differ\");\n \n if (_topology)\n cout << \"WARNING: topology created from .pdb file, charges and masses are wrong!\\n\";\n \n return !_fl.eof();\n}\n\n}}\n\npdbreader: box needs to be scaled as well (A -> nm)\/*\n * Copyright 2009-2013 The VOTCA Development Team (http:\/\/www.votca.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\n#include \n#include \n#include \n#include \n#include \"pdbreader.h\"\n\nnamespace votca { namespace csg {\n using namespace boost;\nusing namespace std;\n\nbool PDBReader::ReadTopology(string file, Topology &top)\n{\n _topology = true;\n top.Cleanup();\n\n _fl.open(file.c_str());\n if(!_fl.is_open())\n throw std::ios_base::failure(\"Error on open topology file: \" + file);\n\n NextFrame(top);\n\n _fl.close();\n\n return true;\n}\n\nbool PDBReader::Open(const string &file)\n{\n _fl.open(file.c_str());\n if(!_fl.is_open())\n throw std::ios_base::failure(\"Error on open trajectory file: \" + file);\n return true;\n}\n\nvoid PDBReader::Close()\n{\n _fl.close();\n}\n\nbool PDBReader::FirstFrame(Topology &top)\n{\n _topology = false;\n NextFrame(top);\n return true;\n}\n\nbool PDBReader::NextFrame(Topology &top)\n{\n string line;\n int i = 0 ;\n while ( std::getline(_fl, line) ){\n if( wildcmp(\"CRYST1*\",line.c_str())){\n\t string a, b, c, alpha, beta, gamma;\n\t try {\n \/\/1 - 6 Record name \"CRYST1\"\n\t a=string(line,(7-1),9); \/\/7 - 15 Real(9.3) a (Angstroms)\n\t b=string(line,(16-1),9); \/\/16 - 24 Real(9.3) b (Angstroms)\n\t c=string(line,(25-1),9); \/\/25 - 33 Real(9.3) c (Angstroms)\n\t alpha=string(line,(34-1),7); \/\/34 - 40 Real(7.2) alpha (degrees)\n beta=string(line,(41-1),7); \/\/41 - 47 Real(7.2) beta (degrees)\n\t gamma=string(line,(48-1),7); \/\/48 - 54 Real(7.2) gamma (degrees)\n \/\/56 - 66 LString Space group\n\t \/\/67 - 70 Integer Z value\n\t } catch (std::out_of_range& err) {\n\t throw std::runtime_error(\"Misformated pdb file in CRYST1 line\");\n\t }\n\t boost::algorithm::trim(a);\n\t boost::algorithm::trim(b);\n\t boost::algorithm::trim(c);\n\t boost::algorithm::trim(alpha);\n\t boost::algorithm::trim(beta);\n\t boost::algorithm::trim(gamma);\n\t if ((!wildcmp(\"90*\",alpha.c_str()))||(!wildcmp(\"90*\",alpha.c_str()))||(!wildcmp(\"90*\",alpha.c_str()))){\n\t throw std::runtime_error(\"Non cubical box in pdb file not implemented, yet!\");\n }\n\t top.setBox(matrix(vec(boost::lexical_cast(a)\/10.0, 0, 0),\n\t vec(0, boost::lexical_cast(b)\/10.0, 0),\n\t\t\t vec(0, 0, boost::lexical_cast(c)\/10.0)));\n\n\t}\n if( wildcmp(\"ATOM*\",line.c_str()) || wildcmp(\"HETATM*\",line.c_str())){\n \n \/\/ according to PDB format\n\t string x,y,z, resNum, resName, atName;\n try {\n\t \/* Some pdb don't include all this, read only what we realy need*\/\n\t \/* leave this here in case we need more later*\/\n \/\/string recType (line,( 1-1),6); \/\/ str, \"ATOM\", \"HETATM\"\n \/\/string atNum (line,( 7-1),6); \/\/ int, Atom serial number\n atName=string(line,(13-1),4); \/\/ str, Atom name\n \/\/string atAltLoc (line,(17-1),1); \/\/ char, Alternate location indicator\n resName=string(line,(18-1),3); \/\/ str, Residue name\n \/\/string chainID (line,(22-1),1); \/\/ char, Chain identifier\n resNum=string(line,(23-1),4); \/\/ int, Residue sequence number\n \/\/string atICode (line,(27-1),1); \/\/ char, Code for insertion of res\n x=string(line,(31-1),8); \/\/ float 8.3 ,x\n y=string(line,(39-1),8); \/\/ float 8.3 ,y\n z=string(line,(47-1),8); \/\/ float 8.3 ,z\n \/\/string atOccup (line,(55-1),6); \/\/ float 6.2, Occupancy\n \/\/string atTFactor (line,(61-1),6); \/\/ float 6.2, Temperature factor\n \/\/string segID (line,(73-1),4); \/\/ str, Segment identifier\n \/\/string atElement (line,(77-1),2); \/\/ str, Element symbol\n \/\/string atCharge (line,(79-1),2); \/\/ str, Charge on the atom\n\n\t } catch (std::out_of_range& err) {\n\t throw std::runtime_error(\"Misformated pdb file in atom line # \"+ boost::lexical_cast(i));\n\t }\n boost::algorithm::trim(atName);\n boost::algorithm::trim(resName);\n boost::algorithm::trim(resNum);\n boost::algorithm::trim(x);\n boost::algorithm::trim(y);\n boost::algorithm::trim(z);\n\n\t i++;\n if(!_topology && i > top.BeadCount())\n throw std::runtime_error(\"number of beads in topology and trajectory differ\");\n\n Bead *b;\n if(_topology){\n\t int resnr;\n\t try {\n\t\tresnr = boost::lexical_cast(resNum);\n\t } catch(bad_lexical_cast &) {\n\t throw std::runtime_error(\"Cannot convert resNum='\"+ resNum+\"' to int, that usallly means: misformated pdb file\");\n\t }\n if (resnr < 1)\n throw std::runtime_error(\"Misformated pdb file, resnr has to be > 0\");\n\t \/\/TODO: fix the case that resnr is not in ascending order\n if(resnr > top.ResidueCount()) {\n while ((resnr-1)>top.ResidueCount()){ \/\/pdb resnr should start with 1 but accept sloppy files\n\t top.CreateResidue(\"DUMMY\"); \/\/ create dummy residue, hopefully it will never show\n\t cout << \"Warning: residue numbers not continous, create DUMMY residue with nr \" << top.ResidueCount() << endl;\n\t\t}\n top.CreateResidue(resName);\n\t }\n \/\/this is not correct, but still better than no type at all!\n\t BeadType *type = top.GetOrCreateBeadType(atName);\n \n\t \/\/ res -1 as internal number starts with 0\n\t b = top.CreateBead(1, atName, type, resnr-1, 1., 0.);\n\t } else {\n b = top.getBead(i-1);\n\t }\n \/\/ convert to nm from A\n b->setPos(vec(\n boost::lexical_cast(x)\/10.0,\n boost::lexical_cast(y)\/10.0,\n boost::lexical_cast(z)\/10.0\n ));\n\n\t}\n\n if (( line == \"ENDMDL\" ) || ( line == \"END\" ) || ( _fl.eof())){\n break;\n\t}\n }\n\n if(!_topology && (i>0) && i != top.BeadCount())\n throw std::runtime_error(\"number of beads in topology and trajectory differ\");\n \n if (_topology)\n cout << \"WARNING: topology created from .pdb file, charges and masses are wrong!\\n\";\n \n return !_fl.eof();\n}\n\n}}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: morphdlg.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2003-11-24 17:10:12 $\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#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n#include \"sdmod.hxx\"\n#include \"sdiocmpt.hxx\"\n#include \"morphdlg.hxx\"\n#include \"morphdlg.hrc\"\n\n#ifndef _SV_CONFIG_HXX \/\/autogen\n#include \n#endif\n#ifndef SVX_XFILLIT0_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_XLINEIT0_HXX \/\/autogen\n#include \n#endif\n#ifndef _XENUM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXITEMPOOL_HXX \/\/autogen\n#include \n#endif\n\n\n\/******************************************************************************\/\n\n\n#define FADE_STEP \"FadeSteps\"\n#define FADE_ATTRIB \"FadeAttributes\"\n#define FADE_ORIENT \"FadeOrientation\"\n#define FADE_TRUE \"true\"\n#define FADE_FALSE \"false\"\n\n\n\/******************************************************************************\/\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nSdMorphDlg::SdMorphDlg( Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :\n ModalDialog ( pParent, SdResId( DLG_MORPH ) ),\n aBtnOK ( this, SdResId( BTN_OK ) ),\n aBtnCancel ( this, SdResId( BTN_CANCEL ) ),\n aBtnHelp ( this, SdResId( BTN_HELP ) ),\n aGrpPreset ( this, SdResId( GRP_PRESET ) ),\n aFtSteps ( this, SdResId( FT_STEPS ) ),\n aMtfSteps ( this, SdResId( MTF_STEPS ) ),\n aCbxAttributes ( this, SdResId( CBX_ATTRIBUTES ) ),\n aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )\n{\n FreeResource();\n LoadSettings();\n\n SfxItemPool* pPool = (SfxItemPool*) pObj1->GetItemPool();\n SfxItemSet aSet1( *pPool );\n SfxItemSet aSet2( *pPool );\n\n aSet1.Put(pObj1->GetMergedItemSet());\n aSet2.Put(pObj2->GetMergedItemSet());\n\n const XLineStyle eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();\n const XLineStyle eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();\n const XFillStyle eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();\n const XFillStyle eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();\n\n if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&\n ( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )\n {\n aCbxAttributes.Disable();\n }\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nSdMorphDlg::~SdMorphDlg()\n{\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nvoid SdMorphDlg::LoadSettings()\n{\n SvStorageStreamRef xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_LOAD ) );\n UINT16 nSteps;\n BOOL bOrient, bAttrib;\n\n if( xIStm.Is() )\n {\n SdIOCompat aCompat( *xIStm, STREAM_READ );\n\n *xIStm >> nSteps >> bOrient >> bAttrib;\n }\n else\n {\n nSteps = 16;\n bOrient = bAttrib = TRUE;\n }\n\n aMtfSteps.SetValue( nSteps );\n aCbxOrientation.Check( bOrient );\n aCbxAttributes.Check( bAttrib );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SdMorphDlg::SaveSettings() const\n{\n SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_STORE ) );\n\n if( xOStm.Is() )\n {\n SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );\n\n *xOStm << (UINT16) aMtfSteps.GetValue()\n << aCbxOrientation.IsChecked()\n << aCbxAttributes.IsChecked();\n }\n}\n\nINTEGRATION: CWS vclcleanup02 (1.5.8); FILE MERGED 2003\/12\/11 09:17:26 mt 1.5.8.1: #i23061# VCL cleanup, removed headers, methods and types...\/*************************************************************************\n *\n * $RCSfile: morphdlg.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2004-01-06 18:44:12 $\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#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n#include \"sdmod.hxx\"\n#include \"sdiocmpt.hxx\"\n#include \"morphdlg.hxx\"\n#include \"morphdlg.hrc\"\n\n#ifndef _CONFIG_HXX\n#include \n#endif\n#ifndef SVX_XFILLIT0_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVX_XLINEIT0_HXX \/\/autogen\n#include \n#endif\n#ifndef _XENUM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXITEMPOOL_HXX \/\/autogen\n#include \n#endif\n\n\n\/******************************************************************************\/\n\n\n#define FADE_STEP \"FadeSteps\"\n#define FADE_ATTRIB \"FadeAttributes\"\n#define FADE_ORIENT \"FadeOrientation\"\n#define FADE_TRUE \"true\"\n#define FADE_FALSE \"false\"\n\n\n\/******************************************************************************\/\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nSdMorphDlg::SdMorphDlg( Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :\n ModalDialog ( pParent, SdResId( DLG_MORPH ) ),\n aBtnOK ( this, SdResId( BTN_OK ) ),\n aBtnCancel ( this, SdResId( BTN_CANCEL ) ),\n aBtnHelp ( this, SdResId( BTN_HELP ) ),\n aGrpPreset ( this, SdResId( GRP_PRESET ) ),\n aFtSteps ( this, SdResId( FT_STEPS ) ),\n aMtfSteps ( this, SdResId( MTF_STEPS ) ),\n aCbxAttributes ( this, SdResId( CBX_ATTRIBUTES ) ),\n aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )\n{\n FreeResource();\n LoadSettings();\n\n SfxItemPool* pPool = (SfxItemPool*) pObj1->GetItemPool();\n SfxItemSet aSet1( *pPool );\n SfxItemSet aSet2( *pPool );\n\n aSet1.Put(pObj1->GetMergedItemSet());\n aSet2.Put(pObj2->GetMergedItemSet());\n\n const XLineStyle eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();\n const XLineStyle eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();\n const XFillStyle eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();\n const XFillStyle eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();\n\n if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&\n ( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )\n {\n aCbxAttributes.Disable();\n }\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nSdMorphDlg::~SdMorphDlg()\n{\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nvoid SdMorphDlg::LoadSettings()\n{\n SvStorageStreamRef xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_LOAD ) );\n UINT16 nSteps;\n BOOL bOrient, bAttrib;\n\n if( xIStm.Is() )\n {\n SdIOCompat aCompat( *xIStm, STREAM_READ );\n\n *xIStm >> nSteps >> bOrient >> bAttrib;\n }\n else\n {\n nSteps = 16;\n bOrient = bAttrib = TRUE;\n }\n\n aMtfSteps.SetValue( nSteps );\n aCbxOrientation.Check( bOrient );\n aCbxAttributes.Check( bAttrib );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SdMorphDlg::SaveSettings() const\n{\n SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_STORE ) );\n\n if( xOStm.Is() )\n {\n SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );\n\n *xOStm << (UINT16) aMtfSteps.GetValue()\n << aCbxOrientation.IsChecked()\n << aCbxAttributes.IsChecked();\n }\n}\n\n<|endoftext|>"} {"text":"#include \"archive.hh\"\n#include \"binary-cache-store.hh\"\n#include \"compression.hh\"\n#include \"derivations.hh\"\n#include \"fs-accessor.hh\"\n#include \"globals.hh\"\n#include \"nar-info.hh\"\n#include \"sync.hh\"\n#include \"remote-fs-accessor.hh\"\n#include \"nar-info-disk-cache.hh\"\n#include \"nar-accessor.hh\"\n#include \"json.hh\"\n\n#include \n\n#include \n\nnamespace nix {\n\nBinaryCacheStore::BinaryCacheStore(const Params & params)\n : Store(params)\n{\n if (secretKeyFile != \"\")\n secretKey = std::unique_ptr(new SecretKey(readFile(secretKeyFile)));\n\n StringSink sink;\n sink << narVersionMagic1;\n narMagic = *sink.s;\n}\n\nvoid BinaryCacheStore::init()\n{\n std::string cacheInfoFile = \"nix-cache-info\";\n\n auto cacheInfo = getFile(cacheInfoFile);\n if (!cacheInfo) {\n upsertFile(cacheInfoFile, \"StoreDir: \" + storeDir + \"\\n\", \"text\/x-nix-cache-info\");\n } else {\n for (auto & line : tokenizeString(*cacheInfo, \"\\n\")) {\n size_t colon = line.find(':');\n if (colon == std::string::npos) continue;\n auto name = line.substr(0, colon);\n auto value = trim(line.substr(colon + 1, std::string::npos));\n if (name == \"StoreDir\") {\n if (value != storeDir)\n throw Error(format(\"binary cache '%s' is for Nix stores with prefix '%s', not '%s'\")\n % getUri() % value % storeDir);\n } else if (name == \"WantMassQuery\") {\n wantMassQuery_ = value == \"1\";\n } else if (name == \"Priority\") {\n string2Int(value, priority);\n }\n }\n }\n}\n\nvoid BinaryCacheStore::getFile(const std::string & path,\n Callback> callback)\n{\n try {\n callback(getFile(path));\n } catch (...) { callback.rethrow(); }\n}\n\nvoid BinaryCacheStore::getFile(const std::string & path, Sink & sink)\n{\n std::promise> promise;\n getFile(path,\n {[&](std::future> result) {\n try {\n promise.set_value(result.get());\n } catch (...) {\n promise.set_exception(std::current_exception());\n }\n }});\n auto data = promise.get_future().get();\n sink((unsigned char *) data->data(), data->size());\n}\n\nstd::shared_ptr BinaryCacheStore::getFile(const std::string & path)\n{\n StringSink sink;\n try {\n getFile(path, sink);\n } catch (NoSuchBinaryCacheFile &) {\n return nullptr;\n }\n return sink.s;\n}\n\nPath BinaryCacheStore::narInfoFileFor(const Path & storePath)\n{\n assertStorePath(storePath);\n return storePathToHash(storePath) + \".narinfo\";\n}\n\nvoid BinaryCacheStore::writeNarInfo(ref narInfo)\n{\n auto narInfoFile = narInfoFileFor(narInfo->path);\n\n upsertFile(narInfoFile, narInfo->to_string(), \"text\/x-nix-narinfo\");\n\n auto hashPart = storePathToHash(narInfo->path);\n\n {\n auto state_(state.lock());\n state_->pathInfoCache.upsert(hashPart, std::shared_ptr(narInfo));\n }\n\n if (diskCache)\n diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr(narInfo));\n}\n\nvoid BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref & nar,\n RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr accessor)\n{\n if (!repair && isValidPath(info.path)) return;\n\n \/* Verify that all references are valid. This may do some .narinfo\n reads, but typically they'll already be cached. *\/\n for (auto & ref : info.references)\n try {\n if (ref != info.path)\n queryPathInfo(ref);\n } catch (InvalidPath &) {\n throw Error(format(\"cannot add '%s' to the binary cache because the reference '%s' is not valid\")\n % info.path % ref);\n }\n\n assert(nar->compare(0, narMagic.size(), narMagic) == 0);\n\n auto narInfo = make_ref(info);\n\n narInfo->narSize = nar->size();\n narInfo->narHash = hashString(htSHA256, *nar);\n\n if (info.narHash && info.narHash != narInfo->narHash)\n throw Error(format(\"refusing to copy corrupted path '%1%' to binary cache\") % info.path);\n\n auto accessor_ = std::dynamic_pointer_cast(accessor);\n\n \/* Optionally write a JSON file containing a listing of the\n contents of the NAR. *\/\n if (writeNARListing) {\n std::ostringstream jsonOut;\n\n {\n JSONObject jsonRoot(jsonOut);\n jsonRoot.attr(\"version\", 1);\n\n auto narAccessor = makeNarAccessor(nar);\n\n if (accessor_)\n accessor_->addToCache(info.path, *nar, narAccessor);\n\n {\n auto res = jsonRoot.placeholder(\"root\");\n listNar(res, narAccessor, \"\", true);\n }\n }\n\n upsertFile(storePathToHash(info.path) + \".ls\", jsonOut.str(), \"application\/json\");\n }\n\n else {\n if (accessor_)\n accessor_->addToCache(info.path, *nar, makeNarAccessor(nar));\n }\n\n \/* Compress the NAR. *\/\n narInfo->compression = compression;\n auto now1 = std::chrono::steady_clock::now();\n auto narCompressed = compress(compression, *nar, parallelCompression);\n auto now2 = std::chrono::steady_clock::now();\n narInfo->fileHash = hashString(htSHA256, *narCompressed);\n narInfo->fileSize = narCompressed->size();\n\n auto duration = std::chrono::duration_cast(now2 - now1).count();\n printMsg(lvlTalkative, format(\"copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache\")\n % narInfo->path % narInfo->narSize\n % ((1.0 - (double) narCompressed->size() \/ nar->size()) * 100.0)\n % duration);\n\n \/* Atomically write the NAR file. *\/\n narInfo->url = \"nar\/\" + narInfo->fileHash.to_string(Base32, false) + \".nar\"\n + (compression == \"xz\" ? \".xz\" :\n compression == \"bzip2\" ? \".bz2\" :\n compression == \"br\" ? \".br\" :\n \"\");\n if (repair || !fileExists(narInfo->url)) {\n stats.narWrite++;\n upsertFile(narInfo->url, *narCompressed, \"application\/x-nix-nar\");\n } else\n stats.narWriteAverted++;\n\n stats.narWriteBytes += nar->size();\n stats.narWriteCompressedBytes += narCompressed->size();\n stats.narWriteCompressionTimeMs += duration;\n\n \/* Atomically write the NAR info file.*\/\n if (secretKey) narInfo->sign(*secretKey);\n\n writeNarInfo(narInfo);\n\n stats.narInfoWrite++;\n}\n\nbool BinaryCacheStore::isValidPathUncached(const Path & storePath)\n{\n \/\/ FIXME: this only checks whether a .narinfo with a matching hash\n \/\/ part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even\n \/\/ though they shouldn't. Not easily fixed.\n return fileExists(narInfoFileFor(storePath));\n}\n\nvoid BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)\n{\n auto info = queryPathInfo(storePath).cast();\n\n uint64_t narSize = 0;\n\n LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {\n sink(data, len);\n narSize += len;\n });\n\n auto decompressor = makeDecompressionSink(info->compression, wrapperSink);\n\n try {\n getFile(info->url, *decompressor);\n } catch (NoSuchBinaryCacheFile & e) {\n throw SubstituteGone(e.what());\n }\n\n decompressor->flush();\n\n stats.narRead++;\n \/\/stats.narReadCompressedBytes += nar->size(); \/\/ FIXME\n stats.narReadBytes += narSize;\n}\n\nvoid BinaryCacheStore::queryPathInfoUncached(const Path & storePath,\n Callback> callback)\n{\n auto uri = getUri();\n auto act = std::make_shared(*logger, lvlTalkative, actQueryPathInfo,\n fmt(\"querying info about '%s' on '%s'\", storePath, uri), Logger::Fields{storePath, uri});\n PushActivity pact(act->id);\n\n auto narInfoFile = narInfoFileFor(storePath);\n\n getFile(narInfoFile,\n {[=](std::future> fut) {\n try {\n auto data = fut.get();\n\n if (!data) return callback(nullptr);\n\n stats.narInfoRead++;\n\n callback((std::shared_ptr)\n std::make_shared(*this, *data, narInfoFile));\n\n (void) act; \/\/ force Activity into this lambda to ensure it stays alive\n } catch (...) {\n callback.rethrow();\n }\n }});\n}\n\nPath BinaryCacheStore::addToStore(const string & name, const Path & srcPath,\n bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)\n{\n \/\/ FIXME: some cut&paste from LocalStore::addToStore().\n\n \/* Read the whole path into memory. This is not a very scalable\n method for very large paths, but `copyPath' is mainly used for\n small files. *\/\n StringSink sink;\n Hash h;\n if (recursive) {\n dumpPath(srcPath, sink, filter);\n h = hashString(hashAlgo, *sink.s);\n } else {\n auto s = readFile(srcPath);\n dumpString(s, sink);\n h = hashString(hashAlgo, s);\n }\n\n ValidPathInfo info;\n info.path = makeFixedOutputPath(recursive, h, name);\n\n addToStore(info, sink.s, repair, CheckSigs, nullptr);\n\n return info.path;\n}\n\nPath BinaryCacheStore::addTextToStore(const string & name, const string & s,\n const PathSet & references, RepairFlag repair)\n{\n ValidPathInfo info;\n info.path = computeStorePathForText(name, s, references);\n info.references = references;\n\n if (repair || !isValidPath(info.path)) {\n StringSink sink;\n dumpString(s, sink);\n addToStore(info, sink.s, repair, CheckSigs, nullptr);\n }\n\n return info.path;\n}\n\nref BinaryCacheStore::getFSAccessor()\n{\n return make_ref(ref(shared_from_this()), localNarCache);\n}\n\nvoid BinaryCacheStore::addSignatures(const Path & storePath, const StringSet & sigs)\n{\n \/* Note: this is inherently racy since there is no locking on\n binary caches. In particular, with S3 this unreliable, even\n when addSignatures() is called sequentially on a path, because\n S3 might return an outdated cached version. *\/\n\n auto narInfo = make_ref((NarInfo &) *queryPathInfo(storePath));\n\n narInfo->sigs.insert(sigs.begin(), sigs.end());\n\n auto narInfoFile = narInfoFileFor(narInfo->path);\n\n writeNarInfo(narInfo);\n}\n\nstd::shared_ptr BinaryCacheStore::getBuildLog(const Path & path)\n{\n Path drvPath;\n\n if (isDerivation(path))\n drvPath = path;\n else {\n try {\n auto info = queryPathInfo(path);\n \/\/ FIXME: add a \"Log\" field to .narinfo\n if (info->deriver == \"\") return nullptr;\n drvPath = info->deriver;\n } catch (InvalidPath &) {\n return nullptr;\n }\n }\n\n auto logPath = \"log\/\" + baseNameOf(drvPath);\n\n debug(\"fetching build log from binary cache '%s\/%s'\", getUri(), logPath);\n\n return getFile(logPath);\n}\n\n}\nFix another 'coroutine has finished' during decompression#include \"archive.hh\"\n#include \"binary-cache-store.hh\"\n#include \"compression.hh\"\n#include \"derivations.hh\"\n#include \"fs-accessor.hh\"\n#include \"globals.hh\"\n#include \"nar-info.hh\"\n#include \"sync.hh\"\n#include \"remote-fs-accessor.hh\"\n#include \"nar-info-disk-cache.hh\"\n#include \"nar-accessor.hh\"\n#include \"json.hh\"\n\n#include \n\n#include \n\nnamespace nix {\n\nBinaryCacheStore::BinaryCacheStore(const Params & params)\n : Store(params)\n{\n if (secretKeyFile != \"\")\n secretKey = std::unique_ptr(new SecretKey(readFile(secretKeyFile)));\n\n StringSink sink;\n sink << narVersionMagic1;\n narMagic = *sink.s;\n}\n\nvoid BinaryCacheStore::init()\n{\n std::string cacheInfoFile = \"nix-cache-info\";\n\n auto cacheInfo = getFile(cacheInfoFile);\n if (!cacheInfo) {\n upsertFile(cacheInfoFile, \"StoreDir: \" + storeDir + \"\\n\", \"text\/x-nix-cache-info\");\n } else {\n for (auto & line : tokenizeString(*cacheInfo, \"\\n\")) {\n size_t colon = line.find(':');\n if (colon == std::string::npos) continue;\n auto name = line.substr(0, colon);\n auto value = trim(line.substr(colon + 1, std::string::npos));\n if (name == \"StoreDir\") {\n if (value != storeDir)\n throw Error(format(\"binary cache '%s' is for Nix stores with prefix '%s', not '%s'\")\n % getUri() % value % storeDir);\n } else if (name == \"WantMassQuery\") {\n wantMassQuery_ = value == \"1\";\n } else if (name == \"Priority\") {\n string2Int(value, priority);\n }\n }\n }\n}\n\nvoid BinaryCacheStore::getFile(const std::string & path,\n Callback> callback)\n{\n try {\n callback(getFile(path));\n } catch (...) { callback.rethrow(); }\n}\n\nvoid BinaryCacheStore::getFile(const std::string & path, Sink & sink)\n{\n std::promise> promise;\n getFile(path,\n {[&](std::future> result) {\n try {\n promise.set_value(result.get());\n } catch (...) {\n promise.set_exception(std::current_exception());\n }\n }});\n auto data = promise.get_future().get();\n sink((unsigned char *) data->data(), data->size());\n}\n\nstd::shared_ptr BinaryCacheStore::getFile(const std::string & path)\n{\n StringSink sink;\n try {\n getFile(path, sink);\n } catch (NoSuchBinaryCacheFile &) {\n return nullptr;\n }\n return sink.s;\n}\n\nPath BinaryCacheStore::narInfoFileFor(const Path & storePath)\n{\n assertStorePath(storePath);\n return storePathToHash(storePath) + \".narinfo\";\n}\n\nvoid BinaryCacheStore::writeNarInfo(ref narInfo)\n{\n auto narInfoFile = narInfoFileFor(narInfo->path);\n\n upsertFile(narInfoFile, narInfo->to_string(), \"text\/x-nix-narinfo\");\n\n auto hashPart = storePathToHash(narInfo->path);\n\n {\n auto state_(state.lock());\n state_->pathInfoCache.upsert(hashPart, std::shared_ptr(narInfo));\n }\n\n if (diskCache)\n diskCache->upsertNarInfo(getUri(), hashPart, std::shared_ptr(narInfo));\n}\n\nvoid BinaryCacheStore::addToStore(const ValidPathInfo & info, const ref & nar,\n RepairFlag repair, CheckSigsFlag checkSigs, std::shared_ptr accessor)\n{\n if (!repair && isValidPath(info.path)) return;\n\n \/* Verify that all references are valid. This may do some .narinfo\n reads, but typically they'll already be cached. *\/\n for (auto & ref : info.references)\n try {\n if (ref != info.path)\n queryPathInfo(ref);\n } catch (InvalidPath &) {\n throw Error(format(\"cannot add '%s' to the binary cache because the reference '%s' is not valid\")\n % info.path % ref);\n }\n\n assert(nar->compare(0, narMagic.size(), narMagic) == 0);\n\n auto narInfo = make_ref(info);\n\n narInfo->narSize = nar->size();\n narInfo->narHash = hashString(htSHA256, *nar);\n\n if (info.narHash && info.narHash != narInfo->narHash)\n throw Error(format(\"refusing to copy corrupted path '%1%' to binary cache\") % info.path);\n\n auto accessor_ = std::dynamic_pointer_cast(accessor);\n\n \/* Optionally write a JSON file containing a listing of the\n contents of the NAR. *\/\n if (writeNARListing) {\n std::ostringstream jsonOut;\n\n {\n JSONObject jsonRoot(jsonOut);\n jsonRoot.attr(\"version\", 1);\n\n auto narAccessor = makeNarAccessor(nar);\n\n if (accessor_)\n accessor_->addToCache(info.path, *nar, narAccessor);\n\n {\n auto res = jsonRoot.placeholder(\"root\");\n listNar(res, narAccessor, \"\", true);\n }\n }\n\n upsertFile(storePathToHash(info.path) + \".ls\", jsonOut.str(), \"application\/json\");\n }\n\n else {\n if (accessor_)\n accessor_->addToCache(info.path, *nar, makeNarAccessor(nar));\n }\n\n \/* Compress the NAR. *\/\n narInfo->compression = compression;\n auto now1 = std::chrono::steady_clock::now();\n auto narCompressed = compress(compression, *nar, parallelCompression);\n auto now2 = std::chrono::steady_clock::now();\n narInfo->fileHash = hashString(htSHA256, *narCompressed);\n narInfo->fileSize = narCompressed->size();\n\n auto duration = std::chrono::duration_cast(now2 - now1).count();\n printMsg(lvlTalkative, format(\"copying path '%1%' (%2% bytes, compressed %3$.1f%% in %4% ms) to binary cache\")\n % narInfo->path % narInfo->narSize\n % ((1.0 - (double) narCompressed->size() \/ nar->size()) * 100.0)\n % duration);\n\n \/* Atomically write the NAR file. *\/\n narInfo->url = \"nar\/\" + narInfo->fileHash.to_string(Base32, false) + \".nar\"\n + (compression == \"xz\" ? \".xz\" :\n compression == \"bzip2\" ? \".bz2\" :\n compression == \"br\" ? \".br\" :\n \"\");\n if (repair || !fileExists(narInfo->url)) {\n stats.narWrite++;\n upsertFile(narInfo->url, *narCompressed, \"application\/x-nix-nar\");\n } else\n stats.narWriteAverted++;\n\n stats.narWriteBytes += nar->size();\n stats.narWriteCompressedBytes += narCompressed->size();\n stats.narWriteCompressionTimeMs += duration;\n\n \/* Atomically write the NAR info file.*\/\n if (secretKey) narInfo->sign(*secretKey);\n\n writeNarInfo(narInfo);\n\n stats.narInfoWrite++;\n}\n\nbool BinaryCacheStore::isValidPathUncached(const Path & storePath)\n{\n \/\/ FIXME: this only checks whether a .narinfo with a matching hash\n \/\/ part exists. So ‘f4kb...-foo’ matches ‘f4kb...-bar’, even\n \/\/ though they shouldn't. Not easily fixed.\n return fileExists(narInfoFileFor(storePath));\n}\n\nvoid BinaryCacheStore::narFromPath(const Path & storePath, Sink & sink)\n{\n auto info = queryPathInfo(storePath).cast();\n\n uint64_t narSize = 0;\n\n LambdaSink wrapperSink([&](const unsigned char * data, size_t len) {\n sink(data, len);\n narSize += len;\n });\n\n auto decompressor = makeDecompressionSink(info->compression, wrapperSink);\n\n try {\n getFile(info->url, *decompressor);\n } catch (NoSuchBinaryCacheFile & e) {\n throw SubstituteGone(e.what());\n }\n\n decompressor->finish();\n\n stats.narRead++;\n \/\/stats.narReadCompressedBytes += nar->size(); \/\/ FIXME\n stats.narReadBytes += narSize;\n}\n\nvoid BinaryCacheStore::queryPathInfoUncached(const Path & storePath,\n Callback> callback)\n{\n auto uri = getUri();\n auto act = std::make_shared(*logger, lvlTalkative, actQueryPathInfo,\n fmt(\"querying info about '%s' on '%s'\", storePath, uri), Logger::Fields{storePath, uri});\n PushActivity pact(act->id);\n\n auto narInfoFile = narInfoFileFor(storePath);\n\n getFile(narInfoFile,\n {[=](std::future> fut) {\n try {\n auto data = fut.get();\n\n if (!data) return callback(nullptr);\n\n stats.narInfoRead++;\n\n callback((std::shared_ptr)\n std::make_shared(*this, *data, narInfoFile));\n\n (void) act; \/\/ force Activity into this lambda to ensure it stays alive\n } catch (...) {\n callback.rethrow();\n }\n }});\n}\n\nPath BinaryCacheStore::addToStore(const string & name, const Path & srcPath,\n bool recursive, HashType hashAlgo, PathFilter & filter, RepairFlag repair)\n{\n \/\/ FIXME: some cut&paste from LocalStore::addToStore().\n\n \/* Read the whole path into memory. This is not a very scalable\n method for very large paths, but `copyPath' is mainly used for\n small files. *\/\n StringSink sink;\n Hash h;\n if (recursive) {\n dumpPath(srcPath, sink, filter);\n h = hashString(hashAlgo, *sink.s);\n } else {\n auto s = readFile(srcPath);\n dumpString(s, sink);\n h = hashString(hashAlgo, s);\n }\n\n ValidPathInfo info;\n info.path = makeFixedOutputPath(recursive, h, name);\n\n addToStore(info, sink.s, repair, CheckSigs, nullptr);\n\n return info.path;\n}\n\nPath BinaryCacheStore::addTextToStore(const string & name, const string & s,\n const PathSet & references, RepairFlag repair)\n{\n ValidPathInfo info;\n info.path = computeStorePathForText(name, s, references);\n info.references = references;\n\n if (repair || !isValidPath(info.path)) {\n StringSink sink;\n dumpString(s, sink);\n addToStore(info, sink.s, repair, CheckSigs, nullptr);\n }\n\n return info.path;\n}\n\nref BinaryCacheStore::getFSAccessor()\n{\n return make_ref(ref(shared_from_this()), localNarCache);\n}\n\nvoid BinaryCacheStore::addSignatures(const Path & storePath, const StringSet & sigs)\n{\n \/* Note: this is inherently racy since there is no locking on\n binary caches. In particular, with S3 this unreliable, even\n when addSignatures() is called sequentially on a path, because\n S3 might return an outdated cached version. *\/\n\n auto narInfo = make_ref((NarInfo &) *queryPathInfo(storePath));\n\n narInfo->sigs.insert(sigs.begin(), sigs.end());\n\n auto narInfoFile = narInfoFileFor(narInfo->path);\n\n writeNarInfo(narInfo);\n}\n\nstd::shared_ptr BinaryCacheStore::getBuildLog(const Path & path)\n{\n Path drvPath;\n\n if (isDerivation(path))\n drvPath = path;\n else {\n try {\n auto info = queryPathInfo(path);\n \/\/ FIXME: add a \"Log\" field to .narinfo\n if (info->deriver == \"\") return nullptr;\n drvPath = info->deriver;\n } catch (InvalidPath &) {\n return nullptr;\n }\n }\n\n auto logPath = \"log\/\" + baseNameOf(drvPath);\n\n debug(\"fetching build log from binary cache '%s\/%s'\", getUri(), logPath);\n\n return getFile(logPath);\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: unmovss.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ka $ $Date: 2001-10-22 13:36: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#pragma hdrstop\n\n#include \"unmovss.hxx\"\n#include \"docshell.hxx\"\n#include \"drawdoc.hxx\"\n#include \"stlsheet.hxx\"\n\n\nTYPEINIT1(SdMoveStyleSheetsUndoAction, SdUndoAction);\n\n\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nSdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction(\n SdDrawDocument* pTheDoc,\n List* pTheStyles,\n BOOL bInserted):\n SdUndoAction(pTheDoc)\n{\n DBG_ASSERT(pTheStyles, \"keine Liste gesetzt!\");\n pStyles = pTheStyles;\n bMySheets = !bInserted;\n\n pListOfChildLists = new List;\n\n \/\/ Liste mit den Listen der StyleSheet-Kinder erstellen\n for (SdStyleSheet* pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n List* pChildList = pSheet->CreateChildList();\n pListOfChildLists->Insert(pChildList, LIST_APPEND);\n }\n}\n\n\/*************************************************************************\n|*\n|* Undo()\n|*\n\\************************************************************************\/\n\nvoid SdMoveStyleSheetsUndoAction::Undo()\n{\n SfxStyleSheetBasePool* pPool = pDoc->GetStyleSheetPool();\n SdStyleSheet* pSheet = NULL;\n\n \/********************************************************************\n |* die StyleSheets sollen wieder in den Pool eingefuegt werden\n \\*******************************************************************\/\n if (bMySheets)\n {\n \/****************************************************************\n |* erst alle StyleSheets wieder in den Pool einfuegen\n \\***************************************************************\/\n for (pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n pPool->Insert(pSheet);\n }\n\n \/****************************************************************\n |* jetzt die ehemaligen Kinder wieder zu Kindern machen\n \\***************************************************************\/\n List* pChildList = (List*)pListOfChildLists->First();\n for (pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n String aParent(pSheet->GetName());\n for (SfxStyleSheet* pChild = (SfxStyleSheet*)pChildList->First();\n pChild;\n pChild = (SfxStyleSheet*)pChildList->Next())\n {\n pChild->SetParent(aParent);\n }\n pChildList = (List*)pListOfChildLists->Next();\n }\n }\n \/********************************************************************\n |* die StyleSheets sollen wieder aus dem, Pool entfernt werden\n \\*******************************************************************\/\n else\n {\n for (pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n pPool->Remove(pSheet);\n }\n }\n bMySheets = !bMySheets;\n}\n\n\/*************************************************************************\n|*\n|* Redo()\n|*\n\\************************************************************************\/\n\nvoid SdMoveStyleSheetsUndoAction::Redo()\n{\n Undo();\n}\n\n\/*************************************************************************\n|*\n|* Repeat()\n|*\n\\************************************************************************\/\n\nvoid SdMoveStyleSheetsUndoAction::Repeat()\n{\n DBG_ASSERT(FALSE, \"SdMoveStyleSheetsUndoAction::Repeat: nicht implementiert\");\n}\n\n\/*************************************************************************\n|*\n|* Destruktor, Liste loeschen; ggfs. die enthaltenen StyleSheets loeschen\n|*\n\\************************************************************************\/\n\nSdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction()\n{\n if (bMySheets)\n {\n \/\/ die Liste rueckwaerts aufdroeseln; wenn Gliederungsvorlagen ent-\n \/\/ halten sind gewaehrleistet dies den geringsten Broadcasting-Aufwand\n SfxStyleSheet* pSheet = (SfxStyleSheet*)pStyles->Last();\n while (pSheet)\n {\n delete pSheet;\n pSheet = (SfxStyleSheet*)pStyles->Prev();\n }\n }\n delete pStyles;\n\n for (List* pChildList = (List*)pListOfChildLists->First();\n pChildList;\n pChildList = (List*)pListOfChildLists->Next())\n {\n delete pChildList;\n }\n delete pListOfChildLists;\n}\n\n\/*************************************************************************\n|*\n|* Kommentar liefern\n|*\n\\************************************************************************\/\n\nString SdMoveStyleSheetsUndoAction::GetComment() const\n{\n return String();\n}\n\n\nINTEGRATION: CWS impress1 (1.2.238); FILE MERGED 2003\/09\/17 09:06:20 af 1.2.238.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.\/*************************************************************************\n *\n * $RCSfile: unmovss.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 11:25:30 $\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#pragma hdrstop\n\n#include \"unmovss.hxx\"\n#include \"DrawDocShell.hxx\"\n#include \"drawdoc.hxx\"\n#include \"stlsheet.hxx\"\n\n\nTYPEINIT1(SdMoveStyleSheetsUndoAction, SdUndoAction);\n\n\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nSdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction(\n SdDrawDocument* pTheDoc,\n List* pTheStyles,\n BOOL bInserted):\n SdUndoAction(pTheDoc)\n{\n DBG_ASSERT(pTheStyles, \"keine Liste gesetzt!\");\n pStyles = pTheStyles;\n bMySheets = !bInserted;\n\n pListOfChildLists = new List;\n\n \/\/ Liste mit den Listen der StyleSheet-Kinder erstellen\n for (SdStyleSheet* pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n List* pChildList = pSheet->CreateChildList();\n pListOfChildLists->Insert(pChildList, LIST_APPEND);\n }\n}\n\n\/*************************************************************************\n|*\n|* Undo()\n|*\n\\************************************************************************\/\n\nvoid SdMoveStyleSheetsUndoAction::Undo()\n{\n SfxStyleSheetBasePool* pPool = pDoc->GetStyleSheetPool();\n SdStyleSheet* pSheet = NULL;\n\n \/********************************************************************\n |* die StyleSheets sollen wieder in den Pool eingefuegt werden\n \\*******************************************************************\/\n if (bMySheets)\n {\n \/****************************************************************\n |* erst alle StyleSheets wieder in den Pool einfuegen\n \\***************************************************************\/\n for (pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n pPool->Insert(pSheet);\n }\n\n \/****************************************************************\n |* jetzt die ehemaligen Kinder wieder zu Kindern machen\n \\***************************************************************\/\n List* pChildList = (List*)pListOfChildLists->First();\n for (pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n String aParent(pSheet->GetName());\n for (SfxStyleSheet* pChild = (SfxStyleSheet*)pChildList->First();\n pChild;\n pChild = (SfxStyleSheet*)pChildList->Next())\n {\n pChild->SetParent(aParent);\n }\n pChildList = (List*)pListOfChildLists->Next();\n }\n }\n \/********************************************************************\n |* die StyleSheets sollen wieder aus dem, Pool entfernt werden\n \\*******************************************************************\/\n else\n {\n for (pSheet = (SdStyleSheet*)pStyles->First();\n pSheet;\n pSheet = (SdStyleSheet*)pStyles->Next())\n {\n pPool->Remove(pSheet);\n }\n }\n bMySheets = !bMySheets;\n}\n\n\/*************************************************************************\n|*\n|* Redo()\n|*\n\\************************************************************************\/\n\nvoid SdMoveStyleSheetsUndoAction::Redo()\n{\n Undo();\n}\n\n\/*************************************************************************\n|*\n|* Repeat()\n|*\n\\************************************************************************\/\n\nvoid SdMoveStyleSheetsUndoAction::Repeat()\n{\n DBG_ASSERT(FALSE, \"SdMoveStyleSheetsUndoAction::Repeat: nicht implementiert\");\n}\n\n\/*************************************************************************\n|*\n|* Destruktor, Liste loeschen; ggfs. die enthaltenen StyleSheets loeschen\n|*\n\\************************************************************************\/\n\nSdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction()\n{\n if (bMySheets)\n {\n \/\/ die Liste rueckwaerts aufdroeseln; wenn Gliederungsvorlagen ent-\n \/\/ halten sind gewaehrleistet dies den geringsten Broadcasting-Aufwand\n SfxStyleSheet* pSheet = (SfxStyleSheet*)pStyles->Last();\n while (pSheet)\n {\n delete pSheet;\n pSheet = (SfxStyleSheet*)pStyles->Prev();\n }\n }\n delete pStyles;\n\n for (List* pChildList = (List*)pListOfChildLists->First();\n pChildList;\n pChildList = (List*)pListOfChildLists->Next())\n {\n delete pChildList;\n }\n delete pListOfChildLists;\n}\n\n\/*************************************************************************\n|*\n|* Kommentar liefern\n|*\n\\************************************************************************\/\n\nString SdMoveStyleSheetsUndoAction::GetComment() const\n{\n return String();\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: unmodpg.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: ka $ $Date: 2001-10-22 13:36:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVDLAYER\n#include \n#endif\n#ifndef _SFXDISPATCH_HXX\n#include \n#endif\n#ifndef _SFXVIEWFRM_HXX\n#include \n#endif\n\n#pragma hdrstop\n\n#include \"strings.hrc\"\n#include \"glob.hrc\" \/\/ STR_BCKGRND, STR_BCKGRNDOBJ\n#include \"app.hrc\" \/\/ SID_SWITCHPAGE\n\n#include \"unmodpg.hxx\"\n#include \"sdpage.hxx\"\n#include \"sdresid.hxx\"\n#include \"drawdoc.hxx\"\n\n\nTYPEINIT1(ModifyPageUndoAction, SdUndoAction);\n\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nModifyPageUndoAction::ModifyPageUndoAction(\n SfxUndoManager* pTheManager, \/\/ #67720#\n SdDrawDocument* pTheDoc,\n SdPage* pThePage,\n String aTheNewName,\n AutoLayout eTheNewAutoLayout,\n BOOL bTheNewBckgrndVisible,\n BOOL bTheNewBckgrndObjsVisible)\n: SdUndoAction(pTheDoc),\n mpManager(pTheManager)\n{\n DBG_ASSERT(pThePage, \"Undo ohne Seite ???\");\n\n pPage = pThePage;\n aNewName = aTheNewName;\n eNewAutoLayout = eTheNewAutoLayout;\n bNewBckgrndVisible = bTheNewBckgrndVisible;\n bNewBckgrndObjsVisible = bTheNewBckgrndObjsVisible;\n\n eOldAutoLayout = pPage->GetAutoLayout();\n\n if (!pPage->IsMasterPage())\n {\n aOldName = pPage->GetName();\n SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n USHORT nPos = 0;\n SetOfByte aVisibleLayers = pPage->GetMasterPageVisibleLayers(nPos);\n\n bOldBckgrndVisible = aVisibleLayers.IsSet(aBckgrnd);\n bOldBckgrndObjsVisible = aVisibleLayers.IsSet(aBckgrndObj);\n }\n\n aComment = String(SdResId(STR_UNDO_MODIFY_PAGE));\n}\n\n\/*************************************************************************\n|*\n|* Undo()\n|*\n\\************************************************************************\/\n\nvoid ModifyPageUndoAction::Undo()\n{\n pPage->SetAutoLayout(eOldAutoLayout, TRUE);\n\n if (!pPage->IsMasterPage())\n {\n if (pPage->GetName() != aOldName)\n {\n pPage->SetName(aOldName);\n\n if (pPage->GetPageKind() == PK_STANDARD)\n {\n SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);\n pNotesPage->SetName(aOldName);\n }\n }\n\n SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n USHORT nPos = 0;\n SetOfByte aVisibleLayers;\n aVisibleLayers.Set(aBckgrnd, bOldBckgrndVisible);\n aVisibleLayers.Set(aBckgrndObj, bOldBckgrndObjsVisible);\n\n nPos = 0;\n pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);\n }\n\n \/\/ Redisplay\n SfxViewFrame::Current()->GetDispatcher()->Execute(\n SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );\n\n \/\/ #67720# clear undo manager\n if(mpManager)\n {\n \/\/ BEWARE: Do this as LAST action here since this will delete\n \/\/ all actions which are added, inclusive to this one (!)\n mpManager->Clear();\n }\n}\n\n\/*************************************************************************\n|*\n|* Redo()\n|*\n\\************************************************************************\/\n\nvoid ModifyPageUndoAction::Redo()\n{\n pPage->SetAutoLayout(eNewAutoLayout, TRUE);\n\n if (!pPage->IsMasterPage())\n {\n if (pPage->GetName() != aNewName)\n {\n pPage->SetName(aNewName);\n\n if (pPage->GetPageKind() == PK_STANDARD)\n {\n SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);\n pNotesPage->SetName(aNewName);\n }\n }\n\n SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n USHORT nPos = 0;\n SetOfByte aVisibleLayers;\n aVisibleLayers.Set(aBckgrnd, bNewBckgrndVisible);\n aVisibleLayers.Set(aBckgrndObj, bNewBckgrndObjsVisible);\n\n nPos = 0;\n pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);\n }\n\n \/\/ Redisplay\n SfxViewFrame::Current()->GetDispatcher()->Execute(\n SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );\n\n \/\/ #67720# clear undo manager\n if(mpManager)\n {\n \/\/ BEWARE: Do this as LAST action here since this will delete\n \/\/ all actions which are added, inclusive to this one (!)\n mpManager->Clear();\n }\n}\n\n\/*************************************************************************\n|*\n|* Repeat()\n|*\n\\************************************************************************\/\n\nvoid ModifyPageUndoAction::Repeat()\n{\n DBG_ASSERT(FALSE, \"ModifyPageUndoAction::Repeat: nicht implementiert\");\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nModifyPageUndoAction::~ModifyPageUndoAction()\n{\n}\n\n\/*************************************************************************\n|*\n|* Kommentar liefern\n|*\n\\************************************************************************\/\n\nString ModifyPageUndoAction::GetComment() const\n{\n return aComment;\n}\n\n\n#94637# invalidate Selection, there could be objects deleted in tis UNDO which are no longer allowed to be selected then.\/*************************************************************************\n *\n * $RCSfile: unmodpg.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: aw $ $Date: 2001-11-13 18:11: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 _SVDLAYER\n#include \n#endif\n#ifndef _SFXDISPATCH_HXX\n#include \n#endif\n#ifndef _SFXVIEWFRM_HXX\n#include \n#endif\n\n#pragma hdrstop\n\n#include \"strings.hrc\"\n#include \"glob.hrc\" \/\/ STR_BCKGRND, STR_BCKGRNDOBJ\n#include \"app.hrc\" \/\/ SID_SWITCHPAGE\n\n#include \"unmodpg.hxx\"\n#include \"sdpage.hxx\"\n#include \"sdresid.hxx\"\n#include \"drawdoc.hxx\"\n\n\nTYPEINIT1(ModifyPageUndoAction, SdUndoAction);\n\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nModifyPageUndoAction::ModifyPageUndoAction(\n SfxUndoManager* pTheManager, \/\/ #67720#\n SdDrawDocument* pTheDoc,\n SdPage* pThePage,\n String aTheNewName,\n AutoLayout eTheNewAutoLayout,\n BOOL bTheNewBckgrndVisible,\n BOOL bTheNewBckgrndObjsVisible)\n: SdUndoAction(pTheDoc),\n mpManager(pTheManager)\n{\n DBG_ASSERT(pThePage, \"Undo ohne Seite ???\");\n\n pPage = pThePage;\n aNewName = aTheNewName;\n eNewAutoLayout = eTheNewAutoLayout;\n bNewBckgrndVisible = bTheNewBckgrndVisible;\n bNewBckgrndObjsVisible = bTheNewBckgrndObjsVisible;\n\n eOldAutoLayout = pPage->GetAutoLayout();\n\n if (!pPage->IsMasterPage())\n {\n aOldName = pPage->GetName();\n SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n USHORT nPos = 0;\n SetOfByte aVisibleLayers = pPage->GetMasterPageVisibleLayers(nPos);\n\n bOldBckgrndVisible = aVisibleLayers.IsSet(aBckgrnd);\n bOldBckgrndObjsVisible = aVisibleLayers.IsSet(aBckgrndObj);\n }\n\n aComment = String(SdResId(STR_UNDO_MODIFY_PAGE));\n}\n\n\/*************************************************************************\n|*\n|* Undo()\n|*\n\\************************************************************************\/\n\n#ifndef _SVDVITER_HXX\n#include \n#endif\n#ifndef _SVDVIEW_HXX\n#include \n#endif\nvoid ModifyPageUndoAction::Undo()\n{\n \/\/ #94637# invalidate Selection, there could be objects deleted in tis UNDO\n \/\/ which are no longer allowed to be selected then.\n SdrViewIter aIter(pPage);\n SdrView* pView = aIter.FirstView();\n\n while(pView)\n {\n if(pView->HasMarked())\n pView->UnmarkAll();\n pView = aIter.NextView();\n }\n\n pPage->SetAutoLayout(eOldAutoLayout, TRUE);\n\n if (!pPage->IsMasterPage())\n {\n if (pPage->GetName() != aOldName)\n {\n pPage->SetName(aOldName);\n\n if (pPage->GetPageKind() == PK_STANDARD)\n {\n SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);\n pNotesPage->SetName(aOldName);\n }\n }\n\n SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n USHORT nPos = 0;\n SetOfByte aVisibleLayers;\n aVisibleLayers.Set(aBckgrnd, bOldBckgrndVisible);\n aVisibleLayers.Set(aBckgrndObj, bOldBckgrndObjsVisible);\n\n nPos = 0;\n pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);\n }\n\n \/\/ Redisplay\n SfxViewFrame::Current()->GetDispatcher()->Execute(\n SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );\n\n \/\/ #67720# clear undo manager\n if(mpManager)\n {\n \/\/ BEWARE: Do this as LAST action here since this will delete\n \/\/ all actions which are added, inclusive to this one (!)\n mpManager->Clear();\n }\n}\n\n\/*************************************************************************\n|*\n|* Redo()\n|*\n\\************************************************************************\/\n\nvoid ModifyPageUndoAction::Redo()\n{\n \/\/ #94637# invalidate Selection, there could be objects deleted in tis UNDO\n \/\/ which are no longer allowed to be selected then.\n SdrViewIter aIter(pPage);\n SdrView* pView = aIter.FirstView();\n\n while(pView)\n {\n if(pView->HasMarked())\n pView->UnmarkAll();\n pView = aIter.NextView();\n }\n\n pPage->SetAutoLayout(eNewAutoLayout, TRUE);\n\n if (!pPage->IsMasterPage())\n {\n if (pPage->GetName() != aNewName)\n {\n pPage->SetName(aNewName);\n\n if (pPage->GetPageKind() == PK_STANDARD)\n {\n SdPage* pNotesPage = (SdPage*)pDoc->GetPage(pPage->GetPageNum() + 1);\n pNotesPage->SetName(aNewName);\n }\n }\n\n SdrLayerAdmin& rLayerAdmin = pDoc->GetLayerAdmin();\n BYTE aBckgrnd = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRND)), FALSE);\n BYTE aBckgrndObj = rLayerAdmin.GetLayerID(String(SdResId(STR_LAYER_BCKGRNDOBJ)), FALSE);\n USHORT nPos = 0;\n SetOfByte aVisibleLayers;\n aVisibleLayers.Set(aBckgrnd, bNewBckgrndVisible);\n aVisibleLayers.Set(aBckgrndObj, bNewBckgrndObjsVisible);\n\n nPos = 0;\n pPage->SetMasterPageVisibleLayers(aVisibleLayers, nPos);\n }\n\n \/\/ Redisplay\n SfxViewFrame::Current()->GetDispatcher()->Execute(\n SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD );\n\n \/\/ #67720# clear undo manager\n if(mpManager)\n {\n \/\/ BEWARE: Do this as LAST action here since this will delete\n \/\/ all actions which are added, inclusive to this one (!)\n mpManager->Clear();\n }\n}\n\n\/*************************************************************************\n|*\n|* Repeat()\n|*\n\\************************************************************************\/\n\nvoid ModifyPageUndoAction::Repeat()\n{\n DBG_ASSERT(FALSE, \"ModifyPageUndoAction::Repeat: nicht implementiert\");\n}\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nModifyPageUndoAction::~ModifyPageUndoAction()\n{\n}\n\n\/*************************************************************************\n|*\n|* Kommentar liefern\n|*\n\\************************************************************************\/\n\nString ModifyPageUndoAction::GetComment() const\n{\n return aComment;\n}\n\n\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"PositionTracker.h\"\n\n\/* implementation system headers *\/\n#include \n#include \n\n\/* implementation common headers *\/\n#include \"MathUtils.h\"\n\n\n\/* private *\/\n\n\/* protected *\/\n\n\/* public: *\/\n\nPositionTracker::PositionTracker()\n{\n return;\n}\nPositionTracker::PositionTracker(const PositionTracker& tracker)\n : _trackedItem(tracker._trackedItem),\n _waypointDistance(tracker._waypointDistance)\n{\n return;\n}\nPositionTracker::~PositionTracker()\n{\n \/\/ clear out all the tracked items vectors\n for (std::map::iterator jano = _trackedItem.begin(); jano != _trackedItem.end(); jano++) {\n TrackedItemVector& trackSet = (*jano).second;\n for (unsigned int i = 0; i != trackSet.size(); i++) {\n \/* sanity clear *\/\n trackSet[i]->id = UNSET_ID;\n trackSet[i]->intID = 0;\n trackSet[i]->strID = std::string(\"\");\n trackSet[i]->lastUpdate = TimeKeeper::getNullTime();\n trackSet[i]->position[0] = trackSet[i]->position[1] = trackSet[i]->position[2] = 0.0;\n trackSet[i]->forgotten = true;\n delete trackSet[i];\n }\n }\n _trackedItem.clear();\n\n \/\/ clear out any waypoints\n _waypointDistance.clear();\n\n return;\n}\n\n\n\/* Linear O(n) time to track a new item since the entire vector is\n * searched. if the item is not found, an item is created and added.\n *\/\nunsigned short PositionTracker::track(const std::string id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n for (unsigned int i = 0; i != trackSet.size(); i++) {\n switch (trackSet[i]->id) {\n case STR_ID:\n\tif (id == trackSet[i]->strID) {\n\t return i;\n\t}\n\tbreak;\n case INT_ID:\n case UNSET_ID:\n\tbreak;\n default:\n\tstd::cerr << \"Unknown tracker ID type (id == \" << trackSet[i]->id << \")\" << std::endl;\n\tbreak;\n }\n }\n\n \/\/ the item was not found, so create it\n item_t *newTracking = new item_t;\n newTracking->id = STR_ID;\n newTracking->intID = 0;\n newTracking->strID = id;\n newTracking->lastUpdate = TimeKeeper::getNullTime();\n newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;\n newTracking->forgotten = false;\n\n \/\/ and add it\n trackSet.push_back(newTracking);\n\n \/\/ nothing is deleted so should be last index\n return trackSet.size() - 1;\n}\n\n\n\/* alternative track() passing our own id *\/\nunsigned short PositionTracker::track(long int id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n for (unsigned int i = 0; i != trackSet.size(); i++) {\n switch (trackSet[i]->id) {\n case INT_ID:\n\tif (id == trackSet[i]->intID) {\n\t return i;\n\t}\n\tbreak;\n case STR_ID:\n case UNSET_ID:\n\tbreak;\n default:\n\tstd::cerr << \"Unknown tracker ID type (id == \" << trackSet[i]->id << \")\" << std::endl;\n\tbreak;\n }\n }\n\n \/\/ the item was not found, so create it\n item_t *newTracking = new item_t;\n newTracking->id = INT_ID;\n newTracking->intID = id;\n newTracking->strID = std::string(\"\");\n newTracking->lastUpdate = TimeKeeper::getNullTime();\n newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;\n newTracking->forgotten = false;\n\n \/\/ and add it\n trackSet.push_back(newTracking);\n\n \/\/ nothing is deleted so should be last index\n return trackSet.size() - 1;\n}\n\n\nbool PositionTracker::update(unsigned short int token, const std::string id, const double position[3], std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) || \n (trackSet[token]->id != STR_ID) || \n (trackSet[token]->strID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = position[0];\n trackSet[token]->position[1] = position[1];\n trackSet[token]->position[2] = position[2];\n trackSet[token]->lastUpdate = TimeKeeper::getCurrent();\n\n return true;\n}\nbool PositionTracker::update(unsigned short int token, const std::string id, const float position[3], std::string group)\n{\n double pos[3];\n pos[0] = (double)position[0];\n pos[1] = (double)position[1];\n pos[2] = (double)position[2];\n return update(token, id, pos, group);\n}\nbool PositionTracker::update(unsigned short int token, long int id, const double position[3], std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) ||\n (trackSet[token]->id != INT_ID) ||\n (trackSet[token]->intID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = position[0];\n trackSet[token]->position[1] = position[1];\n trackSet[token]->position[2] = position[2];\n trackSet[token]->lastUpdate = TimeKeeper::getCurrent();\n\n return true;\n}\nbool PositionTracker::update(unsigned short int token, long int id, const float position[3], std::string group)\n{\n double pos[3];\n pos[0] = (double)position[0];\n pos[1] = (double)position[1];\n pos[2] = (double)position[2];\n return update(token, id, pos, group);\n}\n\n\nbool PositionTracker::addWaypoint(const double from[3], const double to[3], double distance)\n{\n unsigned short int fromToken, toToken;\n bool updated;\n bool foundPoint;\n\n TrackedItemVector& waypointSet = _trackedItem[std::string(\"__waypoint__\")];\n\n \/\/ see if the first point already exists\n foundPoint = false;\n for (unsigned int i = 0; i != waypointSet.size(); i++) {\n if ((waypointSet[i]->position[0] = from[0]) &&\n\t(waypointSet[i]->position[1] = from[1]) &&\n\t(waypointSet[i]->position[2] = from[2])) {\n foundPoint = true;\n fromToken = waypointSet[i]->intID;\n }\n }\n if (!foundPoint) {\n \/\/ add the first point\n unsigned short int nextID = waypointSet.size();\n fromToken = track((long int)nextID, std::string(\"__waypoint__\"));\n updated = update(fromToken, nextID, from, std::string(\"__waypoint__\"));\n if (!updated) {\n std::cerr << \"Unable to add waypoint?!\" << std::endl;\n return false;\n }\n }\n\n \/\/ see if the second point already exists\n foundPoint = false;\n for (unsigned int i = 0; i != waypointSet.size(); i++) {\n if ((waypointSet[i]->position[0] = to[0]) &&\n\t(waypointSet[i]->position[1] = to[1]) &&\n\t(waypointSet[i]->position[2] = to[2])) {\n foundPoint = true;\n toToken = waypointSet[i]->intID;\n }\n }\n if (!foundPoint) {\n \/\/ add the second point\n unsigned short int nextID = waypointSet.size();\n toToken = track((long int)nextID, std::string(\"__waypoint__\"));\n updated = update(toToken, nextID, to, std::string(\"__waypoint__\"));\n if (!updated) {\n std::cerr << \"Unable to add waypoint?!\" << std::endl;\n return false;\n }\n }\n\n \/\/ compute and use real distance if distance passed was negative\n if (distance < 0.0) {\n distance = distanceBetween(fromToken, toToken, std::string(\"__waypoint__\"), std::string(\"__waypoint__\"));\n }\n std::pair waypoint = std::make_pair(fromToken, toToken);\n\n \/\/ see if the waypoint pair have already been added\n \/*\n std::map, double>::iterator jano = _waypointDistance.find(waypoint);\n if (jano != _waypointDistance.end()) {\n \/\/ waypoint already added, but set distance anyways (might be an update)\n (*jano).second = distance;\n }\n *\/\n _waypointDistance[waypoint] = distance;\n \n return true;\n}\nbool PositionTracker::addWaypoint(const float from[3], const float to[3], double distance)\n{\n double fromPos[3], toPos[3];\n fromPos[0] = from[0];\n fromPos[1] = from[1];\n fromPos[2] = from[2];\n toPos[0] = to[0];\n toPos[1] = to[1];\n toPos[2] = to[2];\n return addWaypoint(fromPos, toPos, distance);\n}\n\n\nbool PositionTracker::forget(unsigned short int token, const std::string id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) ||\n (trackSet[token]->id != STR_ID) ||\n (trackSet[token]->strID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;\n trackSet[token]->forgotten = true;\n\n return true;\n}\nbool PositionTracker::forget(unsigned short int token, long int id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) ||\n (trackSet[token]->id != INT_ID) ||\n (trackSet[token]->intID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;\n trackSet[token]->forgotten = true;\n\n return true;\n}\n\n\ndouble PositionTracker::distanceBetween(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const\n{\n \/\/ this indirection nastiness is needed to maintain constness\n std::map ::const_iterator fromIterator = _trackedItem.find(fromGroup);\n std::map ::const_iterator toIterator = _trackedItem.find(toGroup);\n const TrackedItemVector& fromSet = (*fromIterator).second;\n const TrackedItemVector& toSet = (*toIterator).second;\n\n if ((fromToken > fromSet.size()) ||\n (toToken > toSet.size()) ||\n (fromToken == toToken)) {\n return 0.0;\n }\n\n \/\/ basic Cartesian 3-space formula for distance between two points\n double distanceSquared = (((fromSet[fromToken]->position[0] - toSet[toToken]->position[0]) *\n\t\t\t (fromSet[fromToken]->position[0] - toSet[toToken]->position[0])) +\n\t\t\t ((fromSet[fromToken]->position[1] - toSet[toToken]->position[1]) *\n\t\t\t (fromSet[fromToken]->position[1] - toSet[toToken]->position[1])) +\n\t\t\t ((fromSet[fromToken]->position[2] - toSet[toToken]->position[2]) *\n\t\t\t (fromSet[fromToken]->position[2] - toSet[toToken]->position[2])));\n\n return math_util::fastsqrt((float)distanceSquared);\n}\n\n\ndouble PositionTracker::waypointDistance(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const\n{\n double separationDistance = distanceBetween(fromToken, toToken, fromGroup, toGroup);\n double shortestDistance = separationDistance;\n\n \/\/ horrible linear search\n std::map, double>::const_iterator waypointIterator;\n for (waypointIterator = _waypointDistance.begin(); waypointIterator != _waypointDistance.end(); waypointIterator++) {\n double fromDist, toDist, waypointDist;\n fromDist = distanceBetween(fromToken, (*waypointIterator).first.first, fromGroup, std::string(\"__waypoint__\"));\n toDist = distanceBetween((*waypointIterator).first.second, toToken, std::string(\"__waypoint__\"), toGroup);\n waypointDist = fromDist + (*waypointIterator).second + toDist;\n if (waypointDist < shortestDistance) {\n shortestDistance = waypointDist;\n }\n }\n\n return shortestDistance;\n}\n\n\nunsigned short int PositionTracker::trackedCount(std::string group) const\n{\n std::map ::const_iterator i = _trackedItem.find(group);\n const TrackedItemVector& trackSet = (*i).second;\n\n return trackSet.size();\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\nthe redefinition of i strikes again\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"PositionTracker.h\"\n\n\/* implementation system headers *\/\n#include \n#include \n\n\/* implementation common headers *\/\n#include \"MathUtils.h\"\n\n\n\/* private *\/\n\n\/* protected *\/\n\n\/* public: *\/\n\nPositionTracker::PositionTracker()\n{\n return;\n}\nPositionTracker::PositionTracker(const PositionTracker& tracker)\n : _trackedItem(tracker._trackedItem),\n _waypointDistance(tracker._waypointDistance)\n{\n return;\n}\nPositionTracker::~PositionTracker()\n{\n \/\/ clear out all the tracked items vectors\n for (std::map::iterator jano = _trackedItem.begin(); jano != _trackedItem.end(); jano++) {\n TrackedItemVector& trackSet = (*jano).second;\n for (unsigned int i = 0; i != trackSet.size(); i++) {\n \/* sanity clear *\/\n trackSet[i]->id = UNSET_ID;\n trackSet[i]->intID = 0;\n trackSet[i]->strID = std::string(\"\");\n trackSet[i]->lastUpdate = TimeKeeper::getNullTime();\n trackSet[i]->position[0] = trackSet[i]->position[1] = trackSet[i]->position[2] = 0.0;\n trackSet[i]->forgotten = true;\n delete trackSet[i];\n }\n }\n _trackedItem.clear();\n\n \/\/ clear out any waypoints\n _waypointDistance.clear();\n\n return;\n}\n\n\n\/* Linear O(n) time to track a new item since the entire vector is\n * searched. if the item is not found, an item is created and added.\n *\/\nunsigned short PositionTracker::track(const std::string id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n for (unsigned int i = 0; i != trackSet.size(); i++) {\n switch (trackSet[i]->id) {\n case STR_ID:\n\tif (id == trackSet[i]->strID) {\n\t return i;\n\t}\n\tbreak;\n case INT_ID:\n case UNSET_ID:\n\tbreak;\n default:\n\tstd::cerr << \"Unknown tracker ID type (id == \" << trackSet[i]->id << \")\" << std::endl;\n\tbreak;\n }\n }\n\n \/\/ the item was not found, so create it\n item_t *newTracking = new item_t;\n newTracking->id = STR_ID;\n newTracking->intID = 0;\n newTracking->strID = id;\n newTracking->lastUpdate = TimeKeeper::getNullTime();\n newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;\n newTracking->forgotten = false;\n\n \/\/ and add it\n trackSet.push_back(newTracking);\n\n \/\/ nothing is deleted so should be last index\n return trackSet.size() - 1;\n}\n\n\n\/* alternative track() passing our own id *\/\nunsigned short PositionTracker::track(long int id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n for (unsigned int i = 0; i != trackSet.size(); i++) {\n switch (trackSet[i]->id) {\n case INT_ID:\n\tif (id == trackSet[i]->intID) {\n\t return i;\n\t}\n\tbreak;\n case STR_ID:\n case UNSET_ID:\n\tbreak;\n default:\n\tstd::cerr << \"Unknown tracker ID type (id == \" << trackSet[i]->id << \")\" << std::endl;\n\tbreak;\n }\n }\n\n \/\/ the item was not found, so create it\n item_t *newTracking = new item_t;\n newTracking->id = INT_ID;\n newTracking->intID = id;\n newTracking->strID = std::string(\"\");\n newTracking->lastUpdate = TimeKeeper::getNullTime();\n newTracking->position[0] = newTracking->position[1] = newTracking->position[2] = 0.0;\n newTracking->forgotten = false;\n\n \/\/ and add it\n trackSet.push_back(newTracking);\n\n \/\/ nothing is deleted so should be last index\n return trackSet.size() - 1;\n}\n\n\nbool PositionTracker::update(unsigned short int token, const std::string id, const double position[3], std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) || \n (trackSet[token]->id != STR_ID) || \n (trackSet[token]->strID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = position[0];\n trackSet[token]->position[1] = position[1];\n trackSet[token]->position[2] = position[2];\n trackSet[token]->lastUpdate = TimeKeeper::getCurrent();\n\n return true;\n}\nbool PositionTracker::update(unsigned short int token, const std::string id, const float position[3], std::string group)\n{\n double pos[3];\n pos[0] = (double)position[0];\n pos[1] = (double)position[1];\n pos[2] = (double)position[2];\n return update(token, id, pos, group);\n}\nbool PositionTracker::update(unsigned short int token, long int id, const double position[3], std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) ||\n (trackSet[token]->id != INT_ID) ||\n (trackSet[token]->intID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = position[0];\n trackSet[token]->position[1] = position[1];\n trackSet[token]->position[2] = position[2];\n trackSet[token]->lastUpdate = TimeKeeper::getCurrent();\n\n return true;\n}\nbool PositionTracker::update(unsigned short int token, long int id, const float position[3], std::string group)\n{\n double pos[3];\n pos[0] = (double)position[0];\n pos[1] = (double)position[1];\n pos[2] = (double)position[2];\n return update(token, id, pos, group);\n}\n\n\nbool PositionTracker::addWaypoint(const double from[3], const double to[3], double distance)\n{\n unsigned short int fromToken, toToken;\n bool updated;\n bool foundPoint;\n unsigned int i;\n\n TrackedItemVector& waypointSet = _trackedItem[std::string(\"__waypoint__\")];\n\n \/\/ see if the first point already exists\n foundPoint = false;\n for (i = 0; i != waypointSet.size(); i++) {\n if ((waypointSet[i]->position[0] = from[0]) &&\n\t(waypointSet[i]->position[1] = from[1]) &&\n\t(waypointSet[i]->position[2] = from[2])) {\n foundPoint = true;\n fromToken = waypointSet[i]->intID;\n }\n }\n if (!foundPoint) {\n \/\/ add the first point\n unsigned short int nextID = waypointSet.size();\n fromToken = track((long int)nextID, std::string(\"__waypoint__\"));\n updated = update(fromToken, nextID, from, std::string(\"__waypoint__\"));\n if (!updated) {\n std::cerr << \"Unable to add waypoint?!\" << std::endl;\n return false;\n }\n }\n\n \/\/ see if the second point already exists\n foundPoint = false;\n for (i = 0; i != waypointSet.size(); i++) {\n if ((waypointSet[i]->position[0] = to[0]) &&\n\t(waypointSet[i]->position[1] = to[1]) &&\n\t(waypointSet[i]->position[2] = to[2])) {\n foundPoint = true;\n toToken = waypointSet[i]->intID;\n }\n }\n if (!foundPoint) {\n \/\/ add the second point\n unsigned short int nextID = waypointSet.size();\n toToken = track((long int)nextID, std::string(\"__waypoint__\"));\n updated = update(toToken, nextID, to, std::string(\"__waypoint__\"));\n if (!updated) {\n std::cerr << \"Unable to add waypoint?!\" << std::endl;\n return false;\n }\n }\n\n \/\/ compute and use real distance if distance passed was negative\n if (distance < 0.0) {\n distance = distanceBetween(fromToken, toToken, std::string(\"__waypoint__\"), std::string(\"__waypoint__\"));\n }\n std::pair waypoint = std::make_pair(fromToken, toToken);\n\n \/\/ see if the waypoint pair have already been added\n \/*\n std::map, double>::iterator jano = _waypointDistance.find(waypoint);\n if (jano != _waypointDistance.end()) {\n \/\/ waypoint already added, but set distance anyways (might be an update)\n (*jano).second = distance;\n }\n *\/\n _waypointDistance[waypoint] = distance;\n \n return true;\n}\nbool PositionTracker::addWaypoint(const float from[3], const float to[3], double distance)\n{\n double fromPos[3], toPos[3];\n fromPos[0] = from[0];\n fromPos[1] = from[1];\n fromPos[2] = from[2];\n toPos[0] = to[0];\n toPos[1] = to[1];\n toPos[2] = to[2];\n return addWaypoint(fromPos, toPos, distance);\n}\n\n\nbool PositionTracker::forget(unsigned short int token, const std::string id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) ||\n (trackSet[token]->id != STR_ID) ||\n (trackSet[token]->strID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;\n trackSet[token]->forgotten = true;\n\n return true;\n}\nbool PositionTracker::forget(unsigned short int token, long int id, std::string group)\n{\n TrackedItemVector& trackSet = _trackedItem[group];\n if ((token >= trackSet.size()) ||\n (trackSet[token]->id != INT_ID) ||\n (trackSet[token]->intID != id) ||\n (trackSet[token]->forgotten)) {\n return false;\n }\n\n trackSet[token]->position[0] = trackSet[token]->position[1] = trackSet[token]->position[2] = 0.0;\n trackSet[token]->forgotten = true;\n\n return true;\n}\n\n\ndouble PositionTracker::distanceBetween(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const\n{\n \/\/ this indirection nastiness is needed to maintain constness\n std::map ::const_iterator fromIterator = _trackedItem.find(fromGroup);\n std::map ::const_iterator toIterator = _trackedItem.find(toGroup);\n const TrackedItemVector& fromSet = (*fromIterator).second;\n const TrackedItemVector& toSet = (*toIterator).second;\n\n if ((fromToken > fromSet.size()) ||\n (toToken > toSet.size()) ||\n (fromToken == toToken)) {\n return 0.0;\n }\n\n \/\/ basic Cartesian 3-space formula for distance between two points\n double distanceSquared = (((fromSet[fromToken]->position[0] - toSet[toToken]->position[0]) *\n\t\t\t (fromSet[fromToken]->position[0] - toSet[toToken]->position[0])) +\n\t\t\t ((fromSet[fromToken]->position[1] - toSet[toToken]->position[1]) *\n\t\t\t (fromSet[fromToken]->position[1] - toSet[toToken]->position[1])) +\n\t\t\t ((fromSet[fromToken]->position[2] - toSet[toToken]->position[2]) *\n\t\t\t (fromSet[fromToken]->position[2] - toSet[toToken]->position[2])));\n\n return math_util::fastsqrt((float)distanceSquared);\n}\n\n\ndouble PositionTracker::waypointDistance(unsigned short int fromToken, unsigned short int toToken, std::string fromGroup, std::string toGroup) const\n{\n double separationDistance = distanceBetween(fromToken, toToken, fromGroup, toGroup);\n double shortestDistance = separationDistance;\n\n \/\/ horrible linear search\n std::map, double>::const_iterator waypointIterator;\n for (waypointIterator = _waypointDistance.begin(); waypointIterator != _waypointDistance.end(); waypointIterator++) {\n double fromDist, toDist, waypointDist;\n fromDist = distanceBetween(fromToken, (*waypointIterator).first.first, fromGroup, std::string(\"__waypoint__\"));\n toDist = distanceBetween((*waypointIterator).first.second, toToken, std::string(\"__waypoint__\"), toGroup);\n waypointDist = fromDist + (*waypointIterator).second + toDist;\n if (waypointDist < shortestDistance) {\n shortestDistance = waypointDist;\n }\n }\n\n return shortestDistance;\n}\n\n\nunsigned short int PositionTracker::trackedCount(std::string group) const\n{\n std::map ::const_iterator i = _trackedItem.find(group);\n const TrackedItemVector& trackSet = (*i).second;\n\n return trackSet.size();\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":"\/*\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 \n\n#include \"src\/compiler\/config.h\"\n#include \"src\/compiler\/generator_helpers.h\"\n#include \"src\/compiler\/node_generator_helpers.h\"\n\nusing grpc::protobuf::Descriptor;\nusing grpc::protobuf::FileDescriptor;\nusing grpc::protobuf::MethodDescriptor;\nusing grpc::protobuf::ServiceDescriptor;\nusing grpc::protobuf::io::Printer;\nusing grpc::protobuf::io::StringOutputStream;\nusing std::map;\n\nnamespace grpc_node_generator {\nnamespace {\n\n\/\/ Returns the alias we assign to the module of the given .proto filename\n\/\/ when importing. Copied entirely from\n\/\/ github:google\/protobuf\/src\/google\/protobuf\/compiler\/js\/js_generator.cc#L154\ngrpc::string ModuleAlias(const grpc::string filename) {\n \/\/ This scheme could technically cause problems if a file includes any 2 of:\n \/\/ foo\/bar_baz.proto\n \/\/ foo_bar_baz.proto\n \/\/ foo_bar\/baz.proto\n \/\/\n \/\/ We'll worry about this problem if\/when we actually see it. This name isn't\n \/\/ exposed to users so we can change it later if we need to.\n grpc::string basename = grpc_generator::StripProto(filename);\n basename = grpc_generator::StringReplace(basename, \"-\", \"$\");\n basename = grpc_generator::StringReplace(basename, \"\/\", \"_\");\n basename = grpc_generator::StringReplace(basename, \".\", \"_\");\n return basename + \"_pb\";\n}\n\n\/\/ Given a filename like foo\/bar\/baz.proto, returns the corresponding JavaScript\n\/\/ message file foo\/bar\/baz.js\ngrpc::string GetJSMessageFilename(const grpc::string& filename) {\n grpc::string name = filename;\n return grpc_generator::StripProto(name) + \"_pb.js\";\n}\n\n\/\/ Given a filename like foo\/bar\/baz.proto, returns the root directory\n\/\/ path ..\/..\/\ngrpc::string GetRootPath(const grpc::string& from_filename,\n const grpc::string& to_filename) {\n if (to_filename.find(\"google\/protobuf\") == 0) {\n \/\/ Well-known types (.proto files in the google\/protobuf directory) are\n \/\/ assumed to come from the 'google-protobuf' npm package. We may want to\n \/\/ generalize this exception later by letting others put generated code in\n \/\/ their own npm packages.\n return \"google-protobuf\/\";\n }\n size_t slashes = std::count(from_filename.begin(), from_filename.end(), '\/');\n if (slashes == 0) {\n return \".\/\";\n }\n grpc::string result = \"\";\n for (size_t i = 0; i < slashes; i++) {\n result += \"..\/\";\n }\n return result;\n}\n\n\/\/ Return the relative path to load to_file from the directory containing\n\/\/ from_file, assuming that both paths are relative to the same directory\ngrpc::string GetRelativePath(const grpc::string& from_file,\n const grpc::string& to_file) {\n return GetRootPath(from_file, to_file) + to_file;\n}\n\n\/* Finds all message types used in all services in the file, and returns them\n * as a map of fully qualified message type name to message descriptor *\/\nmap GetAllMessages(\n const FileDescriptor* file) {\n map message_types;\n for (int service_num = 0; service_num < file->service_count();\n service_num++) {\n const ServiceDescriptor* service = file->service(service_num);\n for (int method_num = 0; method_num < service->method_count();\n method_num++) {\n const MethodDescriptor* method = service->method(method_num);\n const Descriptor* input_type = method->input_type();\n const Descriptor* output_type = method->output_type();\n message_types[input_type->full_name()] = input_type;\n message_types[output_type->full_name()] = output_type;\n }\n }\n return message_types;\n}\n\ngrpc::string MessageIdentifierName(const grpc::string& name) {\n return grpc_generator::StringReplace(name, \".\", \"_\");\n}\n\ngrpc::string NodeObjectPath(const Descriptor* descriptor) {\n grpc::string module_alias = ModuleAlias(descriptor->file()->name());\n grpc::string name = descriptor->full_name();\n grpc_generator::StripPrefix(&name, descriptor->file()->package() + \".\");\n return module_alias + \".\" + name;\n}\n\n\/\/ Prints out the message serializer and deserializer functions\nvoid PrintMessageTransformer(const Descriptor* descriptor, Printer* out) {\n map template_vars;\n grpc::string full_name = descriptor->full_name();\n template_vars[\"identifier_name\"] = MessageIdentifierName(full_name);\n template_vars[\"name\"] = full_name;\n template_vars[\"node_name\"] = NodeObjectPath(descriptor);\n \/\/ Print the serializer\n out->Print(template_vars, \"function serialize_$identifier_name$(arg) {\\n\");\n out->Indent();\n out->Print(template_vars, \"if (!(arg instanceof $node_name$)) {\\n\");\n out->Indent();\n out->Print(template_vars,\n \"throw new Error('Expected argument of type $name$');\\n\");\n out->Outdent();\n out->Print(\"}\\n\");\n out->Print(\"return new Buffer(arg.serializeBinary());\\n\");\n out->Outdent();\n out->Print(\"}\\n\\n\");\n\n \/\/ Print the deserializer\n out->Print(template_vars,\n \"function deserialize_$identifier_name$(buffer_arg) {\\n\");\n out->Indent();\n out->Print(\n template_vars,\n \"return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\\n\");\n out->Outdent();\n out->Print(\"}\\n\\n\");\n}\n\nvoid PrintMethod(const MethodDescriptor* method, Printer* out) {\n const Descriptor* input_type = method->input_type();\n const Descriptor* output_type = method->output_type();\n map vars;\n vars[\"service_name\"] = method->service()->full_name();\n vars[\"name\"] = method->name();\n vars[\"input_type\"] = NodeObjectPath(input_type);\n vars[\"input_type_id\"] = MessageIdentifierName(input_type->full_name());\n vars[\"output_type\"] = NodeObjectPath(output_type);\n vars[\"output_type_id\"] = MessageIdentifierName(output_type->full_name());\n vars[\"client_stream\"] = method->client_streaming() ? \"true\" : \"false\";\n vars[\"server_stream\"] = method->server_streaming() ? \"true\" : \"false\";\n out->Print(\"{\\n\");\n out->Indent();\n out->Print(vars, \"path: '\/$service_name$\/$name$',\\n\");\n out->Print(vars, \"requestStream: $client_stream$,\\n\");\n out->Print(vars, \"responseStream: $server_stream$,\\n\");\n out->Print(vars, \"requestType: $input_type$,\\n\");\n out->Print(vars, \"responseType: $output_type$,\\n\");\n out->Print(vars, \"requestSerialize: serialize_$input_type_id$,\\n\");\n out->Print(vars, \"requestDeserialize: deserialize_$input_type_id$,\\n\");\n out->Print(vars, \"responseSerialize: serialize_$output_type_id$,\\n\");\n out->Print(vars, \"responseDeserialize: deserialize_$output_type_id$,\\n\");\n out->Outdent();\n out->Print(\"}\");\n}\n\n\/\/ Prints out the service descriptor object\nvoid PrintService(const ServiceDescriptor* service, Printer* out) {\n map template_vars;\n out->Print(GetNodeComments(service, true).c_str());\n template_vars[\"name\"] = service->name();\n out->Print(template_vars, \"var $name$Service = exports.$name$Service = {\\n\");\n out->Indent();\n for (int i = 0; i < service->method_count(); i++) {\n grpc::string method_name =\n grpc_generator::LowercaseFirstLetter(service->method(i)->name());\n out->Print(GetNodeComments(service->method(i), true).c_str());\n out->Print(\"$method_name$: \", \"method_name\", method_name);\n PrintMethod(service->method(i), out);\n out->Print(\",\\n\");\n out->Print(GetNodeComments(service->method(i), false).c_str());\n }\n out->Outdent();\n out->Print(\"};\\n\\n\");\n out->Print(template_vars,\n \"exports.$name$Client = \"\n \"grpc.makeGenericClientConstructor($name$Service);\\n\");\n out->Print(GetNodeComments(service, false).c_str());\n}\n\nvoid PrintImports(const FileDescriptor* file, Printer* out) {\n out->Print(\"var grpc = require('grpc');\\n\");\n if (file->message_type_count() > 0) {\n grpc::string file_path =\n GetRelativePath(file->name(), GetJSMessageFilename(file->name()));\n out->Print(\"var $module_alias$ = require('$file_path$');\\n\", \"module_alias\",\n ModuleAlias(file->name()), \"file_path\", file_path);\n }\n\n for (int i = 0; i < file->dependency_count(); i++) {\n grpc::string file_path = GetRelativePath(\n file->name(), GetJSMessageFilename(file->dependency(i)->name()));\n out->Print(\"var $module_alias$ = require('$file_path$');\\n\", \"module_alias\",\n ModuleAlias(file->dependency(i)->name()), \"file_path\",\n file_path);\n }\n out->Print(\"\\n\");\n}\n\nvoid PrintTransformers(const FileDescriptor* file, Printer* out) {\n map messages = GetAllMessages(file);\n for (std::map::iterator it =\n messages.begin();\n it != messages.end(); it++) {\n PrintMessageTransformer(it->second, out);\n }\n out->Print(\"\\n\");\n}\n\nvoid PrintServices(const FileDescriptor* file, Printer* out) {\n for (int i = 0; i < file->service_count(); i++) {\n PrintService(file->service(i), out);\n }\n}\n} \/\/ namespace\n\ngrpc::string GenerateFile(const FileDescriptor* file) {\n grpc::string output;\n {\n StringOutputStream output_stream(&output);\n Printer out(&output_stream, '$');\n\n if (file->service_count() == 0) {\n return output;\n }\n out.Print(\"\/\/ GENERATED CODE -- DO NOT EDIT!\\n\\n\");\n\n grpc::string leading_comments = GetNodeComments(file, true);\n if (!leading_comments.empty()) {\n out.Print(\"\/\/ Original file comments:\\n\");\n out.PrintRaw(leading_comments.c_str());\n }\n\n out.Print(\"'use strict';\\n\");\n\n PrintImports(file, &out);\n\n PrintTransformers(file, &out);\n\n PrintServices(file, &out);\n\n out.Print(GetNodeComments(file, false).c_str());\n }\n return output;\n}\n\n} \/\/ namespace grpc_node_generator\nSwitch to Buffer.from to avoid using deprecated constructor\/*\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 \n\n#include \"src\/compiler\/config.h\"\n#include \"src\/compiler\/generator_helpers.h\"\n#include \"src\/compiler\/node_generator_helpers.h\"\n\nusing grpc::protobuf::Descriptor;\nusing grpc::protobuf::FileDescriptor;\nusing grpc::protobuf::MethodDescriptor;\nusing grpc::protobuf::ServiceDescriptor;\nusing grpc::protobuf::io::Printer;\nusing grpc::protobuf::io::StringOutputStream;\nusing std::map;\n\nnamespace grpc_node_generator {\nnamespace {\n\n\/\/ Returns the alias we assign to the module of the given .proto filename\n\/\/ when importing. Copied entirely from\n\/\/ github:google\/protobuf\/src\/google\/protobuf\/compiler\/js\/js_generator.cc#L154\ngrpc::string ModuleAlias(const grpc::string filename) {\n \/\/ This scheme could technically cause problems if a file includes any 2 of:\n \/\/ foo\/bar_baz.proto\n \/\/ foo_bar_baz.proto\n \/\/ foo_bar\/baz.proto\n \/\/\n \/\/ We'll worry about this problem if\/when we actually see it. This name isn't\n \/\/ exposed to users so we can change it later if we need to.\n grpc::string basename = grpc_generator::StripProto(filename);\n basename = grpc_generator::StringReplace(basename, \"-\", \"$\");\n basename = grpc_generator::StringReplace(basename, \"\/\", \"_\");\n basename = grpc_generator::StringReplace(basename, \".\", \"_\");\n return basename + \"_pb\";\n}\n\n\/\/ Given a filename like foo\/bar\/baz.proto, returns the corresponding JavaScript\n\/\/ message file foo\/bar\/baz.js\ngrpc::string GetJSMessageFilename(const grpc::string& filename) {\n grpc::string name = filename;\n return grpc_generator::StripProto(name) + \"_pb.js\";\n}\n\n\/\/ Given a filename like foo\/bar\/baz.proto, returns the root directory\n\/\/ path ..\/..\/\ngrpc::string GetRootPath(const grpc::string& from_filename,\n const grpc::string& to_filename) {\n if (to_filename.find(\"google\/protobuf\") == 0) {\n \/\/ Well-known types (.proto files in the google\/protobuf directory) are\n \/\/ assumed to come from the 'google-protobuf' npm package. We may want to\n \/\/ generalize this exception later by letting others put generated code in\n \/\/ their own npm packages.\n return \"google-protobuf\/\";\n }\n size_t slashes = std::count(from_filename.begin(), from_filename.end(), '\/');\n if (slashes == 0) {\n return \".\/\";\n }\n grpc::string result = \"\";\n for (size_t i = 0; i < slashes; i++) {\n result += \"..\/\";\n }\n return result;\n}\n\n\/\/ Return the relative path to load to_file from the directory containing\n\/\/ from_file, assuming that both paths are relative to the same directory\ngrpc::string GetRelativePath(const grpc::string& from_file,\n const grpc::string& to_file) {\n return GetRootPath(from_file, to_file) + to_file;\n}\n\n\/* Finds all message types used in all services in the file, and returns them\n * as a map of fully qualified message type name to message descriptor *\/\nmap GetAllMessages(\n const FileDescriptor* file) {\n map message_types;\n for (int service_num = 0; service_num < file->service_count();\n service_num++) {\n const ServiceDescriptor* service = file->service(service_num);\n for (int method_num = 0; method_num < service->method_count();\n method_num++) {\n const MethodDescriptor* method = service->method(method_num);\n const Descriptor* input_type = method->input_type();\n const Descriptor* output_type = method->output_type();\n message_types[input_type->full_name()] = input_type;\n message_types[output_type->full_name()] = output_type;\n }\n }\n return message_types;\n}\n\ngrpc::string MessageIdentifierName(const grpc::string& name) {\n return grpc_generator::StringReplace(name, \".\", \"_\");\n}\n\ngrpc::string NodeObjectPath(const Descriptor* descriptor) {\n grpc::string module_alias = ModuleAlias(descriptor->file()->name());\n grpc::string name = descriptor->full_name();\n grpc_generator::StripPrefix(&name, descriptor->file()->package() + \".\");\n return module_alias + \".\" + name;\n}\n\n\/\/ Prints out the message serializer and deserializer functions\nvoid PrintMessageTransformer(const Descriptor* descriptor, Printer* out) {\n map template_vars;\n grpc::string full_name = descriptor->full_name();\n template_vars[\"identifier_name\"] = MessageIdentifierName(full_name);\n template_vars[\"name\"] = full_name;\n template_vars[\"node_name\"] = NodeObjectPath(descriptor);\n \/\/ Print the serializer\n out->Print(template_vars, \"function serialize_$identifier_name$(arg) {\\n\");\n out->Indent();\n out->Print(template_vars, \"if (!(arg instanceof $node_name$)) {\\n\");\n out->Indent();\n out->Print(template_vars,\n \"throw new Error('Expected argument of type $name$');\\n\");\n out->Outdent();\n out->Print(\"}\\n\");\n out->Print(\"return Buffer.from(arg.serializeBinary());\\n\");\n out->Outdent();\n out->Print(\"}\\n\\n\");\n\n \/\/ Print the deserializer\n out->Print(template_vars,\n \"function deserialize_$identifier_name$(buffer_arg) {\\n\");\n out->Indent();\n out->Print(\n template_vars,\n \"return $node_name$.deserializeBinary(new Uint8Array(buffer_arg));\\n\");\n out->Outdent();\n out->Print(\"}\\n\\n\");\n}\n\nvoid PrintMethod(const MethodDescriptor* method, Printer* out) {\n const Descriptor* input_type = method->input_type();\n const Descriptor* output_type = method->output_type();\n map vars;\n vars[\"service_name\"] = method->service()->full_name();\n vars[\"name\"] = method->name();\n vars[\"input_type\"] = NodeObjectPath(input_type);\n vars[\"input_type_id\"] = MessageIdentifierName(input_type->full_name());\n vars[\"output_type\"] = NodeObjectPath(output_type);\n vars[\"output_type_id\"] = MessageIdentifierName(output_type->full_name());\n vars[\"client_stream\"] = method->client_streaming() ? \"true\" : \"false\";\n vars[\"server_stream\"] = method->server_streaming() ? \"true\" : \"false\";\n out->Print(\"{\\n\");\n out->Indent();\n out->Print(vars, \"path: '\/$service_name$\/$name$',\\n\");\n out->Print(vars, \"requestStream: $client_stream$,\\n\");\n out->Print(vars, \"responseStream: $server_stream$,\\n\");\n out->Print(vars, \"requestType: $input_type$,\\n\");\n out->Print(vars, \"responseType: $output_type$,\\n\");\n out->Print(vars, \"requestSerialize: serialize_$input_type_id$,\\n\");\n out->Print(vars, \"requestDeserialize: deserialize_$input_type_id$,\\n\");\n out->Print(vars, \"responseSerialize: serialize_$output_type_id$,\\n\");\n out->Print(vars, \"responseDeserialize: deserialize_$output_type_id$,\\n\");\n out->Outdent();\n out->Print(\"}\");\n}\n\n\/\/ Prints out the service descriptor object\nvoid PrintService(const ServiceDescriptor* service, Printer* out) {\n map template_vars;\n out->Print(GetNodeComments(service, true).c_str());\n template_vars[\"name\"] = service->name();\n out->Print(template_vars, \"var $name$Service = exports.$name$Service = {\\n\");\n out->Indent();\n for (int i = 0; i < service->method_count(); i++) {\n grpc::string method_name =\n grpc_generator::LowercaseFirstLetter(service->method(i)->name());\n out->Print(GetNodeComments(service->method(i), true).c_str());\n out->Print(\"$method_name$: \", \"method_name\", method_name);\n PrintMethod(service->method(i), out);\n out->Print(\",\\n\");\n out->Print(GetNodeComments(service->method(i), false).c_str());\n }\n out->Outdent();\n out->Print(\"};\\n\\n\");\n out->Print(template_vars,\n \"exports.$name$Client = \"\n \"grpc.makeGenericClientConstructor($name$Service);\\n\");\n out->Print(GetNodeComments(service, false).c_str());\n}\n\nvoid PrintImports(const FileDescriptor* file, Printer* out) {\n out->Print(\"var grpc = require('grpc');\\n\");\n if (file->message_type_count() > 0) {\n grpc::string file_path =\n GetRelativePath(file->name(), GetJSMessageFilename(file->name()));\n out->Print(\"var $module_alias$ = require('$file_path$');\\n\", \"module_alias\",\n ModuleAlias(file->name()), \"file_path\", file_path);\n }\n\n for (int i = 0; i < file->dependency_count(); i++) {\n grpc::string file_path = GetRelativePath(\n file->name(), GetJSMessageFilename(file->dependency(i)->name()));\n out->Print(\"var $module_alias$ = require('$file_path$');\\n\", \"module_alias\",\n ModuleAlias(file->dependency(i)->name()), \"file_path\",\n file_path);\n }\n out->Print(\"\\n\");\n}\n\nvoid PrintTransformers(const FileDescriptor* file, Printer* out) {\n map messages = GetAllMessages(file);\n for (std::map::iterator it =\n messages.begin();\n it != messages.end(); it++) {\n PrintMessageTransformer(it->second, out);\n }\n out->Print(\"\\n\");\n}\n\nvoid PrintServices(const FileDescriptor* file, Printer* out) {\n for (int i = 0; i < file->service_count(); i++) {\n PrintService(file->service(i), out);\n }\n}\n} \/\/ namespace\n\ngrpc::string GenerateFile(const FileDescriptor* file) {\n grpc::string output;\n {\n StringOutputStream output_stream(&output);\n Printer out(&output_stream, '$');\n\n if (file->service_count() == 0) {\n return output;\n }\n out.Print(\"\/\/ GENERATED CODE -- DO NOT EDIT!\\n\\n\");\n\n grpc::string leading_comments = GetNodeComments(file, true);\n if (!leading_comments.empty()) {\n out.Print(\"\/\/ Original file comments:\\n\");\n out.PrintRaw(leading_comments.c_str());\n }\n\n out.Print(\"'use strict';\\n\");\n\n PrintImports(file, &out);\n\n PrintTransformers(file, &out);\n\n PrintServices(file, &out);\n\n out.Print(GetNodeComments(file, false).c_str());\n }\n return output;\n}\n\n} \/\/ namespace grpc_node_generator\n<|endoftext|>"} {"text":"#include \"components\/BulletMover.h\"\n\n#include \n#include \n\nnamespace Sigma {\n\n\tBulletMover::BulletMover(const int entityID) : IBulletShape(entityID), transform(nullptr) {}\n\n\tBulletMover::~BulletMover() {}\n\n\tvoid BulletMover::ApplyForces(const double delta) {\n\t\tif (this->transform) {\n\t\t\tglm::vec3 deltavec(delta);\n\t\t\tglm::vec3 totalForce;\n\t\t\tglm::vec3 targetrvel;\n\n\t\t\tfor (auto rotitr = this->rotationForces.begin(); rotitr != this->rotationForces.end(); ++rotitr) {\n\t\t\t\tthis->transform->Rotate((*rotitr) * deltavec);\n\t\t\t}\n\n\t\t\t\/\/ Inertial rotation\n\t\t\ttargetrvel = _rotationtarget * deltavec;\n\t\t\tif(fabs(targetrvel.x) > 0.0001f || fabs(targetrvel.y) > 0.0001f || fabs(targetrvel.z) > 0.0001f) {\n\t\t\t\ttargetrvel = this->transform->Restrict(targetrvel);\n\t\t\t\tthis->transform->Rotate(targetrvel);\n\t\t\t\t_rotationtarget -= targetrvel;\n\t\t\t}\n\t\t\ttargetrvel = this->transform->Restrict(targetrvel);\n\t\t\tthis->rotationForces.clear();\n\n\t\t\tfor (auto forceitr = this->forces.begin(); forceitr != this->forces.end(); ++forceitr) {\n\t\t\t\ttotalForce += *forceitr;\n\t\t\t}\n\n\t\t\tglm::vec3 finalForce = (totalForce.z * this->transform->GetForward()) + \n\t\t\t\t\t\t\t\t (totalForce.y * this->transform->GetUp()) + \n\t\t\t\t\t\t\t\t (totalForce.x * this->transform->GetRight());\n\n\t\t\tbody->setActivationState(DISABLE_DEACTIVATION);\n\t\t\tthis->body->setLinearVelocity(btVector3(finalForce.x, this->body->getLinearVelocity().y() + 0.000000001f, finalForce.z));\n\t\t}\n\t}\n\n\tvoid BulletMover::UpdateTransform() {\n\t\tif (this->transform) {\n\t\t\tbtTransform trans;\n\t\t\tthis->body->getMotionState()->getWorldTransform(trans);\n\t\t\tthis->transform->TranslateTo(trans.getOrigin().x(),trans.getOrigin().y(), trans.getOrigin().z());\n\t\t}\n\t}\n\n\tvoid BulletMover::InitializeRigidBody(float x, float y, float z, float rx, float ry, float rz) {\n\t\tthis->shape = new btCapsuleShape(0.3f, 1.3f);\n\t\tbtScalar mass = 1;\n\t\tbtVector3 fallInertia(0,0,0);\n\t\tthis->motionState =\tnew btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(x, y, z)));\n\t\tbtRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, motionState, shape,fallInertia);\n\t\tthis->shape->calculateLocalInertia(mass,fallInertia);\n\t\tthis->body = new btRigidBody(fallRigidBodyCI);\n\t}\n\n\tvoid BulletMover::InitializeRigidBody() {\n\t\tif(this->transform) {\n\t\t\tthis->InitializeRigidBody(\n\t\t\t\tthis->transform->GetPosition().x,\n\t\t\t\tthis->transform->GetPosition().y,\n\t\t\t\tthis->transform->GetPosition().z,\n\t\t\t\tthis->transform->GetPitch(),\n\t\t\t\tthis->transform->GetYaw(),\n\t\t\t\tthis->transform->GetRoll()\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\tthis->InitializeRigidBody(0,1.5f,0,0,0,0);\n\t\t}\n\t}\n\n\t\/\/ immediate mode rotation (for mouse motion)\n\tvoid BulletMover::RotateNow(float x, float y, float z) {\n\t\tif (this->transform) {\n\t\t\tthis->transform->Rotate(x,y,z);\n\t\t}\n\t}\n\tvoid BulletMover::RotateTarget(float x, float y, float z) {\n\t\tif (this->transform) {\n\t\t\tthis->_rotationtarget += glm::vec3(x,y,z);\n\t\t}\n\t}\n}\nFix entity id type of BulletMover#include \"components\/BulletMover.h\"\n\n#include \n#include \n\nnamespace Sigma {\n\n\tBulletMover::BulletMover(const id_t entityID) : IBulletShape(entityID), transform(nullptr) {}\n\n\tBulletMover::~BulletMover() {}\n\n\tvoid BulletMover::ApplyForces(const double delta) {\n\t\tif (this->transform) {\n\t\t\tglm::vec3 deltavec(delta);\n\t\t\tglm::vec3 totalForce;\n\t\t\tglm::vec3 targetrvel;\n\n\t\t\tfor (auto rotitr = this->rotationForces.begin(); rotitr != this->rotationForces.end(); ++rotitr) {\n\t\t\t\tthis->transform->Rotate((*rotitr) * deltavec);\n\t\t\t}\n\n\t\t\t\/\/ Inertial rotation\n\t\t\ttargetrvel = _rotationtarget * deltavec;\n\t\t\tif(fabs(targetrvel.x) > 0.0001f || fabs(targetrvel.y) > 0.0001f || fabs(targetrvel.z) > 0.0001f) {\n\t\t\t\ttargetrvel = this->transform->Restrict(targetrvel);\n\t\t\t\tthis->transform->Rotate(targetrvel);\n\t\t\t\t_rotationtarget -= targetrvel;\n\t\t\t}\n\t\t\ttargetrvel = this->transform->Restrict(targetrvel);\n\t\t\tthis->rotationForces.clear();\n\n\t\t\tfor (auto forceitr = this->forces.begin(); forceitr != this->forces.end(); ++forceitr) {\n\t\t\t\ttotalForce += *forceitr;\n\t\t\t}\n\n\t\t\tglm::vec3 finalForce = (totalForce.z * this->transform->GetForward()) + \n\t\t\t\t\t\t\t\t (totalForce.y * this->transform->GetUp()) + \n\t\t\t\t\t\t\t\t (totalForce.x * this->transform->GetRight());\n\n\t\t\tbody->setActivationState(DISABLE_DEACTIVATION);\n\t\t\tthis->body->setLinearVelocity(btVector3(finalForce.x, this->body->getLinearVelocity().y() + 0.000000001f, finalForce.z));\n\t\t}\n\t}\n\n\tvoid BulletMover::UpdateTransform() {\n\t\tif (this->transform) {\n\t\t\tbtTransform trans;\n\t\t\tthis->body->getMotionState()->getWorldTransform(trans);\n\t\t\tthis->transform->TranslateTo(trans.getOrigin().x(),trans.getOrigin().y(), trans.getOrigin().z());\n\t\t}\n\t}\n\n\tvoid BulletMover::InitializeRigidBody(float x, float y, float z, float rx, float ry, float rz) {\n\t\tthis->shape = new btCapsuleShape(0.3f, 1.3f);\n\t\tbtScalar mass = 1;\n\t\tbtVector3 fallInertia(0,0,0);\n\t\tthis->motionState =\tnew btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(x, y, z)));\n\t\tbtRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, motionState, shape,fallInertia);\n\t\tthis->shape->calculateLocalInertia(mass,fallInertia);\n\t\tthis->body = new btRigidBody(fallRigidBodyCI);\n\t}\n\n\tvoid BulletMover::InitializeRigidBody() {\n\t\tif(this->transform) {\n\t\t\tthis->InitializeRigidBody(\n\t\t\t\tthis->transform->GetPosition().x,\n\t\t\t\tthis->transform->GetPosition().y,\n\t\t\t\tthis->transform->GetPosition().z,\n\t\t\t\tthis->transform->GetPitch(),\n\t\t\t\tthis->transform->GetYaw(),\n\t\t\t\tthis->transform->GetRoll()\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\tthis->InitializeRigidBody(0,1.5f,0,0,0,0);\n\t\t}\n\t}\n\n\t\/\/ immediate mode rotation (for mouse motion)\n\tvoid BulletMover::RotateNow(float x, float y, float z) {\n\t\tif (this->transform) {\n\t\t\tthis->transform->Rotate(x,y,z);\n\t\t}\n\t}\n\tvoid BulletMover::RotateTarget(float x, float y, float z) {\n\t\tif (this->transform) {\n\t\t\tthis->_rotationtarget += glm::vec3(x,y,z);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n \n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"selector.h\"\n\n\nvoid display_fd_set( char *msg, fd_set *set, int max );\n\nint Selector::_fd_select_size = -1;\n\nfd_set *Selector::cached_read_fds = NULL;\nfd_set *Selector::cached_write_fds = NULL;\nfd_set *Selector::cached_except_fds = NULL;\n\nfd_set *Selector::cached_save_read_fds = NULL;\nfd_set *Selector::cached_save_write_fds = NULL;\nfd_set *Selector::cached_save_except_fds = NULL;\n\nSelector::Selector()\n{\n#if defined(WIN32)\n\t\t\/\/ On Windows, we can't treat fd_set as an open-ended bit array.\n\t\t\/\/ fd_set can take up to FD_SETSIZE sockets (not any socket whose\n\t\t\/\/ fd is <= FD_SETSIZE) and that's it. Currently, we set\n\t\t\/\/ FD_SETSIZE to 1024. I'm not sure what we can do if we ever\n\t\t\/\/ have more than 1024 sockets to select on.\n\tfd_set_size = 1;\n#else\n\tint nfdbits = 8 * sizeof(fd_set);\n\tfd_set_size = ( fd_select_size() + (nfdbits - 1) ) \/ nfdbits;\n#endif\n\n\tif ( cached_read_fds ) {\n\t\tread_fds = cached_read_fds;\n\t\twrite_fds = cached_write_fds;\n\t\texcept_fds = cached_except_fds;\n\n\t\tsave_read_fds = cached_save_read_fds;\n\t\tsave_write_fds = cached_save_write_fds;\n\t\tsave_except_fds = cached_save_except_fds;\n\n\t\tcached_read_fds = NULL;\n\t\tcached_write_fds = NULL;\n\t\tcached_except_fds = NULL;\n\t\tcached_save_read_fds = NULL;\n\t\tcached_save_write_fds = NULL;\n\t\tcached_save_except_fds = NULL;\n\t} else {\n\t\tread_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\twrite_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\texcept_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\n\t\tsave_read_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\tsave_write_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\tsave_except_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t}\n\n\treset();\n}\n\nSelector::~Selector()\n{\n\tif ( cached_read_fds == NULL ) {\n\t\tcached_read_fds = read_fds;\n\t\tcached_write_fds = write_fds;\n\t\tcached_except_fds = except_fds;\n\n\t\tcached_save_read_fds = save_read_fds;\n\t\tcached_save_write_fds = save_write_fds;\n\t\tcached_save_except_fds = save_except_fds;\n\t} else {\n\t\tfree( read_fds );\n\t\tfree( write_fds );\n\t\tfree( except_fds );\n\n\t\tfree( save_read_fds );\n\t\tfree( save_write_fds );\n\t\tfree( save_except_fds );\n\t}\n}\n\nvoid\nSelector::reset()\n{\n\t_select_retval = -2;\n\tstate = VIRGIN;\n\ttimeout_wanted = FALSE;\n\tmax_fd = -1;\n#if defined(WIN32)\n\tFD_ZERO( save_read_fds );\n\tFD_ZERO( save_write_fds );\n\tFD_ZERO( save_except_fds );\n#else\n\tmemset( save_read_fds, 0, fd_set_size * sizeof(fd_set) );\n\tmemset( save_write_fds, 0, fd_set_size * sizeof(fd_set) );\n\tmemset( save_except_fds, 0, fd_set_size * sizeof(fd_set) );\n#endif\n}\n\nint\nSelector::fd_select_size()\n{\n\tif ( _fd_select_size < 0 ) {\n#if defined(WIN32)\n\t\t\/\/ On Windows, fd_set is not a bit-array, but a structure that can\n\t\t\/\/ hold up to 1024 different file descriptors (not just file \n\t\t\/\/ descriptors whose value is less than 1024). We set max_fd to\n\t\t\/\/ 1024 (FD_SETSIZE) as a reasonable approximation.\n\t\t_fd_select_size = FD_SETSIZE;\n#elif defined(Solaris)\n\t\t\/\/ Solaris's select() can't handle fds greater than FD_SETSIZE.\n\t\tint max_fds = getdtablesize();\n\t\tif ( max_fds < FD_SETSIZE ) {\n\t\t\t_fd_select_size = max_fds;\n\t\t} else {\n\t\t\t_fd_select_size = FD_SETSIZE;\n\t\t}\n#else\n\t\t_fd_select_size = getdtablesize();\n#endif\n\t}\n\treturn _fd_select_size;\n}\n\nvoid\nSelector::add_fd( int fd, IO_FUNC interest )\n{\n\t\/\/ update max_fd (the highest valid index in fd_set's array) and also\n\t\/\/ make sure we're not overflowing our fd_set\n\t\/\/\n#if defined(WIN32)\n\tmax_fd++;\n\tif (max_fd > fd_select_size() - 1) {\n\t\tEXCEPT(\"Selector::add_fd(): fd_set is full\");\n\t}\n#else\n\tif( fd > max_fd ) {\n\t\tmax_fd = fd;\n\t}\n\tif ( fd < 0 || fd >= fd_select_size() ) {\n\t\tEXCEPT( \"Selector::add_fd(): fd %d outside valid range 0-%d\",\n\t\t\t\tfd, _fd_select_size-1 );\n\t}\n#endif\n\n\tswitch( interest ) {\n\n\t case IO_READ:\n\t\tFD_SET( fd, save_read_fds );\n\t\tbreak;\n\n\t case IO_WRITE:\n\t\tFD_SET( fd, save_write_fds );\n\t\tbreak;\n\n\t case IO_EXCEPT:\n\t\tFD_SET( fd, save_except_fds );\n\t\tbreak;\n\n\t}\n}\n\nvoid\nSelector::delete_fd( int fd, IO_FUNC interest )\n{\n\t\/\/ on Windows, we need to update max_fd since it keeps track of\n\t\/\/ how many sockets are in our fd_set. in UNIX, just do a sanity\n\t\/\/ check based on the value of fd\n\t\/\/\n#if defined(WIN32)\n\tmax_fd--;\n#else\n\tif ( fd < 0 || fd > fd_select_size() ) {\n\t\tEXCEPT( \"Selector::delete_fd(): fd %d outside valid range 0-%d\",\n\t\t\t\tfd, _fd_select_size-1 );\n\t}\n#endif\n\n\tswitch( interest ) {\n\n\t case IO_READ:\n\t\tFD_CLR( fd, save_read_fds );\n\t\tbreak;\n\n\t case IO_WRITE:\n\t\tFD_CLR( fd, save_write_fds );\n\t\tbreak;\n\n\t case IO_EXCEPT:\n\t\tFD_CLR( fd, save_except_fds );\n\t\tbreak;\n\n\t}\n}\n\nvoid\nSelector::set_timeout( time_t sec, long usec )\n{\n\ttimeout_wanted = TRUE;\n\n\ttimeout.tv_sec = sec;\n\ttimeout.tv_usec = usec;\n}\n\nvoid\nSelector::set_timeout( timeval tv )\n{\n\ttimeout_wanted = TRUE;\n\n\ttimeout = tv;\n}\n\nvoid\nSelector::unset_timeout()\n{\n\ttimeout_wanted = FALSE;\n}\n\nvoid\nSelector::execute()\n{\n\tint\t\tnfds;\n\tstruct timeval\t*tp;\n\n\tmemcpy( read_fds, save_read_fds, fd_set_size * sizeof(fd_set) );\n\tmemcpy( write_fds, save_write_fds, fd_set_size * sizeof(fd_set) );\n\tmemcpy( except_fds, save_except_fds, fd_set_size * sizeof(fd_set) );\n\n\tif( timeout_wanted ) {\n\t\ttp = &timeout;\n\t} else {\n\t\ttp = NULL;\n\t}\n\n\tnfds = select( max_fd + 1, \n\t\t\t\t (SELECT_FDSET_PTR) read_fds, \n\t\t\t\t (SELECT_FDSET_PTR) write_fds, \n\t\t\t\t (SELECT_FDSET_PTR) except_fds, \n\t\t\t\t tp );\n\t_select_retval = nfds;\n\n\tif( nfds < 0 ) {\n#if !defined(WIN32)\n\t\tif( errno == EINTR ) {\n\t\t\tstate = SIGNALLED;\n\t\t\treturn;\n\t\t}\n#endif\n\t\tstate = FAILED;\n\t\treturn;\n\t}\n\n\tif( nfds == 0 ) {\n\t\tstate = TIMED_OUT;\n\t} else {\n\t\tstate = FDS_READY;\n\t}\n\treturn;\n}\n\nint\nSelector::select_retval()\n{\n\treturn _select_retval;\n}\n\nBOOLEAN\nSelector::fd_ready( int fd, IO_FUNC interest )\n{\n\tif( state != FDS_READY && state != TIMED_OUT ) {\n\t\tEXCEPT(\n\t\t\t\"Selector::fd_ready() called, but selector not in FDS_READY state\"\n\t\t);\n\t}\n\n#if !defined(WIN32)\n\t\/\/ on UNIX, make sure the value of fd makes sense\n\t\/\/\n\tif ( fd < 0 || fd > fd_select_size() ) {\n\t\treturn FALSE;\n\t}\n#endif\n\n\tswitch( interest ) {\n\n\t case IO_READ:\n\t\treturn FD_ISSET( fd, read_fds );\n\t\tbreak;\n\n\t case IO_WRITE:\n\t\treturn FD_ISSET( fd, write_fds );\n\t\tbreak;\n\n\t case IO_EXCEPT:\n\t\treturn FD_ISSET( fd, except_fds );\n\t\tbreak;\n\n\t}\n\n\t\t\/\/ Can never get here\n\treturn FALSE;\n}\n\nBOOLEAN\nSelector::timed_out()\n{\n\treturn state == TIMED_OUT;\n}\n\nBOOLEAN\nSelector::signalled()\n{\n\treturn state == SIGNALLED;\n}\n\nBOOLEAN\nSelector::failed()\n{\n\treturn state == FAILED;\n}\n\nBOOLEAN\nSelector::has_ready()\n{\n\treturn state == FDS_READY;\n}\n\nvoid\nSelector::display()\n{\n\n\tswitch( state ) {\n\n\t case VIRGIN:\n\t\tdprintf( D_ALWAYS, \"State = VIRGIN\\n\" );\n\t\tbreak;\n\n\t case FDS_READY:\n\t\tdprintf( D_ALWAYS, \"State = FDS_READY\\n\" );\n\t\tbreak;\n\n\t case TIMED_OUT:\n\t\tdprintf( D_ALWAYS, \"State = TIMED_OUT\\n\" );\n\t\tbreak;\n\n\t case SIGNALLED:\n\t\tdprintf( D_ALWAYS, \"State = SIGNALLED\\n\" );\n\t\tbreak;\n\n\t case FAILED:\n\t\tdprintf( D_ALWAYS, \"State = FAILED\\n\" );\n\t\tbreak;\n\t}\n\n\tdprintf( D_ALWAYS, \"max_fd = %d\\n\", max_fd );\n\n\tdprintf( D_ALWAYS, \"Selection FD's\\n\" );\n\tdisplay_fd_set( \"\\tRead\", save_read_fds, max_fd );\n\tdisplay_fd_set( \"\\tWrite\", save_write_fds, max_fd );\n\tdisplay_fd_set( \"\\tExcept\", save_except_fds, max_fd );\n\n\tif( state == FDS_READY ) {\n\t\tdprintf( D_ALWAYS, \"Ready FD's\\n\" );\n\t\tdisplay_fd_set( \"\\tRead\", read_fds, max_fd );\n\t\tdisplay_fd_set( \"\\tWrite\", write_fds, max_fd );\n\t\tdisplay_fd_set( \"\\tExcept\", except_fds, max_fd );\n\t}\n\tif( timeout_wanted ) {\n\t\tdprintf( D_ALWAYS,\n\t\t\t\"Timeout = %ld.%06ld seconds\\n\", (long) timeout.tv_sec, \n\t\t\t(long) timeout.tv_usec\n\t\t);\n\t} else {\n\t\tdprintf( D_ALWAYS, \"Timeout not wanted\\n\" );\n\t}\n\n}\n\nvoid\ndisplay_fd_set( char *msg, fd_set *set, int max )\n{\n\tint\t\ti;\n\n\tdprintf( D_ALWAYS, \"%s {\", msg );\n\tfor( i=0; i<=max; i++ ) {\n\t\tif( FD_ISSET(i,set) ) {\n\t\t\tdprintf( D_ALWAYS | D_NOHEADER, \"%d \", i );\n\t\t}\n\t}\n\tdprintf( D_ALWAYS | D_NOHEADER, \"}\\n\" );\n}\nFix some minor problems in Selector, our wrapper for select(). We have not seen these bite running code yet, so no version history entry. * On Windows, the check for a full fd_set in add_fd() was wrong. * The display functions didn't work correctly on Windows. * Off-by-one errors in checking for out-of-range fds.\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n \n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"selector.h\"\n\n\nvoid display_fd_set( char *msg, fd_set *set, int max );\n\nint Selector::_fd_select_size = -1;\n\nfd_set *Selector::cached_read_fds = NULL;\nfd_set *Selector::cached_write_fds = NULL;\nfd_set *Selector::cached_except_fds = NULL;\n\nfd_set *Selector::cached_save_read_fds = NULL;\nfd_set *Selector::cached_save_write_fds = NULL;\nfd_set *Selector::cached_save_except_fds = NULL;\n\nSelector::Selector()\n{\n#if defined(WIN32)\n\t\t\/\/ On Windows, we can't treat fd_set as an open-ended bit array.\n\t\t\/\/ fd_set can take up to FD_SETSIZE sockets (not any socket whose\n\t\t\/\/ fd is <= FD_SETSIZE) and that's it. Currently, we set\n\t\t\/\/ FD_SETSIZE to 1024. I'm not sure what we can do if we ever\n\t\t\/\/ have more than 1024 sockets to select on.\n\tfd_set_size = 1;\n#else\n\tint nfdbits = 8 * sizeof(fd_set);\n\tfd_set_size = ( fd_select_size() + (nfdbits - 1) ) \/ nfdbits;\n#endif\n\n\tif ( cached_read_fds ) {\n\t\tread_fds = cached_read_fds;\n\t\twrite_fds = cached_write_fds;\n\t\texcept_fds = cached_except_fds;\n\n\t\tsave_read_fds = cached_save_read_fds;\n\t\tsave_write_fds = cached_save_write_fds;\n\t\tsave_except_fds = cached_save_except_fds;\n\n\t\tcached_read_fds = NULL;\n\t\tcached_write_fds = NULL;\n\t\tcached_except_fds = NULL;\n\t\tcached_save_read_fds = NULL;\n\t\tcached_save_write_fds = NULL;\n\t\tcached_save_except_fds = NULL;\n\t} else {\n\t\tread_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\twrite_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\texcept_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\n\t\tsave_read_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\tsave_write_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t\tsave_except_fds = (fd_set *)calloc( fd_set_size, sizeof(fd_set) );\n\t}\n\n\treset();\n}\n\nSelector::~Selector()\n{\n\tif ( cached_read_fds == NULL ) {\n\t\tcached_read_fds = read_fds;\n\t\tcached_write_fds = write_fds;\n\t\tcached_except_fds = except_fds;\n\n\t\tcached_save_read_fds = save_read_fds;\n\t\tcached_save_write_fds = save_write_fds;\n\t\tcached_save_except_fds = save_except_fds;\n\t} else {\n\t\tfree( read_fds );\n\t\tfree( write_fds );\n\t\tfree( except_fds );\n\n\t\tfree( save_read_fds );\n\t\tfree( save_write_fds );\n\t\tfree( save_except_fds );\n\t}\n}\n\nvoid\nSelector::reset()\n{\n\t_select_retval = -2;\n\tstate = VIRGIN;\n\ttimeout_wanted = FALSE;\n\tmax_fd = -1;\n#if defined(WIN32)\n\tFD_ZERO( save_read_fds );\n\tFD_ZERO( save_write_fds );\n\tFD_ZERO( save_except_fds );\n#else\n\tmemset( save_read_fds, 0, fd_set_size * sizeof(fd_set) );\n\tmemset( save_write_fds, 0, fd_set_size * sizeof(fd_set) );\n\tmemset( save_except_fds, 0, fd_set_size * sizeof(fd_set) );\n#endif\n}\n\nint\nSelector::fd_select_size()\n{\n\tif ( _fd_select_size < 0 ) {\n#if defined(WIN32)\n\t\t\/\/ On Windows, fd_set is not a bit-array, but a structure that can\n\t\t\/\/ hold up to 1024 different file descriptors (not just file \n\t\t\/\/ descriptors whose value is less than 1024). We set max_fds to\n\t\t\/\/ 1024 (FD_SETSIZE) as a reasonable approximation.\n\t\t_fd_select_size = FD_SETSIZE;\n#elif defined(Solaris)\n\t\t\/\/ Solaris's select() can't handle fds greater than FD_SETSIZE.\n\t\tint max_fds = getdtablesize();\n\t\tif ( max_fds < FD_SETSIZE ) {\n\t\t\t_fd_select_size = max_fds;\n\t\t} else {\n\t\t\t_fd_select_size = FD_SETSIZE;\n\t\t}\n#else\n\t\t_fd_select_size = getdtablesize();\n#endif\n\t}\n\treturn _fd_select_size;\n}\n\nvoid\nSelector::add_fd( int fd, IO_FUNC interest )\n{\n\t\/\/ update max_fd (the highest valid index in fd_set's array) and also\n\t\/\/ make sure we're not overflowing our fd_set\n\t\/\/ On Windows, we have to check the individual fd_set to see if it's\n\t\/\/ full.\n\tif( fd > max_fd ) {\n\t\tmax_fd = fd;\n\t}\n#if !defined(WIN32)\n\tif ( fd < 0 || fd >= fd_select_size() ) {\n\t\tEXCEPT( \"Selector::add_fd(): fd %d outside valid range 0-%d\",\n\t\t\t\tfd, _fd_select_size-1 );\n\t}\n#endif\n\n\tswitch( interest ) {\n\n\t case IO_READ:\n#if defined(WIN32)\n\t\tif ( save_read_fds->fd_count >= fd_select_size() ) {\n\t\t\tEXCEPT( \"Selector::add_fd(): read fd_set is full\" );\n\t\t}\n#endif\n\t\tFD_SET( fd, save_read_fds );\n\t\tbreak;\n\n\t case IO_WRITE:\n#if defined(WIN32)\n\t\tif ( save_write_fds->fd_count >= fd_select_size() ) {\n\t\t\tEXCEPT( \"Selector::add_fd(): write fd_set is full\" );\n\t\t}\n#endif\n\t\tFD_SET( fd, save_write_fds );\n\t\tbreak;\n\n\t case IO_EXCEPT:\n#if defined(WIN32)\n\t\tif ( save_except_fds->fd_count >= fd_select_size() ) {\n\t\t\tEXCEPT( \"Selector::add_fd(): except fd_set is full\" );\n\t\t}\n#endif\n\t\tFD_SET( fd, save_except_fds );\n\t\tbreak;\n\n\t}\n}\n\nvoid\nSelector::delete_fd( int fd, IO_FUNC interest )\n{\n#if !defined(WIN32)\n\tif ( fd < 0 || fd >= fd_select_size() ) {\n\t\tEXCEPT( \"Selector::delete_fd(): fd %d outside valid range 0-%d\",\n\t\t\t\tfd, _fd_select_size-1 );\n\t}\n#endif\n\n\tswitch( interest ) {\n\n\t case IO_READ:\n\t\tFD_CLR( fd, save_read_fds );\n\t\tbreak;\n\n\t case IO_WRITE:\n\t\tFD_CLR( fd, save_write_fds );\n\t\tbreak;\n\n\t case IO_EXCEPT:\n\t\tFD_CLR( fd, save_except_fds );\n\t\tbreak;\n\n\t}\n}\n\nvoid\nSelector::set_timeout( time_t sec, long usec )\n{\n\ttimeout_wanted = TRUE;\n\n\ttimeout.tv_sec = sec;\n\ttimeout.tv_usec = usec;\n}\n\nvoid\nSelector::set_timeout( timeval tv )\n{\n\ttimeout_wanted = TRUE;\n\n\ttimeout = tv;\n}\n\nvoid\nSelector::unset_timeout()\n{\n\ttimeout_wanted = FALSE;\n}\n\nvoid\nSelector::execute()\n{\n\tint\t\tnfds;\n\tstruct timeval\t*tp;\n\n\tmemcpy( read_fds, save_read_fds, fd_set_size * sizeof(fd_set) );\n\tmemcpy( write_fds, save_write_fds, fd_set_size * sizeof(fd_set) );\n\tmemcpy( except_fds, save_except_fds, fd_set_size * sizeof(fd_set) );\n\n\tif( timeout_wanted ) {\n\t\ttp = &timeout;\n\t} else {\n\t\ttp = NULL;\n\t}\n\n\t\t\/\/ select() ignores its first argument on Windows. We still track\n\t\t\/\/ max_fd for the display() functions.\n\tnfds = select( max_fd + 1, \n\t\t\t\t (SELECT_FDSET_PTR) read_fds, \n\t\t\t\t (SELECT_FDSET_PTR) write_fds, \n\t\t\t\t (SELECT_FDSET_PTR) except_fds, \n\t\t\t\t tp );\n\t_select_retval = nfds;\n\n\tif( nfds < 0 ) {\n#if !defined(WIN32)\n\t\tif( errno == EINTR ) {\n\t\t\tstate = SIGNALLED;\n\t\t\treturn;\n\t\t}\n#endif\n\t\tstate = FAILED;\n\t\treturn;\n\t}\n\n\tif( nfds == 0 ) {\n\t\tstate = TIMED_OUT;\n\t} else {\n\t\tstate = FDS_READY;\n\t}\n\treturn;\n}\n\nint\nSelector::select_retval()\n{\n\treturn _select_retval;\n}\n\nBOOLEAN\nSelector::fd_ready( int fd, IO_FUNC interest )\n{\n\tif( state != FDS_READY && state != TIMED_OUT ) {\n\t\tEXCEPT(\n\t\t\t\"Selector::fd_ready() called, but selector not in FDS_READY state\"\n\t\t);\n\t}\n\n#if !defined(WIN32)\n\t\/\/ on UNIX, make sure the value of fd makes sense\n\t\/\/\n\tif ( fd < 0 || fd >= fd_select_size() ) {\n\t\treturn FALSE;\n\t}\n#endif\n\n\tswitch( interest ) {\n\n\t case IO_READ:\n\t\treturn FD_ISSET( fd, read_fds );\n\t\tbreak;\n\n\t case IO_WRITE:\n\t\treturn FD_ISSET( fd, write_fds );\n\t\tbreak;\n\n\t case IO_EXCEPT:\n\t\treturn FD_ISSET( fd, except_fds );\n\t\tbreak;\n\n\t}\n\n\t\t\/\/ Can never get here\n\treturn FALSE;\n}\n\nBOOLEAN\nSelector::timed_out()\n{\n\treturn state == TIMED_OUT;\n}\n\nBOOLEAN\nSelector::signalled()\n{\n\treturn state == SIGNALLED;\n}\n\nBOOLEAN\nSelector::failed()\n{\n\treturn state == FAILED;\n}\n\nBOOLEAN\nSelector::has_ready()\n{\n\treturn state == FDS_READY;\n}\n\nvoid\nSelector::display()\n{\n\n\tswitch( state ) {\n\n\t case VIRGIN:\n\t\tdprintf( D_ALWAYS, \"State = VIRGIN\\n\" );\n\t\tbreak;\n\n\t case FDS_READY:\n\t\tdprintf( D_ALWAYS, \"State = FDS_READY\\n\" );\n\t\tbreak;\n\n\t case TIMED_OUT:\n\t\tdprintf( D_ALWAYS, \"State = TIMED_OUT\\n\" );\n\t\tbreak;\n\n\t case SIGNALLED:\n\t\tdprintf( D_ALWAYS, \"State = SIGNALLED\\n\" );\n\t\tbreak;\n\n\t case FAILED:\n\t\tdprintf( D_ALWAYS, \"State = FAILED\\n\" );\n\t\tbreak;\n\t}\n\n\tdprintf( D_ALWAYS, \"max_fd = %d\\n\", max_fd );\n\n\tdprintf( D_ALWAYS, \"Selection FD's\\n\" );\n\tdisplay_fd_set( \"\\tRead\", save_read_fds, max_fd );\n\tdisplay_fd_set( \"\\tWrite\", save_write_fds, max_fd );\n\tdisplay_fd_set( \"\\tExcept\", save_except_fds, max_fd );\n\n\tif( state == FDS_READY ) {\n\t\tdprintf( D_ALWAYS, \"Ready FD's\\n\" );\n\t\tdisplay_fd_set( \"\\tRead\", read_fds, max_fd );\n\t\tdisplay_fd_set( \"\\tWrite\", write_fds, max_fd );\n\t\tdisplay_fd_set( \"\\tExcept\", except_fds, max_fd );\n\t}\n\tif( timeout_wanted ) {\n\t\tdprintf( D_ALWAYS,\n\t\t\t\"Timeout = %ld.%06ld seconds\\n\", (long) timeout.tv_sec, \n\t\t\t(long) timeout.tv_usec\n\t\t);\n\t} else {\n\t\tdprintf( D_ALWAYS, \"Timeout not wanted\\n\" );\n\t}\n\n}\n\nvoid\ndisplay_fd_set( char *msg, fd_set *set, int max )\n{\n\tint\t\ti;\n\n\tdprintf( D_ALWAYS, \"%s {\", msg );\n\tfor( i=0; i<=max; i++ ) {\n\t\tif( FD_ISSET(i,set) ) {\n\t\t\tdprintf( D_ALWAYS | D_NOHEADER, \"%d \", i );\n\t\t}\n\t}\n\tdprintf( D_ALWAYS | D_NOHEADER, \"}\\n\" );\n}\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_version.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"daemon.h\"\n#include \"dc_collector.h\"\n#include \"reli_sock.h\"\n#include \"command_strings.h\"\n#include \"condor_distribution.h\"\n\nint handleHistoryDir(ReliSock *);\n\nvoid\nusage( char *cmd )\n{\n\tfprintf(stderr,\"Usage: %s [options] [.ext]\\n\",cmd);\n\tfprintf(stderr,\"Where options are:\\n\");\n\tfprintf(stderr,\" -help Display options\\n\");\n\tfprintf(stderr,\" -version Display Condor version\\n\");\n\tfprintf(stderr,\" -pool Use this central manager\\n\");\n\tfprintf(stderr,\" -debug Show extra debugging info\\n\");\n\tfprintf(stderr,\"To select a particular daemon to talk to (does NOT select log file), use:\\n\");\n\tfprintf(stderr,\" -master\\n\");\n\tfprintf(stderr,\" -schedd\\n\");\n\tfprintf(stderr,\" -startd\\n\");\n\tfprintf(stderr,\" -collector\\n\");\n\tfprintf(stderr,\" -negotiator\\n\");\n\tfprintf(stderr,\" -kbdd\\n\");\n\tfprintf(stderr,\" -view_collector\\n\");\n\tfprintf(stderr,\"The subsystem name plus optional extension specifies the log file.\\n\");\n\tfprintf(stderr,\"Possible subsystem names (anything with an entry XXX_LOG in remote config file):\\n\");\n\n\tfprintf(stderr,\" MASTER\\n\");\n\tfprintf(stderr,\" COLLECTOR\\n\");\n\tfprintf(stderr,\" NEGOTIATOR\\n\");\n\tfprintf(stderr,\" NEGOTIATOR_MATCH\\n\");\n\tfprintf(stderr,\" SCHEDD\\n\");\n\tfprintf(stderr,\" SHADOW\\n\");\n\tfprintf(stderr,\" STARTD\\n\");\n\tfprintf(stderr,\" STARTER\\n\");\n\tfprintf(stderr,\" KBDD\\n\");\n\tfprintf(stderr,\" HISTORY\\n\");\n\tfprintf(stderr,\" STARTD_HISTORY\\n\");\n\tfprintf(stderr,\"\\nExample 1: %s -debug coral STARTD\\n\",cmd);\n\tfprintf(stderr,\"\\nExample 2: %s -debug coral STARTER.slot2\\n\\n\",cmd);\n}\n\nvoid\nversion()\n{\n\tprintf( \"%s\\n%s\\n\", CondorVersion(), CondorPlatform() );\n}\n\nint main( int argc, char *argv[] )\n{\n\tchar *machine_name = 0;\n\tchar *log_name = 0;\n\tchar *pool=0;\n\tint i;\n\n\tdaemon_t type = DT_MASTER;\n\n\tmyDistro->Init( argc, argv );\n\tconfig();\n\n\tfor( i=1; ilocate()) {\n\t\tfprintf(stderr,\"Couldn't locate daemon on %s: %s\\n\",machine_name,daemon->error());\n\t\texit(1);\n\t}\n\n\tdprintf(D_FULLDEBUG,\"Daemon %s is %s\\n\",daemon->hostname(),daemon->addr());\n\t\n\tsock = (ReliSock*)daemon->startCommand( DC_FETCH_LOG, Sock::reli_sock, 1200);\n\n\tif(!sock) {\n\t\tfprintf(stderr,\"couldn't connect to daemon %s at %s\\n\",daemon->hostname(),daemon->addr());\n\t\treturn 1;\n\t}\n\n\tint commandType = DC_FETCH_LOG_TYPE_PLAIN;\n\tif ((strcmp(log_name, \"HISTORY\") == 0) || (strcmp(log_name, \"STARTD_HISTORY\") == 0)) {\n\t\tcommandType = DC_FETCH_LOG_TYPE_HISTORY;\n\t}\n\n\tif ((strcmp(log_name, \"STARTD.PER_JOB_HISTORY_DIR\") == 0) || (strcmp(log_name, \"STARTD.PER_JOB_HISTORY_DIR\") == 0)) {\n\t\tcommandType = DC_FETCH_LOG_TYPE_HISTORY_DIR;\n\t}\n\n\tsock->put( commandType );\n\tsock->put( log_name );\n\tsock->end_of_message();\n\n\tif (commandType == DC_FETCH_LOG_TYPE_HISTORY_DIR) {\n\t\treturn handleHistoryDir(sock);\n\t}\n\n\tint result = -1;\n\tint exitcode = 1;\n\tconst char *reason=NULL;\n\tfilesize_t filesize;\n\n\tsock->decode();\n\tsock->code(result);\n\n\tswitch(result) {\n\t\tcase -1:\n\t\t\treason = \"permission denied\";\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_SUCCESS:\n\t\t\tresult = sock->get_file(&filesize,1,0);\n\t\t\tif(result>=0) {\n\t\t\t\texitcode = 0;\n\t\t\t} else {\n\t\t\t\treason = \"connection lost\";\n\t\t\t}\n\t\t\twhile (!sock->get_file(&filesize, 1, 0)) ;\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_NO_NAME:\n\t\t\treason = \"no log file by that name\";\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_CANT_OPEN:\n\t\t\treason = \"server was unable to access it\";\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_BAD_TYPE:\n\t\t\treason = \"server can't provide that type of log\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treason = \"unknown error\";\n\t\t\tbreak;\n\t}\n\n\tif(exitcode!=0) {\n\t\tfprintf(stderr,\"Couldn't fetch log: %s.\\n\",reason);\n\t}\n\n\treturn exitcode;\n}\n\nint handleHistoryDir(ReliSock *sock) {\n\tint result = -1;\n\tfilesize_t filesize;\n\tchar *filename = 0;\n\n\tsock->decode();\n\n\tsock->code(result);\n\twhile (result == 1) {\n\t\t\tint fd = -1;\n\t\t\tfilename = NULL;\n\t\t\tsock->code(filename);\n\t\t\tfd = safe_open_wrapper_follow(filename, O_CREAT | O_WRONLY);\n\t\t\tif (fd < 0) {\n\t\t\t\tprintf(\"Can't open local file %s for writing\\n\", filename);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tresult = sock->get_file(&filesize,fd,0);\n\t\t\tclose(fd);\n\t\t\t\n\t\t\tsock->code(result);\n\t\t\tfree(filename);\n\t}\n\treturn 0;\n}\nCheck return code from sock->code() #6345\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_version.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"daemon.h\"\n#include \"dc_collector.h\"\n#include \"reli_sock.h\"\n#include \"command_strings.h\"\n#include \"condor_distribution.h\"\n\nint handleHistoryDir(ReliSock *);\n\nvoid\nusage( char *cmd )\n{\n\tfprintf(stderr,\"Usage: %s [options] [.ext]\\n\",cmd);\n\tfprintf(stderr,\"Where options are:\\n\");\n\tfprintf(stderr,\" -help Display options\\n\");\n\tfprintf(stderr,\" -version Display Condor version\\n\");\n\tfprintf(stderr,\" -pool Use this central manager\\n\");\n\tfprintf(stderr,\" -debug Show extra debugging info\\n\");\n\tfprintf(stderr,\"To select a particular daemon to talk to (does NOT select log file), use:\\n\");\n\tfprintf(stderr,\" -master\\n\");\n\tfprintf(stderr,\" -schedd\\n\");\n\tfprintf(stderr,\" -startd\\n\");\n\tfprintf(stderr,\" -collector\\n\");\n\tfprintf(stderr,\" -negotiator\\n\");\n\tfprintf(stderr,\" -kbdd\\n\");\n\tfprintf(stderr,\" -view_collector\\n\");\n\tfprintf(stderr,\"The subsystem name plus optional extension specifies the log file.\\n\");\n\tfprintf(stderr,\"Possible subsystem names (anything with an entry XXX_LOG in remote config file):\\n\");\n\n\tfprintf(stderr,\" MASTER\\n\");\n\tfprintf(stderr,\" COLLECTOR\\n\");\n\tfprintf(stderr,\" NEGOTIATOR\\n\");\n\tfprintf(stderr,\" NEGOTIATOR_MATCH\\n\");\n\tfprintf(stderr,\" SCHEDD\\n\");\n\tfprintf(stderr,\" SHADOW\\n\");\n\tfprintf(stderr,\" STARTD\\n\");\n\tfprintf(stderr,\" STARTER\\n\");\n\tfprintf(stderr,\" KBDD\\n\");\n\tfprintf(stderr,\" HISTORY\\n\");\n\tfprintf(stderr,\" STARTD_HISTORY\\n\");\n\tfprintf(stderr,\"\\nExample 1: %s -debug coral STARTD\\n\",cmd);\n\tfprintf(stderr,\"\\nExample 2: %s -debug coral STARTER.slot2\\n\\n\",cmd);\n}\n\nvoid\nversion()\n{\n\tprintf( \"%s\\n%s\\n\", CondorVersion(), CondorPlatform() );\n}\n\nint main( int argc, char *argv[] )\n{\n\tchar *machine_name = 0;\n\tchar *log_name = 0;\n\tchar *pool=0;\n\tint i;\n\n\tdaemon_t type = DT_MASTER;\n\n\tmyDistro->Init( argc, argv );\n\tconfig();\n\n\tfor( i=1; ilocate()) {\n\t\tfprintf(stderr,\"Couldn't locate daemon on %s: %s\\n\",machine_name,daemon->error());\n\t\texit(1);\n\t}\n\n\tdprintf(D_FULLDEBUG,\"Daemon %s is %s\\n\",daemon->hostname(),daemon->addr());\n\t\n\tsock = (ReliSock*)daemon->startCommand( DC_FETCH_LOG, Sock::reli_sock, 1200);\n\n\tif(!sock) {\n\t\tfprintf(stderr,\"couldn't connect to daemon %s at %s\\n\",daemon->hostname(),daemon->addr());\n\t\treturn 1;\n\t}\n\n\tint commandType = DC_FETCH_LOG_TYPE_PLAIN;\n\tif ((strcmp(log_name, \"HISTORY\") == 0) || (strcmp(log_name, \"STARTD_HISTORY\") == 0)) {\n\t\tcommandType = DC_FETCH_LOG_TYPE_HISTORY;\n\t}\n\n\tif ((strcmp(log_name, \"STARTD.PER_JOB_HISTORY_DIR\") == 0) || (strcmp(log_name, \"STARTD.PER_JOB_HISTORY_DIR\") == 0)) {\n\t\tcommandType = DC_FETCH_LOG_TYPE_HISTORY_DIR;\n\t}\n\n\tsock->put( commandType );\n\tsock->put( log_name );\n\tsock->end_of_message();\n\n\tif (commandType == DC_FETCH_LOG_TYPE_HISTORY_DIR) {\n\t\treturn handleHistoryDir(sock);\n\t}\n\n\tint result = -1;\n\tint exitcode = 1;\n\tconst char *reason=NULL;\n\tfilesize_t filesize;\n\n\tsock->decode();\n\tif (!sock->code(result)) {\n\t\tfprintf(stderr,\"Couldn't fetch log: server did not reply\\n\");\n\t\treturn -1;\n\t}\n\n\tswitch(result) {\n\t\tcase -1:\n\t\t\treason = \"permission denied\";\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_SUCCESS:\n\t\t\tresult = sock->get_file(&filesize,1,0);\n\t\t\tif(result>=0) {\n\t\t\t\texitcode = 0;\n\t\t\t} else {\n\t\t\t\treason = \"connection lost\";\n\t\t\t}\n\t\t\twhile (!sock->get_file(&filesize, 1, 0)) ;\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_NO_NAME:\n\t\t\treason = \"no log file by that name\";\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_CANT_OPEN:\n\t\t\treason = \"server was unable to access it\";\n\t\t\tbreak;\n\t\tcase DC_FETCH_LOG_RESULT_BAD_TYPE:\n\t\t\treason = \"server can't provide that type of log\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treason = \"unknown error\";\n\t\t\tbreak;\n\t}\n\n\tif(exitcode!=0) {\n\t\tfprintf(stderr,\"Couldn't fetch log: %s.\\n\",reason);\n\t}\n\n\treturn exitcode;\n}\n\nint handleHistoryDir(ReliSock *sock) {\n\tint result = -1;\n\tfilesize_t filesize;\n\tchar *filename = 0;\n\n\tsock->decode();\n\n\tif (!sock->code(result)) {\n\t\tprintf(\"Can't connect to server\\n\");\n\t\texit(1);\n\t}\n\twhile (result == 1) {\n\t\t\tint fd = -1;\n\t\t\tfilename = NULL;\n\t\t\tif (!sock->code(filename)) {\n\t\t\t\tprintf(\"Can't get filename from server\\n\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tfd = safe_open_wrapper_follow(filename, O_CREAT | O_WRONLY);\n\t\t\tif (fd < 0) {\n\t\t\t\tprintf(\"Can't open local file %s for writing\\n\", filename);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tresult = sock->get_file(&filesize,fd,0);\n\t\t\tclose(fd);\n\t\t\t\n\t\t\tif (!sock->code(result)) {\n\t\t\t\tprintf(\"Cannot get result status from server\\n\");\n\t\t\t\tresult = -1;\n\t\t\t}\n\t\t\tfree(filename);\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Aldebaran\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 \"memory_list.hpp\"\n\nnamespace alros {\n\nnamespace converter {\n\nMemoryListConverter::MemoryListConverter(const std::vector& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):\n BaseConverter(name, frequency, session),\n p_memory_(session->service(\"ALMemory\")),\n _key_list(key_list)\n{}\n\nvoid MemoryListConverter::reset(){\n\n}\n\nvoid MemoryListConverter::callAll(const std::vector &actions){\n \/\/ Get inertial data\n AL::ALValue memData = p_memory_.call(\"getListData\", _key_list);\n \/\/ Reset message\n _msg = naoqi_msgs::MemoryList();\n for(int i=0; iAccept bool ALValue (convert them in Int)\/*\n * Copyright 2015 Aldebaran\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 \"memory_list.hpp\"\n\nnamespace alros {\n\nnamespace converter {\n\nMemoryListConverter::MemoryListConverter(const std::vector& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):\n BaseConverter(name, frequency, session),\n p_memory_(session->service(\"ALMemory\")),\n _key_list(key_list)\n{}\n\nvoid MemoryListConverter::reset(){\n\n}\n\nvoid MemoryListConverter::callAll(const std::vector &actions){\n \/\/ Get inertial data\n AL::ALValue memData = p_memory_.call(\"getListData\", _key_list);\n \/\/ Reset message\n _msg = naoqi_msgs::MemoryList();\n for(int i=0; i"} {"text":"\/*\n This file is part of the kblog library.\n\n Copyright (c) 2006-2007 Christian Weilbach \n Copyright (c) 2007 Mike Arthur \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 \"blogposting.h\"\n#include \"blogposting_p.h\"\n\n#include \"blog.h\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace KBlog {\n\nBlogPosting::BlogPosting( const KBlog::BlogPosting& posting ):\n d_ptr( new BlogPostingPrivate )\n{\n d_ptr->q_ptr=this;\n d_ptr->mPrivate=posting.isPrivate();\n d_ptr->mPostingId=posting.postingId();\n d_ptr->mTitle=posting.title();\n d_ptr->mContent=posting.content();\n d_ptr->mCategories=posting.categories();\n d_ptr->mError=posting.error();\n d_ptr->mJournalId=posting.journalId();\n d_ptr->mStatus=posting.status();\n d_ptr->mCreationDateTime=posting.creationDateTime();\n d_ptr->mModificationDateTime=posting.modificationDateTime();\n}\n\nBlogPosting::BlogPosting( const QString &postingId ) :\n d_ptr( new BlogPostingPrivate )\n{\n d_ptr->q_ptr = this;\n d_ptr->mPrivate = false;\n d_ptr->mPostingId = postingId;\n d_ptr->mStatus = New;\n}\n\nBlogPosting::BlogPosting( const KCal::Journal &journal ) :\n d_ptr( new BlogPostingPrivate )\n{\n d_ptr->q_ptr = this;\n d_ptr->mPrivate = false;\n d_ptr->mPostingId = journal.customProperty( \"KBLOG\", \"ID\" );\n d_ptr->mJournalId = journal.uid();\n d_ptr->mStatus = New;\n d_ptr->mTitle = journal.summary();\n d_ptr->mContent = journal.description();\n d_ptr->mCategories = journal.categories();\n d_ptr->mCreationDateTime = journal.dtStart();\n}\n\n\/\/ BlogPosting::BlogPosting( const KCal::Journal &journal, BlogPostingPrivate &dd )\n\/\/ : d_ptr( &dd )\n\/\/ {\n\/\/ d_ptr->q_ptr = this;\n\/\/ d_ptr->mPrivate = false;\n\/\/ d_ptr->mPostingId = journal.customProperty( \"KBLOG\", \"ID\" );\n\/\/ d_ptr->mJournalId = journal.uid();\n\/\/ d_ptr->mStatus = New;\n\/\/ d_ptr->mTitle = journal.summary();\n\/\/ d_ptr->mContent = journal.description();\n\/\/ d_ptr->mCategories = journal.categories();\n\/\/ d_ptr->mCreationDateTime = journal.dtStart();\n\/\/ }\n\nBlogPosting::~BlogPosting()\n{\n delete d_ptr;\n}\n\nKCal::Journal* BlogPosting::journal( const Blog &blog ) const\n{\n QString url = blog.url().url();\n QString username = blog.username();\n QString blogId = blog.blogId();\n \/\/ Generate unique ID. Should be unique enough...\n QString id = \"kblog-\" + url + '-' + blogId + '-' + username +\n '-' + d_ptr->mPostingId;\n KCal::Journal *journal = new KCal::Journal();\n journal->setUid( id );\n journal->setSummary( d_ptr->mTitle );\n journal->setCategories( d_ptr->mCategories );\n \/\/journal->setDescription( d_ptr->mContent, true );\n journal->setDtStart( d_ptr->mCreationDateTime );\n journal->setCustomProperty( \"KBLOG\", \"URL\", url );\n journal->setCustomProperty( \"KBLOG\", \"USER\", blog.username() );\n journal->setCustomProperty( \"KBLOG\", \"BLOG\", blogId );\n journal->setCustomProperty( \"KBLOG\", \"ID\", d_ptr->mPostingId );\n return journal;\n}\n\nQString BlogPosting::journalId() const\n{\n return d_ptr->mJournalId;\n}\n\nbool BlogPosting::isPrivate() const\n{\n return d_ptr->mPrivate;\n}\n\nvoid BlogPosting::setPrivate( bool privatePosting )\n{\n d_ptr->mPrivate = privatePosting;\n}\n\nQString BlogPosting::postingId() const\n{\n return d_ptr->mPostingId;\n}\n\nvoid BlogPosting::setPostingId( const QString &postingId )\n{\n d_ptr->mPostingId = postingId;\n}\n\nQString BlogPosting::title() const\n{\n return d_ptr->mTitle;\n}\n\nvoid BlogPosting::setTitle( const QString &title )\n{\n d_ptr->mTitle = title;\n}\n\nQString BlogPosting::content() const\n{\n return d_ptr->mContent;\n}\n\nvoid BlogPosting::setContent( const QString &content )\n{\n d_ptr->mContent = content;\n}\n\n\/\/ QString BlogPosting::abbreviatedContent() const\n\/\/ {\n\/\/ \/\/TODO\n\/\/ return 0;\n\/\/ }\n\/\/ \n\/\/ void BlogPosting::setAbbreviatedContent( const QString &abbreviatedContent )\n\/\/ {\n\/\/ Q_UNUSED( abbreviatedContent );\n\/\/ \/\/TODO\n\/\/ }\n\nKUrl BlogPosting::link() const\n{\n return d_ptr->mLink;\n}\n\nvoid BlogPosting::setLink( const KUrl &link ) const\n{\n d_ptr->mLink = link;\n}\n\nKUrl BlogPosting::permaLink() const\n{\n return d_ptr->mPermaLink;\n}\n\nvoid BlogPosting::setPermaLink( const KUrl &permalink ) const\n{\n d_ptr->mPermaLink = permalink;\n}\n\nbool BlogPosting::isCommentAllowed() const\n{\n return d_ptr->mCommentAllowed;\n}\n\nvoid BlogPosting::setCommentAllowed( bool commentAllowed )\n{\n d_ptr->mCommentAllowed = commentAllowed;\n}\n\nbool BlogPosting::isTrackBackAllowed() const\n{\n return d_ptr->mCommentAllowed;\n}\n\nvoid BlogPosting::setTrackBackAllowed ( bool allowTrackBacks )\n{\n d_ptr->mTrackBackAllowed = allowTrackBacks;\n}\n\nQString BlogPosting::summary() const\n{\n return d_ptr->mSummary;\n}\n\nvoid BlogPosting::setSummary( const QString &summary )\n{\n d_ptr->mSummary = summary;\n}\n\nQStringList BlogPosting::tags() const\n{\n return d_ptr->mTags;\n}\n\nvoid BlogPosting::setTags( const QStringList &tags )\n{\n d_ptr->mTags = tags;\n}\n\n\/\/ QList BlogPosting::trackBackUrls() const\n\/\/ {\n\/\/ \/\/TODO\n\/\/ return QList();\n\/\/ }\n\/\/ \n\/\/ void BlogPosting::setTrackBackUrls( const QList &trackBackUrls )\n\/\/ {\n\/\/ Q_UNUSED( trackBackUrls );\n\/\/ \/\/TODO\n\/\/ }\n\nQString BlogPosting::mood() const\n{\n \/\/TODO\n return QString();\n}\n\nvoid BlogPosting::setMood( const QString &mood )\n{\n Q_UNUSED( mood );\n \/\/TODO\n}\n\nQString BlogPosting::music() const\n{\n \/\/TODO\n return QString();\n}\n\nvoid BlogPosting::setMusic( const QString &music )\n{\n Q_UNUSED( music );\n \/\/TODO\n}\n\nQStringList BlogPosting::categories() const\n{\n return d_ptr->mCategories;\n}\n\nvoid BlogPosting::setCategories( const QStringList &categories )\n{\n d_ptr->mCategories = categories;\n}\n\nKDateTime BlogPosting::creationDateTime() const\n{\n return d_ptr->mCreationDateTime;\n}\n\nvoid BlogPosting::setCreationDateTime( const KDateTime &datetime )\n{\n d_ptr->mCreationDateTime = datetime;\n}\n\nKDateTime BlogPosting::modificationDateTime() const\n{\n return d_ptr->mModificationDateTime;\n}\n\nvoid BlogPosting::setModificationDateTime( const KDateTime &datetime )\n{\n d_ptr->mModificationDateTime = datetime;\n}\n\nBlogPosting::Status BlogPosting::status() const\n{\n return d_ptr->mStatus;\n}\n\nvoid BlogPosting::setStatus( BlogPosting::Status status )\n{\n d_ptr->mStatus = status;\n\/\/ emit statusChanged( status );\n}\n\nQString BlogPosting::error() const\n{\n return d_ptr->mError;\n}\n\nvoid BlogPosting::setError( const QString &error )\n{\n d_ptr->mError = error;\n}\n\nBlogPosting& BlogPosting::operator=(const BlogPosting &posting)\n{\n *this = BlogPosting ( posting );\n return *this;\n}\n\n} \/\/ namespace KBlog\n\nI apologize, i didn't want to comment this line\/*\n This file is part of the kblog library.\n\n Copyright (c) 2006-2007 Christian Weilbach \n Copyright (c) 2007 Mike Arthur \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 \"blogposting.h\"\n#include \"blogposting_p.h\"\n\n#include \"blog.h\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace KBlog {\n\nBlogPosting::BlogPosting( const KBlog::BlogPosting& posting ):\n d_ptr( new BlogPostingPrivate )\n{\n d_ptr->q_ptr=this;\n d_ptr->mPrivate=posting.isPrivate();\n d_ptr->mPostingId=posting.postingId();\n d_ptr->mTitle=posting.title();\n d_ptr->mContent=posting.content();\n d_ptr->mCategories=posting.categories();\n d_ptr->mError=posting.error();\n d_ptr->mJournalId=posting.journalId();\n d_ptr->mStatus=posting.status();\n d_ptr->mCreationDateTime=posting.creationDateTime();\n d_ptr->mModificationDateTime=posting.modificationDateTime();\n}\n\nBlogPosting::BlogPosting( const QString &postingId ) :\n d_ptr( new BlogPostingPrivate )\n{\n d_ptr->q_ptr = this;\n d_ptr->mPrivate = false;\n d_ptr->mPostingId = postingId;\n d_ptr->mStatus = New;\n}\n\nBlogPosting::BlogPosting( const KCal::Journal &journal ) :\n d_ptr( new BlogPostingPrivate )\n{\n d_ptr->q_ptr = this;\n d_ptr->mPrivate = false;\n d_ptr->mPostingId = journal.customProperty( \"KBLOG\", \"ID\" );\n d_ptr->mJournalId = journal.uid();\n d_ptr->mStatus = New;\n d_ptr->mTitle = journal.summary();\n d_ptr->mContent = journal.description();\n d_ptr->mCategories = journal.categories();\n d_ptr->mCreationDateTime = journal.dtStart();\n}\n\n\/\/ BlogPosting::BlogPosting( const KCal::Journal &journal, BlogPostingPrivate &dd )\n\/\/ : d_ptr( &dd )\n\/\/ {\n\/\/ d_ptr->q_ptr = this;\n\/\/ d_ptr->mPrivate = false;\n\/\/ d_ptr->mPostingId = journal.customProperty( \"KBLOG\", \"ID\" );\n\/\/ d_ptr->mJournalId = journal.uid();\n\/\/ d_ptr->mStatus = New;\n\/\/ d_ptr->mTitle = journal.summary();\n\/\/ d_ptr->mContent = journal.description();\n\/\/ d_ptr->mCategories = journal.categories();\n\/\/ d_ptr->mCreationDateTime = journal.dtStart();\n\/\/ }\n\nBlogPosting::~BlogPosting()\n{\n delete d_ptr;\n}\n\nKCal::Journal* BlogPosting::journal( const Blog &blog ) const\n{\n QString url = blog.url().url();\n QString username = blog.username();\n QString blogId = blog.blogId();\n \/\/ Generate unique ID. Should be unique enough...\n QString id = \"kblog-\" + url + '-' + blogId + '-' + username +\n '-' + d_ptr->mPostingId;\n KCal::Journal *journal = new KCal::Journal();\n journal->setUid( id );\n journal->setSummary( d_ptr->mTitle );\n journal->setCategories( d_ptr->mCategories );\n journal->setDescription( d_ptr->mContent, true );\n journal->setDtStart( d_ptr->mCreationDateTime );\n journal->setCustomProperty( \"KBLOG\", \"URL\", url );\n journal->setCustomProperty( \"KBLOG\", \"USER\", blog.username() );\n journal->setCustomProperty( \"KBLOG\", \"BLOG\", blogId );\n journal->setCustomProperty( \"KBLOG\", \"ID\", d_ptr->mPostingId );\n return journal;\n}\n\nQString BlogPosting::journalId() const\n{\n return d_ptr->mJournalId;\n}\n\nbool BlogPosting::isPrivate() const\n{\n return d_ptr->mPrivate;\n}\n\nvoid BlogPosting::setPrivate( bool privatePosting )\n{\n d_ptr->mPrivate = privatePosting;\n}\n\nQString BlogPosting::postingId() const\n{\n return d_ptr->mPostingId;\n}\n\nvoid BlogPosting::setPostingId( const QString &postingId )\n{\n d_ptr->mPostingId = postingId;\n}\n\nQString BlogPosting::title() const\n{\n return d_ptr->mTitle;\n}\n\nvoid BlogPosting::setTitle( const QString &title )\n{\n d_ptr->mTitle = title;\n}\n\nQString BlogPosting::content() const\n{\n return d_ptr->mContent;\n}\n\nvoid BlogPosting::setContent( const QString &content )\n{\n d_ptr->mContent = content;\n}\n\n\/\/ QString BlogPosting::abbreviatedContent() const\n\/\/ {\n\/\/ \/\/TODO\n\/\/ return 0;\n\/\/ }\n\/\/ \n\/\/ void BlogPosting::setAbbreviatedContent( const QString &abbreviatedContent )\n\/\/ {\n\/\/ Q_UNUSED( abbreviatedContent );\n\/\/ \/\/TODO\n\/\/ }\n\nKUrl BlogPosting::link() const\n{\n return d_ptr->mLink;\n}\n\nvoid BlogPosting::setLink( const KUrl &link ) const\n{\n d_ptr->mLink = link;\n}\n\nKUrl BlogPosting::permaLink() const\n{\n return d_ptr->mPermaLink;\n}\n\nvoid BlogPosting::setPermaLink( const KUrl &permalink ) const\n{\n d_ptr->mPermaLink = permalink;\n}\n\nbool BlogPosting::isCommentAllowed() const\n{\n return d_ptr->mCommentAllowed;\n}\n\nvoid BlogPosting::setCommentAllowed( bool commentAllowed )\n{\n d_ptr->mCommentAllowed = commentAllowed;\n}\n\nbool BlogPosting::isTrackBackAllowed() const\n{\n return d_ptr->mCommentAllowed;\n}\n\nvoid BlogPosting::setTrackBackAllowed ( bool allowTrackBacks )\n{\n d_ptr->mTrackBackAllowed = allowTrackBacks;\n}\n\nQString BlogPosting::summary() const\n{\n return d_ptr->mSummary;\n}\n\nvoid BlogPosting::setSummary( const QString &summary )\n{\n d_ptr->mSummary = summary;\n}\n\nQStringList BlogPosting::tags() const\n{\n return d_ptr->mTags;\n}\n\nvoid BlogPosting::setTags( const QStringList &tags )\n{\n d_ptr->mTags = tags;\n}\n\n\/\/ QList BlogPosting::trackBackUrls() const\n\/\/ {\n\/\/ \/\/TODO\n\/\/ return QList();\n\/\/ }\n\/\/ \n\/\/ void BlogPosting::setTrackBackUrls( const QList &trackBackUrls )\n\/\/ {\n\/\/ Q_UNUSED( trackBackUrls );\n\/\/ \/\/TODO\n\/\/ }\n\nQString BlogPosting::mood() const\n{\n \/\/TODO\n return QString();\n}\n\nvoid BlogPosting::setMood( const QString &mood )\n{\n Q_UNUSED( mood );\n \/\/TODO\n}\n\nQString BlogPosting::music() const\n{\n \/\/TODO\n return QString();\n}\n\nvoid BlogPosting::setMusic( const QString &music )\n{\n Q_UNUSED( music );\n \/\/TODO\n}\n\nQStringList BlogPosting::categories() const\n{\n return d_ptr->mCategories;\n}\n\nvoid BlogPosting::setCategories( const QStringList &categories )\n{\n d_ptr->mCategories = categories;\n}\n\nKDateTime BlogPosting::creationDateTime() const\n{\n return d_ptr->mCreationDateTime;\n}\n\nvoid BlogPosting::setCreationDateTime( const KDateTime &datetime )\n{\n d_ptr->mCreationDateTime = datetime;\n}\n\nKDateTime BlogPosting::modificationDateTime() const\n{\n return d_ptr->mModificationDateTime;\n}\n\nvoid BlogPosting::setModificationDateTime( const KDateTime &datetime )\n{\n d_ptr->mModificationDateTime = datetime;\n}\n\nBlogPosting::Status BlogPosting::status() const\n{\n return d_ptr->mStatus;\n}\n\nvoid BlogPosting::setStatus( BlogPosting::Status status )\n{\n d_ptr->mStatus = status;\n\/\/ emit statusChanged( status );\n}\n\nQString BlogPosting::error() const\n{\n return d_ptr->mError;\n}\n\nvoid BlogPosting::setError( const QString &error )\n{\n d_ptr->mError = error;\n}\n\nBlogPosting& BlogPosting::operator=(const BlogPosting &posting)\n{\n *this = BlogPosting ( posting );\n return *this;\n}\n\n} \/\/ namespace KBlog\n\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#if defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \\\n !defined(GPR_CUSTOM_SYNC)\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/lib\/profiling\/timers.h\"\n\n#ifdef GPR_LOW_LEVEL_COUNTERS\ngpr_atm gpr_mu_locks = 0;\ngpr_atm gpr_counter_atm_cas = 0;\ngpr_atm gpr_counter_atm_add = 0;\n#endif\n\nvoid gpr_mu_init(gpr_mu* mu) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_init(&mu->mutex, nullptr) == 0);\n mu->leak_checker = static_cast(malloc(sizeof(*mu->leak_checker)));\n GPR_ASSERT(mu->leak_checker != nullptr);\n#else\n GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0);\n#endif\n}\n\nvoid gpr_mu_destroy(gpr_mu* mu) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_destroy(&mu->mutex) == 0);\n free(mu->leak_checker);\n#else\n GPR_ASSERT(pthread_mutex_destroy(mu) == 0);\n#endif\n}\n\nvoid gpr_mu_lock(gpr_mu* mu) {\n#ifdef GPR_LOW_LEVEL_COUNTERS\n GPR_ATM_INC_COUNTER(gpr_mu_locks);\n#endif\n GPR_TIMER_SCOPE(\"gpr_mu_lock\", 0);\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_lock(&mu->mutex) == 0);\n#else\n GPR_ASSERT(pthread_mutex_lock(mu) == 0);\n#endif\n}\n\nvoid gpr_mu_unlock(gpr_mu* mu) {\n GPR_TIMER_SCOPE(\"gpr_mu_unlock\", 0);\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_unlock(&mu->mutex) == 0);\n#else\n GPR_ASSERT(pthread_mutex_unlock(mu) == 0);\n#endif\n}\n\nint gpr_mu_trylock(gpr_mu* mu) {\n GPR_TIMER_SCOPE(\"gpr_mu_trylock\", 0);\n int err = 0;\n#ifdef GRPC_ASAN_ENABLED\n err = pthread_mutex_trylock(&mu->mutex);\n#else\n err = pthread_mutex_trylock(mu);\n#endif\n GPR_ASSERT(err == 0 || err == EBUSY);\n return err == 0;\n}\n\n\/*----------------------------------------*\/\n\nvoid gpr_cv_init(gpr_cv* cv) {\n pthread_condattr_t attr;\n GPR_ASSERT(pthread_condattr_init(&attr) == 0);\n#if GPR_LINUX\n GPR_ASSERT(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0);\n#endif \/\/ GPR_LINUX\n\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_init(&cv->cond_var, &attr) == 0);\n cv->leak_checker = static_cast(malloc(sizeof(*cv->leak_checker)));\n GPR_ASSERT(cv->leak_checker != nullptr);\n#else\n GPR_ASSERT(pthread_cond_init(cv, &attr) == 0);\n#endif\n}\n\nvoid gpr_cv_destroy(gpr_cv* cv) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_destroy(&cv->cond_var) == 0);\n free(cv->leak_checker);\n#else\n GPR_ASSERT(pthread_cond_destroy(cv) == 0);\n#endif\n}\n\nint gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {\n int err = 0;\n if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==\n 0) {\n#ifdef GRPC_ASAN_ENABLED\n err = pthread_cond_wait(&cv->cond_var, &mu->mutex);\n#else\n err = pthread_cond_wait(cv, mu);\n#endif\n } else {\n struct timespec abs_deadline_ts;\n#if GPR_LINUX\n abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_MONOTONIC);\n#else\n abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);\n#endif \/\/ GPR_LINUX\n abs_deadline_ts.tv_sec = static_cast(abs_deadline.tv_sec);\n abs_deadline_ts.tv_nsec = abs_deadline.tv_nsec;\n#ifdef GRPC_ASAN_ENABLED\n err = pthread_cond_timedwait(&cv->cond_var, &mu->mutex, &abs_deadline_ts);\n#else\n err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);\n#endif\n }\n GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN);\n return err == ETIMEDOUT;\n}\n\nvoid gpr_cv_signal(gpr_cv* cv) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_signal(&cv->cond_var) == 0);\n#else\n GPR_ASSERT(pthread_cond_signal(cv) == 0);\n#endif\n}\n\nvoid gpr_cv_broadcast(gpr_cv* cv) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_broadcast(&cv->cond_var) == 0);\n#else\n GPR_ASSERT(pthread_cond_broadcast(cv) == 0);\n#endif\n}\n\n\/*----------------------------------------*\/\n\nvoid gpr_once_init(gpr_once* once, void (*init_function)(void)) {\n GPR_ASSERT(pthread_once(once, init_function) == 0);\n}\n\n#endif \/* defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \\\n !defined(GPR_CUSTOM_SYNC) *\/\nLook at now before sleeping (#28996)\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#if defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \\\n !defined(GPR_CUSTOM_SYNC)\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/lib\/profiling\/timers.h\"\n\n#ifdef GPR_LOW_LEVEL_COUNTERS\ngpr_atm gpr_mu_locks = 0;\ngpr_atm gpr_counter_atm_cas = 0;\ngpr_atm gpr_counter_atm_add = 0;\n#endif\n\nvoid gpr_mu_init(gpr_mu* mu) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_init(&mu->mutex, nullptr) == 0);\n mu->leak_checker = static_cast(malloc(sizeof(*mu->leak_checker)));\n GPR_ASSERT(mu->leak_checker != nullptr);\n#else\n GPR_ASSERT(pthread_mutex_init(mu, nullptr) == 0);\n#endif\n}\n\nvoid gpr_mu_destroy(gpr_mu* mu) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_destroy(&mu->mutex) == 0);\n free(mu->leak_checker);\n#else\n GPR_ASSERT(pthread_mutex_destroy(mu) == 0);\n#endif\n}\n\nvoid gpr_mu_lock(gpr_mu* mu) {\n#ifdef GPR_LOW_LEVEL_COUNTERS\n GPR_ATM_INC_COUNTER(gpr_mu_locks);\n#endif\n GPR_TIMER_SCOPE(\"gpr_mu_lock\", 0);\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_lock(&mu->mutex) == 0);\n#else\n GPR_ASSERT(pthread_mutex_lock(mu) == 0);\n#endif\n}\n\nvoid gpr_mu_unlock(gpr_mu* mu) {\n GPR_TIMER_SCOPE(\"gpr_mu_unlock\", 0);\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_mutex_unlock(&mu->mutex) == 0);\n#else\n GPR_ASSERT(pthread_mutex_unlock(mu) == 0);\n#endif\n}\n\nint gpr_mu_trylock(gpr_mu* mu) {\n GPR_TIMER_SCOPE(\"gpr_mu_trylock\", 0);\n int err = 0;\n#ifdef GRPC_ASAN_ENABLED\n err = pthread_mutex_trylock(&mu->mutex);\n#else\n err = pthread_mutex_trylock(mu);\n#endif\n GPR_ASSERT(err == 0 || err == EBUSY);\n return err == 0;\n}\n\n\/*----------------------------------------*\/\n\nvoid gpr_cv_init(gpr_cv* cv) {\n pthread_condattr_t attr;\n GPR_ASSERT(pthread_condattr_init(&attr) == 0);\n#if GPR_LINUX\n GPR_ASSERT(pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) == 0);\n#endif \/\/ GPR_LINUX\n\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_init(&cv->cond_var, &attr) == 0);\n cv->leak_checker = static_cast(malloc(sizeof(*cv->leak_checker)));\n GPR_ASSERT(cv->leak_checker != nullptr);\n#else\n GPR_ASSERT(pthread_cond_init(cv, &attr) == 0);\n#endif\n}\n\nvoid gpr_cv_destroy(gpr_cv* cv) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_destroy(&cv->cond_var) == 0);\n free(cv->leak_checker);\n#else\n GPR_ASSERT(pthread_cond_destroy(cv) == 0);\n#endif\n}\n\nint gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {\n int err = 0;\n if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==\n 0) {\n#ifdef GRPC_ASAN_ENABLED\n err = pthread_cond_wait(&cv->cond_var, &mu->mutex);\n#else\n err = pthread_cond_wait(cv, mu);\n#endif\n } else {\n struct timespec abs_deadline_ts;\n#if GPR_LINUX\n abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_MONOTONIC);\n#else\n abs_deadline = gpr_time_max(abs_deadline, gpr_now(abs_deadline.clock_type));\n abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);\n#endif \/\/ GPR_LINUX\n abs_deadline_ts.tv_sec = static_cast(abs_deadline.tv_sec);\n abs_deadline_ts.tv_nsec = abs_deadline.tv_nsec;\n#ifdef GRPC_ASAN_ENABLED\n err = pthread_cond_timedwait(&cv->cond_var, &mu->mutex, &abs_deadline_ts);\n#else\n err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);\n#endif\n }\n GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN);\n return err == ETIMEDOUT;\n}\n\nvoid gpr_cv_signal(gpr_cv* cv) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_signal(&cv->cond_var) == 0);\n#else\n GPR_ASSERT(pthread_cond_signal(cv) == 0);\n#endif\n}\n\nvoid gpr_cv_broadcast(gpr_cv* cv) {\n#ifdef GRPC_ASAN_ENABLED\n GPR_ASSERT(pthread_cond_broadcast(&cv->cond_var) == 0);\n#else\n GPR_ASSERT(pthread_cond_broadcast(cv) == 0);\n#endif\n}\n\n\/*----------------------------------------*\/\n\nvoid gpr_once_init(gpr_once* once, void (*init_function)(void)) {\n GPR_ASSERT(pthread_once(once, init_function) == 0);\n}\n\n#endif \/* defined(GPR_POSIX_SYNC) && !defined(GPR_ABSEIL_SYNC) && \\\n !defined(GPR_CUSTOM_SYNC) *\/\n<|endoftext|>"} {"text":"\/*\n * This file is part of crash-reporter\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n *\n * Contact: Ville Ilvonen \n * Author: Riku Halonen \n *\n * Copyright (C) 2013 Jolla Ltd.\n * Contact: Jakub Adam \n *\n * This program 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 program 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 program; 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\/\/ User includes.\n\n#include \"creporterdaemon.h\"\n#include \"creporterdaemon_p.h\"\n#include \"creporterdaemonadaptor.h\"\n#include \"creporterdaemonmonitor.h\"\n#include \"creporternwsessionmgr.h\"\n#include \"creportersavedstate.h\"\n#include \"creportercoreregistry.h\"\n#include \"creporterutils.h\"\n#include \"creportersettingsobserver.h\"\n#include \"creporternamespace.h\"\n#include \"creporterprivacysettingsmodel.h\"\n#include \"creporternotification.h\"\n\n#ifndef CREPORTER_UNIT_TEST\n#include \"creportersavedstate.h\"\n#endif\n\n\/\/ ======== MEMBER FUNCTIONS ========\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::CReporterDaemon\n\/\/ ----------------------------------------------------------------------------\nCReporterDaemon::CReporterDaemon() :\n d_ptr(new CReporterDaemonPrivate())\n{\n Q_D(CReporterDaemon);\n\n d->monitor = 0;\n d->timerId = 0;\n\n \/\/ Create registry instance preserving core locations.\n d->registry = new CReporterCoreRegistry();\n Q_CHECK_PTR(d->registry);\n\n \/\/ Adaptor class is deleted automatically, when the class, it is\n \/\/ attached to is deleted.\n new CReporterDaemonAdaptor(this);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::~CReporterDaemon\n\/\/ ----------------------------------------------------------------------------\nCReporterDaemon::~CReporterDaemon()\n{\t\n Q_D(CReporterDaemon);\n qDebug() << __PRETTY_FUNCTION__ << \"Daemon destroyed.\";\n\n if (d->monitor) {\n \/\/ Delete monitor instance and stop core monitoring.\n delete d->monitor;\n d->monitor = 0;\n }\n\n\tdelete d->registry;\n d->registry = 0;\n\n CReporterPrivacySettingsModel::instance()->freeSingleton();\n CReporterSavedState::freeSingleton();\n\n\tdelete d_ptr;\n d_ptr = 0;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::setDelayedStartup\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::setDelayedStartup(int timeout)\n{\n Q_D(CReporterDaemon);\n\n qDebug() << __PRETTY_FUNCTION__ << \"Delaying startup for\" << timeout \/ 1000 << \"seconds.\";\n if (timeout > 0) {\n d->timerId = startTimer(timeout);\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::initiateDaemon\n\/\/ ----------------------------------------------------------------------------\nbool CReporterDaemon::initiateDaemon()\n{\n qDebug() << __PRETTY_FUNCTION__ << \"Starting daemon...\";\n\n if (!CReporterPrivacySettingsModel::instance()->isValid())\n {\n qWarning() << __PRETTY_FUNCTION__ << \"Invalid settings\";\n \/\/ Exit, if settings are missing.\n return false;\n }\n\n QString filename = CReporterPrivacySettingsModel::instance()->settingsFile(); \n\n if (!startService())\n {\n\t\treturn false;\n\t}\n\n if (CReporterPrivacySettingsModel::instance()->notificationsEnabled()\n || CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())\n {\n \/\/ Read from settings file, if monitor should be started.\n startCoreMonitoring();\n }\n\n \/\/ Create observer to monitor changes in settings.\n CReporterSettingsObserver *settingsObserver =\n new CReporterSettingsObserver(filename, this);\n\n settingsObserver->addWatcher(Settings::ValueNotifications);\n settingsObserver->addWatcher(Settings::ValueAutomaticSending);\n settingsObserver->addWatcher(Settings::ValueAutoDeleteDuplicates);\n\n connect(settingsObserver, SIGNAL(valueChanged(QString,QVariant)),\n this, SLOT(settingValueChanged(QString,QVariant)));\n\n#ifndef CREPORTER_UNIT_TEST\n \/\/ Each time daemon is started, we count successful core uploads from zero.\n CReporterSavedState *state = CReporterSavedState::instance();\n state->setUploadSuccessCount(0);\n state->writeSettings();\n#endif\n\n if (CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())\n {\n QStringList files = collectAllCoreFiles();\n\n if (!files.isEmpty() &&\n CReporterNwSessionMgr::unpaidConnectionAvailable() &&\n !CReporterUtils::notifyAutoUploader(files))\n {\n qDebug() << __PRETTY_FUNCTION__ << \"Failed to add files to the queue.\";\n }\n }\n else if (CReporterPrivacySettingsModel::instance()->notificationsEnabled())\n {\n QStringList files = collectAllCoreFiles();\n\n if (!files.isEmpty()) {\n CReporterNotification *notification = new CReporterNotification(\n CReporter::ApplicationNotificationEventType,\n \/\/% \"This system has stored crash reports.\"\n qtTrId(\"crash_reporter-notify-has_stored_cores\"),\n QString(), this);\n\n connect(notification, &CReporterNotification::timeouted,\n notification, &CReporterNotification::deleteLater);\n }\n }\n\n return true;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::startCoreMonitoring\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::startCoreMonitoring(const bool fromDBus)\n{\n Q_D(CReporterDaemon);\n\n qDebug() << __PRETTY_FUNCTION__ << \"Core monitoring requested. Called from DBus =\"\n << fromDBus;\n\n if (!d->monitor) {\n\t\t\/\/ Create monitor instance and start monitoring cores.\n d->monitor = new CReporterDaemonMonitor(d->registry);\n Q_CHECK_PTR(d->monitor);\n\n connect(d->monitor, SIGNAL(richCoreNotify(QString)), SLOT(newCoreDump(QString)));\n\n qDebug() << __PRETTY_FUNCTION__ << \"Core monitoring started.\";\n\n if (fromDBus) {\n CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(true);\n CReporterPrivacySettingsModel::instance()->writeSettings();\n }\n d->monitor->setAutoDelete(CReporterPrivacySettingsModel::instance()->autoDeleteDuplicates());\n d->monitor->setAutoDeleteMaxSimilarCores(\n CReporterPrivacySettingsModel::instance()->autoDeleteMaxSimilarCores());\n d->monitor->setAutoUpload(CReporterPrivacySettingsModel::instance()->automaticSendingEnabled());\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::stopCoreMonitoring\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::stopCoreMonitoring(const bool fromDBus)\n{\n Q_D(CReporterDaemon);\n\t\n if (d->monitor) {\n\t\t\/\/ Delete monitor instance and stop core monitoring.\n\t\tdelete d->monitor;\n d->monitor = 0;\n \n\t\tqDebug() << __PRETTY_FUNCTION__ << \"Core monitoring stopped.\";\n\n if (fromDBus) {\n CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(false);\n CReporterPrivacySettingsModel::instance()->writeSettings();\n }\n\t}\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::collectAllCoreFiles\n\/\/ ----------------------------------------------------------------------------\nQStringList CReporterDaemon::collectAllCoreFiles()\n{\n Q_D(CReporterDaemon);\n\n return d->registry->collectAllCoreFiles();\n}\n\n\/\/ ======== LOCAL FUNCTIONS ========\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::settingValueChanged\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::settingValueChanged(const QString &key, const QVariant &value)\n{\n qDebug() << __PRETTY_FUNCTION__ << \"Setting:\" << key << \"has changed; value:\" << value;\n if (key == Settings::ValueNotifications || key == Settings::ValueAutomaticSending)\n {\n if (value.toBool())\n {\n startCoreMonitoring();\n }\n else if (!CReporterPrivacySettingsModel::instance()->notificationsEnabled()\n && !CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())\n {\n if (key == Settings::ValueAutomaticSending)\n {\n if (d_ptr->monitor)\n {\n d_ptr->monitor->setAutoUpload(value.toBool());\n }\n }\n stopCoreMonitoring();\n }\n }\n else if (key == Settings::ValueAutoDeleteDuplicates)\n {\n if (d_ptr->monitor)\n {\n d_ptr->monitor->setAutoDelete(value.toBool());\n }\n }\n\n if (key == Settings::ValueAutomaticSending)\n {\n if (d_ptr->monitor)\n {\n d_ptr->monitor->setAutoUpload(value.toBool());\n }\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::timerEvent\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::timerEvent(QTimerEvent *event)\n{\n Q_D(CReporterDaemon);\n qDebug() << __PRETTY_FUNCTION__ << \"Startup timer elapsed -> start now.\";\n\n if (event->timerId() != d->timerId) return;\n\n \/\/ Kill timer and initiate daemon.\n killTimer(d->timerId);\n d->timerId = 0;\n\n if (!initiateDaemon()) {\n \/\/ If D-Bus registration fails, quit application.\n qApp->quit();\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::startService\n\/\/ ----------------------------------------------------------------------------\nbool CReporterDaemon::startService()\n{\n\tqDebug() << __PRETTY_FUNCTION__ << \"Starting D-Bus service...\";\n\n if (!QDBusConnection::sessionBus().isConnected()) {\n\t qWarning() << __PRETTY_FUNCTION__ << \"D-Bus not running?\";\n\t return false;\n\t }\n\n if (!QDBusConnection::sessionBus().registerService(CReporter::DaemonServiceName)) {\n qWarning() << __PRETTY_FUNCTION__\n << \"Failed to register service, daemon already running?\";\n return false;\n\t }\n\n qDebug() << __PRETTY_FUNCTION__ << \"Service:\"\n << CReporter::DaemonServiceName << \"registered.\";\n\n QDBusConnection::sessionBus().registerObject(CReporter::DaemonObjectPath, this);\n\n qDebug() << __PRETTY_FUNCTION__ << \"Object:\"\n << CReporter::DaemonObjectPath << \"registered.\";\n\n \/\/ Good to go.\n\tqDebug() << __PRETTY_FUNCTION__ << \"D-Bus service started.\";\n\treturn true;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::stopService\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::stopService()\n{\n\tqDebug() << __PRETTY_FUNCTION__ << \"Stopping D-Bus service...\";\n\n QDBusConnection::sessionBus().unregisterObject(CReporter::DaemonObjectPath);\n QDBusConnection::sessionBus().unregisterService(CReporter::DaemonServiceName);\n}\n\n\/\/ End of file\n[daemon] removed superfluous QObject::connect()\/*\n * This file is part of crash-reporter\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n *\n * Contact: Ville Ilvonen \n * Author: Riku Halonen \n *\n * Copyright (C) 2013 Jolla Ltd.\n * Contact: Jakub Adam \n *\n * This program 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 program 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 program; 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\/\/ User includes.\n\n#include \"creporterdaemon.h\"\n#include \"creporterdaemon_p.h\"\n#include \"creporterdaemonadaptor.h\"\n#include \"creporterdaemonmonitor.h\"\n#include \"creporternwsessionmgr.h\"\n#include \"creportersavedstate.h\"\n#include \"creportercoreregistry.h\"\n#include \"creporterutils.h\"\n#include \"creportersettingsobserver.h\"\n#include \"creporternamespace.h\"\n#include \"creporterprivacysettingsmodel.h\"\n#include \"creporternotification.h\"\n\n#ifndef CREPORTER_UNIT_TEST\n#include \"creportersavedstate.h\"\n#endif\n\n\/\/ ======== MEMBER FUNCTIONS ========\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::CReporterDaemon\n\/\/ ----------------------------------------------------------------------------\nCReporterDaemon::CReporterDaemon() :\n d_ptr(new CReporterDaemonPrivate())\n{\n Q_D(CReporterDaemon);\n\n d->monitor = 0;\n d->timerId = 0;\n\n \/\/ Create registry instance preserving core locations.\n d->registry = new CReporterCoreRegistry();\n Q_CHECK_PTR(d->registry);\n\n \/\/ Adaptor class is deleted automatically, when the class, it is\n \/\/ attached to is deleted.\n new CReporterDaemonAdaptor(this);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::~CReporterDaemon\n\/\/ ----------------------------------------------------------------------------\nCReporterDaemon::~CReporterDaemon()\n{\t\n Q_D(CReporterDaemon);\n qDebug() << __PRETTY_FUNCTION__ << \"Daemon destroyed.\";\n\n if (d->monitor) {\n \/\/ Delete monitor instance and stop core monitoring.\n delete d->monitor;\n d->monitor = 0;\n }\n\n\tdelete d->registry;\n d->registry = 0;\n\n CReporterPrivacySettingsModel::instance()->freeSingleton();\n CReporterSavedState::freeSingleton();\n\n\tdelete d_ptr;\n d_ptr = 0;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::setDelayedStartup\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::setDelayedStartup(int timeout)\n{\n Q_D(CReporterDaemon);\n\n qDebug() << __PRETTY_FUNCTION__ << \"Delaying startup for\" << timeout \/ 1000 << \"seconds.\";\n if (timeout > 0) {\n d->timerId = startTimer(timeout);\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::initiateDaemon\n\/\/ ----------------------------------------------------------------------------\nbool CReporterDaemon::initiateDaemon()\n{\n qDebug() << __PRETTY_FUNCTION__ << \"Starting daemon...\";\n\n if (!CReporterPrivacySettingsModel::instance()->isValid())\n {\n qWarning() << __PRETTY_FUNCTION__ << \"Invalid settings\";\n \/\/ Exit, if settings are missing.\n return false;\n }\n\n QString filename = CReporterPrivacySettingsModel::instance()->settingsFile(); \n\n if (!startService())\n {\n\t\treturn false;\n\t}\n\n if (CReporterPrivacySettingsModel::instance()->notificationsEnabled()\n || CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())\n {\n \/\/ Read from settings file, if monitor should be started.\n startCoreMonitoring();\n }\n\n \/\/ Create observer to monitor changes in settings.\n CReporterSettingsObserver *settingsObserver =\n new CReporterSettingsObserver(filename, this);\n\n settingsObserver->addWatcher(Settings::ValueNotifications);\n settingsObserver->addWatcher(Settings::ValueAutomaticSending);\n settingsObserver->addWatcher(Settings::ValueAutoDeleteDuplicates);\n\n connect(settingsObserver, SIGNAL(valueChanged(QString,QVariant)),\n this, SLOT(settingValueChanged(QString,QVariant)));\n\n#ifndef CREPORTER_UNIT_TEST\n \/\/ Each time daemon is started, we count successful core uploads from zero.\n CReporterSavedState *state = CReporterSavedState::instance();\n state->setUploadSuccessCount(0);\n state->writeSettings();\n#endif\n\n if (CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())\n {\n QStringList files = collectAllCoreFiles();\n\n if (!files.isEmpty() &&\n CReporterNwSessionMgr::unpaidConnectionAvailable() &&\n !CReporterUtils::notifyAutoUploader(files))\n {\n qDebug() << __PRETTY_FUNCTION__ << \"Failed to add files to the queue.\";\n }\n }\n else if (CReporterPrivacySettingsModel::instance()->notificationsEnabled())\n {\n QStringList files = collectAllCoreFiles();\n\n if (!files.isEmpty()) {\n CReporterNotification *notification = new CReporterNotification(\n CReporter::ApplicationNotificationEventType,\n \/\/% \"This system has stored crash reports.\"\n qtTrId(\"crash_reporter-notify-has_stored_cores\"),\n QString(), this);\n\n connect(notification, &CReporterNotification::timeouted,\n notification, &CReporterNotification::deleteLater);\n }\n }\n\n return true;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::startCoreMonitoring\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::startCoreMonitoring(const bool fromDBus)\n{\n Q_D(CReporterDaemon);\n\n qDebug() << __PRETTY_FUNCTION__ << \"Core monitoring requested. Called from DBus =\"\n << fromDBus;\n\n if (!d->monitor) {\n\t\t\/\/ Create monitor instance and start monitoring cores.\n d->monitor = new CReporterDaemonMonitor(d->registry);\n Q_CHECK_PTR(d->monitor);\n\n qDebug() << __PRETTY_FUNCTION__ << \"Core monitoring started.\";\n\n if (fromDBus) {\n CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(true);\n CReporterPrivacySettingsModel::instance()->writeSettings();\n }\n d->monitor->setAutoDelete(CReporterPrivacySettingsModel::instance()->autoDeleteDuplicates());\n d->monitor->setAutoDeleteMaxSimilarCores(\n CReporterPrivacySettingsModel::instance()->autoDeleteMaxSimilarCores());\n d->monitor->setAutoUpload(CReporterPrivacySettingsModel::instance()->automaticSendingEnabled());\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::stopCoreMonitoring\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::stopCoreMonitoring(const bool fromDBus)\n{\n Q_D(CReporterDaemon);\n\t\n if (d->monitor) {\n\t\t\/\/ Delete monitor instance and stop core monitoring.\n\t\tdelete d->monitor;\n d->monitor = 0;\n \n\t\tqDebug() << __PRETTY_FUNCTION__ << \"Core monitoring stopped.\";\n\n if (fromDBus) {\n CReporterPrivacySettingsModel::instance()->setNotificationsEnabled(false);\n CReporterPrivacySettingsModel::instance()->writeSettings();\n }\n\t}\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::collectAllCoreFiles\n\/\/ ----------------------------------------------------------------------------\nQStringList CReporterDaemon::collectAllCoreFiles()\n{\n Q_D(CReporterDaemon);\n\n return d->registry->collectAllCoreFiles();\n}\n\n\/\/ ======== LOCAL FUNCTIONS ========\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::settingValueChanged\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::settingValueChanged(const QString &key, const QVariant &value)\n{\n qDebug() << __PRETTY_FUNCTION__ << \"Setting:\" << key << \"has changed; value:\" << value;\n if (key == Settings::ValueNotifications || key == Settings::ValueAutomaticSending)\n {\n if (value.toBool())\n {\n startCoreMonitoring();\n }\n else if (!CReporterPrivacySettingsModel::instance()->notificationsEnabled()\n && !CReporterPrivacySettingsModel::instance()->automaticSendingEnabled())\n {\n if (key == Settings::ValueAutomaticSending)\n {\n if (d_ptr->monitor)\n {\n d_ptr->monitor->setAutoUpload(value.toBool());\n }\n }\n stopCoreMonitoring();\n }\n }\n else if (key == Settings::ValueAutoDeleteDuplicates)\n {\n if (d_ptr->monitor)\n {\n d_ptr->monitor->setAutoDelete(value.toBool());\n }\n }\n\n if (key == Settings::ValueAutomaticSending)\n {\n if (d_ptr->monitor)\n {\n d_ptr->monitor->setAutoUpload(value.toBool());\n }\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::timerEvent\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::timerEvent(QTimerEvent *event)\n{\n Q_D(CReporterDaemon);\n qDebug() << __PRETTY_FUNCTION__ << \"Startup timer elapsed -> start now.\";\n\n if (event->timerId() != d->timerId) return;\n\n \/\/ Kill timer and initiate daemon.\n killTimer(d->timerId);\n d->timerId = 0;\n\n if (!initiateDaemon()) {\n \/\/ If D-Bus registration fails, quit application.\n qApp->quit();\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::startService\n\/\/ ----------------------------------------------------------------------------\nbool CReporterDaemon::startService()\n{\n\tqDebug() << __PRETTY_FUNCTION__ << \"Starting D-Bus service...\";\n\n if (!QDBusConnection::sessionBus().isConnected()) {\n\t qWarning() << __PRETTY_FUNCTION__ << \"D-Bus not running?\";\n\t return false;\n\t }\n\n if (!QDBusConnection::sessionBus().registerService(CReporter::DaemonServiceName)) {\n qWarning() << __PRETTY_FUNCTION__\n << \"Failed to register service, daemon already running?\";\n return false;\n\t }\n\n qDebug() << __PRETTY_FUNCTION__ << \"Service:\"\n << CReporter::DaemonServiceName << \"registered.\";\n\n QDBusConnection::sessionBus().registerObject(CReporter::DaemonObjectPath, this);\n\n qDebug() << __PRETTY_FUNCTION__ << \"Object:\"\n << CReporter::DaemonObjectPath << \"registered.\";\n\n \/\/ Good to go.\n\tqDebug() << __PRETTY_FUNCTION__ << \"D-Bus service started.\";\n\treturn true;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ CReporterDaemon::stopService\n\/\/ ----------------------------------------------------------------------------\nvoid CReporterDaemon::stopService()\n{\n\tqDebug() << __PRETTY_FUNCTION__ << \"Stopping D-Bus service...\";\n\n QDBusConnection::sessionBus().unregisterObject(CReporter::DaemonObjectPath);\n QDBusConnection::sessionBus().unregisterService(CReporter::DaemonServiceName);\n}\n\n\/\/ End of file\n<|endoftext|>"} {"text":"\n\n#include \n\n#include \"backend\/common\/message_queue.h\"\n#include \"backend\/common\/logger.h\"\n\n#define NOTIFY_SIG SIGUSR1\n\nnamespace peloton {\n\nvoid notify_message(mqd_t *mqdp);\n\nstd::string get_mq_name(oid_t id) {\n return std::string(\"\/backend_\" + std::to_string(id));\n}\n\nmqd_t create_mq(const std::string queue_name) {\n\n mqd_t mqd = mq_open(queue_name.c_str(),\n O_CREAT | O_RDONLY | O_NONBLOCK,\n S_IRUSR | S_IWUSR,\n NULL);\n if (mqd == (mqd_t) -1) {\n LOG_ERROR(\"mq_open during create : %s pid : %d \\n\",\n queue_name.c_str(), getpid());\n return mqd;\n }\n\n LOG_TRACE(\"CREATED QUEUE :: %s getpid : %d \\n\",\n queue_name.c_str(), getpid());\n\n return mqd;\n}\n\nmqd_t open_mq(const std::string queue_name) {\n int flags;\n flags = O_WRONLY | O_NONBLOCK;\n\n mqd_t mqd = mq_open(queue_name.c_str(), flags);\n if (mqd == (mqd_t) -1) {\n perror(\"mq_open during open\");\n }\n\n return mqd;\n}\n\nvoid send_message(mqd_t mqd, const std::string message) {\n int prio = 0;\n LOG_TRACE(\"TRYING TO SEND MESSAGE :: %s \\n\", message.c_str());\n\n if (mq_send(mqd, message.c_str(), message.size(), prio) == -1) {\n perror(\"mq_send\");\n }\n\n LOG_TRACE(\"SENT MESSAGE \\n\");\n}\n\nstatic void\nhandler(int sig)\n{\n \/* Just interrupt sigsuspend() *\/\n}\n\nvoid receive_message(mqd_t *mqdp) {\n ssize_t numRead;\n void *buffer;\n struct mq_attr attr;\n\n LOG_TRACE(\"HANDLER START :: pid : %d \\n\", getpid());\n\n \/\/ Determine mq_msgsize for message queue, and allocate space\n if (mq_getattr(*mqdp, &attr) == -1)\n perror(\"mq_getattr\");\n\n buffer = malloc(attr.mq_msgsize);\n if (buffer == NULL)\n perror(\"malloc\");\n\n while ((numRead = mq_receive(*mqdp, (char *) buffer, attr.mq_msgsize, NULL)) >= 0)\n LOG_TRACE(\"Read %ld bytes\\n\", (long) numRead);\n\n if (errno != EAGAIN) \/* Unexpected error *\/\n perror(\"mq_receive\");\n\n free(buffer);\n LOG_TRACE(\"HANDLER DONE \\n\");\n}\n\n\nvoid notify_message(mqd_t *mqdp)\n{\n struct sigevent sev;\n sigset_t blockMask;\n struct sigaction sa;\n\n LOG_TRACE(\"SETUP NOTIFY \\n\");\n\n \/* Block the notification signal and establish a handler for it *\/\n\n sigemptyset(&blockMask);\n sigaddset(&blockMask, NOTIFY_SIG);\n if (sigprocmask(SIG_BLOCK, &blockMask, NULL) == -1)\n perror(\"sigprocmask\");\n\n sigemptyset(&sa.sa_mask);\n sa.sa_flags = 0;\n sa.sa_handler = handler;\n if (sigaction(NOTIFY_SIG, &sa, NULL) == -1)\n perror(\"sigaction\");\n\n \/* Register for message notification via a signal *\/\n\n sev.sigev_notify = SIGEV_SIGNAL;\n sev.sigev_signo = NOTIFY_SIG;\n\n if (mq_notify(*mqdp, &sev) == -1)\n perror(\"mq_notify\");\n\n LOG_TRACE(\"FINISHED SETUP NOTIFY \\n\");\n\n}\n\nvoid wait_for_message(mqd_t *mqdp) {\n sigset_t emptyMask;\n\n notify_message(mqdp);\n LOG_TRACE(\"GOING TO SUSPEND :: pid : %d \\n\", getpid());\n\n sigemptyset(&emptyMask);\n sigsuspend(&emptyMask); \/* Wait for notification signal *\/\n\n LOG_TRACE(\"WOKE UP :: pid : %d \\n\", getpid());\n\n receive_message(mqdp);\n\n LOG_TRACE(\"FINISH PAUSE \\n\");\n}\n\n} \/\/ End peloton namespace\nClean up some stuff.\n\n#include \n\n#include \"backend\/common\/message_queue.h\"\n#include \"backend\/common\/logger.h\"\n\n#define NOTIFY_SIG SIGUSR1\n\nnamespace peloton {\n\nvoid notify_message(mqd_t *mqdp);\n\nstd::string get_mq_name(oid_t id) {\n return std::string(\"\/backend_\" + std::to_string(id));\n}\n\nmqd_t create_mq(const std::string queue_name) {\n\n mqd_t mqd = mq_open(queue_name.c_str(),\n O_CREAT | O_RDONLY | O_NONBLOCK,\n S_IRUSR | S_IWUSR,\n NULL);\n if (mqd == (mqd_t) -1) {\n LOG_ERROR(\"mq_open during create : %s pid : %d \\n\",\n queue_name.c_str(), getpid());\n return mqd;\n }\n LOG_TRACE(\"CREATED QUEUE :: %s getpid : %d \\n\",\n queue_name.c_str(), getpid());\n\n return mqd;\n}\n\nmqd_t open_mq(const std::string queue_name) {\n int flags;\n flags = O_WRONLY | O_NONBLOCK;\n\n mqd_t mqd = mq_open(queue_name.c_str(), flags);\n if (mqd == (mqd_t) -1) {\n perror(\"mq_open during open\");\n }\n\n return mqd;\n}\n\nvoid send_message(mqd_t mqd, const std::string message) {\n int prio = 0;\n LOG_TRACE(\"TRYING TO SEND MESSAGE :: %s \\n\", message.c_str());\n\n if (mq_send(mqd, message.c_str(), message.size(), prio) == -1) {\n perror(\"mq_send\");\n }\n\n LOG_TRACE(\"SENT MESSAGE \\n\");\n}\n\nstatic void\nhandler(int sig)\n{\n \/\/ Just interrupt sigsuspend()\n}\n\nvoid receive_message(mqd_t *mqdp) {\n ssize_t chars_read;\n void *buffer;\n struct mq_attr attr;\n LOG_TRACE(\"HANDLER :: pid : %d \\n\", getpid());\n\n \/\/ Determine mq_msgsize for message queue, and allocate space\n if (mq_getattr(*mqdp, &attr) == -1)\n perror(\"mq_getattr\");\n\n buffer = malloc(attr.mq_msgsize);\n if (buffer == NULL)\n perror(\"malloc\");\n\n while ((chars_read = mq_receive(*mqdp, (char *) buffer, attr.mq_msgsize, NULL)) >= 0)\n LOG_TRACE(\"Read %ld bytes\\n\", (long) chars_read);\n\n if (errno != EAGAIN) \/\/ Unexpected error\n perror(\"mq_receive\");\n\n free(buffer);\n}\n\n\nvoid notify_message(mqd_t *mqdp)\n{\n struct sigevent sev;\n sigset_t blockMask;\n struct sigaction sa;\n\n LOG_TRACE(\"SETUP NOTIFY \\n\");\n\n \/\/ Block the notification signal and establish a handler for it\n sigemptyset(&blockMask);\n sigaddset(&blockMask, NOTIFY_SIG);\n if (sigprocmask(SIG_BLOCK, &blockMask, NULL) == -1)\n perror(\"sigprocmask\");\n\n sigemptyset(&sa.sa_mask);\n sa.sa_flags = 0;\n sa.sa_handler = handler;\n if (sigaction(NOTIFY_SIG, &sa, NULL) == -1)\n perror(\"sigaction\");\n\n \/\/ Register for message notification via a signal\n sev.sigev_notify = SIGEV_SIGNAL;\n sev.sigev_signo = NOTIFY_SIG;\n\n if (mq_notify(*mqdp, &sev) == -1)\n perror(\"mq_notify\");\n\n}\n\nvoid wait_for_message(mqd_t *mqdp) {\n sigset_t emptyMask;\n\n notify_message(mqdp);\n LOG_TRACE(\"SUSPENDING :: pid : %d \\n\", getpid());\n\n sigemptyset(&emptyMask);\n sigsuspend(&emptyMask); \/\/ Wait for notification signal\n\n LOG_TRACE(\"WOKE UP :: pid : %d \\n\", getpid());\n\n receive_message(mqdp);\n}\n\n} \/\/ End peloton namespace\n<|endoftext|>"} {"text":"#include \"cdriver.h\"\n\nstruct Apex {\n\tdouble axis_min, axis_max;\t\/\/ Limits for the movement of this axis.\n\tdouble rodlength, radius;\t\/\/ Length of the tie rod and the horizontal distance between the vertical position and the zero position.\n\tdouble x, y, z;\t\t\/\/ Position of tower on the base plane, and the carriage height at zero position.\n};\n\nstruct Delta_private {\n\tApex apex[3];\n\tdouble angle;\t\t\t\/\/ Adjust the front of the printer.\n};\n\n#define PRIVATE(s) (*reinterpret_cast (s->type_data))\n#define APEX(s, a) (PRIVATE(s).apex[a])\n\nstatic bool check_delta(Space *s, uint8_t a, double *target) {\t\/\/ {{{\n\tdouble dx = target[0] - APEX(s, a).x;\n\tdouble dy = target[1] - APEX(s, a).y;\n\tdouble r2 = dx * dx + dy * dy;\n\tdouble amax = APEX(s, a).axis_max < APEX(s, a).rodlength ? APEX(s, a).axis_max : APEX(s, a).rodlength;\n\tif (r2 > amax * amax) {\n\t\tdebug (\"not ok 1: %f %f %f %f %f %f %f\", target[0], target[1], dx, dy, r2, APEX(s, a).rodlength, APEX(s, a).axis_max);\n\t\t\/\/ target is too far away from axis. Pull it towards axis so that it is on the edge.\n\t\t\/\/ target = axis + (target - axis) * (l - epsilon) \/ r.\n\t\tdouble factor(amax \/ sqrt(r2));\n\t\ttarget[0] = APEX(s, a).x + (target[0] - APEX(s, a).x) * factor;\n\t\ttarget[1] = APEX(s, a).y + (target[1] - APEX(s, a).y) * factor;\n\t\treturn false;\n\t}\n\t\/\/ Inner product shows if projection is inside or outside the printable region.\n\tdouble projection = -(dx \/ APEX(s, a).radius * APEX(s, a).x + dy \/ APEX(s, a).radius * APEX(s, a).y);\n\tdouble amin = APEX(s, a).axis_min < -APEX(s, a).rodlength ? -APEX(s, a).rodlength : APEX(s, a).axis_min;\n\tif (projection < amin) {\n\t\tdebug (\"not ok 2: %f %f %f %f %f\", projection, dx, dy, APEX(s, a).x, APEX(s, a).y);\n\t\t\/\/ target is on the wrong side of axis. Pull it towards plane so it is on the edge.\n\t\ttarget[0] -= ((amin - projection) \/ APEX(s, a).radius - .001) * APEX(s, a).x;\n\t\ttarget[1] -= ((amin - projection) \/ APEX(s, a).radius - .001) * APEX(s, a).y;\n\t\t\/\/ Assume this was a small correction; that way, things will work even if numerical errors cause this to be called for the real move.\n\t\treturn false;\n\t}\n\t\/\/debug(\"ok %d %d %f\", s->id, a, projection);\n\treturn true;\n}\t\/\/ }}}\n\nstatic inline double delta_to_axis(Space *s, uint8_t a, bool *ok) {\n\tdouble dx = s->axis[0]->settings.target - APEX(s, a).x;\n\tdouble dy = s->axis[1]->settings.target - APEX(s, a).y;\n\tdouble dz = s->axis[2]->settings.target - APEX(s, a).z;\n\tdouble r2 = dx * dx + dy * dy;\n\tdouble l2 = APEX(s, a).rodlength * APEX(s, a).rodlength;\n\tdouble dest = sqrt(l2 - r2) + dz;\n\t\/\/debug(\"dta dx %f dy %f dz %f z %f, r %f target %f\", dx, dy, dz, APEX(s, a).z, r, target);\n\treturn dest;\n}\n\nstatic void xyz2motors(Space *s, double *motors, bool *ok) {\n\tif (isnan(s->axis[0]->settings.target) || isnan(s->axis[1]->settings.target) || isnan(s->axis[2]->settings.target)) {\n\t\t\/\/ Fill up missing targets.\n\t\tfor (uint8_t aa = 0; aa < 3; ++aa) {\n\t\t\tif (isnan(s->axis[aa]->settings.target))\n\t\t\t\ts->axis[aa]->settings.target = s->axis[aa]->settings.current;\n\t\t}\n\t}\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\tif (motors)\n\t\t\tmotors[a] = delta_to_axis(s, a, ok);\n\t\telse\n\t\t\ts->motor[a]->settings.endpos = delta_to_axis(s, a, ok);\n\t}\n}\n\nstatic void reset_pos (Space *s) {\n\t\/\/ All axes' current_pos must be valid and equal, in other words, x=y=0.\n\tdouble p[3];\n\tfor (uint8_t i = 0; i < 3; ++i)\n\t\tp[i] = s->motor[i]->settings.current_pos \/ s->motor[i]->steps_per_unit;\n\tif (p[0] != p[1] || p[0] != p[2]) {\n\t\t\/\/debug(\"resetpos fails\");\n\t\ts->axis[0]->settings.source = NAN;\n\t\ts->axis[1]->settings.source = NAN;\n\t\ts->axis[2]->settings.source = NAN;\n\t}\n\telse {\n\t\t\/\/debug(\"resetpos %f\", p[0]);\n\t\ts->axis[0]->settings.source = 0;\n\t\ts->axis[1]->settings.source = 0;\n\t\ts->axis[2]->settings.source = p[0];\n\t}\n}\n\nstatic void check_position(Space *s, double *data) {\n\tif (isnan(data[0]) || isnan(data[1])) {\n\t\t\/\/ Cannot check; assume it's ok.\n\t\treturn;\n\t}\n\tfor (uint8_t counter = 0; counter < 2; ++counter) {\n\t\tbool ok = true;\n\t\tfor (uint8_t a = 0; a < s->num_axes; ++a)\n\t\t\tok &= check_delta(s, a, data);\n\t\tif (ok)\n\t\t\tbreak;\n\t}\n}\n\nstatic void load(Space *s, uint8_t old_type, int32_t &addr) {\n\tif (!s->setup_nums(3, 3)) {\n\t\tdebug(\"Failed to set up delta axes\");\n\t\ts->cancel_update();\n\t\treturn;\n\t}\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\tAPEX(s, a).axis_min = read_float(addr);\n\t\tAPEX(s, a).axis_max = read_float(addr);\n\t\tAPEX(s, a).rodlength = read_float(addr);\n\t\tAPEX(s, a).radius = read_float(addr);\n\t}\n\tPRIVATE(s).angle = read_float(addr);\n\tif (isinf(PRIVATE(s).angle) || isnan(PRIVATE(s).angle))\n\t\tPRIVATE(s).angle = 0;\n#define sin210 -.5\n#define cos210 -0.8660254037844386\t\/\/ .5*sqrt(3)\n#define sin330 -.5\n#define cos330 0.8660254037844386\t\/\/ .5*sqrt(3)\n#define sin90 1\n\t\/\/ Coordinates of axes (at angles 210, 330, 90; each with its own radius).\n\tdouble x[3], y[3];\n\tx[0] = APEX(s, 0).radius * cos210;\n\ty[0] = APEX(s, 0).radius * sin210;\n\tx[1] = APEX(s, 1).radius * cos330;\n\ty[1] = APEX(s, 1).radius * sin330;\n\tx[2] = 0;\n\ty[2] = APEX(s, 2).radius * sin90;\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\tAPEX(s, a).x = x[a] * cos(PRIVATE(s).angle) - y[a] * sin(PRIVATE(s).angle);\n\t\tAPEX(s, a).y = y[a] * cos(PRIVATE(s).angle) + x[a] * sin(PRIVATE(s).angle);\n\t\tAPEX(s, a).z = sqrt(APEX(s, a).rodlength * APEX(s, a).rodlength - APEX(s, a).radius * APEX(s, a).radius);\n\t}\n}\n\nstatic void save(Space *s, int32_t &addr) {\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\twrite_float(addr, APEX(s, a).axis_min);\n\t\twrite_float(addr, APEX(s, a).axis_max);\n\t\twrite_float(addr, APEX(s, a).rodlength);\n\t\twrite_float(addr, APEX(s, a).radius);\n\t}\n\twrite_float(addr, PRIVATE(s).angle);\n}\n\nstatic bool init(Space *s) {\n\ts->type_data = new Delta_private;\n\tif (!s->type_data)\n\t\treturn false;\n\treturn true;\n}\n\nstatic void free(Space *s) {\n\tdelete reinterpret_cast (s->type_data);\n}\n\nstatic void afree(Space *s, int a) {\n}\n\nstatic double change0(Space *s, int axis, double value) {\n\treturn value;\n}\n\nstatic double unchange0(Space *s, int axis, double value) {\n\treturn value;\n}\n\nstatic double probe_speed(Space *s) {\n\tdouble max_spu = 0;\n\tfor (int i = 0; i < s->num_motors; ++i)\n\t\tif (max_spu < s->motor[i]->steps_per_unit)\n\t\t\tmax_spu = s->motor[i]->steps_per_unit;\n\treturn 1e6 \/ hwtime_step \/ max_spu;\n}\n\nvoid Delta_init(int num) {\n\tspace_types[num].xyz2motors = xyz2motors;\n\tspace_types[num].reset_pos = reset_pos;\n\tspace_types[num].check_position = check_position;\n\tspace_types[num].load = load;\n\tspace_types[num].save = save;\n\tspace_types[num].init = init;\n\tspace_types[num].free = free;\n\tspace_types[num].afree = afree;\n\tspace_types[num].change0 = change0;\n\tspace_types[num].unchange0 = unchange0;\n\tspace_types[num].probe_speed = probe_speed;\n}\nfix check_position for single axis moves#include \"cdriver.h\"\n\nstruct Apex {\n\tdouble axis_min, axis_max;\t\/\/ Limits for the movement of this axis.\n\tdouble rodlength, radius;\t\/\/ Length of the tie rod and the horizontal distance between the vertical position and the zero position.\n\tdouble x, y, z;\t\t\/\/ Position of tower on the base plane, and the carriage height at zero position.\n};\n\nstruct Delta_private {\n\tApex apex[3];\n\tdouble angle;\t\t\t\/\/ Adjust the front of the printer.\n};\n\n#define PRIVATE(s) (*reinterpret_cast (s->type_data))\n#define APEX(s, a) (PRIVATE(s).apex[a])\n\nstatic bool check_delta(Space *s, uint8_t a, double *target) {\t\/\/ {{{\n\tdouble dx = target[0] - APEX(s, a).x;\n\tdouble dy = target[1] - APEX(s, a).y;\n\tdouble r2 = dx * dx + dy * dy;\n\tdouble amax = APEX(s, a).axis_max < APEX(s, a).rodlength ? APEX(s, a).axis_max : APEX(s, a).rodlength;\n\tif (r2 > amax * amax) {\n\t\tdebug (\"not ok 1: %f %f %f %f %f %f %f\", target[0], target[1], dx, dy, r2, APEX(s, a).rodlength, APEX(s, a).axis_max);\n\t\t\/\/ target is too far away from axis. Pull it towards axis so that it is on the edge.\n\t\t\/\/ target = axis + (target - axis) * (l - epsilon) \/ r.\n\t\tdouble factor(amax \/ sqrt(r2));\n\t\ttarget[0] = APEX(s, a).x + (target[0] - APEX(s, a).x) * factor;\n\t\ttarget[1] = APEX(s, a).y + (target[1] - APEX(s, a).y) * factor;\n\t\treturn false;\n\t}\n\t\/\/ Inner product shows if projection is inside or outside the printable region.\n\tdouble projection = -(dx \/ APEX(s, a).radius * APEX(s, a).x + dy \/ APEX(s, a).radius * APEX(s, a).y);\n\tdouble amin = APEX(s, a).axis_min < -APEX(s, a).rodlength ? -APEX(s, a).rodlength : APEX(s, a).axis_min;\n\tif (projection < amin) {\n\t\tdebug (\"not ok 2: %f %f %f %f %f\", projection, dx, dy, APEX(s, a).x, APEX(s, a).y);\n\t\t\/\/ target is on the wrong side of axis. Pull it towards plane so it is on the edge.\n\t\ttarget[0] -= ((amin - projection) \/ APEX(s, a).radius - .001) * APEX(s, a).x;\n\t\ttarget[1] -= ((amin - projection) \/ APEX(s, a).radius - .001) * APEX(s, a).y;\n\t\t\/\/ Assume this was a small correction; that way, things will work even if numerical errors cause this to be called for the real move.\n\t\treturn false;\n\t}\n\t\/\/debug(\"ok %d %d %f\", s->id, a, projection);\n\treturn true;\n}\t\/\/ }}}\n\nstatic inline double delta_to_axis(Space *s, uint8_t a, bool *ok) {\n\tdouble dx = s->axis[0]->settings.target - APEX(s, a).x;\n\tdouble dy = s->axis[1]->settings.target - APEX(s, a).y;\n\tdouble dz = s->axis[2]->settings.target - APEX(s, a).z;\n\tdouble r2 = dx * dx + dy * dy;\n\tdouble l2 = APEX(s, a).rodlength * APEX(s, a).rodlength;\n\tdouble dest = sqrt(l2 - r2) + dz;\n\t\/\/debug(\"dta dx %f dy %f dz %f z %f, r %f target %f\", dx, dy, dz, APEX(s, a).z, r, target);\n\treturn dest;\n}\n\nstatic void xyz2motors(Space *s, double *motors, bool *ok) {\n\tif (isnan(s->axis[0]->settings.target) || isnan(s->axis[1]->settings.target) || isnan(s->axis[2]->settings.target)) {\n\t\t\/\/ Fill up missing targets.\n\t\tfor (uint8_t aa = 0; aa < 3; ++aa) {\n\t\t\tif (isnan(s->axis[aa]->settings.target))\n\t\t\t\ts->axis[aa]->settings.target = s->axis[aa]->settings.current;\n\t\t}\n\t}\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\tif (motors)\n\t\t\tmotors[a] = delta_to_axis(s, a, ok);\n\t\telse\n\t\t\ts->motor[a]->settings.endpos = delta_to_axis(s, a, ok);\n\t}\n}\n\nstatic void reset_pos (Space *s) {\n\t\/\/ All axes' current_pos must be valid and equal, in other words, x=y=0.\n\tdouble p[3];\n\tfor (uint8_t i = 0; i < 3; ++i)\n\t\tp[i] = s->motor[i]->settings.current_pos \/ s->motor[i]->steps_per_unit;\n\tif (p[0] != p[1] || p[0] != p[2]) {\n\t\t\/\/debug(\"resetpos fails\");\n\t\ts->axis[0]->settings.source = NAN;\n\t\ts->axis[1]->settings.source = NAN;\n\t\ts->axis[2]->settings.source = NAN;\n\t}\n\telse {\n\t\t\/\/debug(\"resetpos %f\", p[0]);\n\t\ts->axis[0]->settings.source = 0;\n\t\ts->axis[1]->settings.source = 0;\n\t\ts->axis[2]->settings.source = p[0];\n\t}\n}\n\nstatic void check_position(Space *s, double *data) {\n\tif (isnan(data[0]) || isnan(data[1])) {\n\t\tif (!isnan(data[0]))\n\t\t\tdata[1] = s->axis[1]->settings.source;\n\t\telse if (!isnan(data[1]))\n\t\t\tdata[0] = s->axis[0]->settings.source;\n\t\telse {\n\t\t\t\/\/ Cannot check; assume it's ok.\n\t\t\treturn;\n\t\t}\n\t}\n\tfor (uint8_t counter = 0; counter < 2; ++counter) {\n\t\tbool ok = true;\n\t\tfor (uint8_t a = 0; a < s->num_axes; ++a)\n\t\t\tok &= check_delta(s, a, data);\n\t\tif (ok)\n\t\t\tbreak;\n\t}\n}\n\nstatic void load(Space *s, uint8_t old_type, int32_t &addr) {\n\tif (!s->setup_nums(3, 3)) {\n\t\tdebug(\"Failed to set up delta axes\");\n\t\ts->cancel_update();\n\t\treturn;\n\t}\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\tAPEX(s, a).axis_min = read_float(addr);\n\t\tAPEX(s, a).axis_max = read_float(addr);\n\t\tAPEX(s, a).rodlength = read_float(addr);\n\t\tAPEX(s, a).radius = read_float(addr);\n\t}\n\tPRIVATE(s).angle = read_float(addr);\n\tif (isinf(PRIVATE(s).angle) || isnan(PRIVATE(s).angle))\n\t\tPRIVATE(s).angle = 0;\n#define sin210 -.5\n#define cos210 -0.8660254037844386\t\/\/ .5*sqrt(3)\n#define sin330 -.5\n#define cos330 0.8660254037844386\t\/\/ .5*sqrt(3)\n#define sin90 1\n\t\/\/ Coordinates of axes (at angles 210, 330, 90; each with its own radius).\n\tdouble x[3], y[3];\n\tx[0] = APEX(s, 0).radius * cos210;\n\ty[0] = APEX(s, 0).radius * sin210;\n\tx[1] = APEX(s, 1).radius * cos330;\n\ty[1] = APEX(s, 1).radius * sin330;\n\tx[2] = 0;\n\ty[2] = APEX(s, 2).radius * sin90;\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\tAPEX(s, a).x = x[a] * cos(PRIVATE(s).angle) - y[a] * sin(PRIVATE(s).angle);\n\t\tAPEX(s, a).y = y[a] * cos(PRIVATE(s).angle) + x[a] * sin(PRIVATE(s).angle);\n\t\tAPEX(s, a).z = sqrt(APEX(s, a).rodlength * APEX(s, a).rodlength - APEX(s, a).radius * APEX(s, a).radius);\n\t}\n}\n\nstatic void save(Space *s, int32_t &addr) {\n\tfor (uint8_t a = 0; a < 3; ++a) {\n\t\twrite_float(addr, APEX(s, a).axis_min);\n\t\twrite_float(addr, APEX(s, a).axis_max);\n\t\twrite_float(addr, APEX(s, a).rodlength);\n\t\twrite_float(addr, APEX(s, a).radius);\n\t}\n\twrite_float(addr, PRIVATE(s).angle);\n}\n\nstatic bool init(Space *s) {\n\ts->type_data = new Delta_private;\n\tif (!s->type_data)\n\t\treturn false;\n\treturn true;\n}\n\nstatic void free(Space *s) {\n\tdelete reinterpret_cast (s->type_data);\n}\n\nstatic void afree(Space *s, int a) {\n}\n\nstatic double change0(Space *s, int axis, double value) {\n\treturn value;\n}\n\nstatic double unchange0(Space *s, int axis, double value) {\n\treturn value;\n}\n\nstatic double probe_speed(Space *s) {\n\tdouble max_spu = 0;\n\tfor (int i = 0; i < s->num_motors; ++i)\n\t\tif (max_spu < s->motor[i]->steps_per_unit)\n\t\t\tmax_spu = s->motor[i]->steps_per_unit;\n\treturn 1e6 \/ hwtime_step \/ max_spu;\n}\n\nvoid Delta_init(int num) {\n\tspace_types[num].xyz2motors = xyz2motors;\n\tspace_types[num].reset_pos = reset_pos;\n\tspace_types[num].check_position = check_position;\n\tspace_types[num].load = load;\n\tspace_types[num].save = save;\n\tspace_types[num].init = init;\n\tspace_types[num].free = free;\n\tspace_types[num].afree = afree;\n\tspace_types[num].change0 = change0;\n\tspace_types[num].unchange0 = unchange0;\n\tspace_types[num].probe_speed = probe_speed;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: validat.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 11:58:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_VALIDAT_HXX\n#define SC_VALIDAT_HXX\n\n#ifndef SC_CONDITIO_HXX\n#include \"conditio.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SHEET_TABLEVALIDATIONVISIBILITY_HPP_\n#include \n#endif\n\nnamespace ValidListType = ::com::sun::star::sheet::TableValidationVisibility;\n\nclass ScPatternAttr;\nclass ScTokenArray;\nclass TypedStrCollection;\n\nenum ScValidationMode\n{\n SC_VALID_ANY,\n SC_VALID_WHOLE,\n SC_VALID_DECIMAL,\n SC_VALID_DATE,\n SC_VALID_TIME,\n SC_VALID_TEXTLEN,\n SC_VALID_LIST,\n SC_VALID_CUSTOM\n};\n\nenum ScValidErrorStyle\n{\n SC_VALERR_STOP,\n SC_VALERR_WARNING,\n SC_VALERR_INFO,\n SC_VALERR_MACRO\n};\n\n\/\/\n\/\/ Eintrag fuer Gueltigkeit (es gibt nur eine Bedingung)\n\/\/\n\nclass ScValidationData : public ScConditionEntry\n{\n sal_uInt32 nKey; \/\/ Index in Attributen\n\n ScValidationMode eDataMode;\n BOOL bShowInput;\n BOOL bShowError;\n ScValidErrorStyle eErrorStyle;\n sal_Int16 mnListType; \/\/ selection list type: none, unsorted, sorted.\n String aInputTitle;\n String aInputMessage;\n String aErrorTitle;\n String aErrorMessage;\n\n BOOL bIsUsed; \/\/ temporaer beim Speichern\n\n BOOL DoMacro( const ScAddress& rPos, const String& rInput,\n ScFormulaCell* pCell, Window* pParent ) const;\n\n BOOL DoScript( const ScAddress& rPos, const String& rInput,\n ScFormulaCell* pCell, Window* pParent ) const;\n\n using ScConditionEntry::operator==;\n\npublic:\n ScValidationData( ScValidationMode eMode, ScConditionMode eOper,\n const String& rExpr1, const String& rExpr2,\n ScDocument* pDocument, const ScAddress& rPos,\n BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );\n ScValidationData( ScValidationMode eMode, ScConditionMode eOper,\n const ScTokenArray* pArr1, const ScTokenArray* pArr2,\n ScDocument* pDocument, const ScAddress& rPos );\n ScValidationData( const ScValidationData& r );\n ScValidationData( ScDocument* pDocument, const ScValidationData& r );\n ScValidationData( SvStream& rStream, ScMultipleReadHeader& rHdr,\n ScDocument* pDocument );\n virtual ~ScValidationData();\n\n void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;\n\n ScValidationData* Clone() const \/\/ echte Kopie\n { return new ScValidationData( GetDocument(), *this ); }\n ScValidationData* Clone(ScDocument* pNew) const\n { return new ScValidationData( pNew, *this ); }\n\n void ResetInput();\n void ResetError();\n void SetInput( const String& rTitle, const String& rMsg );\n void SetError( const String& rTitle, const String& rMsg,\n ScValidErrorStyle eStyle );\n\n BOOL GetInput( String& rTitle, String& rMsg ) const\n { rTitle = aInputTitle; rMsg = aInputMessage; return bShowInput; }\n BOOL GetErrMsg( String& rTitle, String& rMsg, ScValidErrorStyle& rStyle ) const;\n\n BOOL HasErrMsg() const { return bShowError; }\n\n ScValidationMode GetDataMode() const { return eDataMode; }\n\n inline sal_Int16 GetListType() const { return mnListType; }\n inline void SetListType( sal_Int16 nListType ) { mnListType = nListType; }\n\n \/** Returns true, if the validation cell will show a selection list.\n @descr Use this instead of GetListType() which returns the raw property\n regardless of the validation type. *\/\n bool HasSelectionList() const;\n \/** Tries to fill the passed collection with list validation entries.\n @descr Fills the list only, if this is a list validation and IsShowList() is enabled.\n @param rStrings (out-param) The string list to fill with list validation entires.\n @return true = rStrings has been filled with at least one entry. *\/\n bool FillSelectionList( TypedStrCollection& rStrings, const ScAddress rPos ) const;\n\n \/\/ mit String: bei Eingabe, mit Zelle: fuer Detektiv \/ RC_FORCED\n BOOL IsDataValid( const String& rTest, const ScPatternAttr& rPattern,\n const ScAddress& rPos ) const;\n BOOL IsDataValid( ScBaseCell* pCell, const ScAddress& rPos ) const;\n\n \/\/ TRUE -> Abbruch\n BOOL DoError( Window* pParent, const String& rInput, const ScAddress& rPos ) const;\n void DoCalcError( ScFormulaCell* pCell ) const;\n\n BOOL IsEmpty() const;\n sal_uInt32 GetKey() const { return nKey; }\n void SetKey(sal_uInt32 nNew) { nKey = nNew; } \/\/ nur wenn nicht eingefuegt!\n\n void SetUsed(BOOL bSet) { bIsUsed = bSet; }\n BOOL IsUsed() const { return bIsUsed; }\n\n BOOL EqualEntries( const ScValidationData& r ) const; \/\/ fuer Undo\n\n \/\/ sortiert (per PTRARR) nach Index\n \/\/ operator== nur fuer die Sortierung\n BOOL operator ==( const ScValidationData& r ) const { return nKey == r.nKey; }\n BOOL operator < ( const ScValidationData& r ) const { return nKey < r.nKey; }\n\nprivate:\n \/** Tries to get a cell range from a list validation formula.\n @descr The formula may contain a cell reference, a defined name or a database range.\n @param rRange (out-param) The resulting cell range.\n @param rBaseAddr Base address for relative references.\n @return true = Cell range found, rRange is valid. *\/\n bool GetRangeFromFormula( ScRange& rRange, const ScAddress& rBaseAddr, ScTokenArray& rTokArr, int nRecCount = 0 ) const;\n\n \/** Tests, if pCell is equal to what the passed token array represents. *\/\n bool IsEqualToTokenArray( ScBaseCell* pCell, const ScAddress& rPos, const ScTokenArray& rTokArr ) const;\n\n \/** Tests, if contents of pCell occur in cell range referenced by own formula, or in a string list. *\/\n bool IsListValid( ScBaseCell* pCell, const ScAddress& rPos ) const;\n};\n\n\/\/\n\/\/ Liste der Bedingungen:\n\/\/\n\ntypedef ScValidationData* ScValidationDataPtr;\n\nSV_DECL_PTRARR_SORT(ScValidationEntries_Impl, ScValidationDataPtr,\n SC_COND_GROW, SC_COND_GROW)\n\nclass ScValidationDataList : public ScValidationEntries_Impl\n{\npublic:\n ScValidationDataList() {}\n ScValidationDataList(const ScValidationDataList& rList);\n ScValidationDataList(ScDocument* pNewDoc, const ScValidationDataList& rList);\n ~ScValidationDataList() {}\n\n void InsertNew( ScValidationData* pNew )\n { if (!Insert(pNew)) delete pNew; }\n\n ScValidationData* GetData( sal_uInt32 nKey );\n\n void Load( SvStream& rStream, ScDocument* pDocument );\n void Store( SvStream& rStream ) const;\n void ResetUsed();\n\n void CompileXML();\n void UpdateReference( UpdateRefMode eUpdateRefMode,\n const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );\n void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );\n\n BOOL operator==( const ScValidationDataList& r ) const; \/\/ fuer Ref-Undo\n};\n\n#endif\n\nINTEGRATION: CWS dr54 (1.12.58); FILE MERGED 2007\/05\/25 16:49:45 er 1.12.58.1: #i56566# input validation with dynamic ranges as formua results\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: validat.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2007-07-03 15:46:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_VALIDAT_HXX\n#define SC_VALIDAT_HXX\n\n#ifndef SC_CONDITIO_HXX\n#include \"conditio.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_SHEET_TABLEVALIDATIONVISIBILITY_HPP_\n#include \n#endif\n\nnamespace ValidListType = ::com::sun::star::sheet::TableValidationVisibility;\n\nclass ScPatternAttr;\nclass ScTokenArray;\nclass TypedStrCollection;\n\nenum ScValidationMode\n{\n SC_VALID_ANY,\n SC_VALID_WHOLE,\n SC_VALID_DECIMAL,\n SC_VALID_DATE,\n SC_VALID_TIME,\n SC_VALID_TEXTLEN,\n SC_VALID_LIST,\n SC_VALID_CUSTOM\n};\n\nenum ScValidErrorStyle\n{\n SC_VALERR_STOP,\n SC_VALERR_WARNING,\n SC_VALERR_INFO,\n SC_VALERR_MACRO\n};\n\n\/\/\n\/\/ Eintrag fuer Gueltigkeit (es gibt nur eine Bedingung)\n\/\/\n\nclass ScValidationData : public ScConditionEntry\n{\n sal_uInt32 nKey; \/\/ Index in Attributen\n\n ScValidationMode eDataMode;\n BOOL bShowInput;\n BOOL bShowError;\n ScValidErrorStyle eErrorStyle;\n sal_Int16 mnListType; \/\/ selection list type: none, unsorted, sorted.\n String aInputTitle;\n String aInputMessage;\n String aErrorTitle;\n String aErrorMessage;\n\n BOOL bIsUsed; \/\/ temporaer beim Speichern\n\n BOOL DoMacro( const ScAddress& rPos, const String& rInput,\n ScFormulaCell* pCell, Window* pParent ) const;\n\n BOOL DoScript( const ScAddress& rPos, const String& rInput,\n ScFormulaCell* pCell, Window* pParent ) const;\n\n using ScConditionEntry::operator==;\n\npublic:\n ScValidationData( ScValidationMode eMode, ScConditionMode eOper,\n const String& rExpr1, const String& rExpr2,\n ScDocument* pDocument, const ScAddress& rPos,\n BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );\n ScValidationData( ScValidationMode eMode, ScConditionMode eOper,\n const ScTokenArray* pArr1, const ScTokenArray* pArr2,\n ScDocument* pDocument, const ScAddress& rPos );\n ScValidationData( const ScValidationData& r );\n ScValidationData( ScDocument* pDocument, const ScValidationData& r );\n ScValidationData( SvStream& rStream, ScMultipleReadHeader& rHdr,\n ScDocument* pDocument );\n virtual ~ScValidationData();\n\n void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;\n\n ScValidationData* Clone() const \/\/ echte Kopie\n { return new ScValidationData( GetDocument(), *this ); }\n ScValidationData* Clone(ScDocument* pNew) const\n { return new ScValidationData( pNew, *this ); }\n\n void ResetInput();\n void ResetError();\n void SetInput( const String& rTitle, const String& rMsg );\n void SetError( const String& rTitle, const String& rMsg,\n ScValidErrorStyle eStyle );\n\n BOOL GetInput( String& rTitle, String& rMsg ) const\n { rTitle = aInputTitle; rMsg = aInputMessage; return bShowInput; }\n BOOL GetErrMsg( String& rTitle, String& rMsg, ScValidErrorStyle& rStyle ) const;\n\n BOOL HasErrMsg() const { return bShowError; }\n\n ScValidationMode GetDataMode() const { return eDataMode; }\n\n inline sal_Int16 GetListType() const { return mnListType; }\n inline void SetListType( sal_Int16 nListType ) { mnListType = nListType; }\n\n \/** Returns true, if the validation cell will show a selection list.\n @descr Use this instead of GetListType() which returns the raw property\n regardless of the validation type. *\/\n bool HasSelectionList() const;\n \/** Tries to fill the passed collection with list validation entries.\n @descr Fills the list only, if this is a list validation and IsShowList() is enabled.\n @param rStrings (out-param) The string list to fill with list validation entires.\n @return true = rStrings has been filled with at least one entry. *\/\n bool FillSelectionList( TypedStrCollection& rStrings, const ScAddress& rPos ) const;\n\n \/\/ mit String: bei Eingabe, mit Zelle: fuer Detektiv \/ RC_FORCED\n BOOL IsDataValid( const String& rTest, const ScPatternAttr& rPattern,\n const ScAddress& rPos ) const;\n BOOL IsDataValid( ScBaseCell* pCell, const ScAddress& rPos ) const;\n\n \/\/ TRUE -> Abbruch\n BOOL DoError( Window* pParent, const String& rInput, const ScAddress& rPos ) const;\n void DoCalcError( ScFormulaCell* pCell ) const;\n\n BOOL IsEmpty() const;\n sal_uInt32 GetKey() const { return nKey; }\n void SetKey(sal_uInt32 nNew) { nKey = nNew; } \/\/ nur wenn nicht eingefuegt!\n\n void SetUsed(BOOL bSet) { bIsUsed = bSet; }\n BOOL IsUsed() const { return bIsUsed; }\n\n BOOL EqualEntries( const ScValidationData& r ) const; \/\/ fuer Undo\n\n \/\/ sortiert (per PTRARR) nach Index\n \/\/ operator== nur fuer die Sortierung\n BOOL operator ==( const ScValidationData& r ) const { return nKey == r.nKey; }\n BOOL operator < ( const ScValidationData& r ) const { return nKey < r.nKey; }\n\nprivate:\n \/** Tries to fill the passed collection with list validation entries.\n @descr Fills the list only if it is non-NULL,\n @param pStrings (out-param) Optionally NULL, string list to fill with list validation entires.\n @param pCell can be NULL if it is not necessary to which element in the list is selected.\n @param rPos the base address for relative references.\n @param rTokArr Formula token array.\n @param rMatch (out-param) the index of the first item that matched, -1 if nothing matched.\n @return true = Cell range found, rRange is valid, or an error entry stuffed into the list if pCell==NULL. *\/\n bool GetSelectionFromFormula( TypedStrCollection* pStrings,\n ScBaseCell* pCell, const ScAddress& rPos,\n const ScTokenArray& rTokArr, int& rMatch ) const;\n\n \/** Tests, if pCell is equal to what the passed token array represents. *\/\n bool IsEqualToTokenArray( ScBaseCell* pCell, const ScAddress& rPos, const ScTokenArray& rTokArr ) const;\n\n \/** Tests, if contents of pCell occur in cell range referenced by own formula, or in a string list. *\/\n bool IsListValid( ScBaseCell* pCell, const ScAddress& rPos ) const;\n};\n\n\/\/\n\/\/ Liste der Bedingungen:\n\/\/\n\ntypedef ScValidationData* ScValidationDataPtr;\n\nSV_DECL_PTRARR_SORT(ScValidationEntries_Impl, ScValidationDataPtr,\n SC_COND_GROW, SC_COND_GROW)\n\nclass ScValidationDataList : public ScValidationEntries_Impl\n{\npublic:\n ScValidationDataList() {}\n ScValidationDataList(const ScValidationDataList& rList);\n ScValidationDataList(ScDocument* pNewDoc, const ScValidationDataList& rList);\n ~ScValidationDataList() {}\n\n void InsertNew( ScValidationData* pNew )\n { if (!Insert(pNew)) delete pNew; }\n\n ScValidationData* GetData( sal_uInt32 nKey );\n\n void Load( SvStream& rStream, ScDocument* pDocument );\n void Store( SvStream& rStream ) const;\n void ResetUsed();\n\n void CompileXML();\n void UpdateReference( UpdateRefMode eUpdateRefMode,\n const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );\n void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );\n\n BOOL operator==( const ScValidationDataList& r ) const; \/\/ fuer Ref-Undo\n};\n\n#endif\n\n<|endoftext|>"} {"text":"#ifndef PHPCXX_ARRAY_TCC\n#define PHPCXX_ARRAY_TCC\n\n#ifndef PHPCXX_ARRAY_H\n#error \"Please do not include this file directly, use array.h instead\"\n#endif\n\nnamespace phpcxx {\n\ntemplate\nArray& Array::operator=(const vector& v)\n{\n zval* z = &this->m_z;\n ZVAL_DEREF(z);\n\n zval_ptr_dtor(z);\n _array_init(z, v.size() ZEND_FILE_LINE_CC);\n for (std::size_t i=0; i::value>*>\nArray& Array::operator=(const map& v)\n{\n zval* z = &this->m_z;\n ZVAL_DEREF(z);\n\n zval_ptr_dtor(z);\n _array_init(z, 8 ZEND_FILE_LINE_CC);\n for (auto const& it : v) {\n zval x;\n construct_zval(x, it.second);\n zend_hash_index_add(Z_ARR_P(z), static_cast(it.first), &x);\n }\n\n return *this;\n}\n\ntemplate::value || is_string::value>*>\nArray& Array::operator=(const map& v)\n{\n zval* z = &this->m_z;\n ZVAL_DEREF(z);\n\n zval_ptr_dtor(z);\n _array_init(z, 8 ZEND_FILE_LINE_CC);\n for (auto const& it : v) {\n zval x;\n construct_zval(x, it.second);\n ZendString key(it.first);\n zend_hash_add(Z_ARR_P(z), key.get(), &x);\n }\n\n return *this;\n}\n\n}\n\n#endif \/* PHPCXX_ARRAY_TCC *\/\nUse map.size() in call to _array_init()#ifndef PHPCXX_ARRAY_TCC\n#define PHPCXX_ARRAY_TCC\n\n#ifndef PHPCXX_ARRAY_H\n#error \"Please do not include this file directly, use array.h instead\"\n#endif\n\nnamespace phpcxx {\n\ntemplate\nArray& Array::operator=(const vector& v)\n{\n zval* z = &this->m_z;\n ZVAL_DEREF(z);\n\n zval_ptr_dtor(z);\n _array_init(z, v.size() ZEND_FILE_LINE_CC);\n for (std::size_t i=0; i::value>*>\nArray& Array::operator=(const map& v)\n{\n zval* z = &this->m_z;\n ZVAL_DEREF(z);\n\n zval_ptr_dtor(z);\n _array_init(z, v.size() ZEND_FILE_LINE_CC);\n for (auto const& it : v) {\n zval x;\n construct_zval(x, it.second);\n zend_hash_index_add(Z_ARR_P(z), static_cast(it.first), &x);\n }\n\n return *this;\n}\n\ntemplate::value || is_string::value>*>\nArray& Array::operator=(const map& v)\n{\n zval* z = &this->m_z;\n ZVAL_DEREF(z);\n\n zval_ptr_dtor(z);\n _array_init(z, v.size() ZEND_FILE_LINE_CC);\n for (auto const& it : v) {\n zval x;\n construct_zval(x, it.second);\n ZendString key(it.first);\n zend_hash_add(Z_ARR_P(z), key.get(), &x);\n }\n\n return *this;\n}\n\n}\n\n#endif \/* PHPCXX_ARRAY_TCC *\/\n<|endoftext|>"} {"text":"#include \"apfMPAS.h\"\n#include \n#include \n#include \n#include \n\nnamespace apf {\n\nusing namespace netCDF;\n\nstruct MpasFile\n{\n ~MpasFile()\n {\n delete [] x;\n delete [] y;\n delete [] z;\n delete [] conn;\n }\n int elements;\n int nodes;\n int nodesPerElement;\n double* x;\n double* y;\n double* z;\n\/* conn[i * vertexDegree + j] - 1\n is the index of the j'th node\n of element i *\/\n int* conn;\n};\n\nstatic int readDim(NcFile& f, const char* name)\n{\n return f.getDim(name).getSize();\n}\n\nstatic double* readDoubles(NcFile& f, const char* name, int n)\n{\n double* a = new double[n];\n NcVar v = f.getVar(name);\n v.getVar(a);\n return a;\n}\n\nstatic int* readInts(NcFile& f, const char* name, int n)\n{\n int* a = new int[n];\n NcVar v = f.getVar(name);\n v.getVar(a);\n return a;\n}\n\nvoid readMpasFile(MpasFile& out, const char* filename)\n{\n NcFile in(filename, NcFile::read);\n \/* this is the dual of a hexagonal mesh,\n hence the reversing of terms *\/\n out.nodes = readDim(in, \"nCells\");\n printf(\"%d nodes\\n\", out.nodes);\n out.elements = readDim(in, \"nVertices\");\n printf(\"%d elements\\n\", out.elements);\n out.nodesPerElement = readDim(in, \"vertexDegree\");\n out.x = readDoubles(in, \"xCell\", out.nodes);\n out.y = readDoubles(in, \"yCell\", out.nodes);\n out.z = readDoubles(in, \"zCell\", out.nodes);\n out.conn = readInts(in, \"cellsOnVertex\", out.elements * out.nodesPerElement);\n}\n\nstatic int getType(int nodesPerElement)\n{\n if (nodesPerElement == 3)\n return apf::Mesh::TRIANGLE;\n if (nodesPerElement == 4)\n return apf::Mesh::QUAD;\n abort();\n return 0;\n}\n\nvoid numberInitialNodes(MpasFile& in, apf::Mesh2* out,\n apf::MeshEntity** v)\n{\n apf::Numbering* n = apf::createNumbering(out, \"mpas_id\", out->getShape(), 1);\n for (int i = 0; i < in.nodes; ++i)\n apf::number(n, v[i], 0, 0, i);\n}\n\nvoid buildInitialMesh(MpasFile& in, apf::Mesh2* out)\n{\n apf::MeshEntity** v = new apf::MeshEntity* [in.nodes];\n\/* fake classification for now, deriveMdsModel will fix this up *\/\n apf::ModelEntity* c = out->findModelEntity(2, 0);\n int t = getType(in.nodesPerElement);\n for (int i = 0; i < in.nodes; ++i)\n v[i] = out->createVert(c);\n for (int i = 0; i < in.nodes; ++i) {\n apf::Vector3 x(in.x[i], in.y[i], in.z[i]);\n out->setPoint(v[i], 0, x);\n }\n for (int i = 0; i < in.elements; ++i) {\n apf::Downward ev;\n for (int j = 0; j < in.nodesPerElement; ++j) {\n int vi = in.conn[i * in.nodesPerElement + j] - 1;\n\/* zero indices (-1 after conversion) indicate that an MPAS\n vertex does not have an adjacent cell in that direction\n (it is a boundary vertex). In our dual mesh, we simply\n omit that dual element. This is correct and should not\n cause problems. *\/\n if (vi < 0)\n goto bad_vi;\n assert(vi < in.nodes);\n ev[j] = v[vi];\n }\n apf::buildElement(out, c, t, ev);\nbad_vi:\n continue;\n }\n numberInitialNodes(in, out, v);\n delete [] v;\n}\n\nvoid removeIsolatedNodes(apf::Mesh2* m)\n{\n\/* another problem with the dual: MPAS cells without adjacent\n cells become vertices with no adjacent elements in the\n dual mesh, which our codes don't handle.\n We have to give up on these cells, but tell the user about it.\n We also need to be aware of these omitted cells going forward *\/\n \/\/apf::Numbering* nums = apf::createNumbering(m, \"mpas_id\", m->getShape(), 1);\n apf::MeshIterator* it = m->begin(0);\n int n = 0;\n apf::MeshEntity* e;\n while ((e = m->iterate(it)))\n if ( ! m->countUpward(e)) {\n \/*int num =getNumber(nums, e, 0, 0);\n fprintf(stdout, \"Missing vertex with number %d\\n\",num);\n *\/\n m->destroy(e);\n ++n;\n }\n m->end(it);\n if (n)\n fprintf(stderr,\n \"warning: removed %d isolated nodes from MPAS dual mesh\\n\",\n n);\n}\n\nvoid loadMpasMesh(apf::Mesh2* m, const char* filename)\n{\n assert(PCU_Comm_Peers() == 1);\n MpasFile f;\n readMpasFile(f, filename);\n buildInitialMesh(f, m);\n removeIsolatedNodes(m);\n}\n\n\nvoid writeMpasAssignments(apf::Mesh2* m, const char* filename) {\n NcFile in(filename, NcFile::read);\n \/* this is the dual of a hexagonal mesh,\n hence the reversing of terms *\/\n int numMpasVtx = readDim(in, \"nCells\");\n \n apf::Numbering* n = apf::createNumbering(m, \"mpas_id\", m->getShape(), 1);\n\n \/* collect N\/#parts contiguous vertex assignments on each process\n (and deal with any remainders) *\/\n int numPerPart = numMpasVtx \/ PCU_Comm_Peers();\n apf::MeshIterator* itr = m->begin(0);\n apf::MeshEntity* e;\n int size;\n if (PCU_Comm_Self()==PCU_Comm_Peers()-1)\n size=numMpasVtx%numPerPart+numPerPart;\n else\n size=numPerPart;\n std::vector vtxs(size,-1);\n PCU_Comm_Begin();\n while ((e = m->iterate(itr))) {\n if (!parma::isOwned(m, e))\n continue;\n int num = getNumber(n, e, 0, 0);\n int target = num \/ numPerPart;\n if (target>=PCU_Comm_Peers())\n target = PCU_Comm_Peers()-1;\n if (target == PCU_Comm_Self())\n vtxs[num%size] = PCU_Comm_Self();\n else\n PCU_COMM_PACK(target,num);\n }\n m->end(itr);\n\n PCU_Comm_Send();\n while (PCU_Comm_Receive()) {\n int owner =PCU_Comm_Sender();\n int num;\n PCU_COMM_UNPACK(num);\n vtxs[num%size]=owner;\n }\n\n \/\/ assign missing vertices to a random part id\n int count = 0;\n for (int i = 0;\n (i < size);\n i++)\n if (vtxs[i]==-1) {\n vtxs[i] = 0; \/\/to be random\n \/\/fprintf(stdout,\"missing vertex %d\\n\",i+numPerPart*PCU_Comm_Self());\n count++;\n }\n fprintf(stdout,\"missing vertices found %d\\n\",count);\n \n \/\/ use MPI IO to write the contiguous blocks to a single graph.info.part.<#parts> file\n \/\/ see https:\/\/gist.github.com\/cwsmith\/166d5beb400f3a8136f7 and the comments\n double startTime=MPI_Wtime();\n FILE* file;\n char name[32];\n \n sprintf(name,\"graph.info.part.%d\",PCU_Comm_Peers());\n file = fopen(name, \"w\");\n fseek(file,numPerPart*PCU_Comm_Self()*16,SEEK_SET);\n for (int i=0;ialmost fixed, prints lines correctly and adds extra lines#include \"apfMPAS.h\"\n#include \n#include \n#include \n#include \n\nnamespace apf {\n\nusing namespace netCDF;\n\nstruct MpasFile\n{\n ~MpasFile()\n {\n delete [] x;\n delete [] y;\n delete [] z;\n delete [] conn;\n }\n int elements;\n int nodes;\n int nodesPerElement;\n double* x;\n double* y;\n double* z;\n\/* conn[i * vertexDegree + j] - 1\n is the index of the j'th node\n of element i *\/\n int* conn;\n};\n\nstatic int readDim(NcFile& f, const char* name)\n{\n return f.getDim(name).getSize();\n}\n\nstatic double* readDoubles(NcFile& f, const char* name, int n)\n{\n double* a = new double[n];\n NcVar v = f.getVar(name);\n v.getVar(a);\n return a;\n}\n\nstatic int* readInts(NcFile& f, const char* name, int n)\n{\n int* a = new int[n];\n NcVar v = f.getVar(name);\n v.getVar(a);\n return a;\n}\n\nvoid readMpasFile(MpasFile& out, const char* filename)\n{\n NcFile in(filename, NcFile::read);\n \/* this is the dual of a hexagonal mesh,\n hence the reversing of terms *\/\n out.nodes = readDim(in, \"nCells\");\n printf(\"%d nodes\\n\", out.nodes);\n out.elements = readDim(in, \"nVertices\");\n printf(\"%d elements\\n\", out.elements);\n out.nodesPerElement = readDim(in, \"vertexDegree\");\n out.x = readDoubles(in, \"xCell\", out.nodes);\n out.y = readDoubles(in, \"yCell\", out.nodes);\n out.z = readDoubles(in, \"zCell\", out.nodes);\n out.conn = readInts(in, \"cellsOnVertex\", out.elements * out.nodesPerElement);\n}\n\nstatic int getType(int nodesPerElement)\n{\n if (nodesPerElement == 3)\n return apf::Mesh::TRIANGLE;\n if (nodesPerElement == 4)\n return apf::Mesh::QUAD;\n abort();\n return 0;\n}\n\nvoid numberInitialNodes(MpasFile& in, apf::Mesh2* out,\n apf::MeshEntity** v)\n{\n apf::Numbering* n = apf::createNumbering(out, \"mpas_id\", out->getShape(), 1);\n for (int i = 0; i < in.nodes; ++i)\n apf::number(n, v[i], 0, 0, i);\n}\n\nvoid buildInitialMesh(MpasFile& in, apf::Mesh2* out)\n{\n apf::MeshEntity** v = new apf::MeshEntity* [in.nodes];\n\/* fake classification for now, deriveMdsModel will fix this up *\/\n apf::ModelEntity* c = out->findModelEntity(2, 0);\n int t = getType(in.nodesPerElement);\n for (int i = 0; i < in.nodes; ++i)\n v[i] = out->createVert(c);\n for (int i = 0; i < in.nodes; ++i) {\n apf::Vector3 x(in.x[i], in.y[i], in.z[i]);\n out->setPoint(v[i], 0, x);\n }\n for (int i = 0; i < in.elements; ++i) {\n apf::Downward ev;\n for (int j = 0; j < in.nodesPerElement; ++j) {\n int vi = in.conn[i * in.nodesPerElement + j] - 1;\n\/* zero indices (-1 after conversion) indicate that an MPAS\n vertex does not have an adjacent cell in that direction\n (it is a boundary vertex). In our dual mesh, we simply\n omit that dual element. This is correct and should not\n cause problems. *\/\n if (vi < 0)\n goto bad_vi;\n assert(vi < in.nodes);\n ev[j] = v[vi];\n }\n apf::buildElement(out, c, t, ev);\nbad_vi:\n continue;\n }\n numberInitialNodes(in, out, v);\n delete [] v;\n}\n\nvoid removeIsolatedNodes(apf::Mesh2* m)\n{\n\/* another problem with the dual: MPAS cells without adjacent\n cells become vertices with no adjacent elements in the\n dual mesh, which our codes don't handle.\n We have to give up on these cells, but tell the user about it.\n We also need to be aware of these omitted cells going forward *\/\n \/\/apf::Numbering* nums = apf::createNumbering(m, \"mpas_id\", m->getShape(), 1);\n apf::MeshIterator* it = m->begin(0);\n int n = 0;\n apf::MeshEntity* e;\n while ((e = m->iterate(it)))\n if ( ! m->countUpward(e)) {\n \/*int num =getNumber(nums, e, 0, 0);\n fprintf(stdout, \"Missing vertex with number %d\\n\",num);\n *\/\n m->destroy(e);\n ++n;\n }\n m->end(it);\n if (n)\n fprintf(stderr,\n \"warning: removed %d isolated nodes from MPAS dual mesh\\n\",\n n);\n}\n\nvoid loadMpasMesh(apf::Mesh2* m, const char* filename)\n{\n assert(PCU_Comm_Peers() == 1);\n MpasFile f;\n readMpasFile(f, filename);\n buildInitialMesh(f, m);\n removeIsolatedNodes(m);\n}\n\n\nvoid writeMpasAssignments(apf::Mesh2* m, const char* filename) {\n NcFile in(filename, NcFile::read);\n \/* this is the dual of a hexagonal mesh,\n hence the reversing of terms *\/\n int numMpasVtx = readDim(in, \"nCells\");\n \n apf::Numbering* n = apf::createNumbering(m, \"mpas_id\", m->getShape(), 1);\n\n \/* collect N\/#parts contiguous vertex assignments on each process\n (and deal with any remainders) *\/\n int numPerPart = numMpasVtx \/ PCU_Comm_Peers();\n apf::MeshIterator* itr = m->begin(0);\n apf::MeshEntity* e;\n int size;\n if (PCU_Comm_Self()==PCU_Comm_Peers()-1)\n size=numMpasVtx%numPerPart+numPerPart;\n else\n size=numPerPart;\n std::vector vtxs(size,-1);\n PCU_Comm_Begin();\n while ((e = m->iterate(itr))) {\n if (!parma::isOwned(m, e))\n continue;\n int num = getNumber(n, e, 0, 0);\n int target = num \/ numPerPart;\n if (target>=PCU_Comm_Peers())\n target = PCU_Comm_Peers()-1;\n if (target == PCU_Comm_Self())\n vtxs[num%size] = PCU_Comm_Self();\n else\n PCU_COMM_PACK(target,num);\n }\n m->end(itr);\n\n PCU_Comm_Send();\n while (PCU_Comm_Receive()) {\n int owner =PCU_Comm_Sender();\n int num;\n PCU_COMM_UNPACK(num);\n vtxs[num%size]=owner;\n }\n\n \/\/ assign missing vertices to a random part id\n int count = 0;\n for (int i = 0;\n (i < size);\n i++)\n if (vtxs[i]==-1) {\n vtxs[i] = 0; \/\/to be random\n \/\/fprintf(stdout,\"missing vertex %d\\n\",i+numPerPart*PCU_Comm_Self());\n count++;\n }\n if (count)\n fprintf(stdout,\"missing vertices found %d on part %d\\n\",count,PCU_Comm_Self());\n \n \/\/ use MPI IO to write the contiguous blocks to a single graph.info.part.<#parts> file\n \/\/ see https:\/\/gist.github.com\/cwsmith\/166d5beb400f3a8136f7 and the comments\n double startTime=MPI_Wtime();\n MPI_File file;\n char name[32];\n\n sprintf(name,\"graph.info.part.%d\",PCU_Comm_Peers());\n MPI_File_open(MPI_COMM_WORLD, name, MPI_MODE_CREATE|MPI_MODE_WRONLY,\n\t\tMPI_INFO_NULL, &file);\n MPI_Offset offset = numPerPart*PCU_Comm_Self()*16;\n MPI_File_seek(file, offset, MPI_SEEK_SET);\n MPI_Datatype filetype;\n MPI_Type_contiguous(size,MPI_CHAR,&filetype);\n MPI_Type_commit(&filetype);\n MPI_File_set_view(file,offset,MPI_CHAR,MPI_CHAR,\"internal\",MPI_INFO_NULL);\n char* str = new char[16*size];\n for (int i=0;\n i"} {"text":"\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"bsecategories.hh\"\n#include \"bsesource.hh\"\n#include \"bseprocedure.hh\"\n#include \"bsemain.hh\"\n#include \"bsestandardsynths.hh\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic gchar *indent_inc = NULL;\nstatic guint spacing = 1;\nstatic FILE *f_out = NULL;\nstatic GType root = 0;\nstatic gboolean recursion = TRUE;\nstatic gboolean feature_blurb = FALSE;\nstatic gboolean feature_channels = FALSE;\n\n\/*\n #define\tO_SPACE\t\"\\\\as\"\n #define\tO_ESPACE \" \"\n #define\tO_BRANCH \"\\\\aE\"\n #define\tO_VLINE \"\\\\al\"\n #define\tO_LLEAF\t\"\\\\aL\"\n #define\tO_KEY_FILL \"_\"\n*\/\n\n#define\tO_SPACE\t\" \"\n#define\tO_ESPACE \"\"\n#define\tO_BRANCH \"+\"\n#define\tO_VLINE \"|\"\n#define\tO_LLEAF\t\"`\"\n#define\tO_KEY_FILL \"_\"\n\nstatic void\nshow_nodes (GType type,\n\t GType sibling,\n\t const gchar *indent)\n{\n GType *children;\n guint i;\n\n if (!type)\n return;\n\n children = g_type_children (type, NULL);\n\n if (type != root)\n for (i = 0; i < spacing; i++)\n fprintf (f_out, \"%s%s\\n\", indent, O_VLINE);\n\n fprintf (f_out, \"%s%s%s%s\",\n\t indent,\n\t sibling ? O_BRANCH : (type != root ? O_LLEAF : O_SPACE),\n\t O_ESPACE,\n\t g_type_name (type));\n\n for (i = strlen (g_type_name (type)); i <= strlen (indent_inc); i++)\n fputs (O_KEY_FILL, f_out);\n\n if (feature_blurb && bse_type_get_blurb (type))\n {\n fputs (\"\\t[\", f_out);\n fputs (bse_type_get_blurb (type), f_out);\n fputs (\"]\", f_out);\n }\n\n if (G_TYPE_IS_ABSTRACT (type))\n fputs (\"\\t(abstract)\", f_out);\n\n if (feature_channels && g_type_is_a (type, BSE_TYPE_SOURCE))\n {\n BseSourceClass *klass = (BseSourceClass*) g_type_class_ref (type);\n gchar buffer[1024];\n\n sprintf (buffer,\n\t \"\\t(ichannels %u) (ochannels %u)\",\n\t klass->channel_defs.n_ichannels,\n\t klass->channel_defs.n_ochannels);\n fputs (buffer, f_out);\n g_type_class_unref (klass);\n }\n\n fputc ('\\n', f_out);\n\n if (children && recursion)\n {\n gchar *new_indent;\n GType *child;\n\n if (sibling)\n\tnew_indent = g_strconcat (indent, O_VLINE, indent_inc, NULL);\n else\n\tnew_indent = g_strconcat (indent, O_SPACE, indent_inc, NULL);\n\n for (child = children; *child; child++)\n\tshow_nodes (child[0], child[1], new_indent);\n\n g_free (new_indent);\n }\n\n g_free (children);\n}\n\nstatic void\nshow_cats (void)\n{\n BseCategorySeq *cseq;\n guint i;\n\n cseq = bse_categories_match_typed (\"*\", 0);\n for (i = 0; i < cseq->n_cats; i++)\n fprintf (f_out, \"%s\\t(%s)\\n\",\n\t cseq->cats[i]->category,\n\t cseq->cats[i]->type);\n bse_category_seq_free (cseq);\n}\n\nstatic void\nshow_procdoc (void)\n{\n BseCategorySeq *cseq;\n guint i;\n const gchar *nullstr = \"\"; \/\/ \"???\";\n\n cseq = bse_categories_match_typed (\"*\", BSE_TYPE_PROCEDURE);\n for (i = 0; i < cseq->n_cats; i++)\n {\n GType type = g_type_from_name (cseq->cats[i]->type);\n BseProcedureClass *klass = (BseProcedureClass*) g_type_class_ref (type);\n gchar *pname = g_type_name_to_sname (cseq->cats[i]->type);\n const gchar *blurb = bse_type_get_blurb (type);\n guint j;\n\n fprintf (f_out, \"\/**\\n * %s\\n\", pname);\n for (j = 0; j < klass->n_in_pspecs; j++)\n\t{\n\t GParamSpec *pspec = G_PARAM_SPEC (klass->in_pspecs[j]);\n\n\t fprintf (f_out, \" * @%s: %s\\n\",\n\t\t pspec->name,\n\t\t g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr);\n\t}\n for (j = 0; j < klass->n_out_pspecs; j++)\n\t{\n\t GParamSpec *pspec = G_PARAM_SPEC (klass->out_pspecs[j]);\n\n\t fprintf (f_out, \" * @Returns: %s: %s\\n\",\n\t\t pspec->name,\n\t\t g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr);\n\t}\n if (blurb)\n\tfprintf (f_out, \" * %s\\n\", blurb);\n fprintf (f_out, \" **\/\\n\");\n g_type_class_unref (klass);\n g_free (pname);\n }\n bse_category_seq_free (cseq);\n}\n\nstatic gint\nhelp (gchar *arg)\n{\n fprintf (stderr, \"usage: query [-r ] [-{i|b} \\\"\\\"] [-s #] [-{h|x|y}]\\n\");\n fprintf (stderr, \" -r specifiy root type\\n\");\n fprintf (stderr, \" -n don't descend type tree\\n\");\n fprintf (stderr, \" -p include plugins\\n\");\n fprintf (stderr, \" -x show type blurbs\\n\");\n fprintf (stderr, \" -y show source channels\\n\");\n fprintf (stderr, \" -h guess what ;)\\n\");\n fprintf (stderr, \" -b specifiy indent string\\n\");\n fprintf (stderr, \" -i specifiy incremental indent string\\n\");\n fprintf (stderr, \" -s specifiy line spacing\\n\");\n fprintf (stderr, \" -:f make all warnings fatal\\n\");\n fprintf (stderr, \"qualifiers:\\n\");\n fprintf (stderr, \" froots iterate over fundamental roots\\n\");\n fprintf (stderr, \" tree print BSE type tree\\n\");\n fprintf (stderr, \" cats print categories\\n\");\n fprintf (stderr, \" procdoc print procedure documentation\\n\");\n fprintf (stderr, \" synth dump standard synth definition\\n\");\n\n return arg != NULL;\n}\n\nint\nmain (gint argc,\n gchar *argv[])\n{\n gboolean gen_froots = 0;\n gboolean gen_tree = 0;\n gboolean gen_cats = 0;\n gboolean gen_procdoc = 0;\n gchar *show_synth = NULL;\n gchar *root_name = NULL;\n const char *iindent = \"\";\n const char *pluginbool = \"load-core-plugins=0\";\n const char *scriptbool = \"load-core-scripts=0\";\n f_out = stdout;\n\n bse_init_test (&argc, argv);\n int i;\n for (i = 1; i < argc; i++)\n {\n if (strcmp (\"-s\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t spacing = atoi (argv[i]);\n\t}\n else if (strcmp (\"-i\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t {\n\t char *p;\n\t guint n;\n\n\t p = argv[i];\n\t while (*p)\n\t\tp++;\n\t n = p - argv[i];\n\t indent_inc = g_new (gchar, n * strlen (O_SPACE) + 1);\n\t *indent_inc = 0;\n\t while (n)\n\t\t{\n\t\t n--;\n\t\t strcpy (indent_inc, O_SPACE);\n\t\t}\n\t }\n\t}\n else if (strcmp (\"-b\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t iindent = argv[i];\n\t}\n else if (strcmp (\"-r\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t root_name = argv[i];\n\t}\n else if (strcmp (\"-n\", argv[i]) == 0)\n\t{\n\t recursion = FALSE;\n\t}\n else if (strcmp (\"-x\", argv[i]) == 0)\n\t{\n\t feature_blurb = TRUE;\n\t}\n else if (strcmp (\"-y\", argv[i]) == 0)\n\t{\n\t feature_channels = TRUE;\n\t}\n else if (strcmp (\"froots\", argv[i]) == 0)\n\t{\n\t gen_froots = 1;\n\t}\n else if (strcmp (\"synth\", argv[i]) == 0 && i + 1 < argc)\n\t{\n\t show_synth = argv[++i];\n\t}\n else if (strcmp (\"tree\", argv[i]) == 0)\n\t{\n\t gen_tree = 1;\n\t}\n else if (strcmp (\"cats\", argv[i]) == 0)\n\t{\n\t gen_cats = 1;\n\t}\n else if (strcmp (\"procdoc\", argv[i]) == 0)\n\t{\n\t gen_procdoc = 1;\n\t}\n else if (strcmp (\"-p\", argv[i]) == 0)\n pluginbool = \"load-core-plugins=1\";\n else if (strcmp (\"-:f\", argv[i]) == 0)\n\t{\n\t g_log_set_always_fatal (GLogLevelFlags (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL |\n g_log_set_always_fatal (GLogLevelFlags (G_LOG_FATAL_MASK))));\n\t}\n else if (strcmp (\"-h\", argv[i]) == 0)\n\t{\n\t return help (NULL);\n\t}\n else if (strcmp (\"--help\", argv[i]) == 0)\n\t{\n\t return help (NULL);\n\t}\n else\n\treturn help (argv[i]);\n }\n bse_init_inprocess (&argc, argv, \"BseQuery\", Bse::cstrings_to_vector (pluginbool, scriptbool, NULL));\n if (root_name)\n root = g_type_from_name (root_name);\n else\n root = BSE_TYPE_OBJECT;\n if (!gen_froots && !gen_tree && !gen_cats && !gen_procdoc && !show_synth)\n return help (argv[i-1]);\n if (!indent_inc)\n {\n indent_inc = g_new (gchar, strlen (O_SPACE) + 1);\n *indent_inc = 0;\n strcpy (indent_inc, O_SPACE);\n strcpy (indent_inc, O_SPACE);\n strcpy (indent_inc, O_SPACE);\n }\n\n if (gen_tree)\n show_nodes (root, 0, iindent);\n if (gen_froots)\n {\n root = ~0;\n for (i = 0; i <= G_TYPE_FUNDAMENTAL_MAX; i += G_TYPE_MAKE_FUNDAMENTAL (1))\n\t{\n\t const char *name = g_type_name (i);\n\t if (name)\n\t show_nodes (i, 0, iindent);\n\t}\n }\n if (gen_cats)\n show_cats ();\n if (gen_procdoc)\n show_procdoc ();\n if (show_synth)\n {\n gchar *text = bse_standard_synth_inflate (show_synth, NULL);\n g_print (\"%s\", text);\n g_free (text);\n }\n\n return 0;\n}\nBSE: fix bsequery initialization to avoid crashing\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"bsecategories.hh\"\n#include \"bsesource.hh\"\n#include \"bseprocedure.hh\"\n#include \"bsemain.hh\"\n#include \"bsestandardsynths.hh\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic gchar *indent_inc = NULL;\nstatic guint spacing = 1;\nstatic FILE *f_out = NULL;\nstatic GType root = 0;\nstatic gboolean recursion = TRUE;\nstatic gboolean feature_blurb = FALSE;\nstatic gboolean feature_channels = FALSE;\n\n\/*\n #define\tO_SPACE\t\"\\\\as\"\n #define\tO_ESPACE \" \"\n #define\tO_BRANCH \"\\\\aE\"\n #define\tO_VLINE \"\\\\al\"\n #define\tO_LLEAF\t\"\\\\aL\"\n #define\tO_KEY_FILL \"_\"\n*\/\n\n#define\tO_SPACE\t\" \"\n#define\tO_ESPACE \"\"\n#define\tO_BRANCH \"+\"\n#define\tO_VLINE \"|\"\n#define\tO_LLEAF\t\"`\"\n#define\tO_KEY_FILL \"_\"\n\nstatic void\nshow_nodes (GType type,\n\t GType sibling,\n\t const gchar *indent)\n{\n GType *children;\n guint i;\n\n if (!type)\n return;\n\n children = g_type_children (type, NULL);\n\n if (type != root)\n for (i = 0; i < spacing; i++)\n fprintf (f_out, \"%s%s\\n\", indent, O_VLINE);\n\n fprintf (f_out, \"%s%s%s%s\",\n\t indent,\n\t sibling ? O_BRANCH : (type != root ? O_LLEAF : O_SPACE),\n\t O_ESPACE,\n\t g_type_name (type));\n\n for (i = strlen (g_type_name (type)); i <= strlen (indent_inc); i++)\n fputs (O_KEY_FILL, f_out);\n\n if (feature_blurb && bse_type_get_blurb (type))\n {\n fputs (\"\\t[\", f_out);\n fputs (bse_type_get_blurb (type), f_out);\n fputs (\"]\", f_out);\n }\n\n if (G_TYPE_IS_ABSTRACT (type))\n fputs (\"\\t(abstract)\", f_out);\n\n if (feature_channels && g_type_is_a (type, BSE_TYPE_SOURCE))\n {\n BseSourceClass *klass = (BseSourceClass*) g_type_class_ref (type);\n gchar buffer[1024];\n\n sprintf (buffer,\n\t \"\\t(ichannels %u) (ochannels %u)\",\n\t klass->channel_defs.n_ichannels,\n\t klass->channel_defs.n_ochannels);\n fputs (buffer, f_out);\n g_type_class_unref (klass);\n }\n\n fputc ('\\n', f_out);\n\n if (children && recursion)\n {\n gchar *new_indent;\n GType *child;\n\n if (sibling)\n\tnew_indent = g_strconcat (indent, O_VLINE, indent_inc, NULL);\n else\n\tnew_indent = g_strconcat (indent, O_SPACE, indent_inc, NULL);\n\n for (child = children; *child; child++)\n\tshow_nodes (child[0], child[1], new_indent);\n\n g_free (new_indent);\n }\n\n g_free (children);\n}\n\nstatic void\nshow_cats (void)\n{\n BseCategorySeq *cseq;\n guint i;\n\n cseq = bse_categories_match_typed (\"*\", 0);\n for (i = 0; i < cseq->n_cats; i++)\n fprintf (f_out, \"%s\\t(%s)\\n\",\n\t cseq->cats[i]->category,\n\t cseq->cats[i]->type);\n bse_category_seq_free (cseq);\n}\n\nstatic void\nshow_procdoc (void)\n{\n BseCategorySeq *cseq;\n guint i;\n const gchar *nullstr = \"\"; \/\/ \"???\";\n\n cseq = bse_categories_match_typed (\"*\", BSE_TYPE_PROCEDURE);\n for (i = 0; i < cseq->n_cats; i++)\n {\n GType type = g_type_from_name (cseq->cats[i]->type);\n BseProcedureClass *klass = (BseProcedureClass*) g_type_class_ref (type);\n gchar *pname = g_type_name_to_sname (cseq->cats[i]->type);\n const gchar *blurb = bse_type_get_blurb (type);\n guint j;\n\n fprintf (f_out, \"\/**\\n * %s\\n\", pname);\n for (j = 0; j < klass->n_in_pspecs; j++)\n\t{\n\t GParamSpec *pspec = G_PARAM_SPEC (klass->in_pspecs[j]);\n\n\t fprintf (f_out, \" * @%s: %s\\n\",\n\t\t pspec->name,\n\t\t g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr);\n\t}\n for (j = 0; j < klass->n_out_pspecs; j++)\n\t{\n\t GParamSpec *pspec = G_PARAM_SPEC (klass->out_pspecs[j]);\n\n\t fprintf (f_out, \" * @Returns: %s: %s\\n\",\n\t\t pspec->name,\n\t\t g_param_spec_get_blurb (pspec) ? g_param_spec_get_blurb (pspec) : nullstr);\n\t}\n if (blurb)\n\tfprintf (f_out, \" * %s\\n\", blurb);\n fprintf (f_out, \" **\/\\n\");\n g_type_class_unref (klass);\n g_free (pname);\n }\n bse_category_seq_free (cseq);\n}\n\nstatic gint\nhelp (gchar *arg)\n{\n fprintf (stderr, \"usage: query [-r ] [-{i|b} \\\"\\\"] [-s #] [-{h|x|y}]\\n\");\n fprintf (stderr, \" -r specifiy root type\\n\");\n fprintf (stderr, \" -n don't descend type tree\\n\");\n fprintf (stderr, \" -p include plugins\\n\");\n fprintf (stderr, \" -x show type blurbs\\n\");\n fprintf (stderr, \" -y show source channels\\n\");\n fprintf (stderr, \" -h guess what ;)\\n\");\n fprintf (stderr, \" -b specifiy indent string\\n\");\n fprintf (stderr, \" -i specifiy incremental indent string\\n\");\n fprintf (stderr, \" -s specifiy line spacing\\n\");\n fprintf (stderr, \" -:f make all warnings fatal\\n\");\n fprintf (stderr, \"qualifiers:\\n\");\n fprintf (stderr, \" froots iterate over fundamental roots\\n\");\n fprintf (stderr, \" tree print BSE type tree\\n\");\n fprintf (stderr, \" cats print categories\\n\");\n fprintf (stderr, \" procdoc print procedure documentation\\n\");\n fprintf (stderr, \" synth dump standard synth definition\\n\");\n\n return arg != NULL;\n}\n\nint\nmain (gint argc,\n gchar *argv[])\n{\n gboolean gen_froots = 0;\n gboolean gen_tree = 0;\n gboolean gen_cats = 0;\n gboolean gen_procdoc = 0;\n gchar *show_synth = NULL;\n gchar *root_name = NULL;\n const char *iindent = \"\";\n const char *pluginbool = \"load-core-plugins=0\";\n const char *scriptbool = \"load-core-scripts=0\";\n f_out = stdout;\n\n bse_init_inprocess (&argc, argv, \"BseQuery\", Bse::cstrings_to_vector (pluginbool, scriptbool, NULL));\n \/\/ bse_init_test (&argc, argv);\n int i;\n for (i = 1; i < argc; i++)\n {\n if (strcmp (\"-s\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t spacing = atoi (argv[i]);\n\t}\n else if (strcmp (\"-i\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t {\n\t char *p;\n\t guint n;\n\n\t p = argv[i];\n\t while (*p)\n\t\tp++;\n\t n = p - argv[i];\n\t indent_inc = g_new (gchar, n * strlen (O_SPACE) + 1);\n\t *indent_inc = 0;\n\t while (n)\n\t\t{\n\t\t n--;\n\t\t strcpy (indent_inc, O_SPACE);\n\t\t}\n\t }\n\t}\n else if (strcmp (\"-b\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t iindent = argv[i];\n\t}\n else if (strcmp (\"-r\", argv[i]) == 0)\n\t{\n\t i++;\n\t if (i < argc)\n\t root_name = argv[i];\n\t}\n else if (strcmp (\"-n\", argv[i]) == 0)\n\t{\n\t recursion = FALSE;\n\t}\n else if (strcmp (\"-x\", argv[i]) == 0)\n\t{\n\t feature_blurb = TRUE;\n\t}\n else if (strcmp (\"-y\", argv[i]) == 0)\n\t{\n\t feature_channels = TRUE;\n\t}\n else if (strcmp (\"froots\", argv[i]) == 0)\n\t{\n\t gen_froots = 1;\n\t}\n else if (strcmp (\"synth\", argv[i]) == 0 && i + 1 < argc)\n\t{\n\t show_synth = argv[++i];\n\t}\n else if (strcmp (\"tree\", argv[i]) == 0)\n\t{\n\t gen_tree = 1;\n\t}\n else if (strcmp (\"cats\", argv[i]) == 0)\n\t{\n\t gen_cats = 1;\n\t}\n else if (strcmp (\"procdoc\", argv[i]) == 0)\n\t{\n\t gen_procdoc = 1;\n\t}\n else if (strcmp (\"-p\", argv[i]) == 0)\n pluginbool = \"load-core-plugins=1\";\n else if (strcmp (\"-:f\", argv[i]) == 0)\n\t{\n\t g_log_set_always_fatal (GLogLevelFlags (G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL |\n g_log_set_always_fatal (GLogLevelFlags (G_LOG_FATAL_MASK))));\n\t}\n else if (strcmp (\"-h\", argv[i]) == 0)\n\t{\n\t return help (NULL);\n\t}\n else if (strcmp (\"--help\", argv[i]) == 0)\n\t{\n\t return help (NULL);\n\t}\n else\n\treturn help (argv[i]);\n }\n \/\/ bse_init_inprocess (&argc, argv, \"BseQuery\", Bse::cstrings_to_vector (pluginbool, scriptbool, NULL));\n if (root_name)\n root = g_type_from_name (root_name);\n else\n root = BSE_TYPE_OBJECT;\n if (!gen_froots && !gen_tree && !gen_cats && !gen_procdoc && !show_synth)\n return help (argv[i-1]);\n if (!indent_inc)\n {\n indent_inc = g_new (gchar, strlen (O_SPACE) + 1);\n *indent_inc = 0;\n strcpy (indent_inc, O_SPACE);\n strcpy (indent_inc, O_SPACE);\n strcpy (indent_inc, O_SPACE);\n }\n\n if (gen_tree)\n show_nodes (root, 0, iindent);\n if (gen_froots)\n {\n root = ~0;\n for (i = 0; i <= G_TYPE_FUNDAMENTAL_MAX; i += G_TYPE_MAKE_FUNDAMENTAL (1))\n\t{\n\t const char *name = g_type_name (i);\n\t if (name)\n\t show_nodes (i, 0, iindent);\n\t}\n }\n if (gen_cats)\n show_cats ();\n if (gen_procdoc)\n show_procdoc ();\n if (show_synth)\n {\n gchar *text = bse_standard_synth_inflate (show_synth, NULL);\n g_print (\"%s\", text);\n g_free (text);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"Cast Buffers to Char * for Winsock<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"rational.hh\"\n#include \"zs_error.hh\"\n#include \"zs_memory.hh\"\n\nstatic_assert(sizeof(int) < sizeof(long long),\n \"integer overflow cannot be treated properly\");\n\nusing namespace std;\n\n\/\/ TODO: make this as constructor.\nRational& Rational::normalized_reset(long long n, long long d){\n if(d == 0)\n throw_zs_error({}, \"Rational::denominator is 0\");\n\n auto gcd_val = gcd(n, d);\n n \/= gcd_val;\n d \/= gcd_val;\n\n if(d < 0){\n n = -n;\n d = -d;\n }\n\n if(n < INT_MIN || n > INT_MAX\n || d < INT_MIN || d > INT_MAX){\n overflow_ = true;\n float_ = (double)n \/ (double)d;\n }else{\n ratio_.n_ = static_cast(n);\n ratio_.d_ = static_cast(d);\n }\n\n return *this;\n}\n\nRational::operator double() const{\n assert(is_convertible());\n if(overflow_){\n return float_;\n }else{\n return static_cast(numerator()) \/ static_cast(denominator());\n }\n}\n\nRational& Rational::expt(const Rational& other){\n if(other.denominator() != 1){\n overflow_ = true;\n float_ = std::pow(static_cast(*this),\n static_cast(other));\n return *this;\n }\n\n const auto base_r = *this;\n normalized_reset(1, 1);\n\n auto ex = other.numerator();\n for(; ex > 0; --ex){\n operator*=(base_r);\n if(overflow_) break;\n }\n\n if(overflow_){\n auto base_d = static_cast(base_r);\n for(; ex > 0; --ex) float_ *= base_d;\n }\n\n return *this;\n}\n\n\nRational rationalize(double answer, double error){\n \/\/ from:\n \/\/ http:\/\/en.wikipedia.org\/wiki\/Continued_fraction#Infinite_continued_fractions\n double d = answer;\n\n int h_2 = 0, h_1 = 1;\n int k_2 = 1, k_1 = 0;\n long long h_0;\n long long k_0;\n\n while(1){\n auto int_p = (long long)floor(d);\n auto frac_p = d - floor(d);\n d = 1 \/ frac_p;\n\n h_0 = int_p * h_1 + h_2;\n k_0 = int_p * k_1 + k_2;\n\n if(h_0 < INT_MIN || h_0 > INT_MAX\n || k_0 < INT_MIN || k_0 > INT_MAX){\n \/\/ integer overflow\n break;\n }\n\n auto sub_ans = (double)h_0 \/ (double)k_0;\n\n if(abs(sub_ans - answer) <= error){\n break;\n }\n\n h_2 = h_1;\n h_1 = (int)h_0;\n k_2 = k_1;\n k_1 = (int)k_0;\n }\n\n return Rational{h_0 , k_0};\n}\n\n\/\/ utilities\ntemplate<>\nint coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::integer){\n return p.get();\n }else{\n UNEXP_DEFAULT();\n }\n}\n\ntemplate<>\nRational coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::rational){\n return *p.get();\n }else{\n return Rational(coerce(p), 1);\n }\n}\n\ntemplate<>\ndouble coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::real){\n return *(p.get());\n }else{\n return static_cast(coerce(p));\n }\n}\n\ntemplate<>\nComplex coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::complex){\n return *(p.get());\n }else{\n return Complex(coerce(p), 0);\n }\n}\n\nbool is_numeric_type(Lisp_ptr p){\n switch(p.tag()){\n case Ptr_tag::integer:\n case Ptr_tag::rational:\n case Ptr_tag::real:\n case Ptr_tag::complex:\n return true;\n case Ptr_tag::undefined: case Ptr_tag::boolean:\n case Ptr_tag::character: case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure: case Ptr_tag::n_procedure:\n case Ptr_tag::continuation: case Ptr_tag::syntax_rules:\n case Ptr_tag::string: case Ptr_tag::vector:\n case Ptr_tag::input_port: case Ptr_tag::output_port:\n case Ptr_tag::env: case Ptr_tag::syntactic_closure:\n case Ptr_tag::vm_op: case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n return false;\n }\n}\n\nbool is_numeric_convertible(Lisp_ptr p, Ptr_tag tag){\n switch(p.tag()){\n case Ptr_tag::integer:\n if(tag == Ptr_tag::integer) return true;\n \/\/ fall through\n case Ptr_tag::rational:\n if(tag == Ptr_tag::rational) return true;\n \/\/ fall through\n case Ptr_tag::real:\n if(tag == Ptr_tag::real) return true;\n \/\/ fall through\n case Ptr_tag::complex:\n return (tag == Ptr_tag::complex);\n case Ptr_tag::undefined: case Ptr_tag::boolean:\n case Ptr_tag::character: case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure: case Ptr_tag::n_procedure:\n case Ptr_tag::continuation: case Ptr_tag::syntax_rules:\n case Ptr_tag::string: case Ptr_tag::vector:\n case Ptr_tag::input_port: case Ptr_tag::output_port:\n case Ptr_tag::env: case Ptr_tag::syntactic_closure:\n case Ptr_tag::vm_op: case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n return false;\n }\n}\n\nLisp_ptr wrap_number(const Rational& q){\n if(q.is_convertible()){\n return Lisp_ptr{static_cast(q)};\n }else if(q.is_convertible()){\n return {zs_new(q)};\n }else{\n print_zs_warning(\"integer overflow occured. coerced into real.\");\n return {zs_new(static_cast(q))};\n }\n}\n\nLisp_ptr wrap_number(double d){\n return {zs_new(d)};\n}\n\nLisp_ptr wrap_number(const Complex& z){\n return {zs_new(z)};\n}\n\nLisp_ptr to_exact(Lisp_ptr p){\n switch(p.tag()){\n case Ptr_tag::integer:\n case Ptr_tag::rational:\n return p;\n case Ptr_tag::real:\n return wrap_number(static_cast(*p.get()));\n case Ptr_tag::complex:\n throw_zs_error(p, \"number error: conversion from complex to exact number is not supprted.\\n\");\n case Ptr_tag::undefined:\n case Ptr_tag::boolean:\n case Ptr_tag::character:\n case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure:\n case Ptr_tag::n_procedure:\n case Ptr_tag::continuation:\n case Ptr_tag::string:\n case Ptr_tag::vector:\n case Ptr_tag::input_port:\n case Ptr_tag::output_port:\n case Ptr_tag::env:\n case Ptr_tag::syntactic_closure:\n case Ptr_tag::syntax_rules:\n case Ptr_tag::vm_op:\n case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n UNEXP_DEFAULT();\n }\n}\n\nLisp_ptr to_inexact(Lisp_ptr p){\n switch(p.tag()){\n case Ptr_tag::integer:\n case Ptr_tag::rational:\n return wrap_number(coerce(p));\n case Ptr_tag::real:\n case Ptr_tag::complex:\n return p;\n case Ptr_tag::undefined:\n case Ptr_tag::boolean:\n case Ptr_tag::character:\n case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure:\n case Ptr_tag::n_procedure:\n case Ptr_tag::continuation:\n case Ptr_tag::string:\n case Ptr_tag::vector:\n case Ptr_tag::input_port:\n case Ptr_tag::output_port:\n case Ptr_tag::env:\n case Ptr_tag::syntactic_closure:\n case Ptr_tag::syntax_rules:\n case Ptr_tag::vm_op:\n case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n UNEXP_DEFAULT();\n }\n}\ntrivial cleanup#include \n#include \n#include \n\n#include \"rational.hh\"\n#include \"zs_error.hh\"\n#include \"zs_memory.hh\"\n\nstatic_assert(sizeof(int) < sizeof(long long),\n \"integer overflow cannot be treated properly\");\n\nusing namespace std;\n\n\/\/ TODO: make this as constructor.\nRational& Rational::normalized_reset(long long n, long long d){\n if(d == 0)\n throw_zs_error({}, \"Rational::denominator is 0\");\n\n auto gcd_val = gcd(n, d);\n n \/= gcd_val;\n d \/= gcd_val;\n\n if(d < 0){\n n = -n;\n d = -d;\n }\n\n if(n < INT_MIN || n > INT_MAX\n || d < INT_MIN || d > INT_MAX){\n overflow_ = true;\n float_ = (double)n \/ (double)d;\n }else{\n ratio_.n_ = static_cast(n);\n ratio_.d_ = static_cast(d);\n }\n\n return *this;\n}\n\nRational::operator double() const{\n assert(is_convertible());\n if(overflow_){\n return float_;\n }else{\n return static_cast(numerator()) \/ static_cast(denominator());\n }\n}\n\nRational& Rational::expt(const Rational& other){\n if(other.denominator() != 1){\n overflow_ = true;\n float_ = std::pow(static_cast(*this),\n static_cast(other));\n return *this;\n }\n\n const auto base_r = *this;\n normalized_reset(1, 1);\n\n auto ex = other.numerator();\n for(; ex > 0; --ex){\n operator*=(base_r);\n if(overflow_) break;\n }\n\n if(overflow_){\n auto base_d = static_cast(base_r);\n for(; ex > 0; --ex) float_ *= base_d;\n }\n\n return *this;\n}\n\n\nRational rationalize(double answer, double error){\n \/\/ from:\n \/\/ http:\/\/en.wikipedia.org\/wiki\/Continued_fraction#Infinite_continued_fractions\n double d = answer;\n\n int h_2 = 0, h_1 = 1;\n int k_2 = 1, k_1 = 0;\n long long h_0;\n long long k_0;\n\n while(1){\n auto int_p = (long long)floor(d);\n auto frac_p = d - floor(d);\n d = 1 \/ frac_p;\n\n h_0 = int_p * h_1 + h_2;\n k_0 = int_p * k_1 + k_2;\n\n if(h_0 < INT_MIN || h_0 > INT_MAX\n || k_0 < INT_MIN || k_0 > INT_MAX){\n \/\/ integer overflow\n break;\n }\n\n auto sub_ans = (double)h_0 \/ (double)k_0;\n\n if(abs(sub_ans - answer) <= error){\n break;\n }\n\n h_2 = h_1;\n h_1 = (int)h_0;\n k_2 = k_1;\n k_1 = (int)k_0;\n }\n\n return Rational{h_0 , k_0};\n}\n\n\/\/ utilities\ntemplate<>\nint coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::integer){\n return p.get();\n }else{\n UNEXP_DEFAULT();\n }\n}\n\ntemplate<>\nRational coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::rational){\n return *p.get();\n }else{\n return Rational(coerce(p));\n }\n}\n\ntemplate<>\ndouble coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::real){\n return *(p.get());\n }else{\n return static_cast(coerce(p));\n }\n}\n\ntemplate<>\nComplex coerce(Lisp_ptr p){\n if(p.tag() == Ptr_tag::complex){\n return *(p.get());\n }else{\n return Complex(coerce(p), 0);\n }\n}\n\nbool is_numeric_type(Lisp_ptr p){\n switch(p.tag()){\n case Ptr_tag::integer:\n case Ptr_tag::rational:\n case Ptr_tag::real:\n case Ptr_tag::complex:\n return true;\n case Ptr_tag::undefined: case Ptr_tag::boolean:\n case Ptr_tag::character: case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure: case Ptr_tag::n_procedure:\n case Ptr_tag::continuation: case Ptr_tag::syntax_rules:\n case Ptr_tag::string: case Ptr_tag::vector:\n case Ptr_tag::input_port: case Ptr_tag::output_port:\n case Ptr_tag::env: case Ptr_tag::syntactic_closure:\n case Ptr_tag::vm_op: case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n return false;\n }\n}\n\nbool is_numeric_convertible(Lisp_ptr p, Ptr_tag tag){\n switch(p.tag()){\n case Ptr_tag::integer:\n if(tag == Ptr_tag::integer) return true;\n \/\/ fall through\n case Ptr_tag::rational:\n if(tag == Ptr_tag::rational) return true;\n \/\/ fall through\n case Ptr_tag::real:\n if(tag == Ptr_tag::real) return true;\n \/\/ fall through\n case Ptr_tag::complex:\n return (tag == Ptr_tag::complex);\n case Ptr_tag::undefined: case Ptr_tag::boolean:\n case Ptr_tag::character: case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure: case Ptr_tag::n_procedure:\n case Ptr_tag::continuation: case Ptr_tag::syntax_rules:\n case Ptr_tag::string: case Ptr_tag::vector:\n case Ptr_tag::input_port: case Ptr_tag::output_port:\n case Ptr_tag::env: case Ptr_tag::syntactic_closure:\n case Ptr_tag::vm_op: case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n return false;\n }\n}\n\nLisp_ptr wrap_number(const Rational& q){\n if(q.is_convertible()){\n return Lisp_ptr{static_cast(q)};\n }else if(q.is_convertible()){\n return {zs_new(q)};\n }else{\n print_zs_warning(\"integer overflow occured. coerced into real.\");\n return {zs_new(static_cast(q))};\n }\n}\n\nLisp_ptr wrap_number(double d){\n return {zs_new(d)};\n}\n\nLisp_ptr wrap_number(const Complex& z){\n return {zs_new(z)};\n}\n\nLisp_ptr to_exact(Lisp_ptr p){\n switch(p.tag()){\n case Ptr_tag::integer:\n case Ptr_tag::rational:\n return p;\n case Ptr_tag::real:\n return wrap_number(static_cast(*p.get()));\n case Ptr_tag::complex:\n throw_zs_error(p, \"number error: conversion from complex to exact number is not supprted.\\n\");\n case Ptr_tag::undefined:\n case Ptr_tag::boolean:\n case Ptr_tag::character:\n case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure:\n case Ptr_tag::n_procedure:\n case Ptr_tag::continuation:\n case Ptr_tag::string:\n case Ptr_tag::vector:\n case Ptr_tag::input_port:\n case Ptr_tag::output_port:\n case Ptr_tag::env:\n case Ptr_tag::syntactic_closure:\n case Ptr_tag::syntax_rules:\n case Ptr_tag::vm_op:\n case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n UNEXP_DEFAULT();\n }\n}\n\nLisp_ptr to_inexact(Lisp_ptr p){\n switch(p.tag()){\n case Ptr_tag::integer:\n case Ptr_tag::rational:\n return wrap_number(coerce(p));\n case Ptr_tag::real:\n case Ptr_tag::complex:\n return p;\n case Ptr_tag::undefined:\n case Ptr_tag::boolean:\n case Ptr_tag::character:\n case Ptr_tag::cons:\n case Ptr_tag::symbol:\n case Ptr_tag::i_procedure:\n case Ptr_tag::n_procedure:\n case Ptr_tag::continuation:\n case Ptr_tag::string:\n case Ptr_tag::vector:\n case Ptr_tag::input_port:\n case Ptr_tag::output_port:\n case Ptr_tag::env:\n case Ptr_tag::syntactic_closure:\n case Ptr_tag::syntax_rules:\n case Ptr_tag::vm_op:\n case Ptr_tag::vm_argcount:\n case Ptr_tag::notation:\n default:\n UNEXP_DEFAULT();\n }\n}\n<|endoftext|>"} {"text":"Updated FormattedString function to use precision argument.<|endoftext|>"} {"text":"\/\/ Demonstrates atomically decrementing a counter in shared memory between\n\/\/ multiple processes using boost named_mutex and interprocess APIs.\n\/\/\n\/\/ To run:\n\/\/ .\/harness.o -num_processes 2 .\/test.o\n\/\/\n\/\/ Author: Sam Xi\n\n#include \n#include \n#include \n#include \n\n#include \"mpkeys.h\"\n\nint main() {\n\n using namespace boost::interprocess;\n using namespace xiosim::shared;\n\n managed_shared_memory shm(open_or_create, XIOSIM_SHARED_MEMORY_KEY.c_str(),\n DEFAULT_SHARED_MEMORY_SIZE);\n std::cout << \"Opened shared memory\" << std::endl;\n named_mutex init_lock(open_only, XIOSIM_INIT_SHARED_LOCK.c_str());\n std::cout << \"Opened lock\" << std::endl;\n init_lock.lock();\n std::cout << \"Lock acquired\" << std::endl;\n\n int *counter = shm.find_or_construct(XIOSIM_INIT_COUNTER_KEY.c_str())(0);\n std::cout << \"Counter value is: \" << *counter << std::endl;\n (*counter)--;\n init_lock.unlock();\n while (*counter > 0);\n std::cout << \"COntinuing execution.\" << std::endl;\n\n return 0;\n}\nChanged std::string to c strings\/\/ Demonstrates atomically decrementing a counter in shared memory between\n\/\/ multiple processes using boost named_mutex and interprocess APIs.\n\/\/\n\/\/ To run:\n\/\/ .\/harness.o -num_processes 2 .\/test.o\n\/\/\n\/\/ Author: Sam Xi\n\n#include \n#include \n#include \n#include \n\n#include \"mpkeys.h\"\n\nint main() {\n\n using namespace boost::interprocess;\n using namespace xiosim::shared;\n\n managed_shared_memory shm(open_or_create, XIOSIM_SHARED_MEMORY_KEY,\n DEFAULT_SHARED_MEMORY_SIZE);\n std::cout << \"Opened shared memory\" << std::endl;\n named_mutex init_lock(open_only, XIOSIM_INIT_SHARED_LOCK);\n std::cout << \"Opened lock\" << std::endl;\n init_lock.lock();\n std::cout << \"Lock acquired\" << std::endl;\n\n int *counter = shm.find_or_construct(XIOSIM_INIT_COUNTER_KEY)(0);\n std::cout << \"Counter value is: \" << *counter << std::endl;\n (*counter)--;\n init_lock.unlock();\n while (*counter > 0);\n std::cout << \"COntinuing execution.\" << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"fix msgs, add optional args to chain\/wallet RPC-API additions<|endoftext|>"} {"text":"Mark btf as depending on libbpf in --info<|endoftext|>"} {"text":"Using MsgPack::select() to filter results<|endoftext|>"} {"text":"\/*\n * HttpEndPoint.cpp - Kurento Media Server\n *\n * Copyright (C) 2013 Kurento\n * Contact: Miguel París Díaz \n * Contact: José Antonio Santos Cadenas \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 version 3\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"HttpEndPoint.hpp\"\n\nnamespace kurento\n{\n\nHttpEndPoint::HttpEndPoint (std::shared_ptr parent) : EndPoint (parent)\n{\n this->type.__set_endPoint (EndPointType::type::HTTP_END_POINT);\n}\n\nHttpEndPoint::~HttpEndPoint() throw ()\n{\n this->url = \"DUMMY URL\";\n}\n\nstd::string\nHttpEndPoint::getUrl ()\n{\n return url;\n}\n\n} \/\/ kurento\nImplement constructor and destructor for HttpEndPoint class\/*\n * HttpEndPoint.cpp - Kurento Media Server\n *\n * Copyright (C) 2013 Kurento\n * Contact: Miguel París Díaz \n * Contact: José Antonio Santos Cadenas \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 version 3\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"HttpEndPoint.hpp\"\n\nnamespace kurento\n{\n\nHttpEndPoint::HttpEndPoint (std::shared_ptr parent) :\n EndPoint (parent)\n{\n gchar *name;\n this->type.__set_endPoint (EndPointType::type::HTTP_END_POINT);\n\n name = getIdStr ();\n element = gst_element_factory_make (\"httpendpoint\", name);\n g_free (name);\n\n g_object_ref (element);\n gst_bin_add (GST_BIN (parent->pipeline), element);\n gst_element_sync_state_with_parent (element);\n}\n\nHttpEndPoint::~HttpEndPoint() throw ()\n{\n gst_bin_remove (GST_BIN ( (\n (std::shared_ptr &) parent)->pipeline), element);\n gst_element_set_state (element, GST_STATE_NULL);\n g_object_unref (element);\n}\n\nstd::string\nHttpEndPoint::getUrl ()\n{\n return url;\n}\n\n} \/\/ kurento\n<|endoftext|>"} {"text":"\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(disable:4244 4305) \/\/ for VC++, no precision loss complaints\n#endif\n\n\/\/ select correct drawing functions\n#ifdef dDOUBLE\n#define dsDrawBox dsDrawBoxD\n#endif\n\n\n\/\/ some constants\n#define SIDE (0.5f)\t\/\/ side length of a box\n#define MASS (1.0)\t\/\/ mass of a box\n\n\n\/\/ dynamics and collision objects\nstatic dWorldID world;\nstatic dBodyID body[2];\nstatic dGeomID geom[2];\nstatic dJointID lmotor[2];\nstatic dJointID amotor[2];\nstatic dSpaceID space;\nstatic dJointGroupID contactgroup;\n\n\n\/\/ start simulation - set viewpoint\n\nstatic void start()\n{\n static float xyz[3] = {1.0382f,-1.0811f,1.4700f};\n static float hpr[3] = {135.0000f,-19.5000f,0.0000f};\n dsSetViewpoint (xyz,hpr);\n printf (\"Press 'q,a,z' to control one axis of lmotor connectiong two bodies. (q is +,a is 0, z is -)\\n\");\n printf (\"Press 'w,e,r' to control one axis of lmotor connectiong first body with world. (w is +,e is 0, r is -)\\n\");\n}\n\n\n\/\/ called when a key pressed\n\nstatic void command (int cmd)\n{\n if (cmd == 'q' || cmd == 'Q') {\n \tdJointSetLMotorParam(lmotor[0],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel3,0.1);\n } else if (cmd == 'a' || cmd == 'A') {\n \tdJointSetLMotorParam(lmotor[0],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel3,0);\n } else if (cmd == 'z' || cmd == 'Z') {\n \tdJointSetLMotorParam(lmotor[0],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel3,-0.1);\n } else if (cmd == 'w' || cmd == 'W') {\n \tdJointSetLMotorParam(lmotor[1],dParamVel,0.1);\n \tdJointSetLMotorParam(lmotor[1],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel3,0);\n } else if (cmd == 'e' || cmd == 'E') {\n \tdJointSetLMotorParam(lmotor[1],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel3,0);\n } else if (cmd == 'r' || cmd == 'R') {\n \tdJointSetLMotorParam(lmotor[1],dParamVel,-0.1);\n \tdJointSetLMotorParam(lmotor[1],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel3,0);\n }\n \n}\n\n\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n \/\/ exit without doing anything if the two bodies are connected by a joint\n dBodyID b1 = dGeomGetBody(o1);\n dBodyID b2 = dGeomGetBody(o2);\n\n dContact contact;\n contact.surface.mode = 0;\n contact.surface.mu = dInfinity;\n if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {\n dJointID c = dJointCreateContact (world,contactgroup,&contact);\n dJointAttach (c,b1,b2);\n }\n}\n\n\/\/ simulation loop\n\nstatic void simLoop (int pause)\n{\n if (!pause) {\n dSpaceCollide(space,0,&nearCallback);\n dWorldQuickStep (world,0.05);\n\tdJointGroupEmpty(contactgroup);\n }\n\n dReal sides1[3];\n dGeomBoxGetLengths(geom[0], sides1);\n dReal sides2[3];\n dGeomBoxGetLengths(geom[1], sides2);\n dsSetTexture (DS_WOOD);\n dsSetColor (1,1,0);\n dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides1);\n dsSetColor (0,1,1);\n dsDrawBox (dBodyGetPosition(body[1]),dBodyGetRotation(body[1]),sides2);\n}\n\n\nint main (int argc, char **argv)\n{\n \/\/ setup pointers to drawstuff callback functions\n dsFunctions fn;\n fn.version = DS_VERSION;\n fn.start = &start;\n fn.step = &simLoop;\n fn.command = &command;\n fn.stop = 0;\n fn.path_to_textures = \"..\/..\/drawstuff\/textures\";\n\n \/\/ create world\n contactgroup = dJointGroupCreate(0);\n world = dWorldCreate();\n space = dSimpleSpaceCreate(0);\n dMass m;\n dMassSetBox (&m,1,SIDE,SIDE,SIDE);\n dMassAdjust (&m,MASS);\n\n body[0] = dBodyCreate (world);\n dBodySetMass (body[0],&m);\n dBodySetPosition (body[0],0,0,1);\n geom[0] = dCreateBox(space,SIDE,SIDE,SIDE);\n body[1] = dBodyCreate (world);\n dBodySetMass (body[1],&m);\n dBodySetPosition (body[1],0,0,2);\n geom[1] = dCreateBox(space,SIDE,SIDE,SIDE); \n\n dGeomSetBody(geom[0],body[0]);\n dGeomSetBody(geom[1],body[1]);\n\n lmotor[0] = dJointCreateLMotor (world,0);\n dJointAttach (lmotor[0],body[0],body[1]);\n lmotor[1] = dJointCreateLMotor (world,0);\n dJointAttach (lmotor[1],body[0],0);\n amotor[0] = dJointCreateAMotor(world,0);\n dJointAttach(amotor[0], body[0],body[1]);\n amotor[1] = dJointCreateAMotor(world,0);\n dJointAttach(amotor[1], body[0], 0);\n \n for (int i=0; i<2; i++) {\n\t dJointSetAMotorNumAxes(amotor[i], 3);\n\t dJointSetAMotorAxis(amotor[i],0,1,1,0,0);\n\t dJointSetAMotorAxis(amotor[i],1,1,0,1,0);\n\t dJointSetAMotorAxis(amotor[i],2,1,0,0,1);\n\t dJointSetAMotorParam(amotor[i],dParamFMax,0.00001);\n\t dJointSetAMotorParam(amotor[i],dParamFMax2,0.00001);\n\t dJointSetAMotorParam(amotor[i],dParamFMax3,0.00001);\n\n\t dJointSetAMotorParam(amotor[i],dParamVel,0);\n\t dJointSetAMotorParam(amotor[i],dParamVel2,0);\n\t dJointSetAMotorParam(amotor[i],dParamVel3,0);\n\n\t dJointSetLMotorNumAxes(lmotor[i],3);\n\t dJointSetLMotorAxis(lmotor[i],0,1,1,0,0);\n\t dJointSetLMotorAxis(lmotor[i],1,1,0,1,0);\n\t dJointSetLMotorAxis(lmotor[i],2,1,0,0,1);\n\t \n\t dJointSetLMotorParam(lmotor[i],dParamFMax,0.0001);\n\t dJointSetLMotorParam(lmotor[i],dParamFMax2,0.0001);\n\t dJointSetLMotorParam(lmotor[i],dParamFMax3,0.0001);\n }\n\n \/\/ run simulation\n dsSimulationLoop (argc,argv,352,288,&fn);\n\n dWorldDestroy (world);\n dSpaceDestroy (space);\n dJointGroupDestroy(contactgroup);\n return 0;\n}\naccept a path to textures\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(disable:4244 4305) \/\/ for VC++, no precision loss complaints\n#endif\n\n\/\/ select correct drawing functions\n#ifdef dDOUBLE\n#define dsDrawBox dsDrawBoxD\n#endif\n\n\n\/\/ some constants\n#define SIDE (0.5f)\t\/\/ side length of a box\n#define MASS (1.0)\t\/\/ mass of a box\n\n\n\/\/ dynamics and collision objects\nstatic dWorldID world;\nstatic dBodyID body[2];\nstatic dGeomID geom[2];\nstatic dJointID lmotor[2];\nstatic dJointID amotor[2];\nstatic dSpaceID space;\nstatic dJointGroupID contactgroup;\n\n\n\/\/ start simulation - set viewpoint\n\nstatic void start()\n{\n static float xyz[3] = {1.0382f,-1.0811f,1.4700f};\n static float hpr[3] = {135.0000f,-19.5000f,0.0000f};\n dsSetViewpoint (xyz,hpr);\n printf (\"Press 'q,a,z' to control one axis of lmotor connectiong two bodies. (q is +,a is 0, z is -)\\n\");\n printf (\"Press 'w,e,r' to control one axis of lmotor connectiong first body with world. (w is +,e is 0, r is -)\\n\");\n}\n\n\n\/\/ called when a key pressed\n\nstatic void command (int cmd)\n{\n if (cmd == 'q' || cmd == 'Q') {\n \tdJointSetLMotorParam(lmotor[0],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel3,0.1);\n } else if (cmd == 'a' || cmd == 'A') {\n \tdJointSetLMotorParam(lmotor[0],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel3,0);\n } else if (cmd == 'z' || cmd == 'Z') {\n \tdJointSetLMotorParam(lmotor[0],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[0],dParamVel3,-0.1);\n } else if (cmd == 'w' || cmd == 'W') {\n \tdJointSetLMotorParam(lmotor[1],dParamVel,0.1);\n \tdJointSetLMotorParam(lmotor[1],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel3,0);\n } else if (cmd == 'e' || cmd == 'E') {\n \tdJointSetLMotorParam(lmotor[1],dParamVel,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel3,0);\n } else if (cmd == 'r' || cmd == 'R') {\n \tdJointSetLMotorParam(lmotor[1],dParamVel,-0.1);\n \tdJointSetLMotorParam(lmotor[1],dParamVel2,0);\n \tdJointSetLMotorParam(lmotor[1],dParamVel3,0);\n }\n \n}\n\n\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n \/\/ exit without doing anything if the two bodies are connected by a joint\n dBodyID b1 = dGeomGetBody(o1);\n dBodyID b2 = dGeomGetBody(o2);\n\n dContact contact;\n contact.surface.mode = 0;\n contact.surface.mu = dInfinity;\n if (dCollide (o1,o2,0,&contact.geom,sizeof(dContactGeom))) {\n dJointID c = dJointCreateContact (world,contactgroup,&contact);\n dJointAttach (c,b1,b2);\n }\n}\n\n\/\/ simulation loop\n\nstatic void simLoop (int pause)\n{\n if (!pause) {\n dSpaceCollide(space,0,&nearCallback);\n dWorldQuickStep (world,0.05);\n\tdJointGroupEmpty(contactgroup);\n }\n\n dReal sides1[3];\n dGeomBoxGetLengths(geom[0], sides1);\n dReal sides2[3];\n dGeomBoxGetLengths(geom[1], sides2);\n dsSetTexture (DS_WOOD);\n dsSetColor (1,1,0);\n dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides1);\n dsSetColor (0,1,1);\n dsDrawBox (dBodyGetPosition(body[1]),dBodyGetRotation(body[1]),sides2);\n}\n\n\nint main (int argc, char **argv)\n{\n \/\/ setup pointers to drawstuff callback functions\n dsFunctions fn;\n fn.version = DS_VERSION;\n fn.start = &start;\n fn.step = &simLoop;\n fn.command = &command;\n fn.stop = 0;\n fn.path_to_textures = \"..\/..\/drawstuff\/textures\";\n if(argc>=2)\n {\n fn.path_to_textures = argv[1];\n }\n\n \/\/ create world\n contactgroup = dJointGroupCreate(0);\n world = dWorldCreate();\n space = dSimpleSpaceCreate(0);\n dMass m;\n dMassSetBox (&m,1,SIDE,SIDE,SIDE);\n dMassAdjust (&m,MASS);\n\n body[0] = dBodyCreate (world);\n dBodySetMass (body[0],&m);\n dBodySetPosition (body[0],0,0,1);\n geom[0] = dCreateBox(space,SIDE,SIDE,SIDE);\n body[1] = dBodyCreate (world);\n dBodySetMass (body[1],&m);\n dBodySetPosition (body[1],0,0,2);\n geom[1] = dCreateBox(space,SIDE,SIDE,SIDE); \n\n dGeomSetBody(geom[0],body[0]);\n dGeomSetBody(geom[1],body[1]);\n\n lmotor[0] = dJointCreateLMotor (world,0);\n dJointAttach (lmotor[0],body[0],body[1]);\n lmotor[1] = dJointCreateLMotor (world,0);\n dJointAttach (lmotor[1],body[0],0);\n amotor[0] = dJointCreateAMotor(world,0);\n dJointAttach(amotor[0], body[0],body[1]);\n amotor[1] = dJointCreateAMotor(world,0);\n dJointAttach(amotor[1], body[0], 0);\n \n for (int i=0; i<2; i++) {\n\t dJointSetAMotorNumAxes(amotor[i], 3);\n\t dJointSetAMotorAxis(amotor[i],0,1,1,0,0);\n\t dJointSetAMotorAxis(amotor[i],1,1,0,1,0);\n\t dJointSetAMotorAxis(amotor[i],2,1,0,0,1);\n\t dJointSetAMotorParam(amotor[i],dParamFMax,0.00001);\n\t dJointSetAMotorParam(amotor[i],dParamFMax2,0.00001);\n\t dJointSetAMotorParam(amotor[i],dParamFMax3,0.00001);\n\n\t dJointSetAMotorParam(amotor[i],dParamVel,0);\n\t dJointSetAMotorParam(amotor[i],dParamVel2,0);\n\t dJointSetAMotorParam(amotor[i],dParamVel3,0);\n\n\t dJointSetLMotorNumAxes(lmotor[i],3);\n\t dJointSetLMotorAxis(lmotor[i],0,1,1,0,0);\n\t dJointSetLMotorAxis(lmotor[i],1,1,0,1,0);\n\t dJointSetLMotorAxis(lmotor[i],2,1,0,0,1);\n\t \n\t dJointSetLMotorParam(lmotor[i],dParamFMax,0.0001);\n\t dJointSetLMotorParam(lmotor[i],dParamFMax2,0.0001);\n\t dJointSetLMotorParam(lmotor[i],dParamFMax3,0.0001);\n }\n\n \/\/ run simulation\n dsSimulationLoop (argc,argv,352,288,&fn);\n\n dWorldDestroy (world);\n dSpaceDestroy (space);\n dJointGroupDestroy(contactgroup);\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#include \"query_pagers.hh\"\n#include \"query_pager.hh\"\n#include \"cql3\/selection\/selection.hh\"\n#include \"log.hh\"\n#include \"service\/storage_proxy.hh\"\n#include \"to_string.hh\"\n\nstatic logging::logger qlogger(\"paging\");\n\nclass service::pager::query_pagers::impl : public query_pager {\npublic:\n impl(schema_ptr s, ::shared_ptr selection,\n service::query_state& state,\n const cql3::query_options& options,\n lw_shared_ptr cmd,\n dht::partition_range_vector ranges)\n : _has_clustering_keys(has_clustering_keys(*s, *cmd))\n , _max(cmd->row_limit)\n , _schema(std::move(s))\n , _selection(selection)\n , _state(state)\n , _options(options)\n , _cmd(std::move(cmd))\n , _ranges(std::move(ranges))\n {}\n\nprivate:\n static bool has_clustering_keys(const schema& s, const query::read_command& cmd) {\n return s.clustering_key_size() > 0\n && !cmd.slice.options.contains();\n }\n\n future<> fetch_page(cql3::selection::result_set_builder& builder, uint32_t page_size, gc_clock::time_point now) override {\n auto state = _options.get_paging_state();\n\n if (!_last_pkey && state) {\n _max = state->get_remaining();\n _last_pkey = state->get_partition_key();\n _last_ckey = state->get_clustering_key();\n _cmd->query_uuid = state->get_query_uuid();\n _cmd->is_first_page = false;\n } else {\n \/\/ Reusing readers is currently only supported for singular queries.\n if (_ranges.front().is_singular()) {\n _cmd->query_uuid = utils::make_random_uuid();\n }\n _cmd->is_first_page = true;\n }\n qlogger.trace(\"fetch_page query id {}\", _cmd->query_uuid);\n\n if (_last_pkey) {\n auto dpk = dht::global_partitioner().decorate_key(*_schema, *_last_pkey);\n dht::ring_position lo(dpk);\n\n auto reversed = _cmd->slice.options.contains();\n\n qlogger.trace(\"PKey={}, CKey={}, reversed={}\", dpk, _last_ckey, reversed);\n\n \/\/ Note: we're assuming both that the ranges are checked\n \/\/ and \"cql-compliant\", and that storage_proxy will process\n \/\/ the ranges in order\n \/\/\n \/\/ If the original query has singular restrictions like \"col in (x, y, z)\",\n \/\/ we will eventually generate an empty range. This is ok, because empty range == nothing,\n \/\/ which is what we thus mean.\n auto modify_ranges = [reversed](auto& ranges, auto& lo, bool inclusive, const auto& cmp) {\n typedef typename std::remove_reference_t::value_type range_type;\n typedef typename range_type::bound bound_type;\n bool found = false;\n\n auto i = ranges.begin();\n while (i != ranges.end()) {\n bool contains = i->contains(lo, cmp);\n\n if (contains) {\n found = true;\n }\n\n bool remove = !found\n || (contains && !inclusive && (i->is_singular()\n || (reversed && i->start() && !cmp(i->start()->value(), lo))\n || (!reversed && i->end() && !cmp(i->end()->value(), lo))))\n ;\n\n if (remove) {\n qlogger.trace(\"Remove range {}\", *i);\n i = ranges.erase(i);\n continue;\n }\n if (contains) {\n auto r = reversed && !i->is_singular()\n ? range_type(i->start(), bound_type{ lo, inclusive })\n : range_type( bound_type{ lo, inclusive }, i->end(), i->is_singular())\n ;\n qlogger.trace(\"Modify range {} -> {}\", *i, r);\n *i = std::move(r);\n }\n ++i;\n }\n qlogger.trace(\"Result ranges {}\", ranges);\n };\n\n \/\/ Because of #1446 we don't have a comparator to use with\n \/\/ range which would produce correct results.\n \/\/ This means we cannot reuse the same logic for dealing with\n \/\/ partition and clustering keys.\n auto modify_ck_ranges = [reversed] (const schema& s, auto& ranges, auto& lo) {\n typedef typename std::remove_reference_t::value_type range_type;\n typedef typename range_type::bound bound_type;\n\n auto cmp = [reversed, bv_cmp = bound_view::compare(s)] (const auto& a, const auto& b) {\n return reversed ? bv_cmp(b, a) : bv_cmp(a, b);\n };\n auto start_bound = [reversed] (const auto& range) -> const bound_view& {\n return reversed ? range.second : range.first;\n };\n auto end_bound = [reversed] (const auto& range) -> const bound_view& {\n return reversed ? range.first : range.second;\n };\n clustering_key_prefix::equality eq(s);\n\n auto it = ranges.begin();\n while (it != ranges.end()) {\n auto range = bound_view::from_range(*it);\n if (cmp(end_bound(range), lo) || eq(end_bound(range).prefix, lo)) {\n qlogger.trace(\"Remove ck range {}\", *it);\n it = ranges.erase(it);\n continue;\n } else if (cmp(start_bound(range), lo)) {\n assert(cmp(lo, end_bound(range)));\n auto r = reversed ? range_type(it->start(), bound_type { lo, false })\n : range_type(bound_type { lo, false }, it->end());\n qlogger.trace(\"Modify ck range {} -> {}\", *it, r);\n *it = std::move(r);\n }\n ++it;\n }\n };\n\n \/\/ last ck can be empty depending on whether we\n \/\/ deserialized state or not. This case means \"last page ended on\n \/\/ something-not-bound-by-clustering\" (i.e. a static row, alone)\n const bool has_ck = _has_clustering_keys && _last_ckey;\n\n \/\/ If we have no clustering keys, it should mean we only have one row\n \/\/ per PK. Thus we can just bypass the last one.\n modify_ranges(_ranges, lo, has_ck, dht::ring_position_comparator(*_schema));\n\n if (has_ck) {\n query::clustering_row_ranges row_ranges = _cmd->slice.default_row_ranges();\n clustering_key_prefix ckp = clustering_key_prefix::from_exploded(*_schema, _last_ckey->explode(*_schema));\n modify_ck_ranges(*_schema, row_ranges, ckp);\n\n _cmd->slice.set_range(*_schema, *_last_pkey, row_ranges);\n }\n }\n\n auto max_rows = std::min(_max, page_size);\n\n \/\/ We always need PK so we can determine where to start next.\n _cmd->slice.options.set();\n \/\/ don't add empty bytes (cks) unless we have to\n if (_has_clustering_keys) {\n _cmd->slice.options.set<\n query::partition_slice::option::send_clustering_key>();\n }\n _cmd->row_limit = max_rows;\n\n qlogger.debug(\"Fetching {}, page size={}, max_rows={}\",\n _cmd->cf_id, page_size, max_rows\n );\n\n auto ranges = _ranges;\n auto command = ::make_lw_shared(*_cmd);\n return get_local_storage_proxy().query(_schema, std::move(command), std::move(ranges),\n _options.get_consistency(), _state.get_trace_state()).then(\n [this, &builder, page_size, now](foreign_ptr> results, paging_state::replicas_per_token_range) {\n handle_result(builder, std::move(results), page_size, now);\n });\n }\n\n future> fetch_page(uint32_t page_size,\n gc_clock::time_point now) override {\n return do_with(\n cql3::selection::result_set_builder(*_selection, now,\n _options.get_cql_serialization_format()),\n [this, page_size, now](auto& builder) {\n return this->fetch_page(builder, page_size, now).then([&builder] {\n return builder.build();\n });\n });\n }\n\n void handle_result(\n cql3::selection::result_set_builder& builder,\n foreign_ptr> results,\n uint32_t page_size, gc_clock::time_point now) {\n\n class myvisitor : public cql3::selection::result_set_builder::visitor {\n public:\n uint32_t total_rows = 0;\n std::experimental::optional last_pkey;\n std::experimental::optional last_ckey;\n\n myvisitor(cql3::selection::result_set_builder& builder,\n const schema& s,\n const cql3::selection::selection& selection)\n : visitor(builder, s, selection) {\n }\n\n void accept_new_partition(uint32_t) {\n throw std::logic_error(\"Should not reach!\");\n }\n void accept_new_partition(const partition_key& key, uint32_t row_count) {\n qlogger.trace(\"Accepting partition: {} ({})\", key, row_count);\n total_rows += std::max(row_count, 1u);\n last_pkey = key;\n last_ckey = { };\n visitor::accept_new_partition(key, row_count);\n }\n void accept_new_row(const clustering_key& key,\n const query::result_row_view& static_row,\n const query::result_row_view& row) {\n last_ckey = key;\n visitor::accept_new_row(key, static_row, row);\n }\n void accept_new_row(const query::result_row_view& static_row,\n const query::result_row_view& row) {\n visitor::accept_new_row(static_row, row);\n }\n void accept_partition_end(const query::result_row_view& static_row) {\n visitor::accept_partition_end(static_row);\n }\n };\n\n myvisitor v(builder, *_schema, *_selection);\n query::result_view::consume(*results, _cmd->slice, v);\n\n if (_last_pkey) {\n \/\/ refs #752, when doing aggregate queries we will re-use same\n \/\/ slice repeatedly. Since \"specific ck ranges\" only deal with\n \/\/ a single extra range, we must clear out the old one\n \/\/ Even if it was not so of course, leaving junk in the slice\n \/\/ is bad.\n _cmd->slice.clear_range(*_schema, *_last_pkey);\n }\n\n _max = _max - v.total_rows;\n _exhausted = (v.total_rows < page_size && !results->is_short_read()) || _max == 0;\n _last_pkey = v.last_pkey;\n _last_ckey = v.last_ckey;\n\n qlogger.debug(\"Fetched {} rows, max_remain={} {}\", v.total_rows, _max, _exhausted ? \"(exh)\" : \"\");\n\n if (_last_pkey) {\n qlogger.debug(\"Last partition key: {}\", *_last_pkey);\n }\n if (_has_clustering_keys && _last_ckey) {\n qlogger.debug(\"Last clustering key: {}\", *_last_ckey);\n }\n }\n\n bool is_exhausted() const override {\n return _exhausted;\n }\n\n int max_remaining() const override {\n return _max;\n }\n\n ::shared_ptr state() const override {\n return _exhausted ? nullptr : ::make_shared(*_last_pkey,\n _last_ckey, _max, _cmd->query_uuid, paging_state::replicas_per_token_range{});\n }\n\nprivate:\n \/\/ remember if we use clustering. if not, each partition == one row\n const bool _has_clustering_keys;\n bool _exhausted = false;\n uint32_t _max;\n\n std::experimental::optional _last_pkey;\n std::experimental::optional _last_ckey;\n\n schema_ptr _schema;\n ::shared_ptr _selection;\n service::query_state& _state;\n const cql3::query_options& _options;\n lw_shared_ptr _cmd;\n dht::partition_range_vector _ranges;\n};\n\nbool service::pager::query_pagers::may_need_paging(uint32_t page_size,\n const query::read_command& cmd,\n const dht::partition_range_vector& ranges) {\n auto est_max_rows =\n [&] {\n if (ranges.empty()) {\n return cmd.row_limit;\n }\n uint32_t n = 0;\n for (auto& r : ranges) {\n if (r.is_singular() && cmd.slice.options.contains()) {\n ++n;\n continue;\n }\n return cmd.row_limit;\n }\n return n;\n };\n\n auto est = est_max_rows();\n auto need_paging = est > page_size;\n\n qlogger.debug(\"Query of {}, page_size={}, limit={} {}\", cmd.cf_id, page_size,\n cmd.row_limit,\n need_paging ? \"requires paging\" : \"does not require paging\");\n\n return need_paging;\n}\n\n::shared_ptr service::pager::query_pagers::pager(\n schema_ptr s, ::shared_ptr selection,\n service::query_state& state, const cql3::query_options& options,\n lw_shared_ptr cmd,\n dht::partition_range_vector ranges) {\n return ::make_shared(std::move(s), std::move(selection), state,\n options, std::move(cmd), std::move(ranges));\n}\n\nUse the last_replicas stored in the page_state\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#include \"query_pagers.hh\"\n#include \"query_pager.hh\"\n#include \"cql3\/selection\/selection.hh\"\n#include \"log.hh\"\n#include \"service\/storage_proxy.hh\"\n#include \"to_string.hh\"\n\nstatic logging::logger qlogger(\"paging\");\n\nclass service::pager::query_pagers::impl : public query_pager {\npublic:\n impl(schema_ptr s, ::shared_ptr selection,\n service::query_state& state,\n const cql3::query_options& options,\n lw_shared_ptr cmd,\n dht::partition_range_vector ranges)\n : _has_clustering_keys(has_clustering_keys(*s, *cmd))\n , _max(cmd->row_limit)\n , _schema(std::move(s))\n , _selection(selection)\n , _state(state)\n , _options(options)\n , _cmd(std::move(cmd))\n , _ranges(std::move(ranges))\n {}\n\nprivate:\n static bool has_clustering_keys(const schema& s, const query::read_command& cmd) {\n return s.clustering_key_size() > 0\n && !cmd.slice.options.contains();\n }\n\n future<> fetch_page(cql3::selection::result_set_builder& builder, uint32_t page_size, gc_clock::time_point now) override {\n auto state = _options.get_paging_state();\n\n if (!_last_pkey && state) {\n _max = state->get_remaining();\n _last_pkey = state->get_partition_key();\n _last_ckey = state->get_clustering_key();\n _cmd->query_uuid = state->get_query_uuid();\n _cmd->is_first_page = false;\n _last_replicas = state->get_last_replicas();\n } else {\n \/\/ Reusing readers is currently only supported for singular queries.\n if (_ranges.front().is_singular()) {\n _cmd->query_uuid = utils::make_random_uuid();\n }\n _cmd->is_first_page = true;\n }\n qlogger.trace(\"fetch_page query id {}\", _cmd->query_uuid);\n\n if (_last_pkey) {\n auto dpk = dht::global_partitioner().decorate_key(*_schema, *_last_pkey);\n dht::ring_position lo(dpk);\n\n auto reversed = _cmd->slice.options.contains();\n\n qlogger.trace(\"PKey={}, CKey={}, reversed={}\", dpk, _last_ckey, reversed);\n\n \/\/ Note: we're assuming both that the ranges are checked\n \/\/ and \"cql-compliant\", and that storage_proxy will process\n \/\/ the ranges in order\n \/\/\n \/\/ If the original query has singular restrictions like \"col in (x, y, z)\",\n \/\/ we will eventually generate an empty range. This is ok, because empty range == nothing,\n \/\/ which is what we thus mean.\n auto modify_ranges = [reversed](auto& ranges, auto& lo, bool inclusive, const auto& cmp) {\n typedef typename std::remove_reference_t::value_type range_type;\n typedef typename range_type::bound bound_type;\n bool found = false;\n\n auto i = ranges.begin();\n while (i != ranges.end()) {\n bool contains = i->contains(lo, cmp);\n\n if (contains) {\n found = true;\n }\n\n bool remove = !found\n || (contains && !inclusive && (i->is_singular()\n || (reversed && i->start() && !cmp(i->start()->value(), lo))\n || (!reversed && i->end() && !cmp(i->end()->value(), lo))))\n ;\n\n if (remove) {\n qlogger.trace(\"Remove range {}\", *i);\n i = ranges.erase(i);\n continue;\n }\n if (contains) {\n auto r = reversed && !i->is_singular()\n ? range_type(i->start(), bound_type{ lo, inclusive })\n : range_type( bound_type{ lo, inclusive }, i->end(), i->is_singular())\n ;\n qlogger.trace(\"Modify range {} -> {}\", *i, r);\n *i = std::move(r);\n }\n ++i;\n }\n qlogger.trace(\"Result ranges {}\", ranges);\n };\n\n \/\/ Because of #1446 we don't have a comparator to use with\n \/\/ range which would produce correct results.\n \/\/ This means we cannot reuse the same logic for dealing with\n \/\/ partition and clustering keys.\n auto modify_ck_ranges = [reversed] (const schema& s, auto& ranges, auto& lo) {\n typedef typename std::remove_reference_t::value_type range_type;\n typedef typename range_type::bound bound_type;\n\n auto cmp = [reversed, bv_cmp = bound_view::compare(s)] (const auto& a, const auto& b) {\n return reversed ? bv_cmp(b, a) : bv_cmp(a, b);\n };\n auto start_bound = [reversed] (const auto& range) -> const bound_view& {\n return reversed ? range.second : range.first;\n };\n auto end_bound = [reversed] (const auto& range) -> const bound_view& {\n return reversed ? range.first : range.second;\n };\n clustering_key_prefix::equality eq(s);\n\n auto it = ranges.begin();\n while (it != ranges.end()) {\n auto range = bound_view::from_range(*it);\n if (cmp(end_bound(range), lo) || eq(end_bound(range).prefix, lo)) {\n qlogger.trace(\"Remove ck range {}\", *it);\n it = ranges.erase(it);\n continue;\n } else if (cmp(start_bound(range), lo)) {\n assert(cmp(lo, end_bound(range)));\n auto r = reversed ? range_type(it->start(), bound_type { lo, false })\n : range_type(bound_type { lo, false }, it->end());\n qlogger.trace(\"Modify ck range {} -> {}\", *it, r);\n *it = std::move(r);\n }\n ++it;\n }\n };\n\n \/\/ last ck can be empty depending on whether we\n \/\/ deserialized state or not. This case means \"last page ended on\n \/\/ something-not-bound-by-clustering\" (i.e. a static row, alone)\n const bool has_ck = _has_clustering_keys && _last_ckey;\n\n \/\/ If we have no clustering keys, it should mean we only have one row\n \/\/ per PK. Thus we can just bypass the last one.\n modify_ranges(_ranges, lo, has_ck, dht::ring_position_comparator(*_schema));\n\n if (has_ck) {\n query::clustering_row_ranges row_ranges = _cmd->slice.default_row_ranges();\n clustering_key_prefix ckp = clustering_key_prefix::from_exploded(*_schema, _last_ckey->explode(*_schema));\n modify_ck_ranges(*_schema, row_ranges, ckp);\n\n _cmd->slice.set_range(*_schema, *_last_pkey, row_ranges);\n }\n }\n\n auto max_rows = std::min(_max, page_size);\n\n \/\/ We always need PK so we can determine where to start next.\n _cmd->slice.options.set();\n \/\/ don't add empty bytes (cks) unless we have to\n if (_has_clustering_keys) {\n _cmd->slice.options.set<\n query::partition_slice::option::send_clustering_key>();\n }\n _cmd->row_limit = max_rows;\n\n qlogger.debug(\"Fetching {}, page size={}, max_rows={}\",\n _cmd->cf_id, page_size, max_rows\n );\n\n auto ranges = _ranges;\n auto command = ::make_lw_shared(*_cmd);\n auto& sp = get_local_storage_proxy();\n return sp.query(_schema, std::move(command), std::move(ranges),\n _options.get_consistency(), _state.get_trace_state(), sp.default_query_timeout(), std::move(_last_replicas)).then(\n [this, &builder, page_size, now](foreign_ptr> results, paging_state::replicas_per_token_range last_replicas) {\n _last_replicas = std::move(last_replicas);\n handle_result(builder, std::move(results), page_size, now);\n });\n }\n\n future> fetch_page(uint32_t page_size,\n gc_clock::time_point now) override {\n return do_with(\n cql3::selection::result_set_builder(*_selection, now,\n _options.get_cql_serialization_format()),\n [this, page_size, now](auto& builder) {\n return this->fetch_page(builder, page_size, now).then([&builder] {\n return builder.build();\n });\n });\n }\n\n void handle_result(\n cql3::selection::result_set_builder& builder,\n foreign_ptr> results,\n uint32_t page_size, gc_clock::time_point now) {\n\n class myvisitor : public cql3::selection::result_set_builder::visitor {\n public:\n uint32_t total_rows = 0;\n std::experimental::optional last_pkey;\n std::experimental::optional last_ckey;\n\n myvisitor(cql3::selection::result_set_builder& builder,\n const schema& s,\n const cql3::selection::selection& selection)\n : visitor(builder, s, selection) {\n }\n\n void accept_new_partition(uint32_t) {\n throw std::logic_error(\"Should not reach!\");\n }\n void accept_new_partition(const partition_key& key, uint32_t row_count) {\n qlogger.trace(\"Accepting partition: {} ({})\", key, row_count);\n total_rows += std::max(row_count, 1u);\n last_pkey = key;\n last_ckey = { };\n visitor::accept_new_partition(key, row_count);\n }\n void accept_new_row(const clustering_key& key,\n const query::result_row_view& static_row,\n const query::result_row_view& row) {\n last_ckey = key;\n visitor::accept_new_row(key, static_row, row);\n }\n void accept_new_row(const query::result_row_view& static_row,\n const query::result_row_view& row) {\n visitor::accept_new_row(static_row, row);\n }\n void accept_partition_end(const query::result_row_view& static_row) {\n visitor::accept_partition_end(static_row);\n }\n };\n\n myvisitor v(builder, *_schema, *_selection);\n query::result_view::consume(*results, _cmd->slice, v);\n\n if (_last_pkey) {\n \/\/ refs #752, when doing aggregate queries we will re-use same\n \/\/ slice repeatedly. Since \"specific ck ranges\" only deal with\n \/\/ a single extra range, we must clear out the old one\n \/\/ Even if it was not so of course, leaving junk in the slice\n \/\/ is bad.\n _cmd->slice.clear_range(*_schema, *_last_pkey);\n }\n\n _max = _max - v.total_rows;\n _exhausted = (v.total_rows < page_size && !results->is_short_read()) || _max == 0;\n _last_pkey = v.last_pkey;\n _last_ckey = v.last_ckey;\n\n qlogger.debug(\"Fetched {} rows, max_remain={} {}\", v.total_rows, _max, _exhausted ? \"(exh)\" : \"\");\n\n if (_last_pkey) {\n qlogger.debug(\"Last partition key: {}\", *_last_pkey);\n }\n if (_has_clustering_keys && _last_ckey) {\n qlogger.debug(\"Last clustering key: {}\", *_last_ckey);\n }\n }\n\n bool is_exhausted() const override {\n return _exhausted;\n }\n\n int max_remaining() const override {\n return _max;\n }\n\n ::shared_ptr state() const override {\n return _exhausted ? nullptr : ::make_shared(*_last_pkey,\n _last_ckey, _max, _cmd->query_uuid, _last_replicas);\n }\n\nprivate:\n \/\/ remember if we use clustering. if not, each partition == one row\n const bool _has_clustering_keys;\n bool _exhausted = false;\n uint32_t _max;\n\n std::experimental::optional _last_pkey;\n std::experimental::optional _last_ckey;\n\n schema_ptr _schema;\n ::shared_ptr _selection;\n service::query_state& _state;\n const cql3::query_options& _options;\n lw_shared_ptr _cmd;\n dht::partition_range_vector _ranges;\n paging_state::replicas_per_token_range _last_replicas;\n};\n\nbool service::pager::query_pagers::may_need_paging(uint32_t page_size,\n const query::read_command& cmd,\n const dht::partition_range_vector& ranges) {\n auto est_max_rows =\n [&] {\n if (ranges.empty()) {\n return cmd.row_limit;\n }\n uint32_t n = 0;\n for (auto& r : ranges) {\n if (r.is_singular() && cmd.slice.options.contains()) {\n ++n;\n continue;\n }\n return cmd.row_limit;\n }\n return n;\n };\n\n auto est = est_max_rows();\n auto need_paging = est > page_size;\n\n qlogger.debug(\"Query of {}, page_size={}, limit={} {}\", cmd.cf_id, page_size,\n cmd.row_limit,\n need_paging ? \"requires paging\" : \"does not require paging\");\n\n return need_paging;\n}\n\n::shared_ptr service::pager::query_pagers::pager(\n schema_ptr s, ::shared_ptr selection,\n service::query_state& state, const cql3::query_options& options,\n lw_shared_ptr cmd,\n dht::partition_range_vector ranges) {\n return ::make_shared(std::move(s), std::move(selection), state,\n options, std::move(cmd), std::move(ranges));\n}\n\n<|endoftext|>"} {"text":"\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastracture 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 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#include \"jubatus_serv.hpp\"\n#include \"..\/common\/util.hpp\"\n#include \"..\/common\/cht.hpp\"\n#include \"..\/common\/exception.hpp\"\n#include \"server_util.hpp\"\n\n#include \n#include \n#include \n\nusing std::vector;\nusing std::string;\nusing pfi::network::mprpc::rpc_client;\nusing pfi::lang::function;\n\nusing pfi::system::time::clock_time;\nusing pfi::system::time::get_clock_time;\n\nnamespace jubatus { namespace framework {\n\n jubatus_serv::jubatus_serv(const server_argv& a, const std::string& base_path):\n a_(a),\n update_count_(0),\n#ifdef HAVE_ZOOKEEPER_H\n mixer_(new mixer(a_.name, a_.interval_count, a_.interval_sec,\n pfi::lang::bind(&jubatus_serv::do_mix, this, pfi::lang::_1))),\n use_cht_(false),\n#endif\n base_path_(a_.tmpdir)\n {\n };\n \n int jubatus_serv::start(pfi::network::mprpc::rpc_server& serv){\n\n#ifdef HAVE_ZOOKEEPER_H\n if(! a_.is_standalone()){\n zk_ = pfi::lang::shared_ptr\n\t(common::create_lock_service(\"zk\", a_.z, a_.timeout, \"logfile_jubatus_serv\"));\n ls = zk_;\n jubatus::common::prepare_jubatus(*zk_);\n\n if( a_.join ){ \/\/ join to the existing cluster with -j option\n join_to_cluster(zk_);\n }\n\n if( use_cht_ ){\n\n jubatus::common::cht::setup_cht_dir(*zk_, a_.name);\n jubatus::common::cht ht(zk_, a_.name);\n ht.register_node(a_.eth, a_.port);\n }\n\n mixer_->set_zk(zk_);\n register_actor(*zk_, a_.name, a_.eth, a_.port);\n mixer_->start();\n }\n#endif\n\n { LOG(INFO) << \"running in port=\" << a_.port; }\n return serv.serv(a_.port, a_.threadnum);\n\n }\n\n void jubatus_serv::register_mixable(mixable0* m){\n#ifdef HAVE_ZOOKEEPER_H\n mixables_.push_back(m);\n#endif\n };\n \n void jubatus_serv::use_cht(){\n#ifdef HAVE_ZOOKEEPER_H\n use_cht_ = true;\n#endif\n };\n\n std::map > jubatus_serv::get_status(int) const {\n std::map data;\n util::get_machine_status(data);\n\n data[\"timeout\"] = pfi::lang::lexical_cast(a_.timeout);\n data[\"threadnum\"] = pfi::lang::lexical_cast(a_.threadnum);\n data[\"tmpdir\"] = a_.tmpdir;\n data[\"interval_sec\"] = pfi::lang::lexical_cast(a_.interval_sec);\n data[\"interval_count\"] = pfi::lang::lexical_cast(a_.interval_count);\n data[\"is_standalone\"] = pfi::lang::lexical_cast(a_.is_standalone());\n data[\"VERSION\"] = JUBATUS_VERSION;\n data[\"PROGNAME\"] = JUBATUS_APPNAME;\n\n data[\"update_count\"] = pfi::lang::lexical_cast(update_count_);\n\n#ifdef HAVE_ZOOKEEPER_H\n mixer_->get_status(data);\n data[\"zk\"] = a_.z;\n data[\"use_cht\"] = pfi::lang::lexical_cast(use_cht_);\n#endif\n\n std::map > ret;\n ret[get_server_identifier()] = data;\n return ret;\n };\n\n std::string jubatus_serv::get_server_identifier()const{\n std::stringstream ss;\n ss << a_.eth;\n ss << \"_\";\n ss << a_.port;\n return ss.str();\n };\n\n \/\/here\n#ifdef HAVE_ZOOKEEPER_H\n void jubatus_serv::join_to_cluster(pfi::lang::shared_ptr z){\n std::vector list;\n std::string path = common::ACTOR_BASE_PATH + \"\/\" + a_.name + \"\/nodes\";\n z->list(path, list);\n if(not list.empty()){\n common::lock_service_mutex zlk(*z, common::ACTOR_BASE_PATH + \"\/\" + a_.name + \"\/master_lock\");\n while(not zlk.try_lock()){ ; }\n size_t i = rand() % list.size();\n std::string ip;\n int port;\n common::revert(list[i], ip, port);\n pfi::network::mprpc::rpc_client c(ip, port, a_.timeout);\n\n pfi::lang::function f = c.call(\"get_storage\");\n std::stringstream ss( f() );\n for(size_t i = 0;iclear();\n mixables_[i]->load(ss);\n }\n }\n };\n\n std::string jubatus_serv::get_storage(int i){\n std::stringstream ss;\n for(size_t i=0; isave(ss);\n }\n return ss.str();\n }\n\n std::vector jubatus_serv::get_diff_impl(int){\n \/\/ if(mixables_.empty()){\n \/\/ \/\/throw config_not_set(); nothing to mix\n \/\/ }\n std::vector o;\n {\n scoped_lock lk(rlock(m_));\n for(size_t i=0; iget_diff());\n }\n }\n return o;\n };\n\n int jubatus_serv::put_diff_impl(std::vector unpacked){\n scoped_lock lk(wlock(m_));\n if(unpacked.size() != mixables_.size()){\n \/\/deserialization error\n }\n for(size_t i=0; iput_diff(unpacked[i]);\n }\n return 0;\n };\n\n void jubatus_serv::do_mix(const std::vector >& v){\n vector accs;\n vector serialized_diffs;\n clock_time start = get_clock_time();\n for(size_t s = 0; s < v.size(); ++s ){\n try{\n rpc_client c(v[s].first, v[s].second, a_.timeout);\n function(int)> get_diff_fun = c.call(int)>(\"get_diff\");\n serialized_diffs = get_diff_fun(0);\n }catch(std::exception& e){\n LOG(ERROR) << e.what();\n continue;\n }\n scoped_lock lk(rlock(m_)); \/\/ model_ should not be in mix (reduce)?\n if(accs.empty()){\n accs = serialized_diffs;\n }else{\n for(size_t i=0; ireduce(serialized_diffs[i], accs[i]);\n }\n }\n }\n\n for(size_t s = 0; s < v.size(); ++s ){\n try{\n rpc_client c(v[s].first, v[s].second, a_.timeout);\n function)> put_diff_fun = c.call)>(\"put_diff\");\n put_diff_fun(accs);\n }catch(std::exception& e){\n LOG(ERROR) << e.what();\n continue;\n }\n }\n clock_time end = get_clock_time();\n DLOG(INFO) << \"mixed with \" << v.size() << \" servers in \" << (double)(end - start) << \" secs.\";\n size_t s = 0;\n for(size_t i=0; i(errno) + \")\" );\n }\n try{\n for(size_t i=0; isave(ofs);\n }\n ofs.close();\n LOG(INFO) << \"saved to \" << ofile;\n return 0;\n }catch(const std::exception& e){\n return -1;\n }\n }\n\n int jubatus_serv::load(std::string id) {\n std::string ifile;\n build_local_path_(ifile, \"jubatus\", id);\n \n std::ifstream ifs(ifile.c_str(), std::ios::binary);\n if(!ifs)throw std::runtime_error(ifile + \": cannot open (\" + pfi::lang::lexical_cast(errno) + \")\" );\n try{\n for(size_t i = 0;iclear();\n mixables_[i]->load(ifs);\n }\n ifs.close();\n this->after_load();\n return 0;\n }catch(const std::exception& e){\n ifs.close();\n }\n return -1; \/\/expected never reaching here.\n }\n\n}}\nadd safety check in case of bad pointer passed to mixable set. (fixes #22)\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastracture 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 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#include \"jubatus_serv.hpp\"\n#include \"..\/common\/util.hpp\"\n#include \"..\/common\/cht.hpp\"\n#include \"..\/common\/exception.hpp\"\n#include \"server_util.hpp\"\n\n#include \n#include \n#include \n\nusing std::vector;\nusing std::string;\nusing pfi::network::mprpc::rpc_client;\nusing pfi::lang::function;\n\nusing pfi::system::time::clock_time;\nusing pfi::system::time::get_clock_time;\n\nnamespace jubatus { namespace framework {\n\n jubatus_serv::jubatus_serv(const server_argv& a, const std::string& base_path):\n a_(a),\n update_count_(0),\n#ifdef HAVE_ZOOKEEPER_H\n mixer_(new mixer(a_.name, a_.interval_count, a_.interval_sec,\n pfi::lang::bind(&jubatus_serv::do_mix, this, pfi::lang::_1))),\n use_cht_(false),\n#endif\n base_path_(a_.tmpdir)\n {\n };\n \n int jubatus_serv::start(pfi::network::mprpc::rpc_server& serv){\n\n#ifdef HAVE_ZOOKEEPER_H\n if(! a_.is_standalone()){\n zk_ = pfi::lang::shared_ptr\n\t(common::create_lock_service(\"zk\", a_.z, a_.timeout, \"logfile_jubatus_serv\"));\n ls = zk_;\n jubatus::common::prepare_jubatus(*zk_);\n\n if( a_.join ){ \/\/ join to the existing cluster with -j option\n join_to_cluster(zk_);\n }\n\n if( use_cht_ ){\n\n jubatus::common::cht::setup_cht_dir(*zk_, a_.name);\n jubatus::common::cht ht(zk_, a_.name);\n ht.register_node(a_.eth, a_.port);\n }\n\n mixer_->set_zk(zk_);\n register_actor(*zk_, a_.name, a_.eth, a_.port);\n mixer_->start();\n }\n#endif\n\n { LOG(INFO) << \"running in port=\" << a_.port; }\n return serv.serv(a_.port, a_.threadnum);\n\n }\n\n void jubatus_serv::register_mixable(mixable0* m){\n#ifdef HAVE_ZOOKEEPER_H\n m->get_diff(); \/\/ #22 ensure m is good pointer at process startup\n\n mixables_.push_back(m);\n#endif\n };\n \n void jubatus_serv::use_cht(){\n#ifdef HAVE_ZOOKEEPER_H\n use_cht_ = true;\n#endif\n };\n\n std::map > jubatus_serv::get_status(int) const {\n std::map data;\n util::get_machine_status(data);\n\n data[\"timeout\"] = pfi::lang::lexical_cast(a_.timeout);\n data[\"threadnum\"] = pfi::lang::lexical_cast(a_.threadnum);\n data[\"tmpdir\"] = a_.tmpdir;\n data[\"interval_sec\"] = pfi::lang::lexical_cast(a_.interval_sec);\n data[\"interval_count\"] = pfi::lang::lexical_cast(a_.interval_count);\n data[\"is_standalone\"] = pfi::lang::lexical_cast(a_.is_standalone());\n data[\"VERSION\"] = JUBATUS_VERSION;\n data[\"PROGNAME\"] = JUBATUS_APPNAME;\n\n data[\"update_count\"] = pfi::lang::lexical_cast(update_count_);\n\n#ifdef HAVE_ZOOKEEPER_H\n mixer_->get_status(data);\n data[\"zk\"] = a_.z;\n data[\"use_cht\"] = pfi::lang::lexical_cast(use_cht_);\n#endif\n\n std::map > ret;\n ret[get_server_identifier()] = data;\n return ret;\n };\n\n std::string jubatus_serv::get_server_identifier()const{\n std::stringstream ss;\n ss << a_.eth;\n ss << \"_\";\n ss << a_.port;\n return ss.str();\n };\n\n \/\/here\n#ifdef HAVE_ZOOKEEPER_H\n void jubatus_serv::join_to_cluster(pfi::lang::shared_ptr z){\n std::vector list;\n std::string path = common::ACTOR_BASE_PATH + \"\/\" + a_.name + \"\/nodes\";\n z->list(path, list);\n if(not list.empty()){\n common::lock_service_mutex zlk(*z, common::ACTOR_BASE_PATH + \"\/\" + a_.name + \"\/master_lock\");\n while(not zlk.try_lock()){ ; }\n size_t i = rand() % list.size();\n std::string ip;\n int port;\n common::revert(list[i], ip, port);\n pfi::network::mprpc::rpc_client c(ip, port, a_.timeout);\n\n pfi::lang::function f = c.call(\"get_storage\");\n std::stringstream ss( f() );\n for(size_t i = 0;iclear();\n mixables_[i]->load(ss);\n }\n }\n };\n\n std::string jubatus_serv::get_storage(int i){\n std::stringstream ss;\n for(size_t i=0; isave(ss);\n }\n return ss.str();\n }\n\n std::vector jubatus_serv::get_diff_impl(int){\n \/\/ if(mixables_.empty()){\n \/\/ \/\/throw config_not_set(); nothing to mix\n \/\/ }\n std::vector o;\n {\n scoped_lock lk(rlock(m_));\n for(size_t i=0; iget_diff());\n }\n }\n return o;\n };\n\n int jubatus_serv::put_diff_impl(std::vector unpacked){\n scoped_lock lk(wlock(m_));\n if(unpacked.size() != mixables_.size()){\n \/\/deserialization error\n }\n for(size_t i=0; iput_diff(unpacked[i]);\n }\n return 0;\n };\n\n void jubatus_serv::do_mix(const std::vector >& v){\n vector accs;\n vector serialized_diffs;\n clock_time start = get_clock_time();\n for(size_t s = 0; s < v.size(); ++s ){\n try{\n rpc_client c(v[s].first, v[s].second, a_.timeout);\n function(int)> get_diff_fun = c.call(int)>(\"get_diff\");\n serialized_diffs = get_diff_fun(0);\n }catch(std::exception& e){\n LOG(ERROR) << e.what();\n continue;\n }\n scoped_lock lk(rlock(m_)); \/\/ model_ should not be in mix (reduce)?\n if(accs.empty()){\n accs = serialized_diffs;\n }else{\n for(size_t i=0; ireduce(serialized_diffs[i], accs[i]);\n }\n }\n }\n\n for(size_t s = 0; s < v.size(); ++s ){\n try{\n rpc_client c(v[s].first, v[s].second, a_.timeout);\n function)> put_diff_fun = c.call)>(\"put_diff\");\n put_diff_fun(accs);\n }catch(std::exception& e){\n LOG(ERROR) << e.what();\n continue;\n }\n }\n clock_time end = get_clock_time();\n DLOG(INFO) << \"mixed with \" << v.size() << \" servers in \" << (double)(end - start) << \" secs.\";\n size_t s = 0;\n for(size_t i=0; i(errno) + \")\" );\n }\n try{\n for(size_t i=0; isave(ofs);\n }\n ofs.close();\n LOG(INFO) << \"saved to \" << ofile;\n return 0;\n }catch(const std::exception& e){\n return -1;\n }\n }\n\n int jubatus_serv::load(std::string id) {\n std::string ifile;\n build_local_path_(ifile, \"jubatus\", id);\n \n std::ifstream ifs(ifile.c_str(), std::ios::binary);\n if(!ifs)throw std::runtime_error(ifile + \": cannot open (\" + pfi::lang::lexical_cast(errno) + \")\" );\n try{\n for(size_t i = 0;iclear();\n mixables_[i]->load(ifs);\n }\n ifs.close();\n this->after_load();\n return 0;\n }catch(const std::exception& e){\n ifs.close();\n }\n return -1; \/\/expected never reaching here.\n }\n\n}}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appchild.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 22:55: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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n\n#ifndef GCC\n#endif\n\n#ifndef _SFX_WHITER_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXENUMITEM_HXX \/\/autogen\n#include \n#endif\n\n#include \n#include \"appdata.hxx\"\n#include \"workwin.hxx\"\n#include \n#include \"arrdecl.hxx\"\n#include \n#include \n#include \n#include \n#include \"sfxtypes.hxx\"\n#include \n#include \n\n\/\/=========================================================================\n\n\nvoid SfxApplication::RegisterChildWindow_Impl( SfxModule *pMod, SfxChildWinFactory *pFact )\n{\n if ( pMod )\n {\n pMod->RegisterChildWindow( pFact );\n return;\n }\n\n if (!pAppData_Impl->pFactArr)\n pAppData_Impl->pFactArr = new SfxChildWinFactArr_Impl;\n\n\/\/#ifdef DBG_UTIL\n for (USHORT nFactory=0; nFactorypFactArr->Count(); ++nFactory)\n {\n if (pFact->nId == (*pAppData_Impl->pFactArr)[nFactory]->nId)\n {\n pAppData_Impl->pFactArr->Remove( nFactory );\n\/\/ DBG_ERROR(\"ChildWindow mehrfach registriert!\");\n\/\/ return;\n }\n }\n\/\/#endif\n\n pAppData_Impl->pFactArr->C40_INSERT(\n SfxChildWinFactory, pFact, pAppData_Impl->pFactArr->Count() );\n}\n\nvoid SfxApplication::RegisterChildWindowContext_Impl( SfxModule *pMod, USHORT nId,\n SfxChildWinContextFactory *pFact)\n{\n SfxChildWinFactArr_Impl *pFactories;\n SfxChildWinFactory *pF = NULL;\n if ( pMod )\n {\n \/\/ Modul \"ubergeben, ChildwindowFactory dort suchen\n pFactories = pMod->GetChildWinFactories_Impl();\n if ( pFactories )\n {\n USHORT nCount = pFactories->Count();\n for (USHORT nFactory=0; nFactorynId )\n {\n \/\/ Factory gefunden, Context dort registrieren\n pF = pFac;\n break;\n }\n }\n }\n }\n\n if ( !pF )\n {\n \/\/ Factory an der Application suchen\n DBG_ASSERT( pAppData_Impl, \"Keine AppDaten!\" );\n DBG_ASSERT( pAppData_Impl->pFactArr, \"Keine Factories!\" );\n\n pFactories = pAppData_Impl->pFactArr;\n USHORT nCount = pFactories->Count();\n for (USHORT nFactory=0; nFactorynId )\n {\n if ( pMod )\n {\n \/\/ Wenn der Context von einem Modul registriert wurde,\n \/\/ mu\\s die ChildwindowFactory auch dort zur Verf\"ugung\n \/\/ stehen, sonst m\"u\\ste sich die Contextfactory im DLL-Exit\n \/\/ wieder abmelden !\n pF = new SfxChildWinFactory( pFac->pCtor, pFac->nId,\n pFac->nPos );\n pMod->RegisterChildWindow( pF );\n }\n else\n pF = pFac;\n break;\n }\n }\n }\n\n if ( pF )\n {\n if ( !pF->pArr )\n pF->pArr = new SfxChildWinContextArr_Impl;\n pF->pArr->C40_INSERT( SfxChildWinContextFactory, pFact, pF->pArr->Count() );\n return;\n }\n\n DBG_ERROR( \"Kein ChildWindow fuer diesen Context!\" );\n}\n\n\/\/--------------------------------------------------------------------\n\nSfxChildWinFactArr_Impl& SfxApplication::GetChildWinFactories_Impl() const\n{\n return ( *(pAppData_Impl->pFactArr));\n}\n\n\/\/--------------------------------------------------------------------\n\nSfxTemplateDialog* SfxApplication::GetTemplateDialog()\n{\n if ( pAppData_Impl->pViewFrame )\n {\n SfxChildWindow *pChild = pAppData_Impl->pViewFrame->GetChildWindow(SfxTemplateDialogWrapper::GetChildWindowId());\n return pChild ? (SfxTemplateDialog*) pChild->GetWindow() : 0;\n }\n\n return NULL;\n}\n\n\/\/--------------------------------------------------------------------\n\nSfxWorkWindow* SfxApplication::GetWorkWindow_Impl(const SfxViewFrame *pFrame) const\n{\n if ( pFrame )\n return pFrame->GetFrame()->GetWorkWindow_Impl();\n else if ( pAppData_Impl->pViewFrame )\n return pAppData_Impl->pViewFrame->GetFrame()->GetWorkWindow_Impl();\n else\n return NULL;\n}\n\nINTEGRATION: CWS changefileheader (1.9.216); FILE MERGED 2008\/04\/01 15:38:39 thb 1.9.216.2: #i85898# Stripping all external header guards 2008\/03\/31 13:38:00 rt 1.9.216.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appchild.cxx,v $\n * $Revision: 1.10 $\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_sfx2.hxx\"\n\n#ifndef GCC\n#endif\n#include \n#include \n\n#include \n#include \"appdata.hxx\"\n#include \"workwin.hxx\"\n#include \n#include \"arrdecl.hxx\"\n#include \n#include \n#include \n#include \n#include \"sfxtypes.hxx\"\n#include \n#include \n\n\/\/=========================================================================\n\n\nvoid SfxApplication::RegisterChildWindow_Impl( SfxModule *pMod, SfxChildWinFactory *pFact )\n{\n if ( pMod )\n {\n pMod->RegisterChildWindow( pFact );\n return;\n }\n\n if (!pAppData_Impl->pFactArr)\n pAppData_Impl->pFactArr = new SfxChildWinFactArr_Impl;\n\n\/\/#ifdef DBG_UTIL\n for (USHORT nFactory=0; nFactorypFactArr->Count(); ++nFactory)\n {\n if (pFact->nId == (*pAppData_Impl->pFactArr)[nFactory]->nId)\n {\n pAppData_Impl->pFactArr->Remove( nFactory );\n\/\/ DBG_ERROR(\"ChildWindow mehrfach registriert!\");\n\/\/ return;\n }\n }\n\/\/#endif\n\n pAppData_Impl->pFactArr->C40_INSERT(\n SfxChildWinFactory, pFact, pAppData_Impl->pFactArr->Count() );\n}\n\nvoid SfxApplication::RegisterChildWindowContext_Impl( SfxModule *pMod, USHORT nId,\n SfxChildWinContextFactory *pFact)\n{\n SfxChildWinFactArr_Impl *pFactories;\n SfxChildWinFactory *pF = NULL;\n if ( pMod )\n {\n \/\/ Modul \"ubergeben, ChildwindowFactory dort suchen\n pFactories = pMod->GetChildWinFactories_Impl();\n if ( pFactories )\n {\n USHORT nCount = pFactories->Count();\n for (USHORT nFactory=0; nFactorynId )\n {\n \/\/ Factory gefunden, Context dort registrieren\n pF = pFac;\n break;\n }\n }\n }\n }\n\n if ( !pF )\n {\n \/\/ Factory an der Application suchen\n DBG_ASSERT( pAppData_Impl, \"Keine AppDaten!\" );\n DBG_ASSERT( pAppData_Impl->pFactArr, \"Keine Factories!\" );\n\n pFactories = pAppData_Impl->pFactArr;\n USHORT nCount = pFactories->Count();\n for (USHORT nFactory=0; nFactorynId )\n {\n if ( pMod )\n {\n \/\/ Wenn der Context von einem Modul registriert wurde,\n \/\/ mu\\s die ChildwindowFactory auch dort zur Verf\"ugung\n \/\/ stehen, sonst m\"u\\ste sich die Contextfactory im DLL-Exit\n \/\/ wieder abmelden !\n pF = new SfxChildWinFactory( pFac->pCtor, pFac->nId,\n pFac->nPos );\n pMod->RegisterChildWindow( pF );\n }\n else\n pF = pFac;\n break;\n }\n }\n }\n\n if ( pF )\n {\n if ( !pF->pArr )\n pF->pArr = new SfxChildWinContextArr_Impl;\n pF->pArr->C40_INSERT( SfxChildWinContextFactory, pFact, pF->pArr->Count() );\n return;\n }\n\n DBG_ERROR( \"Kein ChildWindow fuer diesen Context!\" );\n}\n\n\/\/--------------------------------------------------------------------\n\nSfxChildWinFactArr_Impl& SfxApplication::GetChildWinFactories_Impl() const\n{\n return ( *(pAppData_Impl->pFactArr));\n}\n\n\/\/--------------------------------------------------------------------\n\nSfxTemplateDialog* SfxApplication::GetTemplateDialog()\n{\n if ( pAppData_Impl->pViewFrame )\n {\n SfxChildWindow *pChild = pAppData_Impl->pViewFrame->GetChildWindow(SfxTemplateDialogWrapper::GetChildWindowId());\n return pChild ? (SfxTemplateDialog*) pChild->GetWindow() : 0;\n }\n\n return NULL;\n}\n\n\/\/--------------------------------------------------------------------\n\nSfxWorkWindow* SfxApplication::GetWorkWindow_Impl(const SfxViewFrame *pFrame) const\n{\n if ( pFrame )\n return pFrame->GetFrame()->GetWorkWindow_Impl();\n else if ( pAppData_Impl->pViewFrame )\n return pAppData_Impl->pViewFrame->GetFrame()->GetWorkWindow_Impl();\n else\n return NULL;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: imagemgr.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: pb $ $Date: 2001-05-14 10:10:37 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ includes --------------------------------------------------------------\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \"imgmgr.hxx\"\n#include \"app.hxx\"\n#include \"unoctitm.hxx\"\n#include \"dispatch.hxx\"\n#include \"msg.hxx\"\n#include \"msgpool.hxx\"\n#include \"viewfrm.hxx\"\n#include \"module.hxx\"\n#include \"objsh.hxx\"\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::util;\n\nImage SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig )\n{\n INetURLObject aObj( aURL );\n INetProtocol nProtocol = aObj.GetProtocol();\n switch ( nProtocol )\n {\n case INET_PROT_UNO :\n case INET_PROT_SLOT :\n {\n URL aTargetURL;\n SfxViewFrame* pViewFrame = NULL;\n Reference < XController > xController;\n if ( rFrame.is() )\n xController = rFrame->getController();\n\n Reference < XDispatchProvider > xProvider( xController, UNO_QUERY );\n if ( xProvider.is() )\n {\n aTargetURL.Complete = aURL;\n Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii(\"com.sun.star.util.URLTransformer\" )), UNO_QUERY );\n xTrans->parseStrict( aTargetURL );\n\n Reference < XDispatch > xDisp = xProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );\n if ( xDisp.is() )\n {\n Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY );\n SfxOfficeDispatch* pDisp = NULL;\n if ( xTunnel.is() )\n {\n sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier());\n pDisp = (SfxOfficeDispatch*)(nImplementation);\n }\n\n if ( pDisp )\n pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame();\n }\n }\n\n USHORT nId;\n if ( nProtocol == INET_PROT_UNO )\n {\n SfxSlotPool& rPool = SFX_APP()->GetSlotPool( pViewFrame );\n const SfxSlot* pSlot = rPool.GetUnoSlot( aTargetURL.Path );\n if ( pSlot )\n nId = pSlot->GetSlotId();\n }\n else\n nId = ( USHORT ) aTargetURL.Path.toInt32();\n\n SfxModule* pModule = pViewFrame ? pViewFrame->GetObjectShell()->GetModule() : NULL;\n if ( nId )\n return SFX_IMAGEMANAGER()->SeekImage( nId, pModule );\n break;\n }\n\n case INET_PROT_NOT_VALID :\n {\n return Image();\n break;\n }\n }\n\n return SvFileInformationManager::GetImage( aObj, bBig );\n}\n\n#87722#: no global access for ImageManager\/*************************************************************************\n *\n * $RCSfile: imagemgr.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mba $ $Date: 2001-06-11 09:53: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\/\/ includes --------------------------------------------------------------\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \"imgmgr.hxx\"\n#include \"app.hxx\"\n#include \"unoctitm.hxx\"\n#include \"dispatch.hxx\"\n#include \"msg.hxx\"\n#include \"msgpool.hxx\"\n#include \"viewfrm.hxx\"\n#include \"module.hxx\"\n#include \"objsh.hxx\"\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::util;\n\nImage SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig )\n{\n INetURLObject aObj( aURL );\n INetProtocol nProtocol = aObj.GetProtocol();\n switch ( nProtocol )\n {\n case INET_PROT_UNO :\n case INET_PROT_SLOT :\n {\n URL aTargetURL;\n SfxViewFrame* pViewFrame = NULL;\n Reference < XController > xController;\n if ( rFrame.is() )\n xController = rFrame->getController();\n\n Reference < XDispatchProvider > xProvider( xController, UNO_QUERY );\n if ( xProvider.is() )\n {\n aTargetURL.Complete = aURL;\n Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii(\"com.sun.star.util.URLTransformer\" )), UNO_QUERY );\n xTrans->parseStrict( aTargetURL );\n\n Reference < XDispatch > xDisp = xProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 );\n if ( xDisp.is() )\n {\n Reference< XUnoTunnel > xTunnel( xDisp, UNO_QUERY );\n SfxOfficeDispatch* pDisp = NULL;\n if ( xTunnel.is() )\n {\n sal_Int64 nImplementation = xTunnel->getSomething(SfxOfficeDispatch::impl_getStaticIdentifier());\n pDisp = (SfxOfficeDispatch*)(nImplementation);\n }\n\n if ( pDisp )\n pViewFrame = pDisp->GetDispatcher_Impl()->GetFrame();\n }\n }\n\n USHORT nId;\n if ( nProtocol == INET_PROT_UNO )\n {\n SfxSlotPool& rPool = SFX_APP()->GetSlotPool( pViewFrame );\n const SfxSlot* pSlot = rPool.GetUnoSlot( aTargetURL.Path );\n if ( pSlot )\n nId = pSlot->GetSlotId();\n }\n else\n nId = ( USHORT ) aTargetURL.Path.toInt32();\n\n SfxModule* pModule = pViewFrame ? pViewFrame->GetObjectShell()->GetModule() : NULL;\n if ( nId )\n {\n if ( pViewFrame )\n return pViewFrame->GetImageManager()->GetImage( nId, pModule, bBig );\n else\n {\n return SFX_APP()->GetImageManager_Impl()->GetImage( nId, NULL, bBig );\n }\n }\n break;\n }\n\n case INET_PROT_NOT_VALID :\n {\n return Image();\n break;\n }\n }\n\n return SvFileInformationManager::GetImage( aObj, bBig );\n}\n\n<|endoftext|>"} {"text":"\/*\n * Part of HTTPP.\n *\n * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2013 Thomas Sanchez. All rights reserved.\n *\n *\/\n\n#include \"httpp\/utils\/ThreadPool.hpp\"\n\n#include \n\n#include \n\nnamespace HTTPP\n{\nnamespace UTILS\n{\n\nstatic void empty_deleter(boost::asio::io_service*)\n{}\n\nThreadPool::ThreadPool(size_t nb_thread, const std::string& name)\n: service_(std::make_shared(nb_thread))\n, nb_thread_(nb_thread)\n, name_(name)\n{\n}\n\nThreadPool::ThreadPool(size_t nb_thread,\n boost::asio::io_service& service,\n const std::string& name)\n: service_(std::addressof(service), &empty_deleter)\n, nb_thread_(nb_thread)\n, name_(name)\n{\n}\n\nThreadPool::~ThreadPool()\n{\n if (running_)\n {\n stop();\n }\n}\n\nThreadPool::ThreadPool(ThreadPool&& pool)\n: service_(pool.service_)\n, running_(pool.running_)\n, nb_thread_(pool.nb_thread_)\n, work_(std::move(pool.work_))\n, threads_(std::move(pool.threads_))\n, name_(std::move(name_))\n{\n running_threads_.store(pool.running_threads_.load());\n pool.running_ = false;\n}\n\nvoid ThreadPool::start(ThreadInit fct)\n{\n if (running_)\n {\n return;\n }\n\n work_.reset(new boost::asio::io_service::work(*service_));\n for (size_t i = 0; i < nb_thread_; ++i)\n {\n threads_.emplace_back(std::bind(&ThreadPool::run, this,\n [this, fct, i]\n {\n if (name_.empty())\n {\n setCurrentThreadName(\"Pool thread #\" +\n std::to_string(i));\n }\n else\n {\n setCurrentThreadName(name_ + \" #\" + std::to_string(i));\n }\n\n if (fct)\n {\n BOOST_LOG_TRIVIAL(debug) << \"call init fct \" << name_;\n fct();\n }\n }\n ));\n }\n\n while (running_threads_ != nb_thread_)\n {\n std::this_thread::yield();\n }\n\n running_ = true;\n}\n\nvoid ThreadPool::run(ThreadInit fct)\n{\n BOOST_LOG_TRIVIAL(debug) << \"start thread\";\n\n if (fct)\n {\n fct();\n }\n\n BOOST_LOG_TRIVIAL(debug) << \"call run()\";\n ++running_threads_;\n\n this->service_->reset();\n this->service_->run();\n BOOST_LOG_TRIVIAL(debug) << \"is stopping\";\n --running_threads_;\n}\n\nvoid ThreadPool::stop()\n{\n if (!running_)\n {\n return;\n }\n\n running_ = false;\n work_.reset();\n service_->stop();\n for (auto& th : threads_)\n {\n if (th.joinable())\n {\n th.join();\n }\n }\n\n threads_.clear();\n}\n\nbool ThreadPool::runningInPool() const noexcept\n{\n auto current_id = std::this_thread::get_id();\n for (const auto& thread : threads_)\n {\n if (thread.get_id() == current_id)\n {\n return true;\n }\n }\n\n return false;\n}\n\n} \/\/ namespace UTILS\n} \/\/ namespace HTTPP\nFix bug in ThreadPool's move constructor.\/*\n * Part of HTTPP.\n *\n * Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2013 Thomas Sanchez. All rights reserved.\n *\n *\/\n\n#include \"httpp\/utils\/ThreadPool.hpp\"\n\n#include \n\n#include \n\nnamespace HTTPP\n{\nnamespace UTILS\n{\n\nstatic void empty_deleter(boost::asio::io_service*)\n{}\n\nThreadPool::ThreadPool(size_t nb_thread, const std::string& name)\n: service_(std::make_shared(nb_thread))\n, nb_thread_(nb_thread)\n, name_(name)\n{\n}\n\nThreadPool::ThreadPool(size_t nb_thread,\n boost::asio::io_service& service,\n const std::string& name)\n: service_(std::addressof(service), &empty_deleter)\n, nb_thread_(nb_thread)\n, name_(name)\n{\n}\n\nThreadPool::~ThreadPool()\n{\n if (running_)\n {\n stop();\n }\n}\n\nThreadPool::ThreadPool(ThreadPool&& pool)\n: service_(pool.service_)\n, running_(pool.running_)\n, nb_thread_(pool.nb_thread_)\n, work_(std::move(pool.work_))\n, threads_(std::move(pool.threads_))\n, name_(std::move(pool.name_))\n{\n running_threads_.store(pool.running_threads_.load());\n pool.running_ = false;\n}\n\nvoid ThreadPool::start(ThreadInit fct)\n{\n if (running_)\n {\n return;\n }\n\n work_.reset(new boost::asio::io_service::work(*service_));\n for (size_t i = 0; i < nb_thread_; ++i)\n {\n threads_.emplace_back(std::bind(&ThreadPool::run, this,\n [this, fct, i]\n {\n if (name_.empty())\n {\n setCurrentThreadName(\"Pool thread #\" +\n std::to_string(i));\n }\n else\n {\n setCurrentThreadName(name_ + \" #\" + std::to_string(i));\n }\n\n if (fct)\n {\n BOOST_LOG_TRIVIAL(debug) << \"call init fct \" << name_;\n fct();\n }\n }\n ));\n }\n\n while (running_threads_ != nb_thread_)\n {\n std::this_thread::yield();\n }\n\n running_ = true;\n}\n\nvoid ThreadPool::run(ThreadInit fct)\n{\n BOOST_LOG_TRIVIAL(debug) << \"start thread\";\n\n if (fct)\n {\n fct();\n }\n\n BOOST_LOG_TRIVIAL(debug) << \"call run()\";\n ++running_threads_;\n\n this->service_->reset();\n this->service_->run();\n BOOST_LOG_TRIVIAL(debug) << \"is stopping\";\n --running_threads_;\n}\n\nvoid ThreadPool::stop()\n{\n if (!running_)\n {\n return;\n }\n\n running_ = false;\n work_.reset();\n service_->stop();\n for (auto& th : threads_)\n {\n if (th.joinable())\n {\n th.join();\n }\n }\n\n threads_.clear();\n}\n\nbool ThreadPool::runningInPool() const noexcept\n{\n auto current_id = std::this_thread::get_id();\n for (const auto& thread : threads_)\n {\n if (thread.get_id() == current_id)\n {\n return true;\n }\n }\n\n return false;\n}\n\n} \/\/ namespace UTILS\n} \/\/ namespace HTTPP\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2003 by Unai Garro *\n * ugarro@users.sourceforge.net *\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#include \"ingredientpropertylist.h\"\n#include \nIngredientPropertyList::IngredientPropertyList()\n{\n}\n\n\nIngredientPropertyList::~IngredientPropertyList()\n{\n}\n\nvoid IngredientPropertyList::add(IngredientProperty &property)\n{\nlist.append (new IngredientProperty(property));\n}\n\nIngredientProperty* IngredientPropertyList::getFirst(void){\nreturn(list.first());\n}\n\nIngredientProperty* IngredientPropertyList::getNext(void){\nreturn(list.next());\n}\n\nIngredientProperty* IngredientPropertyList::getElement(int index){\nreturn(list.at(index));\n}\n\nvoid IngredientPropertyList::clear(void)\n{\nlist.clear();\n}\n\nbool IngredientPropertyList::isEmpty(void)\n{\nreturn(list.isEmpty());\n}\n\nint IngredientPropertyList::find(IngredientProperty* it)\n{\nreturn(list.find(it));\n}\n\nint IngredientPropertyList::find(int id)\n{\nIngredientProperty ip; ip.id=id;\nreturn(list.find(&ip));\n}\n\nIngredientProperty* IngredientPropertyList::at(int pos)\n{\nreturn(list.at(pos));\n}\n\nvoid IngredientPropertyList::append(IngredientProperty *property)\n{\nlist.append (property);\n}\n\nvoid IngredientPropertyList::divide(int persons)\n{\nfor (IngredientProperty* ip=getFirst();ip;ip=getNext())\n\tip->amount\/=persons;\n}\n\nvoid IngredientPropertyList::filter(int ingredientID,IngredientPropertyList *filteredList)\n{\nfilteredList->clear();\nfor (IngredientProperty* ip=getFirst();ip;ip=getNext())\n\tif (ip->ingredientID==ingredientID) filteredList->add(*ip);\n\n}\n\nint IngredientPropertyList::count(void)\n{\nreturn (list.count());\n}\n\nvoid IngredientPropertyList::remove(IngredientProperty* ip)\n{\nlist->remove(ip);\n}oops, small mistake\/***************************************************************************\n * Copyright (C) 2003 by Unai Garro *\n * ugarro@users.sourceforge.net *\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#include \"ingredientpropertylist.h\"\n#include \nIngredientPropertyList::IngredientPropertyList()\n{\n}\n\n\nIngredientPropertyList::~IngredientPropertyList()\n{\n}\n\nvoid IngredientPropertyList::add(IngredientProperty &property)\n{\nlist.append (new IngredientProperty(property));\n}\n\nIngredientProperty* IngredientPropertyList::getFirst(void){\nreturn(list.first());\n}\n\nIngredientProperty* IngredientPropertyList::getNext(void){\nreturn(list.next());\n}\n\nIngredientProperty* IngredientPropertyList::getElement(int index){\nreturn(list.at(index));\n}\n\nvoid IngredientPropertyList::clear(void)\n{\nlist.clear();\n}\n\nbool IngredientPropertyList::isEmpty(void)\n{\nreturn(list.isEmpty());\n}\n\nint IngredientPropertyList::find(IngredientProperty* it)\n{\nreturn(list.find(it));\n}\n\nint IngredientPropertyList::find(int id)\n{\nIngredientProperty ip; ip.id=id;\nreturn(list.find(&ip));\n}\n\nIngredientProperty* IngredientPropertyList::at(int pos)\n{\nreturn(list.at(pos));\n}\n\nvoid IngredientPropertyList::append(IngredientProperty *property)\n{\nlist.append (property);\n}\n\nvoid IngredientPropertyList::divide(int persons)\n{\nfor (IngredientProperty* ip=getFirst();ip;ip=getNext())\n\tip->amount\/=persons;\n}\n\nvoid IngredientPropertyList::filter(int ingredientID,IngredientPropertyList *filteredList)\n{\nfilteredList->clear();\nfor (IngredientProperty* ip=getFirst();ip;ip=getNext())\n\tif (ip->ingredientID==ingredientID) filteredList->add(*ip);\n\n}\n\nint IngredientPropertyList::count(void)\n{\nreturn (list.count());\n}\n\nvoid IngredientPropertyList::remove(IngredientProperty* ip)\n{\nlist.remove(ip);\n}<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2006, Arvid Norberg & Daniel Wallin\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\/pch.hpp\"\n\n#include \n#include \n#include \n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent { namespace dht\n{\n\nusing asio::ip::udp;\n\nclosest_nodes_observer::~closest_nodes_observer()\n{\n\tif (m_algorithm) m_algorithm->failed(m_self, true);\n}\n\nvoid closest_nodes_observer::reply(msg const& in)\n{\n\tif (!m_algorithm)\n\t{\n\t\tTORRENT_ASSERT(false);\n\t\treturn;\n\t}\n\n\tif (!in.nodes.empty())\n\t{\n\t\tfor (msg::nodes_t::const_iterator i = in.nodes.begin()\n\t\t\t, end(in.nodes.end()); i != end; ++i)\n\t\t{\n\t\t\tm_algorithm->traverse(i->id, i->addr);\n\t\t}\n\t}\n\tm_algorithm->finished(m_self);\n\tm_algorithm = 0;\n}\n\nvoid closest_nodes_observer::timeout()\n{\n\tif (!m_algorithm) return;\n\tm_algorithm->failed(m_self);\n\tm_algorithm = 0;\n}\n\n\nclosest_nodes::closest_nodes(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n\t: traversal_algorithm(\n\t\ttarget\n\t\t, branch_factor\n\t\t, max_results\n\t\t, table\n\t\t, rpc\n\t\t, table.begin()\n\t\t, table.end()\n\t)\n\t, m_done_callback(callback)\n{\n\tboost::intrusive_ptr self(this);\n\tadd_requests();\n}\n\nvoid closest_nodes::invoke(node_id const& id, udp::endpoint addr)\n{\n\tTORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));\n\tobserver_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));\n#ifndef NDEBUG\n\to->m_in_constructor = false;\n#endif\n\tm_rpc.invoke(messages::find_node, addr, o);\n}\n\nvoid closest_nodes::done()\n{\n\tstd::vector results;\n\tint num_results = m_table.bucket_size();\n\tfor (std::vector::iterator i = m_max_results\n\t\t, end(m_results.end()); i != end && num_results >= 0; ++i)\n\t{\n\t\tif (i->flags & result::no_id) continue;\n\t\tif ((i->flags & result::queried) == 0) continue;\n\t\tresults.push_back(node_entry(i->id, i->addr));\n\t\t--num_results;\n\t}\n\tm_done_callback(results);\n}\n\nvoid closest_nodes::initiate(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n{\n\tnew closest_nodes(target, branch_factor, max_results, table, rpc, callback);\n}\n\n} } \/\/ namespace libtorrent::dht\n\nfixed typo in previous dht checkin\/*\n\nCopyright (c) 2006, Arvid Norberg & Daniel Wallin\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\/pch.hpp\"\n\n#include \n#include \n#include \n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent { namespace dht\n{\n\nusing asio::ip::udp;\n\nclosest_nodes_observer::~closest_nodes_observer()\n{\n\tif (m_algorithm) m_algorithm->failed(m_self, true);\n}\n\nvoid closest_nodes_observer::reply(msg const& in)\n{\n\tif (!m_algorithm)\n\t{\n\t\tTORRENT_ASSERT(false);\n\t\treturn;\n\t}\n\n\tif (!in.nodes.empty())\n\t{\n\t\tfor (msg::nodes_t::const_iterator i = in.nodes.begin()\n\t\t\t, end(in.nodes.end()); i != end; ++i)\n\t\t{\n\t\t\tm_algorithm->traverse(i->id, i->addr);\n\t\t}\n\t}\n\tm_algorithm->finished(m_self);\n\tm_algorithm = 0;\n}\n\nvoid closest_nodes_observer::timeout()\n{\n\tif (!m_algorithm) return;\n\tm_algorithm->failed(m_self);\n\tm_algorithm = 0;\n}\n\n\nclosest_nodes::closest_nodes(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n\t: traversal_algorithm(\n\t\ttarget\n\t\t, branch_factor\n\t\t, max_results\n\t\t, table\n\t\t, rpc\n\t\t, table.begin()\n\t\t, table.end()\n\t)\n\t, m_done_callback(callback)\n{\n\tboost::intrusive_ptr self(this);\n\tadd_requests();\n}\n\nvoid closest_nodes::invoke(node_id const& id, udp::endpoint addr)\n{\n\tTORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));\n\tobserver_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));\n#ifndef NDEBUG\n\to->m_in_constructor = false;\n#endif\n\tm_rpc.invoke(messages::find_node, addr, o);\n}\n\nvoid closest_nodes::done()\n{\n\tstd::vector results;\n\tint num_results = m_max_results;\n\tfor (std::vector::iterator i = m_results.begin()\n\t\t, end(m_results.end()); i != end && num_results >= 0; ++i)\n\t{\n\t\tif (i->flags & result::no_id) continue;\n\t\tif ((i->flags & result::queried) == 0) continue;\n\t\tresults.push_back(node_entry(i->id, i->addr));\n\t\t--num_results;\n\t}\n\tm_done_callback(results);\n}\n\nvoid closest_nodes::initiate(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n{\n\tnew closest_nodes(target, branch_factor, max_results, table, rpc, callback);\n}\n\n} } \/\/ namespace libtorrent::dht\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2006, Arvid Norberg & Daniel Wallin\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\/pch.hpp\"\n\n#include \n#include \n#include \n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent { namespace dht\n{\n\nusing asio::ip::udp;\n\nclosest_nodes_observer::~closest_nodes_observer()\n{\n\tif (m_algorithm) m_algorithm->failed(m_self, true);\n}\n\nvoid closest_nodes_observer::reply(msg const& in)\n{\n\tif (!m_algorithm)\n\t{\n\t\tTORRENT_ASSERT(false);\n\t\treturn;\n\t}\n\n\tif (!in.nodes.empty())\n\t{\n\t\tfor (msg::nodes_t::const_iterator i = in.nodes.begin()\n\t\t\t, end(in.nodes.end()); i != end; ++i)\n\t\t{\n\t\t\tm_algorithm->traverse(i->id, i->addr);\n\t\t}\n\t}\n\tm_algorithm->finished(m_self);\n\tm_algorithm = 0;\n}\n\nvoid closest_nodes_observer::timeout()\n{\n\tif (!m_algorithm) return;\n\tm_algorithm->failed(m_self);\n\tm_algorithm = 0;\n}\n\n\nclosest_nodes::closest_nodes(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n\t: traversal_algorithm(\n\t\ttarget\n\t\t, branch_factor\n\t\t, max_results\n\t\t, table\n\t\t, rpc\n\t\t, table.begin()\n\t\t, table.end()\n\t)\n\t, m_done_callback(callback)\n{\n\tboost::intrusive_ptr self(this);\n\tadd_requests();\n}\n\nvoid closest_nodes::invoke(node_id const& id, udp::endpoint addr)\n{\n\tTORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));\n\tobserver_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));\n#ifndef NDEBUG\n\to->m_in_constructor = false;\n#endif\n\tm_rpc.invoke(messages::find_node, addr, o);\n}\n\nvoid closest_nodes::done()\n{\n\tstd::vector results;\n\tint num_results = m_table.bucket_size();\n\tfor (std::vector::iterator i = m_results.begin()\n\t\t, end(m_results.end()); i != end && num_results >= 0; ++i)\n\t{\n\t\tif (i->flags & result::no_id) continue;\n\t\tresults.push_back(node_entry(i->id, i->addr));\n\t\t--num_results;\n\t}\n\tm_done_callback(results);\n}\n\nvoid closest_nodes::initiate(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n{\n\tnew closest_nodes(target, branch_factor, max_results, table, rpc, callback);\n}\n\n} } \/\/ namespace libtorrent::dht\n\ndht fix\/*\n\nCopyright (c) 2006, Arvid Norberg & Daniel Wallin\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\/pch.hpp\"\n\n#include \n#include \n#include \n#include \"libtorrent\/assert.hpp\"\n\nnamespace libtorrent { namespace dht\n{\n\nusing asio::ip::udp;\n\nclosest_nodes_observer::~closest_nodes_observer()\n{\n\tif (m_algorithm) m_algorithm->failed(m_self, true);\n}\n\nvoid closest_nodes_observer::reply(msg const& in)\n{\n\tif (!m_algorithm)\n\t{\n\t\tTORRENT_ASSERT(false);\n\t\treturn;\n\t}\n\n\tif (!in.nodes.empty())\n\t{\n\t\tfor (msg::nodes_t::const_iterator i = in.nodes.begin()\n\t\t\t, end(in.nodes.end()); i != end; ++i)\n\t\t{\n\t\t\tm_algorithm->traverse(i->id, i->addr);\n\t\t}\n\t}\n\tm_algorithm->finished(m_self);\n\tm_algorithm = 0;\n}\n\nvoid closest_nodes_observer::timeout()\n{\n\tif (!m_algorithm) return;\n\tm_algorithm->failed(m_self);\n\tm_algorithm = 0;\n}\n\n\nclosest_nodes::closest_nodes(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n\t: traversal_algorithm(\n\t\ttarget\n\t\t, branch_factor\n\t\t, max_results\n\t\t, table\n\t\t, rpc\n\t\t, table.begin()\n\t\t, table.end()\n\t)\n\t, m_done_callback(callback)\n{\n\tboost::intrusive_ptr self(this);\n\tadd_requests();\n}\n\nvoid closest_nodes::invoke(node_id const& id, udp::endpoint addr)\n{\n\tTORRENT_ASSERT(m_rpc.allocation_size() >= sizeof(closest_nodes_observer));\n\tobserver_ptr o(new (m_rpc.allocator().malloc()) closest_nodes_observer(this, id, m_target));\n#ifndef NDEBUG\n\to->m_in_constructor = false;\n#endif\n\tm_rpc.invoke(messages::find_node, addr, o);\n}\n\nvoid closest_nodes::done()\n{\n\tstd::vector results;\n\tint num_results = m_table.bucket_size();\n\tfor (std::vector::iterator i = m_max_results\n\t\t, end(m_results.end()); i != end && num_results >= 0; ++i)\n\t{\n\t\tif (i->flags & result::no_id) continue;\n\t\tif ((i->flags & result::queried) == 0) continue;\n\t\tresults.push_back(node_entry(i->id, i->addr));\n\t\t--num_results;\n\t}\n\tm_done_callback(results);\n}\n\nvoid closest_nodes::initiate(\n\tnode_id target\n\t, int branch_factor\n\t, int max_results\n\t, routing_table& table\n\t, rpc_manager& rpc\n\t, done_callback const& callback\n)\n{\n\tnew closest_nodes(target, branch_factor, max_results, table, rpc, callback);\n}\n\n} } \/\/ namespace libtorrent::dht\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 2009 Bastian Holst \n\/\/\n\n\/\/ Self\n#include \"AbstractDataPlugin.h\"\n\n\/\/ Marble\n#include \"AbstractDataPluginModel.h\"\n#include \"AbstractDataPluginItem.h\"\n#include \"GeoPainter.h\"\n#include \"GeoSceneLayer.h\"\n#include \"MarbleModel.h\"\n#include \"ViewportParams.h\"\n#include \"MarbleDebug.h\"\n\n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Marble\n{\n\nclass AbstractDataPluginPrivate\n{\n public:\n AbstractDataPluginPrivate()\n : m_model( 0 ),\n m_numberOfItems( 10 ),\n m_delegate( 0 ),\n m_delegateParent( 0 )\n {\n }\n \n ~AbstractDataPluginPrivate() {\n delete m_model;\n }\n \n AbstractDataPluginModel *m_model;\n quint32 m_numberOfItems;\n QDeclarativeComponent* m_delegate;\n QGraphicsItem* m_delegateParent;\n QMap m_delegateInstances;\n};\n\nAbstractDataPlugin::AbstractDataPlugin( const MarbleModel *marbleModel )\n : RenderPlugin( marbleModel ),\n d( new AbstractDataPluginPrivate )\n{\n}\n\nAbstractDataPlugin::~AbstractDataPlugin()\n{\n delete d;\n}\n\nbool AbstractDataPlugin::isInitialized() const\n{\n return model() != 0;\n}\n\nQStringList AbstractDataPlugin::backendTypes() const\n{\n return QStringList( name() );\n}\n\nQString AbstractDataPlugin::renderPolicy() const\n{\n return QString( \"ALWAYS\" );\n}\n\nQStringList AbstractDataPlugin::renderPosition() const\n{\n return QStringList( \"ALWAYS_ON_TOP\" );\n}\n\nbool AbstractDataPlugin::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer)\n{\n Q_UNUSED( renderPos );\n Q_UNUSED( layer );\n\n if ( !d->m_model || !isInitialized() ) {\n return true;\n }\n\n if ( d->m_delegate ) {\n handleViewportChange( viewport );\n } else {\n QList items = d->m_model->items( viewport,\n marbleModel(),\n numberOfItems() );\n painter->save();\n\n \/\/ Paint the most important item at last\n for( int i = items.size() - 1; i >= 0; --i ) {\n items.at( i )->paintEvent( painter, viewport );\n }\n\n painter->restore();\n }\n \n return true;\n}\n\nAbstractDataPluginModel *AbstractDataPlugin::model() const\n{\n return d->m_model;\n}\n\nvoid AbstractDataPlugin::setModel( AbstractDataPluginModel* model )\n{\n if ( d->m_model ) {\n disconnect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );\n delete d->m_model;\n }\n d->m_model = model;\n\n connect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );\n connect( d->m_model, SIGNAL( favoriteItemsChanged( const QStringList& ) ), this,\n SLOT( favoriteItemsChanged( const QStringList& ) ) );\n connect( d->m_model, SIGNAL( favoriteItemsOnlyChanged() ), this,\n SIGNAL( favoriteItemsOnlyChanged() ) );\n\n emit favoritesModelChanged();\n}\n\nconst PluginManager* AbstractDataPlugin::pluginManager() const\n{\n return marbleModel()->pluginManager();\n}\n\nquint32 AbstractDataPlugin::numberOfItems() const\n{\n return d->m_numberOfItems;\n}\n \nvoid AbstractDataPlugin::setNumberOfItems( quint32 number )\n{\n bool changed = ( number != d->m_numberOfItems );\n d->m_numberOfItems = number;\n\n if ( changed )\n emit changedNumberOfItems( number );\n}\n\nQList AbstractDataPlugin::whichItemAt( const QPoint& curpos )\n{\n if ( d->m_model && enabled() && visible()) {\n return d->m_model->whichItemAt( curpos );\n }\n else {\n return QList();\n }\n}\n\nRenderPlugin::RenderType AbstractDataPlugin::renderType() const\n{\n return Online;\n}\n\nvoid AbstractDataPlugin::setDelegate( QDeclarativeComponent *delegate, QGraphicsItem* parent )\n{\n qDeleteAll( d->m_delegateInstances.values() );\n d->m_delegateInstances.clear();\n\n d->m_delegate = delegate;\n d->m_delegateParent = parent;\n}\n\nvoid AbstractDataPlugin::setFavoriteItemsOnly( bool favoriteOnly )\n{\n if ( d->m_model && d->m_model->isFavoriteItemsOnly() != favoriteOnly ) {\n d->m_model->setFavoriteItemsOnly( favoriteOnly );\n }\n}\n\nbool AbstractDataPlugin::isFavoriteItemsOnly() const\n{\n return d->m_model && d->m_model->isFavoriteItemsOnly();\n}\n\nQObject *AbstractDataPlugin::favoritesModel()\n{\n return d->m_model ? d->m_model->favoritesModel() : 0;\n}\n\nvoid AbstractDataPlugin::handleViewportChange( ViewportParams* viewport )\n{\n QList orphane = d->m_delegateInstances.keys();\n QList const items = d->m_model->items( viewport, marbleModel(), numberOfItems() );\n foreach( AbstractDataPluginItem* item, items ) {\n qreal x, y;\n Marble::GeoDataCoordinates const coordinates = item->coordinate();\n bool const visible = viewport->screenCoordinates( coordinates.longitude(), coordinates.latitude(), x, y );\n\n if ( !d->m_delegateInstances.contains( item ) ) {\n if ( !visible ) {\n \/\/ We don't have, but don't need it either. Shouldn't happen though as the model checks for it already.\n continue;\n }\n\n \/\/ Create a new QML object instance using the delegate as the factory. The original\n \/\/ data plugin item is set as the context object, i.e. all its properties are available\n \/\/ to QML directly with their names\n QDeclarativeContext *context = new QDeclarativeContext( qmlContext( d->m_delegate ) );\n context->setContextObject( item );\n QObject* component = d->m_delegate->create( context );\n QDeclarativeItem* newItem = qobject_cast( component );\n QGraphicsItem* graphicsItem = qobject_cast( component );\n if ( graphicsItem && newItem ) {\n graphicsItem->setParentItem( d->m_delegateParent );\n }\n\n if ( newItem ) {\n d->m_delegateInstances[item] = newItem;\n } else {\n mDebug() << \"Failed to create delegate\";\n continue;\n }\n } else if ( !visible ) {\n \/\/ Previously visible but not anymore => needs to be deleted. Orphane list takes care of it later.\n \/\/ Shouldn't happen though as the model checks for it already.\n continue;\n }\n\n Q_ASSERT( visible );\n QDeclarativeItem* declarativeItem = d->m_delegateInstances[item];\n Q_ASSERT( declarativeItem );\n\n \/\/ Make sure we have a valid bounding rect for collision detection\n item->setProjection( viewport );\n item->setSize( QSizeF( declarativeItem->boundingRect().size() ) );\n\n int shiftX( 0 ), shiftY( 0 );\n switch( declarativeItem->transformOrigin() ) {\n case QDeclarativeItem::TopLeft:\n case QDeclarativeItem::Top:\n case QDeclarativeItem::TopRight:\n break;\n case QDeclarativeItem::Left:\n case QDeclarativeItem::Center:\n case QDeclarativeItem::Right:\n shiftY = declarativeItem->height() \/ 2;\n break;\n case QDeclarativeItem::BottomLeft:\n case QDeclarativeItem::Bottom:\n case QDeclarativeItem::BottomRight:\n shiftY = declarativeItem->height();\n break;\n }\n\n switch( declarativeItem->transformOrigin() ) {\n case QDeclarativeItem::TopLeft:\n case QDeclarativeItem::Left:\n case QDeclarativeItem::BottomLeft:\n break;\n case QDeclarativeItem::Top:\n case QDeclarativeItem::Center:\n case QDeclarativeItem::Bottom:\n shiftX = declarativeItem->width() \/ 2;\n break;\n case QDeclarativeItem::TopRight:\n case QDeclarativeItem::Right:\n case QDeclarativeItem::BottomRight:\n shiftX = declarativeItem->width();\n break;\n }\n\n declarativeItem->setPos( x - shiftX, y - shiftY );\n orphane.removeOne( item );\n }\n\n \/\/ Cleanup\n foreach( AbstractDataPluginItem* item, orphane ) {\n Q_ASSERT( d->m_delegateInstances.contains( item ) );\n delete d->m_delegateInstances[item];\n d->m_delegateInstances.remove( item );\n }\n}\n\nvoid AbstractDataPlugin::favoriteItemsChanged( const QStringList& favoriteItems )\n{\n Q_UNUSED( favoriteItems )\n}\n\n} \/\/ namespace Marble\n\n#include \"AbstractDataPlugin.moc\"\nMake dynamic object properties available to QML.\/\/\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 \"AbstractDataPlugin.h\"\n\n\/\/ Marble\n#include \"AbstractDataPluginModel.h\"\n#include \"AbstractDataPluginItem.h\"\n#include \"GeoPainter.h\"\n#include \"GeoSceneLayer.h\"\n#include \"MarbleModel.h\"\n#include \"ViewportParams.h\"\n#include \"MarbleDebug.h\"\n\n\/\/ Qt\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Marble\n{\n\nclass AbstractDataPluginPrivate\n{\n public:\n AbstractDataPluginPrivate()\n : m_model( 0 ),\n m_numberOfItems( 10 ),\n m_delegate( 0 ),\n m_delegateParent( 0 )\n {\n }\n \n ~AbstractDataPluginPrivate() {\n delete m_model;\n }\n \n AbstractDataPluginModel *m_model;\n quint32 m_numberOfItems;\n QDeclarativeComponent* m_delegate;\n QGraphicsItem* m_delegateParent;\n QMap m_delegateInstances;\n};\n\nAbstractDataPlugin::AbstractDataPlugin( const MarbleModel *marbleModel )\n : RenderPlugin( marbleModel ),\n d( new AbstractDataPluginPrivate )\n{\n}\n\nAbstractDataPlugin::~AbstractDataPlugin()\n{\n delete d;\n}\n\nbool AbstractDataPlugin::isInitialized() const\n{\n return model() != 0;\n}\n\nQStringList AbstractDataPlugin::backendTypes() const\n{\n return QStringList( name() );\n}\n\nQString AbstractDataPlugin::renderPolicy() const\n{\n return QString( \"ALWAYS\" );\n}\n\nQStringList AbstractDataPlugin::renderPosition() const\n{\n return QStringList( \"ALWAYS_ON_TOP\" );\n}\n\nbool AbstractDataPlugin::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer)\n{\n Q_UNUSED( renderPos );\n Q_UNUSED( layer );\n\n if ( !d->m_model || !isInitialized() ) {\n return true;\n }\n\n if ( d->m_delegate ) {\n handleViewportChange( viewport );\n } else {\n QList items = d->m_model->items( viewport,\n marbleModel(),\n numberOfItems() );\n painter->save();\n\n \/\/ Paint the most important item at last\n for( int i = items.size() - 1; i >= 0; --i ) {\n items.at( i )->paintEvent( painter, viewport );\n }\n\n painter->restore();\n }\n \n return true;\n}\n\nAbstractDataPluginModel *AbstractDataPlugin::model() const\n{\n return d->m_model;\n}\n\nvoid AbstractDataPlugin::setModel( AbstractDataPluginModel* model )\n{\n if ( d->m_model ) {\n disconnect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );\n delete d->m_model;\n }\n d->m_model = model;\n\n connect( d->m_model, SIGNAL( itemsUpdated() ), this, SIGNAL( repaintNeeded() ) );\n connect( d->m_model, SIGNAL( favoriteItemsChanged( const QStringList& ) ), this,\n SLOT( favoriteItemsChanged( const QStringList& ) ) );\n connect( d->m_model, SIGNAL( favoriteItemsOnlyChanged() ), this,\n SIGNAL( favoriteItemsOnlyChanged() ) );\n\n emit favoritesModelChanged();\n}\n\nconst PluginManager* AbstractDataPlugin::pluginManager() const\n{\n return marbleModel()->pluginManager();\n}\n\nquint32 AbstractDataPlugin::numberOfItems() const\n{\n return d->m_numberOfItems;\n}\n \nvoid AbstractDataPlugin::setNumberOfItems( quint32 number )\n{\n bool changed = ( number != d->m_numberOfItems );\n d->m_numberOfItems = number;\n\n if ( changed )\n emit changedNumberOfItems( number );\n}\n\nQList AbstractDataPlugin::whichItemAt( const QPoint& curpos )\n{\n if ( d->m_model && enabled() && visible()) {\n return d->m_model->whichItemAt( curpos );\n }\n else {\n return QList();\n }\n}\n\nRenderPlugin::RenderType AbstractDataPlugin::renderType() const\n{\n return Online;\n}\n\nvoid AbstractDataPlugin::setDelegate( QDeclarativeComponent *delegate, QGraphicsItem* parent )\n{\n qDeleteAll( d->m_delegateInstances.values() );\n d->m_delegateInstances.clear();\n\n d->m_delegate = delegate;\n d->m_delegateParent = parent;\n}\n\nvoid AbstractDataPlugin::setFavoriteItemsOnly( bool favoriteOnly )\n{\n if ( d->m_model && d->m_model->isFavoriteItemsOnly() != favoriteOnly ) {\n d->m_model->setFavoriteItemsOnly( favoriteOnly );\n }\n}\n\nbool AbstractDataPlugin::isFavoriteItemsOnly() const\n{\n return d->m_model && d->m_model->isFavoriteItemsOnly();\n}\n\nQObject *AbstractDataPlugin::favoritesModel()\n{\n return d->m_model ? d->m_model->favoritesModel() : 0;\n}\n\nvoid AbstractDataPlugin::handleViewportChange( ViewportParams* viewport )\n{\n QList orphane = d->m_delegateInstances.keys();\n QList const items = d->m_model->items( viewport, marbleModel(), numberOfItems() );\n foreach( AbstractDataPluginItem* item, items ) {\n qreal x, y;\n Marble::GeoDataCoordinates const coordinates = item->coordinate();\n bool const visible = viewport->screenCoordinates( coordinates.longitude(), coordinates.latitude(), x, y );\n\n if ( !d->m_delegateInstances.contains( item ) ) {\n if ( !visible ) {\n \/\/ We don't have, but don't need it either. Shouldn't happen though as the model checks for it already.\n continue;\n }\n\n \/\/ Create a new QML object instance using the delegate as the factory. The original\n \/\/ data plugin item is set as the context object, i.e. all its properties are available\n \/\/ to QML directly with their names\n QDeclarativeContext *context = new QDeclarativeContext( qmlContext( d->m_delegate ) );\n context->setContextObject( item );\n QList const dynamicProperties = item->dynamicPropertyNames();\n foreach( const QByteArray &property, dynamicProperties ) {\n context->setContextProperty( property, item->property( property ) );\n }\n\n QObject* component = d->m_delegate->create( context );\n QDeclarativeItem* newItem = qobject_cast( component );\n QGraphicsItem* graphicsItem = qobject_cast( component );\n if ( graphicsItem && newItem ) {\n graphicsItem->setParentItem( d->m_delegateParent );\n }\n\n if ( newItem ) {\n d->m_delegateInstances[item] = newItem;\n } else {\n mDebug() << \"Failed to create delegate\";\n continue;\n }\n } else if ( !visible ) {\n \/\/ Previously visible but not anymore => needs to be deleted. Orphane list takes care of it later.\n \/\/ Shouldn't happen though as the model checks for it already.\n continue;\n }\n\n Q_ASSERT( visible );\n QDeclarativeItem* declarativeItem = d->m_delegateInstances[item];\n Q_ASSERT( declarativeItem );\n\n \/\/ Make sure we have a valid bounding rect for collision detection\n item->setProjection( viewport );\n item->setSize( QSizeF( declarativeItem->boundingRect().size() ) );\n\n int shiftX( 0 ), shiftY( 0 );\n switch( declarativeItem->transformOrigin() ) {\n case QDeclarativeItem::TopLeft:\n case QDeclarativeItem::Top:\n case QDeclarativeItem::TopRight:\n break;\n case QDeclarativeItem::Left:\n case QDeclarativeItem::Center:\n case QDeclarativeItem::Right:\n shiftY = declarativeItem->height() \/ 2;\n break;\n case QDeclarativeItem::BottomLeft:\n case QDeclarativeItem::Bottom:\n case QDeclarativeItem::BottomRight:\n shiftY = declarativeItem->height();\n break;\n }\n\n switch( declarativeItem->transformOrigin() ) {\n case QDeclarativeItem::TopLeft:\n case QDeclarativeItem::Left:\n case QDeclarativeItem::BottomLeft:\n break;\n case QDeclarativeItem::Top:\n case QDeclarativeItem::Center:\n case QDeclarativeItem::Bottom:\n shiftX = declarativeItem->width() \/ 2;\n break;\n case QDeclarativeItem::TopRight:\n case QDeclarativeItem::Right:\n case QDeclarativeItem::BottomRight:\n shiftX = declarativeItem->width();\n break;\n }\n\n declarativeItem->setPos( x - shiftX, y - shiftY );\n orphane.removeOne( item );\n }\n\n \/\/ Cleanup\n foreach( AbstractDataPluginItem* item, orphane ) {\n Q_ASSERT( d->m_delegateInstances.contains( item ) );\n delete d->m_delegateInstances[item];\n d->m_delegateInstances.remove( item );\n }\n}\n\nvoid AbstractDataPlugin::favoriteItemsChanged( const QStringList& favoriteItems )\n{\n Q_UNUSED( favoriteItems )\n}\n\n} \/\/ namespace Marble\n\n#include \"AbstractDataPlugin.moc\"\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"Dumpers.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic QString indent(QString s, int level = 2)\n{\n QString indentString(level, QLatin1Char(' '));\n QString result;\n int last = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (s.at(i) == QLatin1Char('\\n') || i == s.length() - 1) {\n result.append(indentString);\n result.append(s.midRef(last, i + 1));\n last = i + 1;\n }\n }\n return result;\n}\n\nQString CPlusPlus::toString(const Name *name, QString id)\n{\n Overview oo;\n return QString(\"%0: %1\").arg(id, name ? oo(name) : QLatin1String(\"(null)\"));\n}\n\nQString CPlusPlus::toString(FullySpecifiedType ty, QString id)\n{\n Overview oo;\n return QString(\"%0: %1 (a %2)\").arg(id, oo(ty), ty.type() ? typeid(*ty.type()).name() : \"(null)\");\n}\n\nQString CPlusPlus::toString(const Symbol *s, QString id)\n{\n if (!s)\n return QString(\"%0: (null)\").arg(id);\n\n return QString(\"%0: %1 (%2) at %3:%4:%5\\n%6\").arg(\n id,\n QString::fromLatin1(typeid(*s).name()),\n QString::fromUtf8(s->identifier()->chars()),\n QString::fromLatin1(s->fileName()),\n QString::number(s->line()),\n QString::number(s->column()),\n indent(toString(s->type())));\n}\n\nQString CPlusPlus::toString(LookupItem it, QString id)\n{\n QString result = QString(\"%1:\").arg(id);\n if (it.declaration()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.declaration(), QLatin1String(\"Decl\")))));\n }\n if (it.type().isValid()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.type()))));\n }\n if (it.scope()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.scope(), QLatin1String(\"Scope\")))));\n }\n if (it.binding()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.binding(), QLatin1String(\"Binding\")))));\n }\n return result;\n}\n\nQString CPlusPlus::toString(const ClassOrNamespace *binding, QString id)\n{\n if (!binding)\n return QString(\"%0: (null)\").arg(id);\n\n QString result = QString(\"%0: %1 symbols\").arg(\n id,\n QString::number(binding->symbols().length()));\n if (binding->templateId()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(binding->templateId(), QLatin1String(\"Template\")))));\n }\n return result;\n}\n\nvoid CPlusPlus::dump(const Name *name)\n{\n qDebug() << qPrintable(toString(name));\n}\n\nvoid CPlusPlus::dump(FullySpecifiedType ty)\n{\n qDebug() << qPrintable(toString(ty));\n}\n\nvoid CPlusPlus::dump(const Symbol *s)\n{\n qDebug() << qPrintable(toString(s));\n}\n\nvoid CPlusPlus::dump(LookupItem it)\n{\n qDebug() << qPrintable(toString(it));\n}\n\nvoid CPlusPlus::dump(const ClassOrNamespace *binding)\n{\n qDebug() << qPrintable(toString(binding));\n}\nC++: Fix dumpers when symbol has no identifier.\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"Dumpers.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic QString indent(QString s, int level = 2)\n{\n QString indentString(level, QLatin1Char(' '));\n QString result;\n int last = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (s.at(i) == QLatin1Char('\\n') || i == s.length() - 1) {\n result.append(indentString);\n result.append(s.midRef(last, i + 1));\n last = i + 1;\n }\n }\n return result;\n}\n\nQString CPlusPlus::toString(const Name *name, QString id)\n{\n Overview oo;\n return QString(\"%0: %1\").arg(id, name ? oo(name) : QLatin1String(\"(null)\"));\n}\n\nQString CPlusPlus::toString(FullySpecifiedType ty, QString id)\n{\n Overview oo;\n return QString(\"%0: %1 (a %2)\").arg(id, oo(ty), ty.type() ? typeid(*ty.type()).name() : \"(null)\");\n}\n\nQString CPlusPlus::toString(const Symbol *s, QString id)\n{\n if (!s)\n return QString(\"%0: (null)\").arg(id);\n\n return QString(\"%0: %1 (%2) at %3:%4:%5\\n%6\").arg(\n id,\n QString::fromLatin1(typeid(*s).name()),\n s->identifier() ? QString::fromUtf8(s->identifier()->chars()) : \"no id\",\n QString::fromLatin1(s->fileName()),\n QString::number(s->line()),\n QString::number(s->column()),\n indent(toString(s->type())));\n}\n\nQString CPlusPlus::toString(LookupItem it, QString id)\n{\n QString result = QString(\"%1:\").arg(id);\n if (it.declaration()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.declaration(), QLatin1String(\"Decl\")))));\n }\n if (it.type().isValid()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.type()))));\n }\n if (it.scope()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.scope(), QLatin1String(\"Scope\")))));\n }\n if (it.binding()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(it.binding(), QLatin1String(\"Binding\")))));\n }\n return result;\n}\n\nQString CPlusPlus::toString(const ClassOrNamespace *binding, QString id)\n{\n if (!binding)\n return QString(\"%0: (null)\").arg(id);\n\n QString result = QString(\"%0: %1 symbols\").arg(\n id,\n QString::number(binding->symbols().length()));\n if (binding->templateId()) {\n result.append(QString(\"\\n%1\").arg(indent(toString(binding->templateId(), QLatin1String(\"Template\")))));\n }\n return result;\n}\n\nvoid CPlusPlus::dump(const Name *name)\n{\n qDebug() << qPrintable(toString(name));\n}\n\nvoid CPlusPlus::dump(FullySpecifiedType ty)\n{\n qDebug() << qPrintable(toString(ty));\n}\n\nvoid CPlusPlus::dump(const Symbol *s)\n{\n qDebug() << qPrintable(toString(s));\n}\n\nvoid CPlusPlus::dump(LookupItem it)\n{\n qDebug() << qPrintable(toString(it));\n}\n\nvoid CPlusPlus::dump(const ClassOrNamespace *binding)\n{\n qDebug() << qPrintable(toString(binding));\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"crumblepath.h\"\n#include \"stylehelper.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace Utils {\n\nstatic const int ArrowBorderSize = 12;\n\nclass CrumblePathButton : public QPushButton\n{\npublic:\n enum SegmentType {\n LastSegment = 1,\n MiddleSegment = 2,\n FirstSegment = 4\n };\n\n explicit CrumblePathButton(const QString &title, QWidget *parent = 0);\n void setSegmentType(int type);\n void select(bool s);\n void setData(const QVariant &data);\n QVariant data() const;\n\nprotected:\n void paintEvent(QPaintEvent *);\n void mouseMoveEvent(QMouseEvent *e);\n void leaveEvent(QEvent *);\n void mousePressEvent(QMouseEvent *e);\n void mouseReleaseEvent(QMouseEvent *e);\n\nprivate:\n void tintImages();\n\nprivate:\n bool m_isHovering;\n bool m_isPressed;\n bool m_isSelected;\n bool m_isEnd;\n QColor m_baseColor;\n QImage m_segment;\n QImage m_segmentEnd;\n QImage m_segmentSelected;\n QImage m_segmentSelectedEnd;\n QImage m_segmentHover;\n QImage m_segmentHoverEnd;\n QImage m_triangleIcon;\n QPoint m_textPos;\n\n QVariant m_data;\n};\n\nCrumblePathButton::CrumblePathButton(const QString &title, QWidget *parent)\n : QPushButton(title, parent), m_isHovering(false), m_isPressed(false), m_isSelected(false), m_isEnd(true)\n{\n setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n setToolTip(title);\n setMinimumHeight(25);\n setMaximumHeight(25);\n setMouseTracking(true);\n m_textPos.setX(18);\n m_textPos.setY(height());\n m_baseColor = StyleHelper::baseColor();\n\n m_segment = QImage(\":\/utils\/images\/crumblepath-segment.png\");\n m_segmentSelected = QImage(\":\/utils\/images\/crumblepath-segment-selected.png\");\n m_segmentHover = QImage(\":\/utils\/images\/crumblepath-segment-hover.png\");\n m_segmentEnd = QImage(\":\/utils\/images\/crumblepath-segment-end.png\");\n m_segmentSelectedEnd = QImage(\":\/utils\/images\/crumblepath-segment-selected-end.png\");\n m_segmentHoverEnd = QImage(\":\/utils\/images\/crumblepath-segment-hover-end.png\");\n m_triangleIcon = QImage(\":\/utils\/images\/triangle_vert.png\");\n\n tintImages();\n}\n\nvoid CrumblePathButton::paintEvent(QPaintEvent *)\n{\n QPainter p(this);\n QRect geom(0, 0, geometry().width(), geometry().height());\n\n if (StyleHelper::baseColor() != m_baseColor) {\n m_baseColor = StyleHelper::baseColor();\n tintImages();\n }\n\n if (m_isEnd) {\n if (m_isPressed || m_isSelected) {\n Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0);\n } else if (m_isHovering) {\n Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0);\n } else {\n Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0);\n }\n } else {\n if (m_isPressed || m_isSelected) {\n Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0);\n } else if (m_isHovering) {\n Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0);\n } else {\n Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0);\n }\n }\n p.setPen(StyleHelper::panelTextColor());\n QFontMetrics fm(p.font());\n QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x());\n\n p.drawText(QRectF(m_textPos.x(), 4, geom.width(), geom.height()), textToDraw);\n\n if (menu()) {\n p.drawImage(geom.width() - m_triangleIcon.width() - 6,\n geom.center().y() - m_triangleIcon.height() \/ 2,\n m_triangleIcon);\n }\n}\n\nvoid CrumblePathButton::tintImages()\n{\n StyleHelper::tintImage(m_segmentEnd, m_baseColor);\n StyleHelper::tintImage(m_segmentSelectedEnd, m_baseColor);\n StyleHelper::tintImage(m_segmentHoverEnd, m_baseColor);\n StyleHelper::tintImage(m_segmentSelected, m_baseColor);\n StyleHelper::tintImage(m_segmentHover, m_baseColor);\n StyleHelper::tintImage(m_segment, m_baseColor);\n}\n\nvoid CrumblePathButton::leaveEvent(QEvent *e)\n{\n QPushButton::leaveEvent(e);\n m_isHovering = false;\n update();\n}\n\nvoid CrumblePathButton::mouseMoveEvent(QMouseEvent *e)\n{\n QPushButton::mouseMoveEvent(e);\n m_isHovering = true;\n update();\n}\n\nvoid CrumblePathButton::mousePressEvent(QMouseEvent *e)\n{\n QPushButton::mousePressEvent(e);\n m_isPressed = true;\n update();\n}\n\nvoid CrumblePathButton::mouseReleaseEvent(QMouseEvent *e)\n{\n QPushButton::mouseReleaseEvent(e);\n m_isPressed = false;\n update();\n}\n\nvoid CrumblePathButton::select(bool s)\n{\n m_isSelected = s;\n update();\n}\n\nvoid CrumblePathButton::setSegmentType(int type)\n{\n bool useLeftPadding = !(type & FirstSegment);\n m_isEnd = (type & LastSegment);\n m_textPos.setX(useLeftPadding ? 18 : 4);\n}\n\nvoid CrumblePathButton::setData(const QVariant &data)\n{\n m_data = data;\n}\n\nQVariant CrumblePathButton::data() const\n{\n return m_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct CrumblePathPrivate\n{\n explicit CrumblePathPrivate(CrumblePath *q);\n\n QList m_buttons;\n};\n\nCrumblePathPrivate::CrumblePathPrivate(CrumblePath *q)\n{\n Q_UNUSED(q)\n}\n\n\/\/\n\/\/ CrumblePath\n\/\/\nCrumblePath::CrumblePath(QWidget *parent) :\n QWidget(parent), d(new CrumblePathPrivate(this))\n{\n setMinimumHeight(25);\n setMaximumHeight(25);\n setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n}\n\nCrumblePath::~CrumblePath()\n{\n qDeleteAll(d->m_buttons);\n d->m_buttons.clear();\n}\n\nvoid CrumblePath::selectIndex(int index)\n{\n if (index > -1 && index < d->m_buttons.length())\n d->m_buttons[index]->select(true);\n}\n\nQVariant CrumblePath::dataForIndex(int index) const\n{\n if (index > -1 && index < d->m_buttons.length())\n return d->m_buttons[index]->data();\n return QVariant();\n}\n\nvoid CrumblePath::pushElement(const QString &title, const QVariant &data)\n{\n CrumblePathButton *newButton = new CrumblePathButton(title, this);\n newButton->hide();\n connect(newButton, SIGNAL(clicked()), SLOT(mapClickToIndex()));\n\n int segType = CrumblePathButton::MiddleSegment;\n if (!d->m_buttons.isEmpty()) {\n if (d->m_buttons.length() == 1)\n segType = segType | CrumblePathButton::FirstSegment;\n d->m_buttons.last()->setSegmentType(segType);\n } else {\n segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;\n newButton->setSegmentType(segType);\n }\n newButton->setData(data);\n d->m_buttons.append(newButton);\n\n resizeButtons();\n}\n\nvoid CrumblePath::addChild(const QString &title, const QVariant &data)\n{\n QTC_ASSERT(d->m_buttons.count() > 0,return);\n\n QPushButton *lastButton = d->m_buttons.last();\n\n QMenu *childList = lastButton->menu();\n if (childList == 0)\n childList = new QMenu(lastButton);\n\n QAction *childAction = new QAction(title, lastButton);\n childAction->setData(data);\n connect(childAction, SIGNAL(triggered()), this, SLOT(mapClickToIndex()));\n childList->addAction(childAction);\n lastButton->setMenu(childList);\n}\n\nvoid CrumblePath::popElement()\n{\n QWidget *last = d->m_buttons.last();\n d->m_buttons.removeLast();\n last->setParent(0);\n last->deleteLater();\n\n int segType = CrumblePathButton::MiddleSegment | CrumblePathButton::LastSegment;\n if (!d->m_buttons.isEmpty()) {\n if (d->m_buttons.length() == 1)\n segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;\n d->m_buttons.last()->setSegmentType(segType);\n }\n resizeButtons();\n}\n\nvoid CrumblePath::clear()\n{\n while (!d->m_buttons.isEmpty())\n popElement();\n}\n\nvoid CrumblePath::resizeEvent(QResizeEvent *)\n{\n resizeButtons();\n}\n\nvoid CrumblePath::resizeButtons()\n{\n int totalWidthLeft = width();\n\n if (d->m_buttons.length() >= 1) {\n QPoint nextElementPosition(0, 0);\n\n d->m_buttons.first()->raise();\n \/\/ rearrange all items so that the first item is on top (added last).\n\n \/\/ compute relative sizes\n QList sizes;\n int totalSize = 0;\n for (int i = 0; i < d->m_buttons.length() ; ++i) {\n CrumblePathButton *button = d->m_buttons.at(i);\n\n QFontMetrics fm(button->font());\n int originalSize = ArrowBorderSize + fm.width(button->text()) + ArrowBorderSize + 12;\n sizes << originalSize;\n totalSize += originalSize - ArrowBorderSize;\n }\n\n for (int i = 0; i < d->m_buttons.length() ; ++i) {\n CrumblePathButton *button = d->m_buttons.at(i);\n\n int candidateSize = (sizes.at(i) * totalWidthLeft) \/ totalSize;\n if (candidateSize < ArrowBorderSize)\n candidateSize = ArrowBorderSize;\n if (candidateSize > sizes.at(i) * 1.3)\n candidateSize = sizes.at(i) * 1.3;\n\n button->setMinimumWidth(candidateSize);\n button->setMaximumWidth(candidateSize);\n button->move(nextElementPosition);\n\n nextElementPosition.rx() += button->width() - ArrowBorderSize;\n\n button->show();\n if (i > 0)\n button->stackUnder(d->m_buttons[i - 1]);\n }\n }\n}\n\nvoid CrumblePath::mapClickToIndex()\n{\n QObject *element = sender();\n if (QString(\"QAction\") == element->metaObject()->className())\n emit elementClicked(static_cast(element)->data().toInt());\n else if (QString(\"QPushButton\") == element->metaObject()->className())\n emit elementClicked(static_cast(element)->data().toInt());\n}\n\n} \/\/ namespace Utils\nQmlDebug: Fix crash on Mac OS X\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"crumblepath.h\"\n#include \"stylehelper.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace Utils {\n\nstatic const int ArrowBorderSize = 12;\n\nclass CrumblePathButton : public QPushButton\n{\npublic:\n enum SegmentType {\n LastSegment = 1,\n MiddleSegment = 2,\n FirstSegment = 4\n };\n\n explicit CrumblePathButton(const QString &title, QWidget *parent = 0);\n void setSegmentType(int type);\n void select(bool s);\n void setData(const QVariant &data);\n QVariant data() const;\n\nprotected:\n void paintEvent(QPaintEvent *);\n void mouseMoveEvent(QMouseEvent *e);\n void leaveEvent(QEvent *);\n void mousePressEvent(QMouseEvent *e);\n void mouseReleaseEvent(QMouseEvent *e);\n\nprivate:\n void tintImages();\n\nprivate:\n bool m_isHovering;\n bool m_isPressed;\n bool m_isSelected;\n bool m_isEnd;\n QColor m_baseColor;\n QImage m_segment;\n QImage m_segmentEnd;\n QImage m_segmentSelected;\n QImage m_segmentSelectedEnd;\n QImage m_segmentHover;\n QImage m_segmentHoverEnd;\n QImage m_triangleIcon;\n QPoint m_textPos;\n\n QVariant m_data;\n};\n\nCrumblePathButton::CrumblePathButton(const QString &title, QWidget *parent)\n : QPushButton(title, parent), m_isHovering(false), m_isPressed(false), m_isSelected(false), m_isEnd(true)\n{\n setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n setToolTip(title);\n setMinimumHeight(25);\n setMaximumHeight(25);\n setMouseTracking(true);\n m_textPos.setX(18);\n m_textPos.setY(height());\n m_baseColor = StyleHelper::baseColor();\n\n m_segment = QImage(\":\/utils\/images\/crumblepath-segment.png\");\n m_segmentSelected = QImage(\":\/utils\/images\/crumblepath-segment-selected.png\");\n m_segmentHover = QImage(\":\/utils\/images\/crumblepath-segment-hover.png\");\n m_segmentEnd = QImage(\":\/utils\/images\/crumblepath-segment-end.png\");\n m_segmentSelectedEnd = QImage(\":\/utils\/images\/crumblepath-segment-selected-end.png\");\n m_segmentHoverEnd = QImage(\":\/utils\/images\/crumblepath-segment-hover-end.png\");\n m_triangleIcon = QImage(\":\/utils\/images\/triangle_vert.png\");\n\n tintImages();\n}\n\nvoid CrumblePathButton::paintEvent(QPaintEvent *)\n{\n QPainter p(this);\n QRect geom(0, 0, geometry().width(), geometry().height());\n\n if (StyleHelper::baseColor() != m_baseColor) {\n m_baseColor = StyleHelper::baseColor();\n tintImages();\n }\n\n if (m_isEnd) {\n if (m_isPressed || m_isSelected) {\n Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0);\n } else if (m_isHovering) {\n Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0);\n } else {\n Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0);\n }\n } else {\n if (m_isPressed || m_isSelected) {\n Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0);\n } else if (m_isHovering) {\n Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0);\n } else {\n Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0);\n }\n }\n p.setPen(StyleHelper::panelTextColor());\n QFontMetrics fm(p.font());\n QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x());\n\n p.drawText(QRectF(m_textPos.x(), 4, geom.width(), geom.height()), textToDraw);\n\n if (menu()) {\n p.drawImage(geom.width() - m_triangleIcon.width() - 6,\n geom.center().y() - m_triangleIcon.height() \/ 2,\n m_triangleIcon);\n }\n}\n\nvoid CrumblePathButton::tintImages()\n{\n StyleHelper::tintImage(m_segmentEnd, m_baseColor);\n StyleHelper::tintImage(m_segmentSelectedEnd, m_baseColor);\n StyleHelper::tintImage(m_segmentHoverEnd, m_baseColor);\n StyleHelper::tintImage(m_segmentSelected, m_baseColor);\n StyleHelper::tintImage(m_segmentHover, m_baseColor);\n StyleHelper::tintImage(m_segment, m_baseColor);\n}\n\nvoid CrumblePathButton::leaveEvent(QEvent *e)\n{\n QPushButton::leaveEvent(e);\n m_isHovering = false;\n update();\n}\n\nvoid CrumblePathButton::mouseMoveEvent(QMouseEvent *e)\n{\n QPushButton::mouseMoveEvent(e);\n m_isHovering = true;\n update();\n}\n\nvoid CrumblePathButton::mousePressEvent(QMouseEvent *e)\n{\n QPushButton::mousePressEvent(e);\n m_isPressed = true;\n update();\n}\n\nvoid CrumblePathButton::mouseReleaseEvent(QMouseEvent *e)\n{\n QPushButton::mouseReleaseEvent(e);\n m_isPressed = false;\n update();\n}\n\nvoid CrumblePathButton::select(bool s)\n{\n m_isSelected = s;\n update();\n}\n\nvoid CrumblePathButton::setSegmentType(int type)\n{\n bool useLeftPadding = !(type & FirstSegment);\n m_isEnd = (type & LastSegment);\n m_textPos.setX(useLeftPadding ? 18 : 4);\n}\n\nvoid CrumblePathButton::setData(const QVariant &data)\n{\n m_data = data;\n}\n\nQVariant CrumblePathButton::data() const\n{\n return m_data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct CrumblePathPrivate\n{\n explicit CrumblePathPrivate(CrumblePath *q);\n\n QList m_buttons;\n};\n\nCrumblePathPrivate::CrumblePathPrivate(CrumblePath *q)\n{\n Q_UNUSED(q)\n}\n\n\/\/\n\/\/ CrumblePath\n\/\/\nCrumblePath::CrumblePath(QWidget *parent) :\n QWidget(parent), d(new CrumblePathPrivate(this))\n{\n setMinimumHeight(25);\n setMaximumHeight(25);\n setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n}\n\nCrumblePath::~CrumblePath()\n{\n qDeleteAll(d->m_buttons);\n d->m_buttons.clear();\n}\n\nvoid CrumblePath::selectIndex(int index)\n{\n if (index > -1 && index < d->m_buttons.length())\n d->m_buttons[index]->select(true);\n}\n\nQVariant CrumblePath::dataForIndex(int index) const\n{\n if (index > -1 && index < d->m_buttons.length())\n return d->m_buttons[index]->data();\n return QVariant();\n}\n\nvoid CrumblePath::pushElement(const QString &title, const QVariant &data)\n{\n CrumblePathButton *newButton = new CrumblePathButton(title, this);\n newButton->hide();\n connect(newButton, SIGNAL(clicked()), SLOT(mapClickToIndex()));\n\n int segType = CrumblePathButton::MiddleSegment;\n if (!d->m_buttons.isEmpty()) {\n if (d->m_buttons.length() == 1)\n segType = segType | CrumblePathButton::FirstSegment;\n d->m_buttons.last()->setSegmentType(segType);\n } else {\n segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;\n newButton->setSegmentType(segType);\n }\n newButton->setData(data);\n d->m_buttons.append(newButton);\n\n resizeButtons();\n}\n\nvoid CrumblePath::addChild(const QString &title, const QVariant &data)\n{\n QTC_ASSERT(d->m_buttons.count() > 0,return);\n\n QPushButton *lastButton = d->m_buttons.last();\n\n QMenu *childList = lastButton->menu();\n if (childList == 0)\n childList = new QMenu(lastButton);\n\n QAction *childAction = new QAction(title, lastButton);\n childAction->setData(data);\n connect(childAction, SIGNAL(triggered()), this, SLOT(mapClickToIndex()));\n childList->addAction(childAction);\n lastButton->setMenu(childList);\n}\n\nvoid CrumblePath::popElement()\n{\n QWidget *last = d->m_buttons.last();\n d->m_buttons.removeLast();\n last->setParent(0);\n last->deleteLater();\n\n int segType = CrumblePathButton::MiddleSegment | CrumblePathButton::LastSegment;\n if (!d->m_buttons.isEmpty()) {\n if (d->m_buttons.length() == 1)\n segType = CrumblePathButton::FirstSegment | CrumblePathButton::LastSegment;\n d->m_buttons.last()->setSegmentType(segType);\n }\n resizeButtons();\n}\n\nvoid CrumblePath::clear()\n{\n while (!d->m_buttons.isEmpty())\n popElement();\n}\n\nvoid CrumblePath::resizeEvent(QResizeEvent *)\n{\n resizeButtons();\n}\n\nvoid CrumblePath::resizeButtons()\n{\n int totalWidthLeft = width();\n\n if (d->m_buttons.length() >= 1) {\n QPoint nextElementPosition(0, 0);\n\n d->m_buttons.first()->raise();\n \/\/ rearrange all items so that the first item is on top (added last).\n\n \/\/ compute relative sizes\n QList sizes;\n int totalSize = 0;\n for (int i = 0; i < d->m_buttons.length() ; ++i) {\n CrumblePathButton *button = d->m_buttons.at(i);\n\n QFontMetrics fm(button->font());\n int originalSize = ArrowBorderSize + fm.width(button->text()) + ArrowBorderSize + 12;\n sizes << originalSize;\n totalSize += originalSize - ArrowBorderSize;\n }\n\n for (int i = 0; i < d->m_buttons.length() ; ++i) {\n CrumblePathButton *button = d->m_buttons.at(i);\n\n int candidateSize = (sizes.at(i) * totalWidthLeft) \/ totalSize;\n if (candidateSize < ArrowBorderSize)\n candidateSize = ArrowBorderSize;\n if (candidateSize > sizes.at(i) * 1.3)\n candidateSize = sizes.at(i) * 1.3;\n\n button->setMinimumWidth(candidateSize);\n button->setMaximumWidth(candidateSize);\n button->move(nextElementPosition);\n\n nextElementPosition.rx() += button->width() - ArrowBorderSize;\n\n button->show();\n if (i > 0) {\n \/\/ work-around for a compiler \/ optimization bug in i686-apple-darwin9-g\n \/\/ without volatile, the optimizer (-O2) seems to do the wrong thing (tm\n \/\/ the d->m_buttons array with an invalid argument.\n volatile int prevIndex = i - 1;\n button->stackUnder(d->m_buttons[prevIndex]);\n }\n }\n }\n}\n\nvoid CrumblePath::mapClickToIndex()\n{\n QObject *element = sender();\n if (QString(\"QAction\") == element->metaObject()->className())\n emit elementClicked(static_cast(element)->data().toInt());\n else if (QString(\"QPushButton\") == element->metaObject()->className())\n emit elementClicked(static_cast(element)->data().toInt());\n}\n\n} \/\/ namespace Utils\n<|endoftext|>"} {"text":"#ifndef slic3r_TriangleMesh_hpp_\n#define slic3r_TriangleMesh_hpp_\n\n#include \"libslic3r.h\"\n#include \n#include \n#include \n#include \n#include \"BoundingBox.hpp\"\n#include \"Line.hpp\"\n#include \"Point.hpp\"\n#include \"Polygon.hpp\"\n#include \"ExPolygon.hpp\"\n\nnamespace Slic3r {\n\nclass TriangleMesh;\nclass TriangleMeshSlicer;\ntypedef std::vector TriangleMeshPtrs;\n\nclass TriangleMesh\n{\npublic:\n TriangleMesh() : repaired(false) {}\n TriangleMesh(const Pointf3s &points, const std::vector &facets);\n\tvoid clear() { this->stl.clear(); this->its.clear(); this->repaired = false; }\n bool ReadSTLFile(const char* input_file) { return stl_open(&stl, input_file); }\n bool write_ascii(const char* output_file) { return stl_write_ascii(&this->stl, output_file, \"\"); }\n bool write_binary(const char* output_file) { return stl_write_binary(&this->stl, output_file, \"\"); }\n void repair(bool update_shared_vertices = true);\n float volume();\n void check_topology();\n bool is_manifold() const { return this->stl.stats.connected_facets_3_edge == (int)this->stl.stats.number_of_facets; }\n void WriteOBJFile(const char* output_file) const;\n void scale(float factor);\n void scale(const Vec3d &versor);\n void translate(float x, float y, float z);\n void translate(const Vec3f &displacement);\n void rotate(float angle, const Axis &axis);\n void rotate(float angle, const Vec3d& axis);\n void rotate_x(float angle) { this->rotate(angle, X); }\n void rotate_y(float angle) { this->rotate(angle, Y); }\n void rotate_z(float angle) { this->rotate(angle, Z); }\n void mirror(const Axis &axis);\n void mirror_x() { this->mirror(X); }\n void mirror_y() { this->mirror(Y); }\n void mirror_z() { this->mirror(Z); }\n void transform(const Transform3d& t, bool fix_left_handed = false);\n\tvoid transform(const Matrix3d& t, bool fix_left_handed = false);\n void align_to_origin();\n void rotate(double angle, Point* center);\n TriangleMeshPtrs split() const;\n void merge(const TriangleMesh &mesh);\n ExPolygons horizontal_projection() const;\n const float* first_vertex() const { return this->stl.facet_start.empty() ? nullptr : &this->stl.facet_start.front().vertex[0](0); }\n \/\/ 2D convex hull of a 3D mesh projected into the Z=0 plane.\n Polygon convex_hull();\n BoundingBoxf3 bounding_box() const;\n \/\/ Returns the bbox of this TriangleMesh transformed by the given transformation\n BoundingBoxf3 transformed_bounding_box(const Transform3d &trafo) const;\n \/\/ Return the size of the mesh in coordinates.\n Vec3d size() const { return stl.stats.size.cast(); }\n \/\/\/ Return the center of the related bounding box.\n\tVec3d center() const { return this->bounding_box().center(); }\n \/\/ Returns the convex hull of this TriangleMesh\n TriangleMesh convex_hull_3d() const;\n \/\/ Slice this mesh at the provided Z levels and return the vector\n std::vector slice(const std::vector& z);\n void reset_repair_stats();\n bool needed_repair() const;\n void require_shared_vertices();\n bool has_shared_vertices() const { return ! this->its.vertices.empty(); }\n size_t facets_count() const { return this->stl.stats.number_of_facets; }\n bool empty() const { return this->facets_count() == 0; }\n bool is_splittable() const;\n \/\/ Estimate of the memory occupied by this structure, important for keeping an eye on the Undo \/ Redo stack allocation.\n size_t memsize() const;\n \/\/ Release optional data from the mesh if the object is on the Undo \/ Redo stack only. Returns the amount of memory released.\n size_t release_optional();\n\t\/\/ Restore optional data possibly released by release_optional().\n\tvoid restore_optional();\n\n stl_file stl;\n indexed_triangle_set its;\n bool repaired;\n\nprivate:\n std::deque find_unvisited_neighbors(std::vector &facet_visited) const;\n};\n\nenum FacetEdgeType { \n \/\/ A general case, the cutting plane intersect a face at two different edges.\n feGeneral,\n \/\/ Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane.\n feTop,\n \/\/ Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane.\n feBottom,\n \/\/ All three vertices of a face are aligned with the cutting plane.\n feHorizontal\n};\n\nclass IntersectionReference\n{\npublic:\n IntersectionReference() : point_id(-1), edge_id(-1) {};\n IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {}\n \/\/ Where is this intersection point located? On mesh vertex or mesh edge?\n \/\/ Only one of the following will be set, the other will remain set to -1.\n \/\/ Index of the mesh vertex.\n int point_id;\n \/\/ Index of the mesh edge.\n int edge_id;\n};\n\nclass IntersectionPoint : public Point, public IntersectionReference\n{\npublic:\n IntersectionPoint() {};\n IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {}\n IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {}\n \/\/ Inherits coord_t x, y\n};\n\nclass IntersectionLine : public Line\n{\npublic:\n IntersectionLine() : a_id(-1), b_id(-1), edge_a_id(-1), edge_b_id(-1), edge_type(feGeneral), flags(0) {}\n\n bool skip() const { return (this->flags & SKIP) != 0; }\n void set_skip() { this->flags |= SKIP; }\n\n bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); }\n void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; }\n \n \/\/ Inherits Point a, b\n \/\/ For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1.\n \/\/ Vertex indices of the line end points.\n int a_id;\n int b_id;\n \/\/ Source mesh edges of the line end points.\n int edge_a_id;\n int edge_b_id;\n \/\/ feGeneral, feTop, feBottom, feHorizontal\n FacetEdgeType edge_type;\n \/\/ Used by TriangleMeshSlicer::slice() to skip duplicate edges.\n enum {\n \/\/ Triangle edge added, because it has no neighbor.\n EDGE0_NO_NEIGHBOR = 0x001,\n EDGE1_NO_NEIGHBOR = 0x002,\n EDGE2_NO_NEIGHBOR = 0x004,\n \/\/ Triangle edge added, because it makes a fold with another horizontal edge.\n EDGE0_FOLD = 0x010,\n EDGE1_FOLD = 0x020,\n EDGE2_FOLD = 0x040,\n \/\/ The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds).\n NO_SEED = 0x100,\n SKIP = 0x200,\n };\n uint32_t flags;\n};\ntypedef std::vector IntersectionLines;\ntypedef std::vector IntersectionLinePtrs;\n\nclass TriangleMeshSlicer\n{\npublic:\n typedef std::function throw_on_cancel_callback_type;\n TriangleMeshSlicer() : mesh(nullptr) {}\n\tTriangleMeshSlicer(const TriangleMesh* mesh) { this->init(mesh, [](){}); }\n void init(const TriangleMesh *mesh, throw_on_cancel_callback_type throw_on_cancel);\n void slice(const std::vector &z, std::vector* layers, throw_on_cancel_callback_type throw_on_cancel) const;\n void slice(const std::vector &z, const float closing_radius, std::vector* layers, throw_on_cancel_callback_type throw_on_cancel) const;\n enum FacetSliceType {\n NoSlice = 0,\n Slicing = 1,\n Cutting = 2\n };\n FacetSliceType slice_facet(float slice_z, const stl_facet &facet, const int facet_idx,\n const float min_z, const float max_z, IntersectionLine *line_out) const;\n void cut(float z, TriangleMesh* upper, TriangleMesh* lower) const;\n void set_up_direction(const Vec3f& up);\n \nprivate:\n const TriangleMesh *mesh;\n \/\/ Map from a facet to an edge index.\n std::vector facets_edges;\n \/\/ Scaled copy of this->mesh->stl.v_shared\n std::vector v_scaled_shared;\n \/\/ Quaternion that will be used to rotate every facet before the slicing\n Eigen::Quaternion m_quaternion;\n \/\/ Whether or not the above quaterion should be used\n bool m_use_quaternion = false;\n\n void _slice_do(size_t facet_idx, std::vector* lines, boost::mutex* lines_mutex, const std::vector &z) const;\n void make_loops(std::vector &lines, Polygons* loops) const;\n void make_expolygons(const Polygons &loops, const float closing_radius, ExPolygons* slices) const;\n void make_expolygons_simple(std::vector &lines, ExPolygons* slices) const;\n void make_expolygons(std::vector &lines, const float closing_radius, ExPolygons* slices) const;\n};\n\nTriangleMesh make_cube(double x, double y, double z);\n\n\/\/ Generate a TriangleMesh of a cylinder\nTriangleMesh make_cylinder(double r, double h, double fa=(2*PI\/360));\n\nTriangleMesh make_sphere(double rho, double fa=(2*PI\/360));\n\n}\n\n\/\/ Serialization through the Cereal library\n#include \nnamespace cereal {\n\ttemplate struct specialize {};\n\ttemplate void load(Archive &archive, Slic3r::TriangleMesh &mesh) {\n stl_file &stl = mesh.stl;\n stl.stats.type = inmemory;\n\t\tarchive(stl.stats.number_of_facets, stl.stats.original_num_facets);\n stl_allocate(&stl);\n\t\tarchive.loadBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);\n stl_get_size(&stl);\n mesh.repair();\n\t}\n\ttemplate void save(Archive &archive, const Slic3r::TriangleMesh &mesh) {\n\t\tconst stl_file& stl = mesh.stl;\n\t\tarchive(stl.stats.number_of_facets, stl.stats.original_num_facets);\n\t\tarchive.saveBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);\n\t}\n}\n\n#endif\nAdd free functions to slice a TriangleMesh#ifndef slic3r_TriangleMesh_hpp_\n#define slic3r_TriangleMesh_hpp_\n\n#include \"libslic3r.h\"\n#include \n#include \n#include \n#include \n#include \"BoundingBox.hpp\"\n#include \"Line.hpp\"\n#include \"Point.hpp\"\n#include \"Polygon.hpp\"\n#include \"ExPolygon.hpp\"\n\nnamespace Slic3r {\n\nclass TriangleMesh;\nclass TriangleMeshSlicer;\ntypedef std::vector TriangleMeshPtrs;\n\nclass TriangleMesh\n{\npublic:\n TriangleMesh() : repaired(false) {}\n TriangleMesh(const Pointf3s &points, const std::vector &facets);\n\tvoid clear() { this->stl.clear(); this->its.clear(); this->repaired = false; }\n bool ReadSTLFile(const char* input_file) { return stl_open(&stl, input_file); }\n bool write_ascii(const char* output_file) { return stl_write_ascii(&this->stl, output_file, \"\"); }\n bool write_binary(const char* output_file) { return stl_write_binary(&this->stl, output_file, \"\"); }\n void repair(bool update_shared_vertices = true);\n float volume();\n void check_topology();\n bool is_manifold() const { return this->stl.stats.connected_facets_3_edge == (int)this->stl.stats.number_of_facets; }\n void WriteOBJFile(const char* output_file) const;\n void scale(float factor);\n void scale(const Vec3d &versor);\n void translate(float x, float y, float z);\n void translate(const Vec3f &displacement);\n void rotate(float angle, const Axis &axis);\n void rotate(float angle, const Vec3d& axis);\n void rotate_x(float angle) { this->rotate(angle, X); }\n void rotate_y(float angle) { this->rotate(angle, Y); }\n void rotate_z(float angle) { this->rotate(angle, Z); }\n void mirror(const Axis &axis);\n void mirror_x() { this->mirror(X); }\n void mirror_y() { this->mirror(Y); }\n void mirror_z() { this->mirror(Z); }\n void transform(const Transform3d& t, bool fix_left_handed = false);\n\tvoid transform(const Matrix3d& t, bool fix_left_handed = false);\n void align_to_origin();\n void rotate(double angle, Point* center);\n TriangleMeshPtrs split() const;\n void merge(const TriangleMesh &mesh);\n ExPolygons horizontal_projection() const;\n const float* first_vertex() const { return this->stl.facet_start.empty() ? nullptr : &this->stl.facet_start.front().vertex[0](0); }\n \/\/ 2D convex hull of a 3D mesh projected into the Z=0 plane.\n Polygon convex_hull();\n BoundingBoxf3 bounding_box() const;\n \/\/ Returns the bbox of this TriangleMesh transformed by the given transformation\n BoundingBoxf3 transformed_bounding_box(const Transform3d &trafo) const;\n \/\/ Return the size of the mesh in coordinates.\n Vec3d size() const { return stl.stats.size.cast(); }\n \/\/\/ Return the center of the related bounding box.\n\tVec3d center() const { return this->bounding_box().center(); }\n \/\/ Returns the convex hull of this TriangleMesh\n TriangleMesh convex_hull_3d() const;\n \/\/ Slice this mesh at the provided Z levels and return the vector\n std::vector slice(const std::vector& z);\n void reset_repair_stats();\n bool needed_repair() const;\n void require_shared_vertices();\n bool has_shared_vertices() const { return ! this->its.vertices.empty(); }\n size_t facets_count() const { return this->stl.stats.number_of_facets; }\n bool empty() const { return this->facets_count() == 0; }\n bool is_splittable() const;\n \/\/ Estimate of the memory occupied by this structure, important for keeping an eye on the Undo \/ Redo stack allocation.\n size_t memsize() const;\n \/\/ Release optional data from the mesh if the object is on the Undo \/ Redo stack only. Returns the amount of memory released.\n size_t release_optional();\n\t\/\/ Restore optional data possibly released by release_optional().\n\tvoid restore_optional();\n\n stl_file stl;\n indexed_triangle_set its;\n bool repaired;\n\nprivate:\n std::deque find_unvisited_neighbors(std::vector &facet_visited) const;\n};\n\nenum FacetEdgeType { \n \/\/ A general case, the cutting plane intersect a face at two different edges.\n feGeneral,\n \/\/ Two vertices are aligned with the cutting plane, the third vertex is below the cutting plane.\n feTop,\n \/\/ Two vertices are aligned with the cutting plane, the third vertex is above the cutting plane.\n feBottom,\n \/\/ All three vertices of a face are aligned with the cutting plane.\n feHorizontal\n};\n\nclass IntersectionReference\n{\npublic:\n IntersectionReference() : point_id(-1), edge_id(-1) {};\n IntersectionReference(int point_id, int edge_id) : point_id(point_id), edge_id(edge_id) {}\n \/\/ Where is this intersection point located? On mesh vertex or mesh edge?\n \/\/ Only one of the following will be set, the other will remain set to -1.\n \/\/ Index of the mesh vertex.\n int point_id;\n \/\/ Index of the mesh edge.\n int edge_id;\n};\n\nclass IntersectionPoint : public Point, public IntersectionReference\n{\npublic:\n IntersectionPoint() {};\n IntersectionPoint(int point_id, int edge_id, const Point &pt) : IntersectionReference(point_id, edge_id), Point(pt) {}\n IntersectionPoint(const IntersectionReference &ir, const Point &pt) : IntersectionReference(ir), Point(pt) {}\n \/\/ Inherits coord_t x, y\n};\n\nclass IntersectionLine : public Line\n{\npublic:\n IntersectionLine() : a_id(-1), b_id(-1), edge_a_id(-1), edge_b_id(-1), edge_type(feGeneral), flags(0) {}\n\n bool skip() const { return (this->flags & SKIP) != 0; }\n void set_skip() { this->flags |= SKIP; }\n\n bool is_seed_candidate() const { return (this->flags & NO_SEED) == 0 && ! this->skip(); }\n void set_no_seed(bool set) { if (set) this->flags |= NO_SEED; else this->flags &= ~NO_SEED; }\n \n \/\/ Inherits Point a, b\n \/\/ For each line end point, either {a,b}_id or {a,b}edge_a_id is set, the other is left to -1.\n \/\/ Vertex indices of the line end points.\n int a_id;\n int b_id;\n \/\/ Source mesh edges of the line end points.\n int edge_a_id;\n int edge_b_id;\n \/\/ feGeneral, feTop, feBottom, feHorizontal\n FacetEdgeType edge_type;\n \/\/ Used by TriangleMeshSlicer::slice() to skip duplicate edges.\n enum {\n \/\/ Triangle edge added, because it has no neighbor.\n EDGE0_NO_NEIGHBOR = 0x001,\n EDGE1_NO_NEIGHBOR = 0x002,\n EDGE2_NO_NEIGHBOR = 0x004,\n \/\/ Triangle edge added, because it makes a fold with another horizontal edge.\n EDGE0_FOLD = 0x010,\n EDGE1_FOLD = 0x020,\n EDGE2_FOLD = 0x040,\n \/\/ The edge cannot be a seed of a greedy loop extraction (folds are not safe to become seeds).\n NO_SEED = 0x100,\n SKIP = 0x200,\n };\n uint32_t flags;\n};\ntypedef std::vector IntersectionLines;\ntypedef std::vector IntersectionLinePtrs;\n\nclass TriangleMeshSlicer\n{\npublic:\n typedef std::function throw_on_cancel_callback_type;\n TriangleMeshSlicer() : mesh(nullptr) {}\n\tTriangleMeshSlicer(const TriangleMesh* mesh) { this->init(mesh, [](){}); }\n void init(const TriangleMesh *mesh, throw_on_cancel_callback_type throw_on_cancel);\n void slice(const std::vector &z, std::vector* layers, throw_on_cancel_callback_type throw_on_cancel) const;\n void slice(const std::vector &z, const float closing_radius, std::vector* layers, throw_on_cancel_callback_type throw_on_cancel) const;\n enum FacetSliceType {\n NoSlice = 0,\n Slicing = 1,\n Cutting = 2\n };\n FacetSliceType slice_facet(float slice_z, const stl_facet &facet, const int facet_idx,\n const float min_z, const float max_z, IntersectionLine *line_out) const;\n void cut(float z, TriangleMesh* upper, TriangleMesh* lower) const;\n void set_up_direction(const Vec3f& up);\n \nprivate:\n const TriangleMesh *mesh;\n \/\/ Map from a facet to an edge index.\n std::vector facets_edges;\n \/\/ Scaled copy of this->mesh->stl.v_shared\n std::vector v_scaled_shared;\n \/\/ Quaternion that will be used to rotate every facet before the slicing\n Eigen::Quaternion m_quaternion;\n \/\/ Whether or not the above quaterion should be used\n bool m_use_quaternion = false;\n\n void _slice_do(size_t facet_idx, std::vector* lines, boost::mutex* lines_mutex, const std::vector &z) const;\n void make_loops(std::vector &lines, Polygons* loops) const;\n void make_expolygons(const Polygons &loops, const float closing_radius, ExPolygons* slices) const;\n void make_expolygons_simple(std::vector &lines, ExPolygons* slices) const;\n void make_expolygons(std::vector &lines, const float closing_radius, ExPolygons* slices) const;\n};\n\ninline void slice_mesh(\n const TriangleMesh & mesh,\n const std::vector & z,\n std::vector & layers,\n TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr)\n{\n if (mesh.empty()) return;\n TriangleMeshSlicer slicer(&mesh);\n slicer.slice(z, &layers, thr);\n}\n\ninline void slice_mesh(\n const TriangleMesh & mesh,\n const std::vector & z,\n std::vector & layers,\n float closing_radius,\n TriangleMeshSlicer::throw_on_cancel_callback_type thr = nullptr)\n{\n if (mesh.empty()) return;\n TriangleMeshSlicer slicer(&mesh);\n slicer.slice(z, closing_radius, &layers, thr);\n}\n\nTriangleMesh make_cube(double x, double y, double z);\n\n\/\/ Generate a TriangleMesh of a cylinder\nTriangleMesh make_cylinder(double r, double h, double fa=(2*PI\/360));\n\nTriangleMesh make_sphere(double rho, double fa=(2*PI\/360));\n\n}\n\n\/\/ Serialization through the Cereal library\n#include \nnamespace cereal {\n\ttemplate struct specialize {};\n\ttemplate void load(Archive &archive, Slic3r::TriangleMesh &mesh) {\n stl_file &stl = mesh.stl;\n stl.stats.type = inmemory;\n\t\tarchive(stl.stats.number_of_facets, stl.stats.original_num_facets);\n stl_allocate(&stl);\n\t\tarchive.loadBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);\n stl_get_size(&stl);\n mesh.repair();\n\t}\n\ttemplate void save(Archive &archive, const Slic3r::TriangleMesh &mesh) {\n\t\tconst stl_file& stl = mesh.stl;\n\t\tarchive(stl.stats.number_of_facets, stl.stats.original_num_facets);\n\t\tarchive.saveBinary((char*)stl.facet_start.data(), stl.facet_start.size() * 50);\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"projwrapper_p.h\"\n#include \n#include \n#include \n#include \n#include \n\nQTM_BEGIN_NAMESPACE\n\nclass ProjCoordinateSystemPrivate : public QSharedData\n{\npublic:\n ProjCoordinateSystemPrivate(const QString &projection, bool latLon);\n ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other);\n ~ProjCoordinateSystemPrivate();\n\n projPJ projection;\n bool latLon;\n};\n\nProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const QString &projStr, bool isLatLon)\n{\n projection = pj_init_plus(projStr.toLatin1().constData());\n Q_ASSERT_X(projection, \"pj_init_plus\", \"invalid projection string\");\n latLon = isLatLon;\n}\n\nProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other) :\n QSharedData(other), projection(other.projection)\n{}\n\nProjCoordinateSystemPrivate::~ProjCoordinateSystemPrivate()\n{}\n\nProjCoordinateSystem::ProjCoordinateSystem(const QString &projection, bool latLon) :\n d(new ProjCoordinateSystemPrivate(projection, latLon))\n{}\n\nProjCoordinateSystem::ProjCoordinateSystem(const ProjCoordinateSystem &other) :\n d(other.d)\n{}\n\nProjCoordinateSystem::~ProjCoordinateSystem()\n{}\n\nbool ProjCoordinateSystem::isLatLon() const\n{\n return d->latLon;\n}\n\nclass ProjCoordinatePrivate\n{\npublic:\n ProjCoordinateSystem currentSystem;\n double x;\n double y;\n double z;\n};\n\nProjCoordinate::ProjCoordinate(double x, double y, double z, const ProjCoordinateSystem &system) :\n d(new ProjCoordinatePrivate)\n{\n d->x = x;\n d->y = y;\n d->z = z;\n d->currentSystem = system;\n}\n\nProjCoordinate::ProjCoordinate(const ProjCoordinate &other) :\n d(new ProjCoordinatePrivate)\n{\n d->x = other.d->x;\n d->y = other.d->y;\n d->z = other.d->z;\n d->currentSystem = other.d->currentSystem;\n}\n\nProjCoordinate::~ProjCoordinate()\n{}\n\ndouble ProjCoordinate::x() const\n{\n return d->x;\n}\n\ndouble ProjCoordinate::y() const\n{\n return d->y;\n}\n\ndouble ProjCoordinate::z() const\n{\n return d->z;\n}\n\nbool ProjCoordinate::convert(const ProjCoordinateSystem &system)\n{\n int result;\n double x = d->x, y = d->y, z = d->z;\n\n if (d->currentSystem.isLatLon()) {\n x *= DEG_TO_RAD;\n y *= DEG_TO_RAD;\n }\n\n result = pj_transform(d->currentSystem.d->projection,\n system.d->projection,\n 1, 1, &x, &y, &z);\n if (result) {\n return false;\n } else {\n if (system.isLatLon()) {\n x *= RAD_TO_DEG;\n y *= RAD_TO_DEG;\n }\n d->x = x;\n d->y = y;\n d->z = z;\n d->currentSystem = system;\n return true;\n }\n}\n\nclass ProjPolygonPrivate\n{\npublic:\n ProjCoordinateSystem currentSystem;\n};\n\nProjPolygon::ProjPolygon(const ProjCoordinateSystem &system) :\n QList(),\n d(new ProjPolygonPrivate)\n{\n d->currentSystem = system;\n}\n\nProjPolygon::ProjPolygon(const QPolygonF &poly, const ProjCoordinateSystem &system, double scale) :\n QList(),\n d(new ProjPolygonPrivate)\n{\n d->currentSystem = system;\n foreach (QPointF point, poly) {\n double x = point.x();\n x \/= scale;\n double y = point.y();\n y \/= scale;\n append(ProjCoordinate(x, y, 0.0, system));\n }\n}\n\nbool ProjPolygon::convert(const ProjCoordinateSystem &system)\n{\n for (int i=0; icurrentSystem = system;\n return true;\n}\n\nQPolygonF ProjPolygon::toPolygonF(double scale) const\n{\n QPolygonF poly;\n for (int i=0; iAdding destructor implementation for ProjPolygon\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"projwrapper_p.h\"\n#include \n#include \n#include \n#include \n#include \n\nQTM_BEGIN_NAMESPACE\n\nclass ProjCoordinateSystemPrivate : public QSharedData\n{\npublic:\n ProjCoordinateSystemPrivate(const QString &projection, bool latLon);\n ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other);\n ~ProjCoordinateSystemPrivate();\n\n projPJ projection;\n bool latLon;\n};\n\nProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const QString &projStr, bool isLatLon)\n{\n projection = pj_init_plus(projStr.toLatin1().constData());\n Q_ASSERT_X(projection, \"pj_init_plus\", \"invalid projection string\");\n latLon = isLatLon;\n}\n\nProjCoordinateSystemPrivate::ProjCoordinateSystemPrivate(const ProjCoordinateSystemPrivate &other) :\n QSharedData(other), projection(other.projection)\n{}\n\nProjCoordinateSystemPrivate::~ProjCoordinateSystemPrivate()\n{}\n\nProjCoordinateSystem::ProjCoordinateSystem(const QString &projection, bool latLon) :\n d(new ProjCoordinateSystemPrivate(projection, latLon))\n{}\n\nProjCoordinateSystem::ProjCoordinateSystem(const ProjCoordinateSystem &other) :\n d(other.d)\n{}\n\nProjCoordinateSystem::~ProjCoordinateSystem()\n{}\n\nbool ProjCoordinateSystem::isLatLon() const\n{\n return d->latLon;\n}\n\nclass ProjCoordinatePrivate\n{\npublic:\n ProjCoordinateSystem currentSystem;\n double x;\n double y;\n double z;\n};\n\nProjCoordinate::ProjCoordinate(double x, double y, double z, const ProjCoordinateSystem &system) :\n d(new ProjCoordinatePrivate)\n{\n d->x = x;\n d->y = y;\n d->z = z;\n d->currentSystem = system;\n}\n\nProjCoordinate::ProjCoordinate(const ProjCoordinate &other) :\n d(new ProjCoordinatePrivate)\n{\n d->x = other.d->x;\n d->y = other.d->y;\n d->z = other.d->z;\n d->currentSystem = other.d->currentSystem;\n}\n\nProjCoordinate::~ProjCoordinate()\n{}\n\ndouble ProjCoordinate::x() const\n{\n return d->x;\n}\n\ndouble ProjCoordinate::y() const\n{\n return d->y;\n}\n\ndouble ProjCoordinate::z() const\n{\n return d->z;\n}\n\nbool ProjCoordinate::convert(const ProjCoordinateSystem &system)\n{\n int result;\n double x = d->x, y = d->y, z = d->z;\n\n if (d->currentSystem.isLatLon()) {\n x *= DEG_TO_RAD;\n y *= DEG_TO_RAD;\n }\n\n result = pj_transform(d->currentSystem.d->projection,\n system.d->projection,\n 1, 1, &x, &y, &z);\n if (result) {\n return false;\n } else {\n if (system.isLatLon()) {\n x *= RAD_TO_DEG;\n y *= RAD_TO_DEG;\n }\n d->x = x;\n d->y = y;\n d->z = z;\n d->currentSystem = system;\n return true;\n }\n}\n\nclass ProjPolygonPrivate\n{\npublic:\n ProjCoordinateSystem currentSystem;\n};\n\nProjPolygon::ProjPolygon(const ProjCoordinateSystem &system) :\n QList(),\n d(new ProjPolygonPrivate)\n{\n d->currentSystem = system;\n}\n\nProjPolygon::ProjPolygon(const QPolygonF &poly, const ProjCoordinateSystem &system, double scale) :\n QList(),\n d(new ProjPolygonPrivate)\n{\n d->currentSystem = system;\n foreach (QPointF point, poly) {\n double x = point.x();\n x \/= scale;\n double y = point.y();\n y \/= scale;\n append(ProjCoordinate(x, y, 0.0, system));\n }\n}\n\nProjPolygon::~ProjPolygon()\n{}\n\nbool ProjPolygon::convert(const ProjCoordinateSystem &system)\n{\n for (int i=0; icurrentSystem = system;\n return true;\n}\n\nQPolygonF ProjPolygon::toPolygonF(double scale) const\n{\n QPolygonF poly;\n for (int i=0; i"} {"text":"\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\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: 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 copyright holders 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 * Authors: Nathan Binkert\n * Steve Reinhardt\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/misc.hh\"\n#include \"params\/Root.hh\"\n#include \"sim\/sim_object.hh\"\n\n\/\/ Dummy Object\nstruct Root : public SimObject\n{\n Root(RootParams *params) : SimObject(params) {}\n};\n\nRoot *\nRootParams::create()\n{\n static bool created = false;\n if (created)\n panic(\"only one root object allowed!\");\n\n created = true;\n\n return new Root(this);\n}\nRoot: Get rid of unnecessary includes in root.cc.\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\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: 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 copyright holders 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 * Authors: Nathan Binkert\n * Steve Reinhardt\n *\/\n\n#include \"base\/misc.hh\"\n#include \"params\/Root.hh\"\n#include \"sim\/sim_object.hh\"\n\n\/\/ Dummy Object\nstruct Root : public SimObject\n{\n Root(RootParams *params) : SimObject(params) {}\n};\n\nRoot *\nRootParams::create()\n{\n static bool created = false;\n if (created)\n panic(\"only one root object allowed!\");\n\n created = true;\n\n return new Root(this);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\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** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \n\n#if defined(HAVE_WIDGETS)\n#include \n#endif\n\n#include \"qgstreamerplayerservice.h\"\n#include \"qgstreamerplayercontrol.h\"\n#include \"qgstreamerplayersession.h\"\n#include \"qgstreamermetadataprovider.h\"\n#include \"qgstreameravailabilitycontrol.h\"\n\n#if defined(HAVE_WIDGETS)\n#include \n#include \n#include \n#endif\n\n#include \n\n#if defined(Q_WS_MAEMO_6) && defined(__arm__)\n#include \"private\/qgstreamergltexturerenderer.h\"\n#endif\n\n#if defined(HAVE_MIR) && defined (__arm__)\n#include \"private\/qgstreamermirtexturerenderer_p.h\"\n#endif\n\n#include \"qgstreamerstreamscontrol.h\"\n#include \n#include \n\n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nQGstreamerPlayerService::QGstreamerPlayerService(QObject *parent):\n QMediaService(parent)\n , m_videoOutput(0)\n , m_videoRenderer(0)\n#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)\n , m_videoWindow(0)\n , m_videoWidget(0)\n#endif\n , m_videoReferenceCount(0)\n{\n m_session = new QGstreamerPlayerSession(this);\n m_control = new QGstreamerPlayerControl(m_session, this);\n m_metaData = new QGstreamerMetaDataProvider(m_session, this);\n m_streamsControl = new QGstreamerStreamsControl(m_session,this);\n m_availabilityControl = new QGStreamerAvailabilityControl(m_control->resources(), this);\n\n#if defined(Q_WS_MAEMO_6) && defined(__arm__)\n m_videoRenderer = new QGstreamerGLTextureRenderer(this);\n\/\/ TODO: Implement HAVE_UBUNTU_TOUCH configure check and remove QGstreamerMirTextureRenderer from the else case\n#elif defined(HAVE_MIR) && defined (__arm__)\n m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session);\n#else\n \/\/m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session);\n m_videoRenderer = new QGstreamerVideoRenderer(this);\n#endif\n\n#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)\n#ifdef Q_WS_MAEMO_6\n m_videoWindow = new QGstreamerVideoWindow(this, \"omapxvsink\");\n\/\/ TODO: Implement Q_WS_UBUNTU_TOUCH configure check and remove mirsink from the else case\n\/\/#elif defined(HAVE_MIR)\n\/\/ m_videoWindow = new QGstreamerVideoWindow(this, \"mirsink\");\n#else\n qDebug() << \"Creating new QGstreamerVideoWindow, passing 'this'\" << endl;\n \/\/m_videoWindow = new QGstreamerVideoWindow(this, \"mirsink\");\n m_videoWindow = new QGstreamerVideoOverlay(this);\n#endif\n m_videoWidget = new QGstreamerVideoWidgetControl(this);\n#endif\n}\n\nQGstreamerPlayerService::~QGstreamerPlayerService()\n{\n}\n\nQMediaControl *QGstreamerPlayerService::requestControl(const char *name)\n{\n if (qstrcmp(name,QMediaPlayerControl_iid) == 0)\n return m_control;\n\n if (qstrcmp(name,QMetaDataReaderControl_iid) == 0)\n return m_metaData;\n\n if (qstrcmp(name,QMediaStreamsControl_iid) == 0)\n return m_streamsControl;\n\n if (qstrcmp(name, QMediaAvailabilityControl_iid) == 0)\n return m_availabilityControl;\n\n if (qstrcmp(name,QMediaVideoProbeControl_iid) == 0) {\n if (m_session) {\n QGstreamerVideoProbeControl *probe = new QGstreamerVideoProbeControl(this);\n increaseVideoRef();\n m_session->addProbe(probe);\n return probe;\n }\n return 0;\n }\n\n if (qstrcmp(name,QMediaAudioProbeControl_iid) == 0) {\n if (m_session) {\n QGstreamerAudioProbeControl *probe = new QGstreamerAudioProbeControl(this);\n m_session->addProbe(probe);\n return probe;\n }\n return 0;\n }\n\n if (!m_videoOutput) {\n if (qstrcmp(name, QVideoRendererControl_iid) == 0)\n m_videoOutput = m_videoRenderer;\n#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)\n else if (qstrcmp(name, QVideoWidgetControl_iid) == 0)\n m_videoOutput = m_videoWidget;\n else if (qstrcmp(name, QVideoWindowControl_iid) == 0)\n m_videoOutput = m_videoWindow;\n#endif\n\n if (m_videoOutput) {\n increaseVideoRef();\n m_control->setVideoOutput(m_videoOutput);\n return m_videoOutput;\n }\n }\n\n return 0;\n}\n\nvoid QGstreamerPlayerService::releaseControl(QMediaControl *control)\n{\n if (control == m_videoOutput) {\n m_videoOutput = 0;\n m_control->setVideoOutput(0);\n decreaseVideoRef();\n }\n\n QGstreamerVideoProbeControl* videoProbe = qobject_cast(control);\n if (videoProbe) {\n if (m_session) {\n m_session->removeProbe(videoProbe);\n decreaseVideoRef();\n }\n delete videoProbe;\n return;\n }\n\n QGstreamerAudioProbeControl* audioProbe = qobject_cast(control);\n if (audioProbe) {\n if (m_session)\n m_session->removeProbe(audioProbe);\n delete audioProbe;\n return;\n }\n}\n\nvoid QGstreamerPlayerService::increaseVideoRef()\n{\n m_videoReferenceCount++;\n if (m_videoReferenceCount == 1) {\n m_control->resources()->setVideoEnabled(true);\n }\n}\n\nvoid QGstreamerPlayerService::decreaseVideoRef()\n{\n m_videoReferenceCount--;\n if (m_videoReferenceCount == 0) {\n m_control->resources()->setVideoEnabled(false);\n }\n}\n\nQT_END_NAMESPACE\nClean up the renderer choosing code after adding support for creating a QGstreamerMirTextureRenderer instance.\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\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** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n#include \n\n#if defined(HAVE_WIDGETS)\n#include \n#endif\n\n#include \"qgstreamerplayerservice.h\"\n#include \"qgstreamerplayercontrol.h\"\n#include \"qgstreamerplayersession.h\"\n#include \"qgstreamermetadataprovider.h\"\n#include \"qgstreameravailabilitycontrol.h\"\n\n#if defined(HAVE_WIDGETS)\n#include \n#include \n#include \n#endif\n\n#include \n\n#if defined(Q_WS_MAEMO_6) && defined(__arm__)\n#include \"private\/qgstreamergltexturerenderer.h\"\n#endif\n\n#if defined(HAVE_MIR) && defined (__arm__)\n#include \"private\/qgstreamermirtexturerenderer_p.h\"\n#endif\n\n#include \"qgstreamerstreamscontrol.h\"\n#include \n#include \n\n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nQGstreamerPlayerService::QGstreamerPlayerService(QObject *parent):\n QMediaService(parent)\n , m_videoOutput(0)\n , m_videoRenderer(0)\n#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)\n , m_videoWindow(0)\n , m_videoWidget(0)\n#endif\n , m_videoReferenceCount(0)\n{\n m_session = new QGstreamerPlayerSession(this);\n m_control = new QGstreamerPlayerControl(m_session, this);\n m_metaData = new QGstreamerMetaDataProvider(m_session, this);\n m_streamsControl = new QGstreamerStreamsControl(m_session,this);\n m_availabilityControl = new QGStreamerAvailabilityControl(m_control->resources(), this);\n\n#if defined(Q_WS_MAEMO_6) && defined(__arm__)\n m_videoRenderer = new QGstreamerGLTextureRenderer(this);\n#elif defined(HAVE_MIR) && defined (__arm__)\n m_videoRenderer = new QGstreamerMirTextureRenderer(this, m_session);\n#else\n m_videoRenderer = new QGstreamerVideoRenderer(this);\n#endif\n\n#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)\n#ifdef Q_WS_MAEMO_6\n m_videoWindow = new QGstreamerVideoWindow(this, \"omapxvsink\");\n#else\n m_videoWindow = new QGstreamerVideoOverlay(this);\n#endif\n m_videoWidget = new QGstreamerVideoWidgetControl(this);\n#endif\n}\n\nQGstreamerPlayerService::~QGstreamerPlayerService()\n{\n}\n\nQMediaControl *QGstreamerPlayerService::requestControl(const char *name)\n{\n if (qstrcmp(name,QMediaPlayerControl_iid) == 0)\n return m_control;\n\n if (qstrcmp(name,QMetaDataReaderControl_iid) == 0)\n return m_metaData;\n\n if (qstrcmp(name,QMediaStreamsControl_iid) == 0)\n return m_streamsControl;\n\n if (qstrcmp(name, QMediaAvailabilityControl_iid) == 0)\n return m_availabilityControl;\n\n if (qstrcmp(name,QMediaVideoProbeControl_iid) == 0) {\n if (m_session) {\n QGstreamerVideoProbeControl *probe = new QGstreamerVideoProbeControl(this);\n increaseVideoRef();\n m_session->addProbe(probe);\n return probe;\n }\n return 0;\n }\n\n if (qstrcmp(name,QMediaAudioProbeControl_iid) == 0) {\n if (m_session) {\n QGstreamerAudioProbeControl *probe = new QGstreamerAudioProbeControl(this);\n m_session->addProbe(probe);\n return probe;\n }\n return 0;\n }\n\n if (!m_videoOutput) {\n if (qstrcmp(name, QVideoRendererControl_iid) == 0)\n m_videoOutput = m_videoRenderer;\n#if defined(HAVE_XVIDEO) && defined(HAVE_WIDGETS)\n else if (qstrcmp(name, QVideoWidgetControl_iid) == 0)\n m_videoOutput = m_videoWidget;\n else if (qstrcmp(name, QVideoWindowControl_iid) == 0)\n m_videoOutput = m_videoWindow;\n#endif\n\n if (m_videoOutput) {\n increaseVideoRef();\n m_control->setVideoOutput(m_videoOutput);\n return m_videoOutput;\n }\n }\n\n return 0;\n}\n\nvoid QGstreamerPlayerService::releaseControl(QMediaControl *control)\n{\n if (control == m_videoOutput) {\n m_videoOutput = 0;\n m_control->setVideoOutput(0);\n decreaseVideoRef();\n }\n\n QGstreamerVideoProbeControl* videoProbe = qobject_cast(control);\n if (videoProbe) {\n if (m_session) {\n m_session->removeProbe(videoProbe);\n decreaseVideoRef();\n }\n delete videoProbe;\n return;\n }\n\n QGstreamerAudioProbeControl* audioProbe = qobject_cast(control);\n if (audioProbe) {\n if (m_session)\n m_session->removeProbe(audioProbe);\n delete audioProbe;\n return;\n }\n}\n\nvoid QGstreamerPlayerService::increaseVideoRef()\n{\n m_videoReferenceCount++;\n if (m_videoReferenceCount == 1) {\n m_control->resources()->setVideoEnabled(true);\n }\n}\n\nvoid QGstreamerPlayerService::decreaseVideoRef()\n{\n m_videoReferenceCount--;\n if (m_videoReferenceCount == 0) {\n m_control->resources()->setVideoEnabled(false);\n }\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nAlvarLoggerNode::AlvarLoggerNode(ros::NodeHandle &nh) : nh_(nh), it_(nh), frame_number_(0)\n{\n std::string camera_info_topic;\n if (!nh_.getParam(\"camera_info_topic\", camera_info_topic))\n {\n ROS_ERROR(\"Camera info topic needs to be specified\");\n exit(0);\n }\n\n cam_ = new alvar::Camera(nh_, camera_info_topic);\n\n std::string log_file_name;\n if (!nh_.getParam(\"log_file\", log_file_name))\n {\n ROS_ERROR(\"Log file needs to be specified\");\n exit(0);\n }\n \n if (!nh_.hasParam(\"video_file\"))\n {\n ROS_ERROR(\"Video file needs to be specified\");\n exit(0);\n }\n\n file_out_.open(log_file_name.c_str());\n\n image_publisher_ = it_.advertise(\"detected_markers\", 1);\n image_subscriber_ = it_.subscribe(\"input_image\", 0, &AlvarLoggerNode::imageCallback, this);\n}\n\nAlvarLoggerNode::~AlvarLoggerNode()\n{\n file_out_.close();\n delete cam_;\n}\n\nvoid AlvarLoggerNode::imageCallback(const sensor_msgs::ImageConstPtr &image)\n{ \n if (cam_->getCamInfo_)\n {\n if (!video_writer_.isOpened())\n {\n cv::Size image_size(image->width, image->height);\n double frame_rate = 30.0;\n std::string video_file_name;\n nh_.getParam(\"video_file\", video_file_name);\n video_writer_.open(video_file_name, CV_FOURCC('D','I','V','X'), frame_rate, image_size, true);\n }\n cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);\n IplImage ipl_image = cv_image->image;\n marker_detector_.Detect(&ipl_image, cam_); \n\n video_writer_.write(cv_image->image);\n\n cv::Mat debug_image;\n cv_image->image.copyTo(debug_image);\n\n for (size_t i = 0; i < marker_detector_.markers->size(); i++)\n {\n int id = (*(marker_detector_.markers))[i].GetId();\n std::vector marker_corners = (*(marker_detector_.markers))[i].marker_corners_img;\n for (int i = 0; i < marker_corners.size() - 1; i++)\n {\n cv::Point start_point(marker_corners.at(i).x, marker_corners.at(i).y);\n cv::Point end_point(marker_corners.at(i + 1).x, marker_corners.at(i + 1).y);\n cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);\n if (i == 0)\n {\n file_out_ << id << \", \" << frame_number_ << \", \" << start_point.x << \", \" << start_point.y;\n }\n else\n {\n file_out_ << \", \" << start_point.x << \", \" << start_point.y;\n }\n }\n cv::Point start_point(marker_corners.at(marker_corners.size() - 1).x, marker_corners.at(marker_corners.size() - 1).y);\n cv::Point end_point(marker_corners.at(0).x, marker_corners.at(0).y);\n cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);\n file_out_ << \", \" << start_point.x << \", \" << start_point.y << std::endl;\n }\n cv_bridge::CvImage debug_image_msg;\n debug_image_msg.encoding = sensor_msgs::image_encodings::BGR8;\n debug_image_msg.image = debug_image;\n image_publisher_.publish(debug_image_msg.toImageMsg());\n }\n \n frame_number_++;\n}\n\nint main(int argc, char **argv)\n{ \n ros::init(argc, argv, \"alvar_logger\");\n\n ros::NodeHandle n(\"~\");\n\n ROS_INFO(\"[alvar_logger] node started\");\n\n AlvarLoggerNode alvar_logger_node(n); \n\n ros::spin();\n\n return 0;\n}\nlog frame id first then marker id#include \n#include \n#include \n\nAlvarLoggerNode::AlvarLoggerNode(ros::NodeHandle &nh) : nh_(nh), it_(nh), frame_number_(0)\n{\n std::string camera_info_topic;\n if (!nh_.getParam(\"camera_info_topic\", camera_info_topic))\n {\n ROS_ERROR(\"Camera info topic needs to be specified\");\n exit(0);\n }\n\n cam_ = new alvar::Camera(nh_, camera_info_topic);\n\n std::string log_file_name;\n if (!nh_.getParam(\"log_file\", log_file_name))\n {\n ROS_ERROR(\"Log file needs to be specified\");\n exit(0);\n }\n \n if (!nh_.hasParam(\"video_file\"))\n {\n ROS_ERROR(\"Video file needs to be specified\");\n exit(0);\n }\n\n file_out_.open(log_file_name.c_str());\n\n image_publisher_ = it_.advertise(\"detected_markers\", 1);\n image_subscriber_ = it_.subscribe(\"input_image\", 0, &AlvarLoggerNode::imageCallback, this);\n}\n\nAlvarLoggerNode::~AlvarLoggerNode()\n{\n file_out_.close();\n delete cam_;\n}\n\nvoid AlvarLoggerNode::imageCallback(const sensor_msgs::ImageConstPtr &image)\n{ \n if (cam_->getCamInfo_)\n {\n if (!video_writer_.isOpened())\n {\n cv::Size image_size(image->width, image->height);\n double frame_rate = 30.0;\n std::string video_file_name;\n nh_.getParam(\"video_file\", video_file_name);\n video_writer_.open(video_file_name, CV_FOURCC('D','I','V','X'), frame_rate, image_size, true);\n }\n cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);\n IplImage ipl_image = cv_image->image;\n marker_detector_.Detect(&ipl_image, cam_); \n\n video_writer_.write(cv_image->image);\n\n cv::Mat debug_image;\n cv_image->image.copyTo(debug_image);\n\n for (size_t i = 0; i < marker_detector_.markers->size(); i++)\n {\n int id = (*(marker_detector_.markers))[i].GetId();\n std::vector marker_corners = (*(marker_detector_.markers))[i].marker_corners_img;\n for (int i = 0; i < marker_corners.size() - 1; i++)\n {\n cv::Point start_point(marker_corners.at(i).x, marker_corners.at(i).y);\n cv::Point end_point(marker_corners.at(i + 1).x, marker_corners.at(i + 1).y);\n cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);\n if (i == 0)\n {\n file_out_ << frame_number_ << \", \" << id << \", \" << start_point.x << \", \" << start_point.y;\n }\n else\n {\n file_out_ << \", \" << start_point.x << \", \" << start_point.y;\n }\n }\n cv::Point start_point(marker_corners.at(marker_corners.size() - 1).x, marker_corners.at(marker_corners.size() - 1).y);\n cv::Point end_point(marker_corners.at(0).x, marker_corners.at(0).y);\n cv::line(debug_image, start_point, end_point, CV_RGB(255, 0, 0), 3, CV_AA, 0);\n file_out_ << \", \" << start_point.x << \", \" << start_point.y << std::endl;\n }\n cv_bridge::CvImage debug_image_msg;\n debug_image_msg.encoding = sensor_msgs::image_encodings::BGR8;\n debug_image_msg.image = debug_image;\n image_publisher_.publish(debug_image_msg.toImageMsg());\n }\n \n frame_number_++;\n}\n\nint main(int argc, char **argv)\n{ \n ros::init(argc, argv, \"alvar_logger\");\n\n ros::NodeHandle n(\"~\");\n\n ROS_INFO(\"[alvar_logger] node started\");\n\n AlvarLoggerNode alvar_logger_node(n); \n\n ros::spin();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkInstantiator.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 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 \"vtkInstantiator.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkDebugLeaks.h\"\n\nvtkCxxRevisionMacro(vtkInstantiator, \"1.4\");\nvtkStandardNewMacro(vtkInstantiator);\n\n\/\/ Node in hash table.\nclass vtkInstantiatorHashNode\n{\npublic:\n typedef vtkInstantiator::CreateFunction CreateFunction;\n \n vtkInstantiatorHashNode() { this->ClassName = 0; this->Function = 0; }\n \n void SetClassName(const char* className) { this->ClassName = className; } \n const char* GetClassName() { return this->ClassName; }\n \n void SetFunction(CreateFunction function) { this->Function = function; }\n CreateFunction GetFunction() { return this->Function; }\n \nprivate:\n const char* ClassName;\n CreateFunction Function;\n};\n\n\/\/ Hash table used by vtkInstantiator.\nclass vtkInstantiatorHashTable : public vtkObject\n{\npublic:\n vtkTypeRevisionMacro(vtkInstantiatorHashTable,vtkObject);\n void PrintSelf(ostream& os, vtkIndent indent); \n \n static vtkInstantiatorHashTable* New();\n \n typedef vtkInstantiator::CreateFunction CreateFunction;\n void Insert(const char* className, CreateFunction function);\n void Erase(const char* className, CreateFunction function);\n CreateFunction Find(const char* className);\n \nprotected:\n vtkInstantiatorHashTable();\n ~vtkInstantiatorHashTable();\n \n unsigned long Hash(const char* s);\n void ExtendBucket(unsigned long bucket);\n const char* AddClassName(const char* className);\n \n vtkInstantiatorHashNode** Buckets;\n unsigned int* BucketCounts;\n unsigned int* BucketSizes;\n unsigned long NumberOfBuckets;\n char** ClassNames;\n unsigned long NumberOfClassNames;\n unsigned long ClassNamesSize;\n \nprivate:\n vtkInstantiatorHashTable(const vtkInstantiatorHashTable&); \/\/ Not implemented.\n void operator=(const vtkInstantiatorHashTable&); \/\/ Not implemented.\n};\n\nvtkCxxRevisionMacro(vtkInstantiatorHashTable, \"1.4\");\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorHashTable* vtkInstantiatorHashTable::New()\n{\n#ifdef VTK_DEBUG_LEAKS\n vtkDebugLeaks::ConstructClass(\"vtkInstantiatorHashTable\");\n#endif \n \/\/ Don't use the object factory because it may not have been\n \/\/ initialized when this table is allocated.\n return new vtkInstantiatorHashTable;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorHashTable::vtkInstantiatorHashTable()\n{\n this->NumberOfBuckets = 101;\n this->Buckets = new vtkInstantiatorHashNode*[this->NumberOfBuckets];\n this->BucketCounts = new unsigned int[this->NumberOfBuckets];\n this->BucketSizes = new unsigned int[this->NumberOfBuckets];\n \n unsigned int i;\n for(i=0;i < this->NumberOfBuckets;++i)\n {\n this->BucketCounts[i] = 0;\n this->BucketSizes[i] = 16;\n this->Buckets[i] = new vtkInstantiatorHashNode[this->BucketSizes[i]];\n }\n \n this->NumberOfClassNames = 0;\n this->ClassNamesSize = 256;\n this->ClassNames = new char*[this->ClassNamesSize];\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorHashTable::~vtkInstantiatorHashTable()\n{\n unsigned long i;\n for(i=0; i < this->NumberOfBuckets;++i)\n {\n delete [] this->Buckets[i];\n }\n delete [] this->BucketSizes;\n delete [] this->BucketCounts;\n delete [] this->Buckets; \n \n for(i=0;i < this->NumberOfClassNames;++i)\n {\n delete [] this->ClassNames[i];\n }\n delete [] this->ClassNames;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkObject::PrintSelf(os, indent);\n os << indent << \"NumberOfBuckets: \" << this->NumberOfBuckets << \"\\n\";\n unsigned int i;\n float avgBucketSize = 0;\n unsigned int maxBucketSize = 0;\n unsigned int minBucketSize = this->NumberOfClassNames;\n for(i=0;i < this->NumberOfBuckets;++i)\n {\n avgBucketSize += this->BucketCounts[i];\n if(this->BucketCounts[i] > maxBucketSize)\n { maxBucketSize = this->BucketCounts[i]; }\n if(this->BucketCounts[i] < minBucketSize)\n { minBucketSize = this->BucketCounts[i]; }\n }\n avgBucketSize \/= float(this->NumberOfBuckets);\n os << indent << \"Average Bucket Size: \" << avgBucketSize << \"\\n\";\n os << indent << \"Minimum Bucket Size: \" << minBucketSize << \"\\n\";\n os << indent << \"Maximum Bucket Size: \" << maxBucketSize << \"\\n\";\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::Insert(const char* className,\n CreateFunction function)\n{\n unsigned long bucket = this->Hash(className);\n \n if(this->BucketCounts[bucket] == this->BucketSizes[bucket])\n { this->ExtendBucket(bucket); }\n \n \/\/ Do not check if the class is already registered. It is possible\n \/\/ that more than one create function will be registered for the\n \/\/ same class, and even that the same function is registered more\n \/\/ than once. Each register should have a corresponding unregister.\n \/\/ As long as any register has not had its corresponding unregister,\n \/\/ we want to allow the class to be created.\n unsigned int pos = this->BucketCounts[bucket]++;\n this->Buckets[bucket][pos].SetClassName(this->AddClassName(className));\n this->Buckets[bucket][pos].SetFunction(function);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::Erase(const char* className,\n CreateFunction function)\n{\n unsigned long bucket = this->Hash(className);\n \n \/\/ Find the exact registration function we have been given, and\n \/\/ remove it only once. If more than one funcion has been\n \/\/ registered for this class, or the same function more than once,\n \/\/ each register should have its corresponding unregister.\n unsigned int i;\n for(i=0; i < this->BucketCounts[bucket];++i)\n {\n if(((this->Buckets[bucket][i].GetFunction() == function)\n && (strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)))\n {\n unsigned int j;\n --this->BucketCounts[bucket];\n for(j=i;j < this->BucketCounts[bucket];++j)\n {\n this->Buckets[bucket][j] = this->Buckets[bucket][j+1];\n }\n return;\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorHashTable::CreateFunction\nvtkInstantiatorHashTable::Find(const char* className)\n{\n unsigned long bucket = this->Hash(className);\n \n unsigned int i;\n for(i=0; i < this->BucketCounts[bucket];++i)\n {\n if(strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)\n { return this->Buckets[bucket][i].GetFunction(); }\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned long vtkInstantiatorHashTable::Hash(const char* s)\n{\n unsigned long h = 0;\n for(;*s;++s) { h = 5*h + *s; }\n return h % this->NumberOfBuckets;\n}\n \n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::ExtendBucket(unsigned long bucket)\n{\n unsigned int newSize = this->BucketSizes[bucket] * 2;\n \n vtkInstantiatorHashNode* newBucket =\n new vtkInstantiatorHashNode[newSize];\n \n unsigned int i;\n for(i=0; i < this->BucketCounts[bucket];++i)\n { newBucket[i] = this->Buckets[bucket][i]; }\n \n delete [] this->Buckets[bucket];\n this->Buckets[bucket] = newBucket;\n this->BucketSizes[bucket] = newSize;\n}\n \n\/\/----------------------------------------------------------------------------\nconst char* vtkInstantiatorHashTable::AddClassName(const char* className)\n{\n if(this->NumberOfClassNames == this->ClassNamesSize)\n {\n unsigned long newSize = this->ClassNamesSize * 2;\n char** newNames = new char*[newSize];\n \n unsigned long i;\n for(i=0;i < this->NumberOfClassNames;++i)\n { newNames[i] = this->ClassNames[i]; }\n \n delete [] this->ClassNames;\n this->ClassNames = newNames;\n this->ClassNamesSize = newSize;\n }\n \n char* newName = new char[strlen(className)+1];\n strcpy(newName, className);\n this->ClassNames[this->NumberOfClassNames++] = newName;\n \n return newName;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Implementation of actual vtkInstantiator class.\n\/\/----------------------------------------------------------------------------\nvtkInstantiator::vtkInstantiator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiator::~vtkInstantiator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n vtkInstantiator::CreatorTable->PrintSelf(os, indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkObject* vtkInstantiator::CreateInstance(const char* className)\n{\n CreateFunction function = vtkInstantiator::CreatorTable->Find(className);\n if(function) { return function(); }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::RegisterInstantiator(const char* className,\n CreateFunction createFunction)\n{\n vtkInstantiator::CreatorTable->Insert(className, createFunction);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::UnRegisterInstantiator(const char* className,\n CreateFunction createFunction)\n{\n vtkInstantiator::CreatorTable->Erase(className, createFunction);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::ClassInitialize()\n{\n vtkInstantiator::CreatorTable = vtkInstantiatorHashTable::New();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::ClassFinalize()\n{\n vtkInstantiator::CreatorTable->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorInitialize::vtkInstantiatorInitialize()\n{\n if(++vtkInstantiatorInitialize::Count == 1)\n { vtkInstantiator::ClassInitialize(); }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorInitialize::~vtkInstantiatorInitialize()\n{\n if(--vtkInstantiatorInitialize::Count == 0)\n { vtkInstantiator::ClassFinalize(); }\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkInstantiatorInitialize::Count;\nvtkInstantiatorHashTable* vtkInstantiator::CreatorTable;\nBUG: vtkInstantiatorHashTable must not be a subclass of vtkObject because vtkObject's constructor touches vtkTimeStamp's global, which may not yet be initialized by the time vtkInstantiatorHashTable is constructed (on certain platforms).\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkInstantiator.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 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 \"vtkInstantiator.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkCxxRevisionMacro(vtkInstantiator, \"1.5\");\nvtkStandardNewMacro(vtkInstantiator);\n\n\/\/ Node in hash table.\nclass vtkInstantiatorHashNode\n{\npublic:\n typedef vtkInstantiator::CreateFunction CreateFunction;\n \n vtkInstantiatorHashNode() { this->ClassName = 0; this->Function = 0; }\n \n void SetClassName(const char* className) { this->ClassName = className; } \n const char* GetClassName() { return this->ClassName; }\n \n void SetFunction(CreateFunction function) { this->Function = function; }\n CreateFunction GetFunction() { return this->Function; }\n \nprivate:\n const char* ClassName;\n CreateFunction Function;\n};\n\n\/\/ Hash table used by vtkInstantiator. Must not be a vtkObject.\nclass vtkInstantiatorHashTable\n{\npublic:\n vtkInstantiatorHashTable();\n ~vtkInstantiatorHashTable();\n \n void PrintSelf(ostream& os, vtkIndent indent); \n \n typedef vtkInstantiator::CreateFunction CreateFunction;\n void Insert(const char* className, CreateFunction function);\n void Erase(const char* className, CreateFunction function);\n CreateFunction Find(const char* className);\n \nprotected:\n unsigned long Hash(const char* s);\n void ExtendBucket(unsigned long bucket);\n const char* AddClassName(const char* className);\n \n vtkInstantiatorHashNode** Buckets;\n unsigned int* BucketCounts;\n unsigned int* BucketSizes;\n unsigned long NumberOfBuckets;\n char** ClassNames;\n unsigned long NumberOfClassNames;\n unsigned long ClassNamesSize;\n \nprivate:\n vtkInstantiatorHashTable(const vtkInstantiatorHashTable&); \/\/ Not implemented.\n void operator=(const vtkInstantiatorHashTable&); \/\/ Not implemented.\n};\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorHashTable::vtkInstantiatorHashTable()\n{\n this->NumberOfBuckets = 101;\n this->Buckets = new vtkInstantiatorHashNode*[this->NumberOfBuckets];\n this->BucketCounts = new unsigned int[this->NumberOfBuckets];\n this->BucketSizes = new unsigned int[this->NumberOfBuckets];\n \n unsigned int i;\n for(i=0;i < this->NumberOfBuckets;++i)\n {\n this->BucketCounts[i] = 0;\n this->BucketSizes[i] = 16;\n this->Buckets[i] = new vtkInstantiatorHashNode[this->BucketSizes[i]];\n }\n \n this->NumberOfClassNames = 0;\n this->ClassNamesSize = 256;\n this->ClassNames = new char*[this->ClassNamesSize];\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorHashTable::~vtkInstantiatorHashTable()\n{\n unsigned long i;\n for(i=0; i < this->NumberOfBuckets;++i)\n {\n delete [] this->Buckets[i];\n }\n delete [] this->BucketSizes;\n delete [] this->BucketCounts;\n delete [] this->Buckets; \n \n for(i=0;i < this->NumberOfClassNames;++i)\n {\n delete [] this->ClassNames[i];\n }\n delete [] this->ClassNames;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::PrintSelf(ostream& os, vtkIndent indent)\n{\n os << indent << \"NumberOfBuckets: \" << this->NumberOfBuckets << \"\\n\";\n unsigned int i;\n float avgBucketSize = 0;\n unsigned int maxBucketSize = 0;\n unsigned int minBucketSize = this->NumberOfClassNames;\n for(i=0;i < this->NumberOfBuckets;++i)\n {\n avgBucketSize += this->BucketCounts[i];\n if(this->BucketCounts[i] > maxBucketSize)\n { maxBucketSize = this->BucketCounts[i]; }\n if(this->BucketCounts[i] < minBucketSize)\n { minBucketSize = this->BucketCounts[i]; }\n }\n avgBucketSize \/= float(this->NumberOfBuckets);\n os << indent << \"Average Bucket Size: \" << avgBucketSize << \"\\n\";\n os << indent << \"Minimum Bucket Size: \" << minBucketSize << \"\\n\";\n os << indent << \"Maximum Bucket Size: \" << maxBucketSize << \"\\n\";\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::Insert(const char* className,\n CreateFunction function)\n{\n unsigned long bucket = this->Hash(className);\n \n if(this->BucketCounts[bucket] == this->BucketSizes[bucket])\n { this->ExtendBucket(bucket); }\n \n \/\/ Do not check if the class is already registered. It is possible\n \/\/ that more than one create function will be registered for the\n \/\/ same class, and even that the same function is registered more\n \/\/ than once. Each register should have a corresponding unregister.\n \/\/ As long as any register has not had its corresponding unregister,\n \/\/ we want to allow the class to be created.\n unsigned int pos = this->BucketCounts[bucket]++;\n this->Buckets[bucket][pos].SetClassName(this->AddClassName(className));\n this->Buckets[bucket][pos].SetFunction(function);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::Erase(const char* className,\n CreateFunction function)\n{\n unsigned long bucket = this->Hash(className);\n \n \/\/ Find the exact registration function we have been given, and\n \/\/ remove it only once. If more than one funcion has been\n \/\/ registered for this class, or the same function more than once,\n \/\/ each register should have its corresponding unregister.\n unsigned int i;\n for(i=0; i < this->BucketCounts[bucket];++i)\n {\n if(((this->Buckets[bucket][i].GetFunction() == function)\n && (strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)))\n {\n unsigned int j;\n --this->BucketCounts[bucket];\n for(j=i;j < this->BucketCounts[bucket];++j)\n {\n this->Buckets[bucket][j] = this->Buckets[bucket][j+1];\n }\n return;\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorHashTable::CreateFunction\nvtkInstantiatorHashTable::Find(const char* className)\n{\n unsigned long bucket = this->Hash(className);\n \n unsigned int i;\n for(i=0; i < this->BucketCounts[bucket];++i)\n {\n if(strcmp(this->Buckets[bucket][i].GetClassName(), className) == 0)\n { return this->Buckets[bucket][i].GetFunction(); }\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned long vtkInstantiatorHashTable::Hash(const char* s)\n{\n unsigned long h = 0;\n for(;*s;++s) { h = 5*h + *s; }\n return h % this->NumberOfBuckets;\n}\n \n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiatorHashTable::ExtendBucket(unsigned long bucket)\n{\n unsigned int newSize = this->BucketSizes[bucket] * 2;\n \n vtkInstantiatorHashNode* newBucket =\n new vtkInstantiatorHashNode[newSize];\n \n unsigned int i;\n for(i=0; i < this->BucketCounts[bucket];++i)\n { newBucket[i] = this->Buckets[bucket][i]; }\n \n delete [] this->Buckets[bucket];\n this->Buckets[bucket] = newBucket;\n this->BucketSizes[bucket] = newSize;\n}\n \n\/\/----------------------------------------------------------------------------\nconst char* vtkInstantiatorHashTable::AddClassName(const char* className)\n{\n if(this->NumberOfClassNames == this->ClassNamesSize)\n {\n unsigned long newSize = this->ClassNamesSize * 2;\n char** newNames = new char*[newSize];\n \n unsigned long i;\n for(i=0;i < this->NumberOfClassNames;++i)\n { newNames[i] = this->ClassNames[i]; }\n \n delete [] this->ClassNames;\n this->ClassNames = newNames;\n this->ClassNamesSize = newSize;\n }\n \n char* newName = new char[strlen(className)+1];\n strcpy(newName, className);\n this->ClassNames[this->NumberOfClassNames++] = newName;\n \n return newName;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Implementation of actual vtkInstantiator class.\n\/\/----------------------------------------------------------------------------\nvtkInstantiator::vtkInstantiator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiator::~vtkInstantiator()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n vtkInstantiator::CreatorTable->PrintSelf(os, indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkObject* vtkInstantiator::CreateInstance(const char* className)\n{\n CreateFunction function = vtkInstantiator::CreatorTable->Find(className);\n if(function) { return function(); }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::RegisterInstantiator(const char* className,\n CreateFunction createFunction)\n{\n vtkInstantiator::CreatorTable->Insert(className, createFunction);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::UnRegisterInstantiator(const char* className,\n CreateFunction createFunction)\n{\n vtkInstantiator::CreatorTable->Erase(className, createFunction);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::ClassInitialize()\n{\n vtkInstantiator::CreatorTable = new vtkInstantiatorHashTable;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkInstantiator::ClassFinalize()\n{\n delete vtkInstantiator::CreatorTable;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorInitialize::vtkInstantiatorInitialize()\n{\n if(++vtkInstantiatorInitialize::Count == 1)\n { vtkInstantiator::ClassInitialize(); }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkInstantiatorInitialize::~vtkInstantiatorInitialize()\n{\n if(--vtkInstantiatorInitialize::Count == 0)\n { vtkInstantiator::ClassFinalize(); }\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned int vtkInstantiatorInitialize::Count;\nvtkInstantiatorHashTable* vtkInstantiator::CreatorTable;\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: global.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 13:09:53 $\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 GLOBAL_HXX_INCLUDED\n#define GLOBAL_HXX_INCLUDED\n\n#if defined _MSC_VER\n#pragma warning(push, 1)\n#endif\n#ifndef OS2\n#include \n#endif\n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\n#ifndef DBGMACROS_HXX_INCLUDED\n#include \"internal\/dbgmacros.hxx\"\n#endif\n\nextern long g_DllRefCnt;\n\n#endif\nINTEGRATION: CWS changefileheader (1.5.40); FILE MERGED 2008\/04\/01 12:41:07 thb 1.5.40.2: #i85898# Stripping all external header guards 2008\/03\/31 13:17:04 rt 1.5.40.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: global.hxx,v $\n * $Revision: 1.6 $\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 GLOBAL_HXX_INCLUDED\n#define GLOBAL_HXX_INCLUDED\n\n#if defined _MSC_VER\n#pragma warning(push, 1)\n#endif\n#ifndef OS2\n#include \n#endif\n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n#include \"internal\/dbgmacros.hxx\"\n\nextern long g_DllRefCnt;\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file dt_main.cpp\n * @ Parikshit Ram (pram@cc.gatech.edu)\n *\n * This file provides an example use of the DET\n *\/\n\n#include \n#include \"dt_utils.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::det;\nusing namespace std;\n\nPROGRAM_INFO(\"Density estimation with DET\", \"This program \"\n \"provides an example use of the Density Estimation \"\n\t \"Tree for density estimation. For more details, \"\n\t \"please look at the paper titled \"\n\t \"'Density Estimation Trees'.\");\n\n\/\/ input data files\nPARAM_STRING_REQ(\"input\/training_set\", \"The data set on which to \"\n\t\t \"perform density estimation.\", \"S\");\nPARAM_STRING(\"input\/test_set\", \"An extra set of test points on \"\n\t \"which to estimate the density given the estimator.\",\n\t \"T\", \"\");\nPARAM_STRING(\"input\/labels\", \"The labels for the given training data to \"\n\t \"generate the class membership of each leaf (as an \"\n\t \"extra statistic)\", \"L\", \"\");\n\n\/\/ output data files\nPARAM_STRING(\"output\/unpruned_tree_estimates\", \"The file \"\n\t \"in which to output the estimates on the \"\n\t \"training set from the large unpruned tree.\", \"u\", \"\");\nPARAM_STRING(\"output\/training_set_estimates\", \"The file \"\n\t \"in which to output the estimates on the \"\n\t \"training set from the final optimally pruned\"\n\t \" tree.\", \"s\", \"\");\nPARAM_STRING(\"output\/test_set_estimates\", \"The file \"\n\t \"in which to output the estimates on the \"\n\t \"test set from the final optimally pruned\"\n\t \" tree.\", \"t\", \"\");\nPARAM_STRING(\"output\/leaf_class_table\", \"The file \"\n\t \"in which to output the leaf class membership \"\n\t \"table.\", \"l\", \"leaf_class_membership.txt\");\nPARAM_STRING(\"output\/tree\", \"The file in which to print \"\n\t \"the final optimally pruned tree.\", \"p\", \"\");\nPARAM_STRING(\"output\/vi\", \"The file to output the \"\n\t \"variable importance values for each feature.\",\n\t \"i\", \"\");\n\n\/\/ parameters for the algorithm\nPARAM_INT(\"param\/number_of_classes\", \"The number of classes present \"\n\t \"in the 'labels' set provided\", \"C\", 0);\nPARAM_INT(\"param\/folds\", \"The number of folds of cross-validation\"\n\t \" to performed for the estimation (enter 0 for LOOCV)\",\n\t \"F\", 10);\nPARAM_INT(\"DET\/min_leaf_size\", \"The minimum size of a leaf\"\n\t \" in the unpruned fully grown DET.\", \"N\", 5);\nPARAM_INT(\"DET\/max_leaf_size\", \"The maximum size of a leaf\"\n\t \" in the unpruned fully grown DET.\", \"M\", 10);\nPARAM_FLAG(\"DET\/use_volume_reg\", \"This flag gives the used the \"\n\t \"option to use a form of regularization similar to \"\n\t \"the usual alpha-pruning in decision tree. But \"\n\t \"instead of regularizing on the number of leaves, \"\n\t \"you regularize on the sum of the inverse of the volume \"\n\t \"of the leaves (meaning you penalize \"\n\t \"low volume leaves.\", \"R\");\n\n\/\/ some flags for output of some information about the tree\nPARAM_FLAG(\"flag\/print_tree\", \"If you just wish to print the tree \"\n\t \"out on the command line.\", \"P\");\nPARAM_FLAG(\"flag\/print_vi\", \"If you just wish to print the \"\n\t \"variable importance of each feature \"\n\t \"out on the command line.\", \"I\");\n\nint main(int argc, char *argv[]) \n{\n CLI::ParseCommandLine(argc, argv);\n\n string train_set_file = CLI::GetParam(\"S\");\n arma::Mat training_data;\n\n Log::Info << \"Loading training set...\" << endl;\n if (!data::Load(train_set_file, training_data))\n Log::Fatal << \"Training set file \"<< train_set_file \n\t << \" can't be loaded.\" << endl;\n\n Log::Info << \"Training set (\" << training_data.n_rows \n\t << \", \" << training_data.n_cols\n\t << \")\" << endl;\n\n \/\/ cross-validation here\n size_t folds = CLI::GetParam(\"F\");\n if (folds == 0) {\n folds = training_data.n_cols;\n Log::Info << \"Starting Leave-One-Out Cross validation\" << endl;\n } else \n Log::Info << \"Starting \" << folds \n\t << \"-fold Cross validation\" << endl;\n\n\n \n \/\/ obtaining the optimal tree\n string unpruned_tree_estimate_file \n = CLI::GetParam(\"u\");\n\n Timer::Start(\"DET\/Training\");\n DTree *dtree_opt = Trainer\n (&training_data, folds, CLI::HasParam(\"R\"), CLI::GetParam(\"M\"),\n CLI::GetParam(\"N\"), unpruned_tree_estimate_file);\n Timer::Stop(\"DET\/Training\");\n \n \/\/ computing densities for the train points in the\n \/\/ optimal tree\n FILE *fp = NULL;\n\n if (CLI::GetParam(\"s\") != \"\") {\n string optimal_estimates_file = CLI::GetParam(\"s\");\n fp = fopen(optimal_estimates_file.c_str(), \"w\");\n } \n\n \/\/ Computation timing is more accurate when you do not \n \/\/ perform the printing.\n Timer::Start(\"DET\/EstimationTime\");\n for (size_t i = 0; i < training_data.n_cols; i++) {\n arma::Col test_p = training_data.unsafe_col(i);\n long double f = dtree_opt->ComputeValue(&test_p);\n if (fp != NULL)\n fprintf(fp, \"%Lg\\n\", f);\n } \/\/ end for\n Timer::Stop(\"DET\/EstimationTime\");\n\n if (fp != NULL)\n fclose(fp);\n \n\n \/\/ computing the density at the provided test points\n \/\/ and outputting the density in the given file.\n if (CLI::GetParam(\"T\") != \"\") {\n string test_file = CLI::GetParam(\"T\");\n arma::Mat test_data;\n Log::Info << \"Loading test set...\" << endl;\n if (!data::Load(test_file, test_data))\n Log::Fatal << \"Test set file \"<< test_file \n\t\t << \" can't be loaded.\" << endl;\n\n Log::Info << \"Test set (\" << test_data.n_rows \n\t << \", \" << test_data.n_cols\n\t << \")\" << endl;\n\n fp = NULL;\n\n if (CLI::GetParam(\"t\") != \"\") {\n string test_density_file\n\t= CLI::GetParam(\"t\");\n fp = fopen(test_density_file.c_str(), \"w\");\n }\n\n Timer::Start(\"DET\/TestSetEstimation\");\n for (size_t i = 0; i < test_data.n_cols; i++) {\n arma::Col test_p = test_data.unsafe_col(i);\n long double f = dtree_opt->ComputeValue(&test_p);\n if (fp != NULL)\n\tfprintf(fp, \"%Lg\\n\", f);\n } \/\/ end for\n Timer::Stop(\"DET\/TestSetEstimation\");\n\n if (fp != NULL) \n fclose(fp);\n } \/\/ Test set estimation\n\n \/\/ printing the final tree\n if (CLI::HasParam(\"P\")) {\n\n fp = NULL;\n if (CLI::GetParam(\"p\") != \"\") {\n string print_tree_file = CLI::GetParam(\"p\");\n fp = fopen(print_tree_file.c_str(), \"w\");\n\n if (fp != NULL) {\n\tdtree_opt->WriteTree(0, fp);\n\tfclose(fp);\n }\n } else {\n dtree_opt->WriteTree(0, stdout);\n printf(\"\\n\");\n }\n } \/\/ Printing the tree\n\n \/\/ print the leaf memberships for the optimal tree\n if (CLI::GetParam(\"L\") != \"\") {\n std::string labels_file = CLI::GetParam(\"L\");\n arma::Mat labels;\n\n Log::Info << \"Loading label file...\" << endl;\n if (!data::Load(labels_file, labels))\n Log::Fatal << \"Label file \"<< labels_file \n\t\t << \" can't be loaded.\" << endl;\n\n Log::Info << \"Labels (\" << labels.n_rows \n\t << \", \" << labels.n_cols\n\t << \")\" << endl;\n \n size_t num_classes = CLI::GetParam(\"C\");\n if (num_classes == 0)\n Log::Fatal << \"Please provide the number of classes\"\n\t\t << \" present in the label file\" << endl;\n\n assert(training_data.n_cols == labels.n_cols);\n assert(labels.n_rows == 1);\n\n PrintLeafMembership\n (dtree_opt, training_data, labels, num_classes,\n (string) CLI::GetParam(\"l\"));\n } \/\/ leaf class membership\n \n\n if(CLI::HasParam(\"I\")) {\n PrintVariableImportance\n (dtree_opt, training_data.n_rows,\n (string) CLI::GetParam(\"i\"));\n } \/\/ print variable importance\n\n\n delete dtree_opt;\n return 0;\n} \/\/ end main\nSwitch to doubles not floats in main executable so it compiles.\/**\n * @file dt_main.cpp\n * @ Parikshit Ram (pram@cc.gatech.edu)\n *\n * This file provides an example use of the DET\n *\/\n\n#include \n#include \"dt_utils.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::det;\nusing namespace std;\n\nPROGRAM_INFO(\"Density estimation with DET\", \"This program provides an example \"\n \"use of the Density Estimation \"\n\t \"Tree for density estimation. For more details, \"\n\t \"please look at the paper titled \"\n\t \"'Density Estimation Trees'.\");\n\n\/\/ input data files\nPARAM_STRING_REQ(\"input\/training_set\", \"The data set on which to \"\n\t\t \"perform density estimation.\", \"S\");\nPARAM_STRING(\"input\/test_set\", \"An extra set of test points on \"\n\t \"which to estimate the density given the estimator.\",\n\t \"T\", \"\");\nPARAM_STRING(\"input\/labels\", \"The labels for the given training data to \"\n\t \"generate the class membership of each leaf (as an \"\n\t \"extra statistic)\", \"L\", \"\");\n\n\/\/ output data files\nPARAM_STRING(\"output\/unpruned_tree_estimates\", \"The file \"\n\t \"in which to output the estimates on the \"\n\t \"training set from the large unpruned tree.\", \"u\", \"\");\nPARAM_STRING(\"output\/training_set_estimates\", \"The file \"\n\t \"in which to output the estimates on the \"\n\t \"training set from the final optimally pruned\"\n\t \" tree.\", \"s\", \"\");\nPARAM_STRING(\"output\/test_set_estimates\", \"The file \"\n\t \"in which to output the estimates on the \"\n\t \"test set from the final optimally pruned\"\n\t \" tree.\", \"t\", \"\");\nPARAM_STRING(\"output\/leaf_class_table\", \"The file \"\n\t \"in which to output the leaf class membership \"\n\t \"table.\", \"l\", \"leaf_class_membership.txt\");\nPARAM_STRING(\"output\/tree\", \"The file in which to print \"\n\t \"the final optimally pruned tree.\", \"p\", \"\");\nPARAM_STRING(\"output\/vi\", \"The file to output the \"\n\t \"variable importance values for each feature.\",\n\t \"i\", \"\");\n\n\/\/ parameters for the algorithm\nPARAM_INT(\"param\/number_of_classes\", \"The number of classes present \"\n\t \"in the 'labels' set provided\", \"C\", 0);\nPARAM_INT(\"param\/folds\", \"The number of folds of cross-validation\"\n\t \" to performed for the estimation (enter 0 for LOOCV)\",\n\t \"F\", 10);\nPARAM_INT(\"DET\/min_leaf_size\", \"The minimum size of a leaf\"\n\t \" in the unpruned fully grown DET.\", \"N\", 5);\nPARAM_INT(\"DET\/max_leaf_size\", \"The maximum size of a leaf\"\n\t \" in the unpruned fully grown DET.\", \"M\", 10);\nPARAM_FLAG(\"DET\/use_volume_reg\", \"This flag gives the used the \"\n\t \"option to use a form of regularization similar to \"\n\t \"the usual alpha-pruning in decision tree. But \"\n\t \"instead of regularizing on the number of leaves, \"\n\t \"you regularize on the sum of the inverse of the volume \"\n\t \"of the leaves (meaning you penalize \"\n\t \"low volume leaves.\", \"R\");\n\n\/\/ some flags for output of some information about the tree\nPARAM_FLAG(\"flag\/print_tree\", \"If you just wish to print the tree \"\n\t \"out on the command line.\", \"P\");\nPARAM_FLAG(\"flag\/print_vi\", \"If you just wish to print the \"\n\t \"variable importance of each feature \"\n\t \"out on the command line.\", \"I\");\n\nint main(int argc, char *argv[])\n{\n CLI::ParseCommandLine(argc, argv);\n\n string train_set_file = CLI::GetParam(\"S\");\n arma::Mat training_data;\n\n Log::Info << \"Loading training set...\" << endl;\n if (!data::Load(train_set_file, training_data))\n Log::Fatal << \"Training set file \"<< train_set_file\n\t << \" can't be loaded.\" << endl;\n\n Log::Info << \"Training set (\" << training_data.n_rows\n\t << \", \" << training_data.n_cols\n\t << \")\" << endl;\n\n \/\/ cross-validation here\n size_t folds = CLI::GetParam(\"F\");\n if (folds == 0) {\n folds = training_data.n_cols;\n Log::Info << \"Starting Leave-One-Out Cross validation\" << endl;\n } else\n Log::Info << \"Starting \" << folds\n\t << \"-fold Cross validation\" << endl;\n\n\n\n \/\/ obtaining the optimal tree\n string unpruned_tree_estimate_file\n = CLI::GetParam(\"u\");\n\n Timer::Start(\"DET\/Training\");\n DTree *dtree_opt = Trainer\n (&training_data, folds, CLI::HasParam(\"R\"), CLI::GetParam(\"M\"),\n CLI::GetParam(\"N\"), unpruned_tree_estimate_file);\n Timer::Stop(\"DET\/Training\");\n\n \/\/ computing densities for the train points in the\n \/\/ optimal tree\n FILE *fp = NULL;\n\n if (CLI::GetParam(\"s\") != \"\") {\n string optimal_estimates_file = CLI::GetParam(\"s\");\n fp = fopen(optimal_estimates_file.c_str(), \"w\");\n }\n\n \/\/ Computation timing is more accurate when you do not\n \/\/ perform the printing.\n Timer::Start(\"DET\/EstimationTime\");\n for (size_t i = 0; i < training_data.n_cols; i++) {\n arma::Col test_p = training_data.unsafe_col(i);\n long double f = dtree_opt->ComputeValue(&test_p);\n if (fp != NULL)\n fprintf(fp, \"%Lg\\n\", f);\n } \/\/ end for\n Timer::Stop(\"DET\/EstimationTime\");\n\n if (fp != NULL)\n fclose(fp);\n\n\n \/\/ computing the density at the provided test points\n \/\/ and outputting the density in the given file.\n if (CLI::GetParam(\"T\") != \"\") {\n string test_file = CLI::GetParam(\"T\");\n arma::Mat test_data;\n Log::Info << \"Loading test set...\" << endl;\n if (!data::Load(test_file, test_data))\n Log::Fatal << \"Test set file \"<< test_file\n\t\t << \" can't be loaded.\" << endl;\n\n Log::Info << \"Test set (\" << test_data.n_rows\n\t << \", \" << test_data.n_cols\n\t << \")\" << endl;\n\n fp = NULL;\n\n if (CLI::GetParam(\"t\") != \"\") {\n string test_density_file\n\t= CLI::GetParam(\"t\");\n fp = fopen(test_density_file.c_str(), \"w\");\n }\n\n Timer::Start(\"DET\/TestSetEstimation\");\n for (size_t i = 0; i < test_data.n_cols; i++) {\n arma::Col test_p = test_data.unsafe_col(i);\n long double f = dtree_opt->ComputeValue(&test_p);\n if (fp != NULL)\n\tfprintf(fp, \"%Lg\\n\", f);\n } \/\/ end for\n Timer::Stop(\"DET\/TestSetEstimation\");\n\n if (fp != NULL)\n fclose(fp);\n } \/\/ Test set estimation\n\n \/\/ printing the final tree\n if (CLI::HasParam(\"P\")) {\n\n fp = NULL;\n if (CLI::GetParam(\"p\") != \"\") {\n string print_tree_file = CLI::GetParam(\"p\");\n fp = fopen(print_tree_file.c_str(), \"w\");\n\n if (fp != NULL) {\n\tdtree_opt->WriteTree(0, fp);\n\tfclose(fp);\n }\n } else {\n dtree_opt->WriteTree(0, stdout);\n printf(\"\\n\");\n }\n } \/\/ Printing the tree\n\n \/\/ print the leaf memberships for the optimal tree\n if (CLI::GetParam(\"L\") != \"\") {\n std::string labels_file = CLI::GetParam(\"L\");\n arma::Mat labels;\n\n Log::Info << \"Loading label file...\" << endl;\n if (!data::Load(labels_file, labels))\n Log::Fatal << \"Label file \"<< labels_file\n\t\t << \" can't be loaded.\" << endl;\n\n Log::Info << \"Labels (\" << labels.n_rows\n\t << \", \" << labels.n_cols\n\t << \")\" << endl;\n\n size_t num_classes = CLI::GetParam(\"C\");\n if (num_classes == 0)\n Log::Fatal << \"Please provide the number of classes\"\n\t\t << \" present in the label file\" << endl;\n\n assert(training_data.n_cols == labels.n_cols);\n assert(labels.n_rows == 1);\n\n PrintLeafMembership\n (dtree_opt, training_data, labels, num_classes,\n (string) CLI::GetParam(\"l\"));\n } \/\/ leaf class membership\n\n\n if(CLI::HasParam(\"I\")) {\n PrintVariableImportance\n (dtree_opt, training_data.n_rows,\n (string) CLI::GetParam(\"i\"));\n } \/\/ print variable importance\n\n\n delete dtree_opt;\n return 0;\n} \/\/ end main\n<|endoftext|>"} {"text":"#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX24T\/RX66T グループ・CMPC 定義\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2018 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"common\/device.hpp\"\r\n\r\n\/\/\/ CMPC モジュールが無いデバイスでエラーとする\r\n#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)\r\n# error \"cmpc.hpp: This module does not exist\"\r\n#endif\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief コンパレータ C(CMPC)\r\n\t\t@param[in]\tbase\tベース・アドレス\r\n\t\t@param[in]\tper\t\tペリフェラル型\r\n\t\t@param[in]\tivec\t割り込みベクタ型\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate \r\n\tstruct cmpc_t {\r\n\r\n\t\tstatic const auto PERIPHERAL = per;\t\t\/\/\/< ペリフェラル型\r\n\t\tstatic const auto IVEC = ivec;\t\t\t\/\/\/< 割り込みベクター\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンパレータ制御レジスタ(CMPCTL)\r\n\t\t\t@param[in]\tofs\tオフセット\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct cmpctl_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbit_rw_t CINV;\r\n\t\t\tbit_rw_t COE;\r\n\t\t\tbits_rw_t CEG;\r\n\t\t\tbits_rw_t CDFS;\r\n\t\t\tbit_rw_t HCMPON;\r\n\t\t};\r\n\t\tstatic cmpctl_t CMPCTL;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンパレータ入力切り替えレジスタ(CMPSEL0)\r\n\t\t\t@param[in]\tofs\tオフセット\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct cmpsel0_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbits_rw_t CMPSEL;\r\n\t\t};\r\n\t\tstatic cmpsel0_t CMPSEL0;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンパレータ入力切り替えレジスタ(CMPSEL1)\r\n\t\t\t@param[in]\tofs\tオフセット\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct cmpsel1_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbits_rw_t CVRS;\r\n\t\t};\r\n\t\tstatic cmpsel1_t CMPSEL1;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンパレータ出力モニタレジスタ(CMPMON)\r\n\t\t\t@param[in]\tofs\tオフセット\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct cmpmon_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbit_rw_t CMPMON0;\r\n\t\t};\r\n\t\tstatic cmpmon_t CMPMON;\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンパレータ外部出力許可レジスタ(CMPIOC)\r\n\t\t\t@param[in]\tofs\tオフセット\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\ttemplate \r\n\t\tstruct cmpioc_t : public rw8_t {\r\n\t\t\ttypedef rw8_t io_;\r\n\t\t\tusing io_::operator =;\r\n\t\t\tusing io_::operator ();\r\n\t\t\tusing io_::operator |=;\r\n\t\t\tusing io_::operator &=;\r\n\r\n\t\t\tbit_rw_t CPOE;\r\n\t\t};\r\n\t\tstatic cmpioc_t CMPIOC;\r\n\t};\r\n\r\n#if defined(SIG_RX24T)\r\n\ttypedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;\r\n\ttypedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;\r\n\ttypedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;\r\n\ttypedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;\r\n#elif defined(SIG_RX66T)\r\n\ttypedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;\r\n\ttypedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;\r\n\ttypedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;\r\n\ttypedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;\r\n\ttypedef cmpc_t<0x000A0D00, peripheral::CMPC4, ICU::VECTOR::CMPC4> CMPC4;\r\n\ttypedef cmpc_t<0x000A0D20, peripheral::CMPC5, ICU::VECTOR::CMPC5> CMPC5;\r\n#endif\r\n}\r\nUpdate: The reality of the template when it is not optimized#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX24T\/RX66T グループ・CMPC 定義\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2016, 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/device.hpp\"\n\n\/\/\/ CMPC モジュールが無いデバイスでエラーとする\n#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)\n# error \"cmpc.hpp: This module does not exist\"\n#endif\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief コンパレータ C(CMPC)\n\t\t@param[in]\tbase\tベース・アドレス\n\t\t@param[in]\tper\t\tペリフェラル型\n\t\t@param[in]\tivec\t割り込みベクタ型\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct cmpc_t {\n\n\t\tstatic const auto PERIPHERAL = per;\t\t\/\/\/< ペリフェラル型\n\t\tstatic const auto IVEC = ivec;\t\t\t\/\/\/< 割り込みベクター\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンパレータ制御レジスタ(CMPCTL)\n\t\t\t@param[in]\tofs\tオフセット\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct cmpctl_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbit_rw_t CINV;\n\t\t\tbit_rw_t COE;\n\t\t\tbits_rw_t CEG;\n\t\t\tbits_rw_t CDFS;\n\t\t\tbit_rw_t HCMPON;\n\t\t};\n\t\ttypedef cmpctl_t CMPCTL_;\n\t\tstatic CMPCTL_ CMPCTL;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンパレータ入力切り替えレジスタ(CMPSEL0)\n\t\t\t@param[in]\tofs\tオフセット\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct cmpsel0_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbits_rw_t CMPSEL;\n\t\t};\n\t\ttypedef cmpsel0_t CMPSEL0_;\n\t\tstatic CMPSEL0_ CMPSEL0;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンパレータ入力切り替えレジスタ(CMPSEL1)\n\t\t\t@param[in]\tofs\tオフセット\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct cmpsel1_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbits_rw_t CVRS;\n\t\t};\n\t\ttypedef cmpsel1_t CMPSEL1_;\n\t\tstatic CMPSEL1_ CMPSEL1;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンパレータ出力モニタレジスタ(CMPMON)\n\t\t\t@param[in]\tofs\tオフセット\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct cmpmon_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbit_rw_t CMPMON0;\n\t\t};\n\t\ttypedef cmpmon_t CMPMON_;\n\t\tstatic CMPMON_ CMPMON;\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンパレータ外部出力許可レジスタ(CMPIOC)\n\t\t\t@param[in]\tofs\tオフセット\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\ttemplate \n\t\tstruct cmpioc_t : public rw8_t {\n\t\t\ttypedef rw8_t io_;\n\t\t\tusing io_::operator =;\n\t\t\tusing io_::operator ();\n\t\t\tusing io_::operator |=;\n\t\t\tusing io_::operator &=;\n\n\t\t\tbit_rw_t CPOE;\n\t\t};\n\t\ttypedef cmpioc_t CMPIOC_;\n\t\tstatic CMPIOC_ CMPIOC;\n\t};\n\ttemplate \n\t\ttypename cmpc_t::CMPCTL_ cmpc_t::CMPCTL;\n\ttemplate \n\t\ttypename cmpc_t::CMPSEL0_ cmpc_t::CMPSEL0;\n\ttemplate \n\t\ttypename cmpc_t::CMPSEL1_ cmpc_t::CMPSEL1;\n\ttemplate \n\t\ttypename cmpc_t::CMPMON_ cmpc_t::CMPMON;\n\ttemplate \n\t\ttypename cmpc_t::CMPIOC_ cmpc_t::CMPIOC;\n\n\n#if defined(SIG_RX24T)\n\ttypedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;\n\ttypedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;\n\ttypedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;\n\ttypedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;\n#elif defined(SIG_RX66T)\n\ttypedef cmpc_t<0x000A0C80, peripheral::CMPC0, ICU::VECTOR::CMPC0> CMPC0;\n\ttypedef cmpc_t<0x000A0CA0, peripheral::CMPC1, ICU::VECTOR::CMPC1> CMPC1;\n\ttypedef cmpc_t<0x000A0CC0, peripheral::CMPC2, ICU::VECTOR::CMPC2> CMPC2;\n\ttypedef cmpc_t<0x000A0CE0, peripheral::CMPC3, ICU::VECTOR::CMPC3> CMPC3;\n\ttypedef cmpc_t<0x000A0D00, peripheral::CMPC4, ICU::VECTOR::CMPC4> CMPC4;\n\ttypedef cmpc_t<0x000A0D20, peripheral::CMPC5, ICU::VECTOR::CMPC5> CMPC5;\n#endif\n}\n<|endoftext|>"} {"text":"#include \"shadow\/util\/boxes.hpp\"\n#include \"shadow\/util\/log.hpp\"\n\nnamespace Boxes {\n\ntemplate \nvoid Clip(const Box &box, Box *clip_box, Dtype min, Dtype max) {\n clip_box->xmin = std::max(std::min(box.xmin, max), min);\n clip_box->ymin = std::max(std::min(box.ymin, max), min);\n clip_box->xmax = std::max(std::min(box.xmax, max), min);\n clip_box->ymax = std::max(std::min(box.ymax, max), min);\n}\n\ntemplate \nDtype Size(const Box &box) {\n return (box.xmax - box.xmin) * (box.ymax - box.ymin);\n}\n\ntemplate \ninline Dtype BorderOverlap(Dtype a1, Dtype a2, Dtype b1, Dtype b2) {\n Dtype left = a1 > b1 ? a1 : b1;\n Dtype right = a2 < b2 ? a2 : b2;\n return right - left;\n}\n\ntemplate \nfloat Intersection(const Box &box_a, const Box &box_b) {\n Dtype width = BorderOverlap(box_a.xmin, box_a.xmax, box_b.xmin, box_b.xmax);\n Dtype height = BorderOverlap(box_a.ymin, box_a.ymax, box_b.ymin, box_b.ymax);\n if (width < 0 || height < 0) return 0;\n return width * height;\n}\n\ntemplate \nfloat Union(const Box &box_a, const Box &box_b) {\n return Size(box_a) + Size(box_b) - Intersection(box_a, box_b);\n}\n\ntemplate \nfloat IoU(const Box &box_a, const Box &box_b) {\n return Intersection(box_a, box_b) \/ Union(box_a, box_b);\n}\n\ntemplate \nstd::vector> NMS(const std::vector>> &Bboxes,\n float iou_threshold) {\n std::vector> all_boxes;\n for (const auto &boxes : Bboxes) {\n for (const auto &box : boxes) {\n if (box.label != -1) all_boxes.push_back(box);\n }\n }\n for (int i = 0; i < all_boxes.size(); ++i) {\n Box &box_i = all_boxes[i];\n if (box_i.label == -1) continue;\n for (int j = i + 1; j < all_boxes.size(); ++j) {\n Box &box_j = all_boxes[j];\n if (box_j.label == -1 || box_i.label != box_j.label) continue;\n if (IoU(box_i, box_j) > iou_threshold) {\n float smooth = box_i.score \/ (box_i.score + box_j.score);\n Smooth(box_j, &box_i, smooth);\n box_j.label = -1;\n continue;\n }\n float in = Intersection(box_i, box_j);\n float cover_i = in \/ Size(box_i);\n float cover_j = in \/ Size(box_j);\n if (cover_i > cover_j && cover_i > 0.7) box_i.label = -1;\n if (cover_i < cover_j && cover_j > 0.7) box_j.label = -1;\n }\n }\n std::vector> out_boxes;\n for (const auto &box : all_boxes) {\n if (box.label != -1) out_boxes.push_back(box);\n }\n all_boxes.clear();\n return out_boxes;\n}\n\ntemplate \nvoid Smooth(const Box &old_box, Box *new_box, float smooth) {\n new_box->xmin = old_box.xmin + (new_box->xmin - old_box.xmin) * smooth;\n new_box->ymin = old_box.ymin + (new_box->ymin - old_box.ymin) * smooth;\n new_box->xmax = old_box.xmax + (new_box->xmax - old_box.xmax) * smooth;\n new_box->ymax = old_box.ymax + (new_box->ymax - old_box.ymax) * smooth;\n}\n\ntemplate \nvoid Smooth(const std::vector> &old_boxes,\n std::vector> *new_boxes, float smooth) {\n for (auto &new_box : *new_boxes) {\n for (auto &old_box : old_boxes) {\n if (IoU(old_box, new_box) > 0.7) {\n Smooth(old_box, &new_box, smooth);\n break;\n }\n }\n }\n}\n\ntemplate \nvoid Amend(std::vector>> *Bboxes, const VecRectF &crops,\n int height, int width) {\n CHECK_EQ(Bboxes->size(), crops.size());\n for (int i = 0; i < crops.size(); ++i) {\n std::vector> &boxes = Bboxes->at(i);\n const RectF &crop = crops[i];\n float x_off = crop.x <= 1 ? crop.x * width : crop.x;\n float y_off = crop.y <= 1 ? crop.y * height : crop.y;\n for (auto &box : boxes) {\n box.xmin += x_off;\n box.xmax += x_off;\n box.ymin += y_off;\n box.ymax += y_off;\n }\n }\n}\n\n\/\/ Explicit instantiation\ntemplate void Clip(const BoxI &box, BoxI *clip_box, int min, int max);\ntemplate void Clip(const BoxF &box, BoxF *clip_box, float min, float max);\n\ntemplate int Size(const BoxI &box);\ntemplate float Size(const BoxF &box);\n\ntemplate float Intersection(const BoxI &box_a, const BoxI &box_b);\ntemplate float Intersection(const BoxF &box_a, const BoxF &box_b);\n\ntemplate float Union(const BoxI &box_a, const BoxI &box_b);\ntemplate float Union(const BoxF &box_a, const BoxF &box_b);\n\ntemplate float IoU(const BoxI &box_a, const BoxI &box_b);\ntemplate float IoU(const BoxF &box_a, const BoxF &box_b);\n\ntemplate VecBoxI NMS(const std::vector &Bboxes, float iou_threshold);\ntemplate VecBoxF NMS(const std::vector &Bboxes, float iou_threshold);\n\ntemplate void Smooth(const BoxI &old_boxes, BoxI *new_boxes, float smooth);\ntemplate void Smooth(const BoxF &old_boxes, BoxF *new_boxes, float smooth);\n\ntemplate void Smooth(const VecBoxI &old_boxes, VecBoxI *new_boxes,\n float smooth);\ntemplate void Smooth(const VecBoxF &old_boxes, VecBoxF *new_boxes,\n float smooth);\n\ntemplate void Amend(std::vector *Bboxes, const VecRectF &crops,\n int height, int width);\ntemplate void Amend(std::vector *Bboxes, const VecRectF &crops,\n int height, int width);\n\n} \/\/ namespace Boxes\nfix bug: fix crop region normalize or none normalize error in amend function#include \"shadow\/util\/boxes.hpp\"\n#include \"shadow\/util\/log.hpp\"\n\nnamespace Boxes {\n\ntemplate \nvoid Clip(const Box &box, Box *clip_box, Dtype min, Dtype max) {\n clip_box->xmin = std::max(std::min(box.xmin, max), min);\n clip_box->ymin = std::max(std::min(box.ymin, max), min);\n clip_box->xmax = std::max(std::min(box.xmax, max), min);\n clip_box->ymax = std::max(std::min(box.ymax, max), min);\n}\n\ntemplate \nDtype Size(const Box &box) {\n return (box.xmax - box.xmin) * (box.ymax - box.ymin);\n}\n\ntemplate \ninline Dtype BorderOverlap(Dtype a1, Dtype a2, Dtype b1, Dtype b2) {\n Dtype left = a1 > b1 ? a1 : b1;\n Dtype right = a2 < b2 ? a2 : b2;\n return right - left;\n}\n\ntemplate \nfloat Intersection(const Box &box_a, const Box &box_b) {\n Dtype width = BorderOverlap(box_a.xmin, box_a.xmax, box_b.xmin, box_b.xmax);\n Dtype height = BorderOverlap(box_a.ymin, box_a.ymax, box_b.ymin, box_b.ymax);\n if (width < 0 || height < 0) return 0;\n return width * height;\n}\n\ntemplate \nfloat Union(const Box &box_a, const Box &box_b) {\n return Size(box_a) + Size(box_b) - Intersection(box_a, box_b);\n}\n\ntemplate \nfloat IoU(const Box &box_a, const Box &box_b) {\n return Intersection(box_a, box_b) \/ Union(box_a, box_b);\n}\n\ntemplate \nstd::vector> NMS(const std::vector>> &Bboxes,\n float iou_threshold) {\n std::vector> all_boxes;\n for (const auto &boxes : Bboxes) {\n for (const auto &box : boxes) {\n if (box.label != -1) all_boxes.push_back(box);\n }\n }\n for (int i = 0; i < all_boxes.size(); ++i) {\n Box &box_i = all_boxes[i];\n if (box_i.label == -1) continue;\n for (int j = i + 1; j < all_boxes.size(); ++j) {\n Box &box_j = all_boxes[j];\n if (box_j.label == -1 || box_i.label != box_j.label) continue;\n if (IoU(box_i, box_j) > iou_threshold) {\n float smooth = box_i.score \/ (box_i.score + box_j.score);\n Smooth(box_j, &box_i, smooth);\n box_j.label = -1;\n continue;\n }\n float in = Intersection(box_i, box_j);\n float cover_i = in \/ Size(box_i);\n float cover_j = in \/ Size(box_j);\n if (cover_i > cover_j && cover_i > 0.7) box_i.label = -1;\n if (cover_i < cover_j && cover_j > 0.7) box_j.label = -1;\n }\n }\n std::vector> out_boxes;\n for (const auto &box : all_boxes) {\n if (box.label != -1) out_boxes.push_back(box);\n }\n all_boxes.clear();\n return out_boxes;\n}\n\ntemplate \nvoid Smooth(const Box &old_box, Box *new_box, float smooth) {\n new_box->xmin = old_box.xmin + (new_box->xmin - old_box.xmin) * smooth;\n new_box->ymin = old_box.ymin + (new_box->ymin - old_box.ymin) * smooth;\n new_box->xmax = old_box.xmax + (new_box->xmax - old_box.xmax) * smooth;\n new_box->ymax = old_box.ymax + (new_box->ymax - old_box.ymax) * smooth;\n}\n\ntemplate \nvoid Smooth(const std::vector> &old_boxes,\n std::vector> *new_boxes, float smooth) {\n for (auto &new_box : *new_boxes) {\n for (auto &old_box : old_boxes) {\n if (IoU(old_box, new_box) > 0.7) {\n Smooth(old_box, &new_box, smooth);\n break;\n }\n }\n }\n}\n\ntemplate \nvoid Amend(std::vector>> *Bboxes, const VecRectF &crops,\n int height, int width) {\n CHECK_EQ(Bboxes->size(), crops.size());\n for (int i = 0; i < crops.size(); ++i) {\n std::vector> &boxes = Bboxes->at(i);\n const RectF &crop = crops[i];\n bool normalize = crop.h <= 1 || crop.w <= 1;\n if (normalize) {\n CHECK_GT(height, 1);\n CHECK_GT(width, 1);\n }\n float x_off = normalize ? crop.x * width : crop.x;\n float y_off = normalize ? crop.y * height : crop.y;\n for (auto &box : boxes) {\n box.xmin += x_off;\n box.xmax += x_off;\n box.ymin += y_off;\n box.ymax += y_off;\n }\n }\n}\n\n\/\/ Explicit instantiation\ntemplate void Clip(const BoxI &box, BoxI *clip_box, int min, int max);\ntemplate void Clip(const BoxF &box, BoxF *clip_box, float min, float max);\n\ntemplate int Size(const BoxI &box);\ntemplate float Size(const BoxF &box);\n\ntemplate float Intersection(const BoxI &box_a, const BoxI &box_b);\ntemplate float Intersection(const BoxF &box_a, const BoxF &box_b);\n\ntemplate float Union(const BoxI &box_a, const BoxI &box_b);\ntemplate float Union(const BoxF &box_a, const BoxF &box_b);\n\ntemplate float IoU(const BoxI &box_a, const BoxI &box_b);\ntemplate float IoU(const BoxF &box_a, const BoxF &box_b);\n\ntemplate VecBoxI NMS(const std::vector &Bboxes, float iou_threshold);\ntemplate VecBoxF NMS(const std::vector &Bboxes, float iou_threshold);\n\ntemplate void Smooth(const BoxI &old_boxes, BoxI *new_boxes, float smooth);\ntemplate void Smooth(const BoxF &old_boxes, BoxF *new_boxes, float smooth);\n\ntemplate void Smooth(const VecBoxI &old_boxes, VecBoxI *new_boxes,\n float smooth);\ntemplate void Smooth(const VecBoxF &old_boxes, VecBoxF *new_boxes,\n float smooth);\n\ntemplate void Amend(std::vector *Bboxes, const VecRectF &crops,\n int height, int width);\ntemplate void Amend(std::vector *Bboxes, const VecRectF &crops,\n int height, int width);\n\n} \/\/ namespace Boxes\n<|endoftext|>"} {"text":"#include \n#include \n\nextern \"C\"\nstruct TensorWrapper minCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)\n{\n GpuMatT dstMat = dst.toGpuMatT();\n cuda::GpuMat & mat = dstMat.mat;\n cuda::min(src1.toGpuMat(), src2.toGpuMat(), dstMat, prepareStream(info));\n return TensorWrapper(dstMat, info.state);\n}\n\nextern \"C\"\nstruct TensorWrapper maxCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::max(src1.toGpuMat(), src2.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::max(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorPlusDouble thresholdCuda(\n struct cutorchInfo info, struct TensorWrapper src,\n struct TensorWrapper dst, double thresh, double maxval, int type)\n{\n TensorPlusDouble retval;\n\n if (dst.isNull()) {\n cuda::GpuMat result;\n retval.val = cuda::threshold(src.toGpuMat(), result, thresh, maxval, type, prepareStream(info));\n new (&retval.tensor) TensorWrapper(result, info.state);\n } else {\n retval.val = cuda::threshold(src.toGpuMat(), dst.toGpuMat(), thresh, maxval, type, prepareStream(info));\n retval.tensor = dst;\n }\n return retval;\n}\n\nextern \"C\"\nstruct TensorWrapper magnitudeCuda(\n struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)\n{\n if (magnitude.isNull()) {\n cuda::GpuMat result;\n cuda::magnitude(xy.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitude(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));\n return magnitude;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper magnitudeSqrCuda(\n struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)\n{\n if (magnitude.isNull()) {\n cuda::GpuMat result;\n cuda::magnitudeSqr(xy.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitudeSqr(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));\n return magnitude;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper magnitude2Cuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude)\n{\n if (magnitude.isNull()) {\n cuda::GpuMat result;\n cuda::magnitude(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitude(x.toGpuMat(), y.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));\n return magnitude;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper magnitudeSqr2Cuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitudeSqr)\n{\n if (magnitudeSqr.isNull()) {\n cuda::GpuMat result;\n cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), magnitudeSqr.toGpuMat(), prepareStream(info));\n return magnitudeSqr;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper phaseCuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,\n struct TensorWrapper angle, bool angleInDegrees)\n{\n if (angle.isNull()) {\n cuda::GpuMat result;\n cuda::phase(x.toGpuMat(), y.toGpuMat(), result, angleInDegrees, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::phase(x.toGpuMat(), y.toGpuMat(), angle.toGpuMat(), angleInDegrees, prepareStream(info));\n return angle;\n }\n}\n\nextern \"C\"\nstruct TensorArray cartToPolarCuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,\n struct TensorWrapper magnitude, struct TensorWrapper angle, bool angleInDegrees)\n{\n std::vector result(2);\n result[0] = magnitude.toGpuMat();\n result[1] = angle.toGpuMat();\n\n cuda::cartToPolar(x.toGpuMat(), y.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));\n\n return TensorArray(result, info.state);\n}\n\nextern \"C\"\nstruct TensorArray polarToCartCuda(\n struct cutorchInfo info, struct TensorWrapper magnitude, struct TensorWrapper angle,\n struct TensorWrapper x, struct TensorWrapper y, bool angleInDegrees)\n{\n std::vector result;\n result[0] = x.toGpuMat();\n result[1] = y.toGpuMat();\n\n cuda::polarToCart(magnitude.toGpuMat(), angle.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));\n\n return TensorArray(result, info.state);\n}\n\nextern \"C\"\nstruct LookUpTablePtr LookUpTable_ctorCuda(\n struct cutorchInfo info, struct TensorWrapper lut)\n{\n return rescueObjectFromPtr(cuda::createLookUpTable(lut.toGpuMat()));\n}\n\nextern \"C\"\nstruct TensorWrapper LookUpTable_transformCuda(\n struct cutorchInfo info, struct LookUpTablePtr ptr,\n struct TensorWrapper src, struct TensorWrapper dst)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n ptr->transform(src.toGpuMat(), result);\n return TensorWrapper(result, info.state);\n } else {\n ptr->transform(src.toGpuMat(), dst.toGpuMat(), prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper rectStdDevCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sqr,\n struct TensorWrapper dst, struct RectWrapper rect)\n{\n if (dst.isNull()) {\n cv::Mat result;\n cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), result, rect, prepareStream(info));\n return TensorWrapper(result);\n } else {\n cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), dst.toGpuMat(), rect, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper normalizeCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst,\n double alpha, double beta, int norm_type, int dtype, struct TensorWrapper mask)\n{\n if (dst.isNull()) {\n cv::Mat result;\n cuda::normalize(src.toGpuMat(), result, alpha, beta, norm_type,\n dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));\n return TensorWrapper(result);\n } else {\n cuda::normalize(src.toGpuMat(), dst.toGpuMat(), alpha, beta, norm_type,\n dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper integralCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)\n{\n if (sum.isNull()) {\n cv::Mat result;\n cuda::integral(src.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result);\n } else {\n cuda::integral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));\n return sum;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper sqrIntegralCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)\n{\n if (sum.isNull()) {\n cv::Mat result;\n cuda::sqrIntegral(src.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result);\n } else {\n cuda::sqrIntegral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));\n return sum;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper mulSpectrumsCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,\n struct TensorWrapper dst, int flags, bool conjB)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, conjB, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, conjB, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper mulAndScaleSpectrumsCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,\n struct TensorWrapper dst, int flags, float scale, bool conjB)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, scale, conjB, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, scale, conjB, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper dftCuda(\n struct cutorchInfo info, struct TensorWrapper src,\n struct TensorWrapper dst, struct SizeWrapper dft_size, int flags)\n{\n if (dst.isNull()) {\n cv::Mat result;\n cuda::dft(src.toGpuMat(), result, dft_size, flags, prepareStream(info));\n return TensorWrapper(result);\n } else {\n cuda::dft(src.toGpuMat(), dst.toGpuMat(), dft_size, flags, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct ConvolutionPtr Convolution_ctorCuda(\n struct cutorchInfo info, struct SizeWrapper user_block_size)\n{\n return rescueObjectFromPtr(cuda::createConvolution(user_block_size));\n}\n\nextern \"C\"\nstruct TensorWrapper Convolution_convolveCuda(\n struct cutorchInfo info, struct ConvolutionPtr ptr, struct TensorWrapper image,\n struct TensorWrapper templ, struct TensorWrapper result, bool ccor)\n{\n if (result.isNull()) {\n cuda::GpuMat resultMat;\n ptr->convolve(image.toGpuMat(), templ.toGpuMat(), resultMat, ccor, prepareStream(info));\n return TensorWrapper(resultMat, info.state);\n } else {\n ptr->convolve(image.toGpuMat(), templ.toGpuMat(), result.toGpuMat(), ccor);\n return result;\n }\n}\nFix #193#include \n#include \n\nextern \"C\"\nstruct TensorWrapper minCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)\n{\n GpuMatT dstMat = dst.toGpuMatT();\n cuda::GpuMat & mat = dstMat.mat;\n cuda::min(src1.toGpuMat(), src2.toGpuMat(), dstMat, prepareStream(info));\n return TensorWrapper(dstMat, info.state);\n}\n\nextern \"C\"\nstruct TensorWrapper maxCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2, struct TensorWrapper dst)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::max(src1.toGpuMat(), src2.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::max(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorPlusDouble thresholdCuda(\n struct cutorchInfo info, struct TensorWrapper src,\n struct TensorWrapper dst, double thresh, double maxval, int type)\n{\n TensorPlusDouble retval;\n\n if (dst.isNull()) {\n cuda::GpuMat result;\n retval.val = cuda::threshold(src.toGpuMat(), result, thresh, maxval, type, prepareStream(info));\n new (&retval.tensor) TensorWrapper(result, info.state);\n } else {\n retval.val = cuda::threshold(src.toGpuMat(), dst.toGpuMat(), thresh, maxval, type, prepareStream(info));\n retval.tensor = dst;\n }\n return retval;\n}\n\nextern \"C\"\nstruct TensorWrapper magnitudeCuda(\n struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)\n{\n if (magnitude.isNull()) {\n cuda::GpuMat result;\n cuda::magnitude(xy.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitude(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));\n return magnitude;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper magnitudeSqrCuda(\n struct cutorchInfo info, struct TensorWrapper xy, struct TensorWrapper magnitude)\n{\n if (magnitude.isNull()) {\n cuda::GpuMat result;\n cuda::magnitudeSqr(xy.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitudeSqr(xy.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));\n return magnitude;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper magnitude2Cuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitude)\n{\n if (magnitude.isNull()) {\n cuda::GpuMat result;\n cuda::magnitude(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitude(x.toGpuMat(), y.toGpuMat(), magnitude.toGpuMat(), prepareStream(info));\n return magnitude;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper magnitudeSqr2Cuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y, struct TensorWrapper magnitudeSqr)\n{\n if (magnitudeSqr.isNull()) {\n cuda::GpuMat result;\n cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::magnitudeSqr(x.toGpuMat(), y.toGpuMat(), magnitudeSqr.toGpuMat(), prepareStream(info));\n return magnitudeSqr;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper phaseCuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,\n struct TensorWrapper angle, bool angleInDegrees)\n{\n if (angle.isNull()) {\n cuda::GpuMat result;\n cuda::phase(x.toGpuMat(), y.toGpuMat(), result, angleInDegrees, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::phase(x.toGpuMat(), y.toGpuMat(), angle.toGpuMat(), angleInDegrees, prepareStream(info));\n return angle;\n }\n}\n\nextern \"C\"\nstruct TensorArray cartToPolarCuda(\n struct cutorchInfo info, struct TensorWrapper x, struct TensorWrapper y,\n struct TensorWrapper magnitude, struct TensorWrapper angle, bool angleInDegrees)\n{\n std::vector result(2);\n result[0] = magnitude.toGpuMat();\n result[1] = angle.toGpuMat();\n\n cuda::cartToPolar(x.toGpuMat(), y.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));\n\n return TensorArray(result, info.state);\n}\n\nextern \"C\"\nstruct TensorArray polarToCartCuda(\n struct cutorchInfo info, struct TensorWrapper magnitude, struct TensorWrapper angle,\n struct TensorWrapper x, struct TensorWrapper y, bool angleInDegrees)\n{\n std::vector result;\n result[0] = x.toGpuMat();\n result[1] = y.toGpuMat();\n\n cuda::polarToCart(magnitude.toGpuMat(), angle.toGpuMat(), result[0], result[1], angleInDegrees, prepareStream(info));\n\n return TensorArray(result, info.state);\n}\n\nextern \"C\"\nstruct LookUpTablePtr LookUpTable_ctorCuda(\n struct cutorchInfo info, struct TensorWrapper lut)\n{\n return rescueObjectFromPtr(cuda::createLookUpTable(lut.toGpuMat()));\n}\n\nextern \"C\"\nstruct TensorWrapper LookUpTable_transformCuda(\n struct cutorchInfo info, struct LookUpTablePtr ptr,\n struct TensorWrapper src, struct TensorWrapper dst)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n ptr->transform(src.toGpuMat(), result);\n return TensorWrapper(result, info.state);\n } else {\n ptr->transform(src.toGpuMat(), dst.toGpuMat(), prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper rectStdDevCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sqr,\n struct TensorWrapper dst, struct RectWrapper rect)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), result, rect, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::rectStdDev(src.toGpuMat(), sqr.toGpuMat(), dst.toGpuMat(), rect, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper normalizeCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper dst,\n double alpha, double beta, int norm_type, int dtype, struct TensorWrapper mask)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::normalize(src.toGpuMat(), result, alpha, beta, norm_type,\n dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::normalize(src.toGpuMat(), dst.toGpuMat(), alpha, beta, norm_type,\n dtype, TO_MAT_OR_NOARRAY(mask), prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper integralCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)\n{\n if (sum.isNull()) {\n cuda::GpuMat result;\n cuda::integral(src.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::integral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));\n return sum;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper sqrIntegralCuda(\n struct cutorchInfo info, struct TensorWrapper src, struct TensorWrapper sum)\n{\n if (sum.isNull()) {\n cuda::GpuMat result;\n cuda::sqrIntegral(src.toGpuMat(), result, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::sqrIntegral(src.toGpuMat(), sum.toGpuMat(), prepareStream(info));\n return sum;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper mulSpectrumsCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,\n struct TensorWrapper dst, int flags, bool conjB)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, conjB, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::mulSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, conjB, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper mulAndScaleSpectrumsCuda(\n struct cutorchInfo info, struct TensorWrapper src1, struct TensorWrapper src2,\n struct TensorWrapper dst, int flags, float scale, bool conjB)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), result, flags, scale, conjB, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::mulAndScaleSpectrums(src1.toGpuMat(), src2.toGpuMat(), dst.toGpuMat(), flags, scale, conjB, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct TensorWrapper dftCuda(\n struct cutorchInfo info, struct TensorWrapper src,\n struct TensorWrapper dst, struct SizeWrapper dft_size, int flags)\n{\n if (dst.isNull()) {\n cuda::GpuMat result;\n cuda::dft(src.toGpuMat(), result, dft_size, flags, prepareStream(info));\n return TensorWrapper(result, info.state);\n } else {\n cuda::dft(src.toGpuMat(), dst.toGpuMat(), dft_size, flags, prepareStream(info));\n return dst;\n }\n}\n\nextern \"C\"\nstruct ConvolutionPtr Convolution_ctorCuda(\n struct cutorchInfo info, struct SizeWrapper user_block_size)\n{\n return rescueObjectFromPtr(cuda::createConvolution(user_block_size));\n}\n\nextern \"C\"\nstruct TensorWrapper Convolution_convolveCuda(\n struct cutorchInfo info, struct ConvolutionPtr ptr, struct TensorWrapper image,\n struct TensorWrapper templ, struct TensorWrapper result, bool ccor)\n{\n if (result.isNull()) {\n cuda::GpuMat resultMat;\n ptr->convolve(image.toGpuMat(), templ.toGpuMat(), resultMat, ccor, prepareStream(info));\n return TensorWrapper(resultMat, info.state);\n } else {\n ptr->convolve(image.toGpuMat(), templ.toGpuMat(), result.toGpuMat(), ccor);\n return result;\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\nclass gcd_utility final {\npublic:\n class scoped_queue final {\n public:\n scoped_queue(void) {\n auto label = get_next_queue_label();\n queue_ = dispatch_queue_create(label.c_str(), nullptr);\n }\n\n ~scoped_queue(void) {\n dispatch_release(queue_);\n }\n\n dispatch_queue_t _Nonnull get(void) { return queue_; }\n\n private:\n dispatch_queue_t _Nonnull queue_;\n };\n\nprivate:\n static std::string get_next_queue_label(void) {\n static std::mutex mutex;\n static int id = 0;\n\n std::lock_guard guard(mutex);\n\n std::stringstream stream;\n stream << \"org.pqrs.gcd_utility.\" << id++;\n return stream.str();\n }\n};\nadd gcd_utility::scoped_queue::get_label#pragma once\n\n#include \n#include \n#include \n\nclass gcd_utility final {\npublic:\n class scoped_queue final {\n public:\n scoped_queue(void) {\n auto label = get_next_queue_label();\n queue_ = dispatch_queue_create(label.c_str(), nullptr);\n }\n\n ~scoped_queue(void) {\n dispatch_release(queue_);\n }\n\n dispatch_queue_t _Nonnull get(void) { return queue_; }\n\n std::string get_label(void) {\n auto p = dispatch_queue_get_label(queue_);\n return p ? p : \"\";\n }\n\n private:\n dispatch_queue_t _Nonnull queue_;\n };\n\nprivate:\n static std::string get_next_queue_label(void) {\n static std::mutex mutex;\n static int id = 0;\n\n std::lock_guard guard(mutex);\n\n std::stringstream stream;\n stream << \"org.pqrs.gcd_utility.\" << id++;\n return stream.str();\n }\n};\n<|endoftext|>"} {"text":"#include \"SysConfig.h\"\n#if(HAS_PCA9539)\n\n#include \n#include \"CPCA9539.h\"\n#include \"CTimer.h\"\n#include \"NDataManager.h\"\n\nnamespace\n{\n CTimer pcaSampleTimer;\n\n namespace knight_rider\n { \n \/\/Knight rider stuff\n \n \/\/Bit counter\n uint8_t counter;\n \n \/\/Value that stores the mutated counter\n uint8_t value;\n\n \/\/Bit mask for the PCA\n uint8_t bitmask = 0x1F;\n\n bool firstPass;\n }\n}\n\nCPCA9539::CPCA9539( CI2C *i2cInterfaceIn )\n : m_pca( i2cInterfaceIn )\n{\n\n}\n\nvoid CPCA9539::Initialize()\n{\n Serial.println( \"CPCA9539.Status:INIT;\" );\n\n \/\/Timer resets\n pcaSampleTimer.Reset();\n\n \/\/Knight rider stuff\n knight_rider::counter = 0;\n knight_rider::firstPass = true;\n\n \/\/Expander init\n m_pca.Initialize();\n m_pca.PinMode( OUTPUT );\n\n Serial.println( \"CPCA9539.Status:POST_INIT;\");\n}\n\nvoid CPCA9539::Update( CCommand &commandIn )\n{\n if( pcaSampleTimer.HasElapsed( 100 ) )\n {\n KnightRider(); \n }\n}\n\nvoid CPCA9539::KnightRider()\n{\n if( knight_rider::firstPass )\n {\n if( knight_rider::counter = 0 )\n {\n knight_rider::counter = 2;\n }\n\n \/\/For the PCA, 1 is low and 0 is high\n \/\/So we need to not and then mask the counter to get the desired pattern\n knight_rider::value = ~(knight_rider::counter);\n knight_rider::value &= knight_rider::bitmask;\n\n \/\/Write the desired pattern\n auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );\n if( ret != pca9539::ERetCode::SUCCESS )\n {\n Serial.println(ret);\n }\n\n \/\/Increase the counter\n knight_rider::counter <<= 1;\n\n if( knight_rider::counter == 16 )\n {\n \/\/Start the second half of the pattern\n knight_rider::firstPass = false;\n }\n } \n else\n {\n \/\/For the PCA, 1 is low and 0 is high\n \/\/So we need to not and then mask the counter to get the desired pattern\n knight_rider::value = ~(knight_rider::counter);\n knight_rider::value &= knight_rider::bitmask;\n\n \/\/Write the desired pattern\n auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );\n if( ret != pca9539::ERetCode::SUCCESS )\n {\n Serial.println(ret);\n }\n\n \/\/Increase the counter\n knight_rider::counter >>= 1;\n\n if( knight_rider::counter == 0 )\n {\n \/\/Reset the counter to the first section of the pattern\n knight_rider::firstPass = true;\n }\n } \n}\n\n\n#endiftypo Honestly I don't know how this compiles w\/o warns#include \"SysConfig.h\"\n#if(HAS_PCA9539)\n\n#include \n#include \"CPCA9539.h\"\n#include \"CTimer.h\"\n#include \"NDataManager.h\"\n\nnamespace\n{\n CTimer pcaSampleTimer;\n\n namespace knight_rider\n { \n \/\/Knight rider stuff\n \n \/\/Bit counter\n uint8_t counter;\n \n \/\/Value that stores the mutated counter\n uint8_t value;\n\n \/\/Bit mask for the PCA\n uint8_t bitmask = 0x1F;\n\n bool firstPass;\n }\n}\n\nCPCA9539::CPCA9539( CI2C *i2cInterfaceIn )\n : m_pca( i2cInterfaceIn )\n{\n\n}\n\nvoid CPCA9539::Initialize()\n{\n Serial.println( \"CPCA9539.Status:INIT;\" );\n\n \/\/Timer resets\n pcaSampleTimer.Reset();\n\n \/\/Knight rider stuff\n knight_rider::counter = 0;\n knight_rider::firstPass = true;\n\n \/\/Expander init\n m_pca.Initialize();\n m_pca.PinMode( OUTPUT );\n\n Serial.println( \"CPCA9539.Status:POST_INIT;\");\n}\n\nvoid CPCA9539::Update( CCommand &commandIn )\n{\n if( pcaSampleTimer.HasElapsed( 100 ) )\n {\n KnightRider(); \n }\n}\n\nvoid CPCA9539::KnightRider()\n{\n if( knight_rider::firstPass )\n {\n if( knight_rider::counter == 0 )\n {\n knight_rider::counter = 2;\n }\n\n \/\/For the PCA, 1 is low and 0 is high\n \/\/So we need to not and then mask the counter to get the desired pattern\n knight_rider::value = ~(knight_rider::counter);\n knight_rider::value &= knight_rider::bitmask;\n\n \/\/Write the desired pattern\n auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );\n if( ret != pca9539::ERetCode::SUCCESS )\n {\n Serial.println(ret);\n }\n\n \/\/Increase the counter\n knight_rider::counter <<= 1;\n\n if( knight_rider::counter == 16 )\n {\n \/\/Start the second half of the pattern\n knight_rider::firstPass = false;\n }\n } \n else\n {\n \/\/For the PCA, 1 is low and 0 is high\n \/\/So we need to not and then mask the counter to get the desired pattern\n knight_rider::value = ~(knight_rider::counter);\n knight_rider::value &= knight_rider::bitmask;\n\n \/\/Write the desired pattern\n auto ret = m_pca.DigitalWriteDecimal( knight_rider::value );\n if( ret != pca9539::ERetCode::SUCCESS )\n {\n Serial.println(ret);\n }\n\n \/\/Increase the counter\n knight_rider::counter >>= 1;\n\n if( knight_rider::counter == 0 )\n {\n \/\/Reset the counter to the first section of the pattern\n knight_rider::firstPass = true;\n }\n } \n}\n\n\n#endif<|endoftext|>"} {"text":"\/*\n * AddSimMessage.cpp\n *\n * Created on: 18.04.2016\n * Author: Marc Hartung\n *\/\n\n#include \"..\/..\/include\/messages\/AddSimMessage.hpp\"\n#include \"..\/..\/include\/messages\/AbstractMessage.hpp\"\n#include \"..\/..\/include\/AdditionalTypes.hpp\"\n#include \"..\/..\/include\/network_impl\/SimNetworkFunctions.hpp\"\n\n#include \n\nnamespace NetOff\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/AddSimRequestMessage\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n AddSimRequestMessage::AddSimRequestMessage(const int & id, const std::string & path)\n : AbstractMessage(InitialClientMessageSpecifyer::ADD_SIM)\n {\n _dataSize = sizeof(InitialClientMessageSpecifyer) + sizeof(int) + getStringDataSize(path);\n _data = std::shared_ptr(new char[_dataSize]);\n char * p = _data.get();\n p = saveShiftIntegralInData(InitialClientMessageSpecifyer::ADD_SIM, p);\n p = saveShiftIntegralInData(id, p);\n saveStringInData(path, p);\n }\n\n AddSimRequestMessage::AddSimRequestMessage(std::shared_ptr & data)\n : AbstractMessage(*reinterpret_cast(data.get())),\n _data(data),\n _dataSize(0)\n {\n }\n\n char * AddSimRequestMessage::data()\n {\n return _data.get();\n }\n\n const char * AddSimRequestMessage::data() const\n {\n return _data.get();\n }\n\n size_t AddSimRequestMessage::dataSize() const\n {\n return _dataSize;\n }\n\n int AddSimRequestMessage::getSimId()\n {\n return *reinterpret_cast(shift(_data.get()));\n }\n\n std::string AddSimRequestMessage::getPath()\n {\n return createStringFromData(shift(shift(_data.get())));\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/AddSimRequestSuccessMessage\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n AddSimSuccessMessage::AddSimSuccessMessage(const int & id, const VariableList & inputs, const VariableList & outputs)\n : AbstractMessage(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM),\n _dataSize(0)\n\n {\n _dataSize = sizeof(InitialServerMessageSpecifyer) + sizeof(int) + inputs.dataSize() + outputs.dataSize();\n _data = std::shared_ptr(new char[_dataSize]);\n char * p = _data.get();\n p = saveShiftIntegralInData(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM, p);\n p = saveShiftIntegralInData(id, p);\n inputs.saveVariablesTo(p);\n p = shiftDataAccessable(inputs,p);\n outputs.saveVariablesTo(p);\n }\n\n AddSimSuccessMessage::AddSimSuccessMessage(std::shared_ptr & data)\n : AbstractMessage(getIntegralFromData(data.get())),\n _data(data),\n _dataSize(0)\n {\n }\n\n char * AddSimSuccessMessage::data()\n {\n return _data.get();\n }\n\n const char * AddSimSuccessMessage::data() const\n {\n return _data.get();\n }\n\n size_t AddSimSuccessMessage::dataSize() const\n {\n return _dataSize;\n }\n\n const int & AddSimSuccessMessage::getSimId() const\n {\n return *reinterpret_cast(shift(_data.get()));\n }\n\n VariableList AddSimSuccessMessage::getInputVariableList() const\n {\n return VariableList::getVariableListFromData(shift(shift(_data.get())));\n }\n\n VariableList AddSimSuccessMessage::getOutputVariableList() const\n {\n return VariableList::getVariableListFromData(shift(shiftDataAccessable(getInputVariableList(),shift(_data.get()))));\n }\n\n std::string AddSimSuccessMessage::getPath()\n {\n return createStringFromData(shift(shift(_data.get())));\n }\n}\n\nAdd default initialization of members to constructor\/*\n * AddSimMessage.cpp\n *\n * Created on: 18.04.2016\n * Author: Marc Hartung\n *\/\n\n#include \"..\/..\/include\/messages\/AddSimMessage.hpp\"\n#include \"..\/..\/include\/messages\/AbstractMessage.hpp\"\n#include \"..\/..\/include\/AdditionalTypes.hpp\"\n#include \"..\/..\/include\/network_impl\/SimNetworkFunctions.hpp\"\n\n#include \n\nnamespace NetOff\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/AddSimRequestMessage\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n AddSimRequestMessage::AddSimRequestMessage(const int & id, const std::string & path)\n : AbstractMessage(InitialClientMessageSpecifyer::ADD_SIM),\n _data(nullptr),\n _dataSize(0)\n {\n _dataSize = sizeof(InitialClientMessageSpecifyer) + sizeof(int) + getStringDataSize(path);\n _data = std::shared_ptr(new char[_dataSize]);\n char * p = _data.get();\n p = saveShiftIntegralInData(InitialClientMessageSpecifyer::ADD_SIM, p);\n p = saveShiftIntegralInData(id, p);\n saveStringInData(path, p);\n }\n\n AddSimRequestMessage::AddSimRequestMessage(std::shared_ptr & data)\n : AbstractMessage(*reinterpret_cast(data.get())),\n _data(data),\n _dataSize(0)\n {\n }\n\n char * AddSimRequestMessage::data()\n {\n return _data.get();\n }\n\n const char * AddSimRequestMessage::data() const\n {\n return _data.get();\n }\n\n size_t AddSimRequestMessage::dataSize() const\n {\n return _dataSize;\n }\n\n int AddSimRequestMessage::getSimId()\n {\n return *reinterpret_cast(shift(_data.get()));\n }\n\n std::string AddSimRequestMessage::getPath()\n {\n return createStringFromData(shift(shift(_data.get())));\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/AddSimRequestSuccessMessage\/\/\/\/\/\/\/\/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n AddSimSuccessMessage::AddSimSuccessMessage(const int & id, const VariableList & inputs, const VariableList & outputs)\n : AbstractMessage(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM),\n _data(nullptr),\n _dataSize(0)\n {\n _dataSize = sizeof(InitialServerMessageSpecifyer) + sizeof(int) + inputs.dataSize() + outputs.dataSize();\n _data = std::shared_ptr(new char[_dataSize]);\n char * p = _data.get();\n p = saveShiftIntegralInData(InitialServerMessageSpecifyer::SUCCESS_ADD_SIM, p);\n p = saveShiftIntegralInData(id, p);\n inputs.saveVariablesTo(p);\n p = shiftDataAccessable(inputs, p);\n outputs.saveVariablesTo(p);\n }\n\n AddSimSuccessMessage::AddSimSuccessMessage(std::shared_ptr & data)\n : AbstractMessage(getIntegralFromData(data.get())),\n _data(data),\n _dataSize(0)\n {\n }\n\n char * AddSimSuccessMessage::data()\n {\n return _data.get();\n }\n\n const char * AddSimSuccessMessage::data() const\n {\n return _data.get();\n }\n\n size_t AddSimSuccessMessage::dataSize() const\n {\n return _dataSize;\n }\n\n const int & AddSimSuccessMessage::getSimId() const\n {\n return *reinterpret_cast(shift(_data.get()));\n }\n\n VariableList AddSimSuccessMessage::getInputVariableList() const\n {\n return VariableList::getVariableListFromData(shift(shift(_data.get())));\n }\n\n VariableList AddSimSuccessMessage::getOutputVariableList() const\n {\n return VariableList::getVariableListFromData(shift(shiftDataAccessable(getInputVariableList(), shift(_data.get()))));\n }\n\n std::string AddSimSuccessMessage::getPath()\n {\n return createStringFromData(shift(shift(_data.get())));\n }\n}\n<|endoftext|>"} {"text":"\/*!\r\n * Copyright (c) 2017 Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License. See LICENSE file in the project root for license information.\r\n *\/\r\n#ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_\r\n#define LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/*\r\n * Implements three related metrics:\r\n *\r\n * (1) standard cross-entropy that can be used for continuous labels in [0, 1]\r\n * (2) \"intensity-weighted\" cross-entropy, also for continuous labels in [0, 1]\r\n * (3) Kullback-Leibler divergence, also for continuous labels in [0, 1]\r\n *\r\n * (3) adds an offset term to (1); the entropy of the label\r\n *\r\n * See xentropy_objective.hpp for further details.\r\n *\r\n *\/\r\n\r\nnamespace LightGBM {\r\n\r\n \/\/ label should be in interval [0, 1];\r\n \/\/ prob should be in interval (0, 1); prob is clipped if needed\r\n inline static double XentLoss(label_t label, double prob) {\r\n const double log_arg_epsilon = 1.0e-12;\r\n double a = label;\r\n if (prob > log_arg_epsilon) {\r\n a *= std::log(prob);\r\n } else {\r\n a *= std::log(log_arg_epsilon);\r\n }\r\n double b = 1.0f - label;\r\n if (1.0f - prob > log_arg_epsilon) {\r\n b *= std::log(1.0f - prob);\r\n } else {\r\n b *= std::log(log_arg_epsilon);\r\n }\r\n return - (a + b);\r\n }\r\n\r\n \/\/ hhat >(=) 0 assumed; and weight > 0 required; but not checked here\r\n inline static double XentLambdaLoss(label_t label, label_t weight, double hhat) {\r\n return XentLoss(label, 1.0f - std::exp(-weight * hhat));\r\n }\r\n\r\n \/\/ Computes the (negative) entropy for label p; p should be in interval [0, 1];\r\n \/\/ This is used to presum the KL-divergence offset term (to be _added_ to the cross-entropy loss).\r\n \/\/ NOTE: x*log(x) = 0 for x=0,1; so only add when in (0, 1); avoid log(0)*0\r\n inline static double YentLoss(double p) {\r\n double hp = 0.0;\r\n if (p > 0) hp += p * std::log(p);\r\n double q = 1.0f - p;\r\n if (q > 0) hp += q * std::log(q);\r\n return hp;\r\n }\r\n\r\n\/\/\r\n\/\/ CrossEntropyMetric : \"xentropy\" : (optional) weights are used linearly\r\n\/\/\r\nclass CrossEntropyMetric : public Metric {\r\n public:\r\n explicit CrossEntropyMetric(const Config&) {}\r\n virtual ~CrossEntropyMetric() {}\r\n\r\n void Init(const Metadata& metadata, data_size_t num_data) override {\r\n name_.emplace_back(\"cross_entropy\");\r\n num_data_ = num_data;\r\n label_ = metadata.label();\r\n weights_ = metadata.weights();\r\n\r\n CHECK_NOTNULL(label_);\r\n\r\n \/\/ ensure that labels are in interval [0, 1], interval ends included\r\n Common::CheckElementsIntervalClosed(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str());\r\n Log::Info(\"[%s:%s]: (metric) labels passed interval [0, 1] check\", GetName()[0].c_str(), __func__);\r\n\r\n \/\/ check that weights are non-negative and sum is positive\r\n if (weights_ == nullptr) {\r\n sum_weights_ = static_cast(num_data_);\r\n } else {\r\n label_t minw;\r\n Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast(nullptr), &sum_weights_);\r\n if (minw < 0.0f) {\r\n Log::Fatal(\"[%s:%s]: (metric) weights not allowed to be negative\", GetName()[0].c_str(), __func__);\r\n }\r\n }\r\n\r\n \/\/ check weight sum (may fail to be zero)\r\n if (sum_weights_ <= 0.0f) {\r\n Log::Fatal(\"[%s:%s]: sum-of-weights = %f is non-positive\", __func__, GetName()[0].c_str(), sum_weights_);\r\n }\r\n Log::Info(\"[%s:%s]: sum-of-weights = %f\", GetName()[0].c_str(), __func__, sum_weights_);\r\n }\r\n\r\n std::vector Eval(const double* score, const ObjectiveFunction* objective) const override {\r\n double sum_loss = 0.0f;\r\n if (objective == nullptr) {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]); \/\/ NOTE: does not work unless score is a probability\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; \/\/ NOTE: does not work unless score is a probability\r\n }\r\n }\r\n } else {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p) * weights_[i];\r\n }\r\n }\r\n }\r\n double loss = sum_loss \/ sum_weights_;\r\n return std::vector(1, loss);\r\n }\r\n\r\n const std::vector& GetName() const override {\r\n return name_;\r\n }\r\n\r\n double factor_to_bigger_better() const override {\r\n return -1.0f; \/\/ negative means smaller loss is better, positive means larger loss is better\r\n }\r\n\r\n private:\r\n \/*! \\brief Number of data points *\/\r\n data_size_t num_data_;\r\n \/*! \\brief Pointer to label *\/\r\n const label_t* label_;\r\n \/*! \\brief Pointer to weights *\/\r\n const label_t* weights_;\r\n \/*! \\brief Sum of weights *\/\r\n double sum_weights_;\r\n \/*! \\brief Name of this metric *\/\r\n std::vector name_;\r\n};\r\n\r\n\/\/\r\n\/\/ CrossEntropyLambdaMetric : \"xentlambda\" : (optional) weights have a different meaning than for \"xentropy\"\r\n\/\/ ATTENTION: Supposed to be used when the objective also is \"xentlambda\"\r\n\/\/\r\nclass CrossEntropyLambdaMetric : public Metric {\r\n public:\r\n explicit CrossEntropyLambdaMetric(const Config&) {}\r\n virtual ~CrossEntropyLambdaMetric() {}\r\n\r\n void Init(const Metadata& metadata, data_size_t num_data) override {\r\n name_.emplace_back(\"cross_entropy_lambda\");\r\n num_data_ = num_data;\r\n label_ = metadata.label();\r\n weights_ = metadata.weights();\r\n\r\n CHECK_NOTNULL(label_);\r\n Common::CheckElementsIntervalClosed(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str());\r\n Log::Info(\"[%s:%s]: (metric) labels passed interval [0, 1] check\", GetName()[0].c_str(), __func__);\r\n\r\n \/\/ check all weights are strictly positive; throw error if not\r\n if (weights_ != nullptr) {\r\n label_t minw;\r\n Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast(nullptr), static_cast(nullptr));\r\n if (minw <= 0.0f) {\r\n Log::Fatal(\"[%s:%s]: (metric) all weights must be positive\", GetName()[0].c_str(), __func__);\r\n }\r\n }\r\n }\r\n\r\n std::vector Eval(const double* score, const ObjectiveFunction* objective) const override {\r\n double sum_loss = 0.0f;\r\n if (objective == nullptr) {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = std::log(1.0f + std::exp(score[i])); \/\/ auto-convert\r\n sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = std::log(1.0f + std::exp(score[i])); \/\/ auto-convert\r\n sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat);\r\n }\r\n }\r\n } else {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = 0;\r\n objective->ConvertOutput(&score[i], &hhat); \/\/ NOTE: this only works if objective = \"xentlambda\"\r\n sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = 0;\r\n objective->ConvertOutput(&score[i], &hhat); \/\/ NOTE: this only works if objective = \"xentlambda\"\r\n sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat);\r\n }\r\n }\r\n }\r\n return std::vector(1, sum_loss \/ static_cast(num_data_));\r\n }\r\n\r\n const std::vector& GetName() const override {\r\n return name_;\r\n }\r\n\r\n double factor_to_bigger_better() const override {\r\n return -1.0f;\r\n }\r\n\r\n private:\r\n \/*! \\brief Number of data points *\/\r\n data_size_t num_data_;\r\n \/*! \\brief Pointer to label *\/\r\n const label_t* label_;\r\n \/*! \\brief Pointer to weights *\/\r\n const label_t* weights_;\r\n \/*! \\brief Name of this metric *\/\r\n std::vector name_;\r\n};\r\n\r\n\/\/\r\n\/\/ KullbackLeiblerDivergence : \"kldiv\" : (optional) weights are used linearly\r\n\/\/\r\nclass KullbackLeiblerDivergence : public Metric {\r\n public:\r\n explicit KullbackLeiblerDivergence(const Config&) {}\r\n virtual ~KullbackLeiblerDivergence() {}\r\n\r\n void Init(const Metadata& metadata, data_size_t num_data) override {\r\n name_.emplace_back(\"kullback_leibler\");\r\n num_data_ = num_data;\r\n label_ = metadata.label();\r\n weights_ = metadata.weights();\r\n\r\n CHECK_NOTNULL(label_);\r\n Common::CheckElementsIntervalClosed(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str());\r\n Log::Info(\"[%s:%s]: (metric) labels passed interval [0, 1] check\", GetName()[0].c_str(), __func__);\r\n\r\n if (weights_ == nullptr) {\r\n sum_weights_ = static_cast(num_data_);\r\n } else {\r\n label_t minw;\r\n Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast(nullptr), &sum_weights_);\r\n if (minw < 0.0f) {\r\n Log::Fatal(\"[%s:%s]: (metric) at least one weight is negative\", GetName()[0].c_str(), __func__);\r\n }\r\n }\r\n\r\n \/\/ check weight sum\r\n if (sum_weights_ <= 0.0f) {\r\n Log::Fatal(\"[%s:%s]: sum-of-weights = %f is non-positive\", GetName()[0].c_str(), __func__, sum_weights_);\r\n }\r\n\r\n Log::Info(\"[%s:%s]: sum-of-weights = %f\", GetName()[0].c_str(), __func__, sum_weights_);\r\n\r\n \/\/ evaluate offset term\r\n presum_label_entropy_ = 0.0f;\r\n if (weights_ == nullptr) {\r\n \/\/ #pragma omp parallel for schedule(static)\r\n for (data_size_t i = 0; i < num_data; ++i) {\r\n presum_label_entropy_ += YentLoss(label_[i]);\r\n }\r\n } else {\r\n \/\/ #pragma omp parallel for schedule(static)\r\n for (data_size_t i = 0; i < num_data; ++i) {\r\n presum_label_entropy_ += YentLoss(label_[i]) * weights_[i];\r\n }\r\n }\r\n presum_label_entropy_ \/= sum_weights_;\r\n\r\n \/\/ communicate the value of the offset term to be added\r\n Log::Info(\"%s offset term = %f\", GetName()[0].c_str(), presum_label_entropy_);\r\n }\r\n\r\n std::vector Eval(const double* score, const ObjectiveFunction* objective) const override {\r\n double sum_loss = 0.0f;\r\n if (objective == nullptr) {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]); \/\/ NOTE: does not work unless score is a probability\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; \/\/ NOTE: does not work unless score is a probability\r\n }\r\n }\r\n } else {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p) * weights_[i];\r\n }\r\n }\r\n }\r\n double loss = presum_label_entropy_ + sum_loss \/ sum_weights_;\r\n return std::vector(1, loss);\r\n }\r\n\r\n const std::vector& GetName() const override {\r\n return name_;\r\n }\r\n\r\n double factor_to_bigger_better() const override {\r\n return -1.0f;\r\n }\r\n\r\n private:\r\n \/*! \\brief Number of data points *\/\r\n data_size_t num_data_;\r\n \/*! \\brief Pointer to label *\/\r\n const label_t* label_;\r\n \/*! \\brief Pointer to weights *\/\r\n const label_t* weights_;\r\n \/*! \\brief Sum of weights *\/\r\n double sum_weights_;\r\n \/*! \\brief Offset term to cross-entropy; precomputed during init *\/\r\n double presum_label_entropy_;\r\n \/*! \\brief Name of this metric *\/\r\n std::vector name_;\r\n};\r\n\r\n} \/\/ end namespace LightGBM\r\n\r\n#endif \/\/ end #ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_\r\nremove commented-out code in cross-entropy metric source (#3999)\/*!\r\n * Copyright (c) 2017 Microsoft Corporation. All rights reserved.\r\n * Licensed under the MIT License. See LICENSE file in the project root for license information.\r\n *\/\r\n#ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_\r\n#define LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/*\r\n * Implements three related metrics:\r\n *\r\n * (1) standard cross-entropy that can be used for continuous labels in [0, 1]\r\n * (2) \"intensity-weighted\" cross-entropy, also for continuous labels in [0, 1]\r\n * (3) Kullback-Leibler divergence, also for continuous labels in [0, 1]\r\n *\r\n * (3) adds an offset term to (1); the entropy of the label\r\n *\r\n * See xentropy_objective.hpp for further details.\r\n *\r\n *\/\r\n\r\nnamespace LightGBM {\r\n\r\n \/\/ label should be in interval [0, 1];\r\n \/\/ prob should be in interval (0, 1); prob is clipped if needed\r\n inline static double XentLoss(label_t label, double prob) {\r\n const double log_arg_epsilon = 1.0e-12;\r\n double a = label;\r\n if (prob > log_arg_epsilon) {\r\n a *= std::log(prob);\r\n } else {\r\n a *= std::log(log_arg_epsilon);\r\n }\r\n double b = 1.0f - label;\r\n if (1.0f - prob > log_arg_epsilon) {\r\n b *= std::log(1.0f - prob);\r\n } else {\r\n b *= std::log(log_arg_epsilon);\r\n }\r\n return - (a + b);\r\n }\r\n\r\n \/\/ hhat >(=) 0 assumed; and weight > 0 required; but not checked here\r\n inline static double XentLambdaLoss(label_t label, label_t weight, double hhat) {\r\n return XentLoss(label, 1.0f - std::exp(-weight * hhat));\r\n }\r\n\r\n \/\/ Computes the (negative) entropy for label p; p should be in interval [0, 1];\r\n \/\/ This is used to presum the KL-divergence offset term (to be _added_ to the cross-entropy loss).\r\n \/\/ NOTE: x*log(x) = 0 for x=0,1; so only add when in (0, 1); avoid log(0)*0\r\n inline static double YentLoss(double p) {\r\n double hp = 0.0;\r\n if (p > 0) hp += p * std::log(p);\r\n double q = 1.0f - p;\r\n if (q > 0) hp += q * std::log(q);\r\n return hp;\r\n }\r\n\r\n\/\/\r\n\/\/ CrossEntropyMetric : \"xentropy\" : (optional) weights are used linearly\r\n\/\/\r\nclass CrossEntropyMetric : public Metric {\r\n public:\r\n explicit CrossEntropyMetric(const Config&) {}\r\n virtual ~CrossEntropyMetric() {}\r\n\r\n void Init(const Metadata& metadata, data_size_t num_data) override {\r\n name_.emplace_back(\"cross_entropy\");\r\n num_data_ = num_data;\r\n label_ = metadata.label();\r\n weights_ = metadata.weights();\r\n\r\n CHECK_NOTNULL(label_);\r\n\r\n \/\/ ensure that labels are in interval [0, 1], interval ends included\r\n Common::CheckElementsIntervalClosed(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str());\r\n Log::Info(\"[%s:%s]: (metric) labels passed interval [0, 1] check\", GetName()[0].c_str(), __func__);\r\n\r\n \/\/ check that weights are non-negative and sum is positive\r\n if (weights_ == nullptr) {\r\n sum_weights_ = static_cast(num_data_);\r\n } else {\r\n label_t minw;\r\n Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast(nullptr), &sum_weights_);\r\n if (minw < 0.0f) {\r\n Log::Fatal(\"[%s:%s]: (metric) weights not allowed to be negative\", GetName()[0].c_str(), __func__);\r\n }\r\n }\r\n\r\n \/\/ check weight sum (may fail to be zero)\r\n if (sum_weights_ <= 0.0f) {\r\n Log::Fatal(\"[%s:%s]: sum-of-weights = %f is non-positive\", __func__, GetName()[0].c_str(), sum_weights_);\r\n }\r\n Log::Info(\"[%s:%s]: sum-of-weights = %f\", GetName()[0].c_str(), __func__, sum_weights_);\r\n }\r\n\r\n std::vector Eval(const double* score, const ObjectiveFunction* objective) const override {\r\n double sum_loss = 0.0f;\r\n if (objective == nullptr) {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]); \/\/ NOTE: does not work unless score is a probability\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; \/\/ NOTE: does not work unless score is a probability\r\n }\r\n }\r\n } else {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p) * weights_[i];\r\n }\r\n }\r\n }\r\n double loss = sum_loss \/ sum_weights_;\r\n return std::vector(1, loss);\r\n }\r\n\r\n const std::vector& GetName() const override {\r\n return name_;\r\n }\r\n\r\n double factor_to_bigger_better() const override {\r\n return -1.0f; \/\/ negative means smaller loss is better, positive means larger loss is better\r\n }\r\n\r\n private:\r\n \/*! \\brief Number of data points *\/\r\n data_size_t num_data_;\r\n \/*! \\brief Pointer to label *\/\r\n const label_t* label_;\r\n \/*! \\brief Pointer to weights *\/\r\n const label_t* weights_;\r\n \/*! \\brief Sum of weights *\/\r\n double sum_weights_;\r\n \/*! \\brief Name of this metric *\/\r\n std::vector name_;\r\n};\r\n\r\n\/\/\r\n\/\/ CrossEntropyLambdaMetric : \"xentlambda\" : (optional) weights have a different meaning than for \"xentropy\"\r\n\/\/ ATTENTION: Supposed to be used when the objective also is \"xentlambda\"\r\n\/\/\r\nclass CrossEntropyLambdaMetric : public Metric {\r\n public:\r\n explicit CrossEntropyLambdaMetric(const Config&) {}\r\n virtual ~CrossEntropyLambdaMetric() {}\r\n\r\n void Init(const Metadata& metadata, data_size_t num_data) override {\r\n name_.emplace_back(\"cross_entropy_lambda\");\r\n num_data_ = num_data;\r\n label_ = metadata.label();\r\n weights_ = metadata.weights();\r\n\r\n CHECK_NOTNULL(label_);\r\n Common::CheckElementsIntervalClosed(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str());\r\n Log::Info(\"[%s:%s]: (metric) labels passed interval [0, 1] check\", GetName()[0].c_str(), __func__);\r\n\r\n \/\/ check all weights are strictly positive; throw error if not\r\n if (weights_ != nullptr) {\r\n label_t minw;\r\n Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast(nullptr), static_cast(nullptr));\r\n if (minw <= 0.0f) {\r\n Log::Fatal(\"[%s:%s]: (metric) all weights must be positive\", GetName()[0].c_str(), __func__);\r\n }\r\n }\r\n }\r\n\r\n std::vector Eval(const double* score, const ObjectiveFunction* objective) const override {\r\n double sum_loss = 0.0f;\r\n if (objective == nullptr) {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = std::log(1.0f + std::exp(score[i])); \/\/ auto-convert\r\n sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = std::log(1.0f + std::exp(score[i])); \/\/ auto-convert\r\n sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat);\r\n }\r\n }\r\n } else {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = 0;\r\n objective->ConvertOutput(&score[i], &hhat); \/\/ NOTE: this only works if objective = \"xentlambda\"\r\n sum_loss += XentLambdaLoss(label_[i], 1.0f, hhat);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double hhat = 0;\r\n objective->ConvertOutput(&score[i], &hhat); \/\/ NOTE: this only works if objective = \"xentlambda\"\r\n sum_loss += XentLambdaLoss(label_[i], weights_[i], hhat);\r\n }\r\n }\r\n }\r\n return std::vector(1, sum_loss \/ static_cast(num_data_));\r\n }\r\n\r\n const std::vector& GetName() const override {\r\n return name_;\r\n }\r\n\r\n double factor_to_bigger_better() const override {\r\n return -1.0f;\r\n }\r\n\r\n private:\r\n \/*! \\brief Number of data points *\/\r\n data_size_t num_data_;\r\n \/*! \\brief Pointer to label *\/\r\n const label_t* label_;\r\n \/*! \\brief Pointer to weights *\/\r\n const label_t* weights_;\r\n \/*! \\brief Name of this metric *\/\r\n std::vector name_;\r\n};\r\n\r\n\/\/\r\n\/\/ KullbackLeiblerDivergence : \"kldiv\" : (optional) weights are used linearly\r\n\/\/\r\nclass KullbackLeiblerDivergence : public Metric {\r\n public:\r\n explicit KullbackLeiblerDivergence(const Config&) {}\r\n virtual ~KullbackLeiblerDivergence() {}\r\n\r\n void Init(const Metadata& metadata, data_size_t num_data) override {\r\n name_.emplace_back(\"kullback_leibler\");\r\n num_data_ = num_data;\r\n label_ = metadata.label();\r\n weights_ = metadata.weights();\r\n\r\n CHECK_NOTNULL(label_);\r\n Common::CheckElementsIntervalClosed(label_, 0.0f, 1.0f, num_data_, GetName()[0].c_str());\r\n Log::Info(\"[%s:%s]: (metric) labels passed interval [0, 1] check\", GetName()[0].c_str(), __func__);\r\n\r\n if (weights_ == nullptr) {\r\n sum_weights_ = static_cast(num_data_);\r\n } else {\r\n label_t minw;\r\n Common::ObtainMinMaxSum(weights_, num_data_, &minw, static_cast(nullptr), &sum_weights_);\r\n if (minw < 0.0f) {\r\n Log::Fatal(\"[%s:%s]: (metric) at least one weight is negative\", GetName()[0].c_str(), __func__);\r\n }\r\n }\r\n\r\n \/\/ check weight sum\r\n if (sum_weights_ <= 0.0f) {\r\n Log::Fatal(\"[%s:%s]: sum-of-weights = %f is non-positive\", GetName()[0].c_str(), __func__, sum_weights_);\r\n }\r\n\r\n Log::Info(\"[%s:%s]: sum-of-weights = %f\", GetName()[0].c_str(), __func__, sum_weights_);\r\n\r\n \/\/ evaluate offset term\r\n presum_label_entropy_ = 0.0f;\r\n if (weights_ == nullptr) {\r\n for (data_size_t i = 0; i < num_data; ++i) {\r\n presum_label_entropy_ += YentLoss(label_[i]);\r\n }\r\n } else {\r\n for (data_size_t i = 0; i < num_data; ++i) {\r\n presum_label_entropy_ += YentLoss(label_[i]) * weights_[i];\r\n }\r\n }\r\n presum_label_entropy_ \/= sum_weights_;\r\n\r\n \/\/ communicate the value of the offset term to be added\r\n Log::Info(\"%s offset term = %f\", GetName()[0].c_str(), presum_label_entropy_);\r\n }\r\n\r\n std::vector Eval(const double* score, const ObjectiveFunction* objective) const override {\r\n double sum_loss = 0.0f;\r\n if (objective == nullptr) {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]); \/\/ NOTE: does not work unless score is a probability\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n sum_loss += XentLoss(label_[i], score[i]) * weights_[i]; \/\/ NOTE: does not work unless score is a probability\r\n }\r\n }\r\n } else {\r\n if (weights_ == nullptr) {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p);\r\n }\r\n } else {\r\n #pragma omp parallel for schedule(static) reduction(+:sum_loss)\r\n for (data_size_t i = 0; i < num_data_; ++i) {\r\n double p = 0;\r\n objective->ConvertOutput(&score[i], &p);\r\n sum_loss += XentLoss(label_[i], p) * weights_[i];\r\n }\r\n }\r\n }\r\n double loss = presum_label_entropy_ + sum_loss \/ sum_weights_;\r\n return std::vector(1, loss);\r\n }\r\n\r\n const std::vector& GetName() const override {\r\n return name_;\r\n }\r\n\r\n double factor_to_bigger_better() const override {\r\n return -1.0f;\r\n }\r\n\r\n private:\r\n \/*! \\brief Number of data points *\/\r\n data_size_t num_data_;\r\n \/*! \\brief Pointer to label *\/\r\n const label_t* label_;\r\n \/*! \\brief Pointer to weights *\/\r\n const label_t* weights_;\r\n \/*! \\brief Sum of weights *\/\r\n double sum_weights_;\r\n \/*! \\brief Offset term to cross-entropy; precomputed during init *\/\r\n double presum_label_entropy_;\r\n \/*! \\brief Name of this metric *\/\r\n std::vector name_;\r\n};\r\n\r\n} \/\/ end namespace LightGBM\r\n\r\n#endif \/\/ end #ifndef LIGHTGBM_METRIC_XENTROPY_METRIC_HPP_\r\n<|endoftext|>"} {"text":"#include \"GPU.H\"\n\n#include \"CAMERA.H\"\n#include \"LOAD_LEV.H\"\n#include \"PROFILE.H\"\n\n#include \n#include \n\nunsigned long GnFrameCounter = 19;\nunsigned long GnLastFrameCount = 19;\nstruct PSXTEXTSTRUCT* psxtextinfo;\nstruct PSXSPRITESTRUCT* psxspriteinfo;\nint rgbscaleme = 256;\nint gfx_debugging_mode;\nstruct DB_STRUCT db;\nstruct MMTEXTURE* RoomTextInfo;\nunsigned long GadwOrderingTables_V2[512];\nstatic int LnFlipFrame;\nunsigned long GadwOrderingTables[5128];\nunsigned long GadwPolygonBuffers[52260];\n\n\nvoid GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)\/\/5DF68(<), 5F1C8(<)\n{\n\tdb.order_table[0] = &pBuffers[0];\n\tdb.order_table[1] = &pBuffers[nOTSize];\n\tdb.nOTSize = nOTSize;\n\tdb.pickup_order_table[0] = &db.disp[1];\n\tdb.pickup_order_table[1] = &GadwOrderingTables_V2[256];\n#if 0\n\t\/\/Should be safe to use 32-bit ptrs tho\n\tdb.order_table[0] = (unsigned long*)((unsigned long) pBuffers & 0xFFFFFF);\n\tdb.order_table[1] = (unsigned long*)((unsigned long) &pBuffers[nOTSize] & 0xFFFFFF);\n\tdb.nOTSize = nOTSize;\n\tdb.pickup_order_table[0] = (unsigned long*)((unsigned long)&db.disp[1] & 0xFFFFFF);\n\tdb.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256] & 0xFFFFFF);\n#endif\n\treturn;\n}\n\nvoid GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)\/\/5DFB0(<), \n{\n#if 1\n\tdb.nPBSize = nPBSize;\n\tdb.poly_buffer[0] = &pBuffers[0];\n\tdb.poly_buffer[1] = &pBuffers[nPBSize];\n#else\n\tdb.nPBSize = nPBSize;\n\tdb.poly_buffer[0] = (unsigned long*)((unsigned long)pBuffers & 0xFFFFFF);\n\tdb.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize] & 0xFFFFFF);\n#endif\n\treturn;\n}\n\nvoid GPU_SyncBothScreens()\/\/5F374(<), 60054(<)\n{\n\tDrawSync(0);\n\n\tdb.current_buffer ^= 1;\n\tif (db.current_buffer != 0)\n\t{\n\t\tMoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);\n\t\t\/\/TODO: Verify ra += 0x10;! prolly else skip loc_5F3A8 (implemented but should be checked).\n\t}\n\telse\n\t{\n\t\t\/\/loc_5F3A8\n\t\tMoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);\n\t}\n\n\tDrawSync(0);\n\n\treturn;\n}\n\nvoid GPU_BeginScene()\/\/5F0F0(<), 5FDD0(<)\n{\n\tdb.ot = db.order_table[db.current_buffer];\n\tdb.polyptr = (char*)db.poly_buffer[db.current_buffer];\n\tdb.curpolybuf = (char*)db.poly_buffer[db.current_buffer];\n\tdb.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer]) + 26000;\n\tdb.pickup_ot = db.pickup_order_table[db.current_buffer];\n\tClearOTagR(db.order_table[db.current_buffer], db.nOTSize);\n\n\treturn;\n}\n\nint GPU_FlipNoIdle()\/\/5E078(<), 5F264(<)\n{\n#if INTERNAL\n\tif (ProfileDraw)\n\t{\n\t\tProfileRGB(255, 255, 255);\n\t\tProfileAddOT(&db.ot[0]);\n\t}\/\/loc_5E0B0\n#endif\n\n\tDrawSync(0);\/\/TODO confirm retail is sub_6B144 draw sync\n\n#if _INTERNAL\n\tif (ProfileDraw)\n\t{\n\t\tProfileAddDrawOT(&db.ot[0]);\n\t}\/\/loc_5E0D8\n#endif\n\n\tLnFlipFrame = GnLastFrameCount;\n\n\tif (GnLastFrameCount < 2)\n\t{\n\t\t\/\/loc_5E0F4\n\t\tdo\n\t\t{\n\t\t\tVSync(0);\n\t\t\tLnFlipFrame++;\n\t\t} while (LnFlipFrame < 2);\n\t}\n\telse\n\t{\n\t\t\/\/loc_5E120\n\t\tVSync(0);\n\t\tLnFlipFrame++;\n\t}\n\n\t\/\/loc_5E138\n\t\/\/v0 = db.current_buffer;\n\tGnLastFrameCount = 0;\n\tPutDispEnv(&db.disp[db.current_buffer]);\n\tDrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]);\n\n#if INTERNAL\n\tProfileStartCount();\n#endif\n\n\tdb.current_buffer ^= 1;\n\n\treturn LnFlipFrame;\n}\n\nvoid GPU_GetScreenPosition(short* x, short* y)\/\/5F34C, ?\n{\n\t*x = db.disp[0].screen.x;\n\t*y = db.disp[0].screen.y;\n\treturn;\n}\n\n\/* PSX VRAM (H)\n * ----------- 512px\n * | TL | TR | |\n * ----------- v\n * | BL | BR | \n * -----------\n *(W)1024px-->\n * \n *\/\nvoid GPU_ClearVRAM()\/\/5F2D0(<), 5FFB0(<) (F)\n{\n\tRECT r;\n\n\tDrawSync(0);\n\tVSync(0);\n\n\t\/\/Clear TL\n\tr.x = 0;\n\tr.y = 0;\n\tr.w = 512;\n\tr.h = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BL\n\tr.y = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BR\n\tr.x = 512;\n\tclear_a_rect(&r);\n\n\t\/\/Clear TR\n\tr.y = 0;\n\tclear_a_rect(&r);\n\n\tDrawSync(0);\n\tVSync(0);\n\n\treturn;\n}\n\nvoid clear_a_rect(RECT* r)\/\/5F334(<), 60014(<) (F)\n{\n\tClearImage(r, 0, 48, 0);\n\n\treturn;\n}\n\n\/\/@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.\nvoid GPU_FlipToBuffer(int buffer_index)\/\/5F3C8(<), 600A8(<) (F)\n{\n\tDrawSync(0);\n\tVSync(0);\n\n\tbuffer_index &= 1;\n\n\tif (buffer_index)\n\t{\n\t\tPutDispEnv(&db.disp[1]);\n\t\tdb.current_buffer = buffer_index ^ 1;\n\t\tPutDrawEnv(&db.draw[1]);\n\t}\n\telse\n\t{\n\t\tPutDispEnv(&db.disp[0]);\n\t\tdb.current_buffer = buffer_index ^ 1;\n\t\tPutDrawEnv(&db.draw[0]);\n\t}\n\n\treturn;\n}\n\nvoid GPU_EndScene()\/\/5DFDC(<), 5F23C(!)\n{\n#if 0\n\t\/\/int nPolys;\n\t\/\/static int nWorstPolys;\n\n\tlui\t$v0, 0x4EC4\n\tint a0 = &db.polyptr[0];\n\tint v1 = &db.curpolybuf[0];\n\tint v0 = 0x4EC4EC4F;\n\ta0 -= v1;\n\tv0 = a0 * v0;\n\ta0 >>= 31;\n\tv1 = psxtextinfo->u2v2pad;\n\tv0 >>= 4;\n\tv0 -= a0;\n\n\tif (v1 < v0)\n\t{\n\t\tu2v2pad = v0;\n\t}\/\/loc_5E020\n\t\n\t\/\/loc_5E020\n#endif\n\n\tOptimiseOTagR(&db.ot[0], db.nOTSize);\n\n#if 0\n\tnop\n\n\tProfileRGB(-1, -1, -1);\n\n\ta0 = db.nOTSize;\n\tdo_gfx_debug_mode(&db.ot[db.nOTSize - 1]);\n\n\tProfileRGB(0, -1, -1);\n#endif\n\treturn;\n}\n\nlong OptimiseOTagR(unsigned long* ot, int nOTSize)\/\/86CC4(<), 88D08(<)\n{\n\tunsigned long* a1;\n\tunsigned long* a3;\n\tunsigned long v0;\n\tunsigned long* v1;\n\tlong at = 0;\n\n\tif (nOTSize < 8)\n\t{\n\t\treturn 0;\n\t}\n\n\ta1 = &ot[nOTSize - 1];\n\tv1 = &ot[1];\n\tv0 = a1[0];\n\n\t\/\/loc_86CE4\n\tdo\n\t{\n\t\ta1--;\n\n\t\tif ((unsigned long*)v0 == a1)\n\t\t{\n\t\t\ta3 = a1 - 1;\n\t\t\tif (a1 == ot)\n\t\t\t{\n\t\t\t\treturn at;\n\t\t\t}\n\n\t\t\t\/\/loc_86CF4\n\t\t\tdo\n\t\t\t{\n\t\t\t\tv0 = a1[0];\n\t\t\t\ta1--;\n\t\t\t\tif (a1 == v1)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tat++;\n\t\t\t} while ((unsigned long*) v0 == a1);\n\n\t\t\t\/\/loc_86D08\n\t\t\ta3[0] = v0;\n\t\t}\n\t\tv0 = a1[0];\n\t} while (a1 != ot);\n\n\t\/\/loc_86D0C\n\treturn at;\n}\n\nvoid draw_rotate_sprite(long a0, long a1, long a2)\/\/5F134, 5FE14\n{\n#if 1\n\tlong t0;\n\tshort* v0;\n\tlong t6;\n\tlong t5;\n\tlong* a33;\n\tlong t2;\n\tlong at;\n\tlong* t3;\n\tlong v1;\n\tlong t1;\n\tlong t4;\n\n\tlong v00;\n\n\tt0 = (DelRotAng - 52) & 0xFFF;\n\ta2 = -a2;\n\tv0 = &rcossin_tbl[t0 * 2];\n\tt6 = v0[0];\n\ta2 >>= 1;\n\tt6 = a2 * t6;\/\/\n\n\tt3 = &db.ot[0];\n\tt5 = v0[1];\n\ta33 = db.polyptr;\n\n\tt2 = 0x2C808080;\n\tt5 = a2 * t5;\n\n\tat = 0x1303F00;\n\tDelRotAng = t0;\n\t*(long*) &db.polyptr[4] = t2;\n\t*(long*) &db.polyptr[12] = 0;\n\t*(long*) &db.polyptr[20] = at;\n\n\tt6 >>= 12;\n\tt5 >>= 12;\n\n\tt0 = t6 - t5;\n\ta2 = -t6;\n\tt4 = a2 - t5;\n\ta2 += t5;\n\tt1 = t6 + t5;\n\n\tv00 = t0 >> 1;\n\tv00 += a0;\n\tt0 += v00;\n\n\tv1 = t4 >> 1;\n\tv1 += a0;\n\tt4 += v1;\n\n\tv00 = a2 >> 1;\n\tv00 += a0;\n\ta2 += v00;\n\n\tv1 = t1 >> 1;\n\tv1 += a0;\n\tt1 += v1;\n\n\tv00 = t5 + t6;\n\tv00 += a1;\n\tv1 = -t5;\n\n\t*(short*) &db.polyptr[8] = t0;\n\t*(short*) &db.polyptr[10] = v00;\n\n\tv00 = v1 + t6;\n\tv00 += a1;\n\n\t*(short*) &db.polyptr[16] = t4;\n\t*(short*) &db.polyptr[18] = v00;\n\n\tv00 = t5 - t6;\n\tv00 += a1;\n\tv1 -= t6;\n\n\t*(short*) &db.polyptr[24] = t1;\n\t*(short*) &db.polyptr[26] = v00;\n\n\tt4 = 0x3F;\/\/width\/height?\n\n\t*(short*) &db.polyptr[28] = t4;\n\n\tt4 = 0x3F3F;\n\t*(short*) &db.polyptr[36] = t4;\n\n\ta1 += v1;\n\n\t*(short*) &db.polyptr[32] = a2;\n\t*(short*) &db.polyptr[34] = a1;\/\/Verified\n\n\tv00 = db.ot[0];\n\tat = 0x09000000;\n\tv00 |= at;\n\n\tdb.ot[0] = &db.polyptr[0];\n\t*(int*) &db.polyptr[0] = v00;\n\t\n\tdb.polyptr += 0x28;\/\/sizeof(POLY_F3); * 2\n\n\tv00 = 0x780100;\n\tv1 = 0x6800;\n\ta0 = 0x7801FF;\n\n\t*(long*) &db.polyptr[4] = t2;\n\t*(long*) &db.polyptr[8] = v00;\n\t*(long*) &db.polyptr[12] = v1;\n\t*(long*) &db.polyptr[16] = a0;\n\n\tat = 0x13468FF;\n\tv00 = 0xEF0100;\n\tv1 = 0xDF00;\n\ta0 = 0xEF01FF;\n\n\t*(long*) &db.polyptr[20] = at;\n\t*(long*) &db.polyptr[24] = v00;\n\t*(short*) &db.polyptr[28] = v1;\n\t*(long*) &db.polyptr[32] = a0;\n\n\tat = 0xDFFF;\n\t*(short*) &db.polyptr[36] = at;\n\n\tv00 = t3[0];\n\tv00 |= 0x9000000;\n\n\tt3[0] = db.polyptr;\n\t*(long*) &db.polyptr[0] = v00;\n\tdb.polyptr += 0x28;\n#endif\n\treturn;\n}\n\nvoid GPU_SetScreenPosition(short x, short y)\/\/5F360(<), 60040(<)\n{\n\tdb.disp[0].screen.x = x;\n\tdb.disp[0].screen.y = y;\n\tdb.disp[1].screen.x = x;\n\tdb.disp[1].screen.y = y;\n\n\treturn;\n}draw_rotate_sprite Clean#include \"GPU.H\"\n\n#include \"CAMERA.H\"\n#include \"LOAD_LEV.H\"\n#include \"PROFILE.H\"\n\n#include \n#include \n\nunsigned long GnFrameCounter = 19;\nunsigned long GnLastFrameCount = 19;\nstruct PSXTEXTSTRUCT* psxtextinfo;\nstruct PSXSPRITESTRUCT* psxspriteinfo;\nint rgbscaleme = 256;\nint gfx_debugging_mode;\nstruct DB_STRUCT db;\nstruct MMTEXTURE* RoomTextInfo;\nunsigned long GadwOrderingTables_V2[512];\nstatic int LnFlipFrame;\nunsigned long GadwOrderingTables[5128];\nunsigned long GadwPolygonBuffers[52260];\n\n\nvoid GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)\/\/5DF68(<), 5F1C8(<)\n{\n\tdb.order_table[0] = &pBuffers[0];\n\tdb.order_table[1] = &pBuffers[nOTSize];\n\tdb.nOTSize = nOTSize;\n\tdb.pickup_order_table[0] = &db.disp[1];\n\tdb.pickup_order_table[1] = &GadwOrderingTables_V2[256];\n#if 0\n\t\/\/Should be safe to use 32-bit ptrs tho\n\tdb.order_table[0] = (unsigned long*)((unsigned long) pBuffers & 0xFFFFFF);\n\tdb.order_table[1] = (unsigned long*)((unsigned long) &pBuffers[nOTSize] & 0xFFFFFF);\n\tdb.nOTSize = nOTSize;\n\tdb.pickup_order_table[0] = (unsigned long*)((unsigned long)&db.disp[1] & 0xFFFFFF);\n\tdb.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256] & 0xFFFFFF);\n#endif\n\treturn;\n}\n\nvoid GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)\/\/5DFB0(<), \n{\n#if 1\n\tdb.nPBSize = nPBSize;\n\tdb.poly_buffer[0] = &pBuffers[0];\n\tdb.poly_buffer[1] = &pBuffers[nPBSize];\n#else\n\tdb.nPBSize = nPBSize;\n\tdb.poly_buffer[0] = (unsigned long*)((unsigned long)pBuffers & 0xFFFFFF);\n\tdb.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize] & 0xFFFFFF);\n#endif\n\treturn;\n}\n\nvoid GPU_SyncBothScreens()\/\/5F374(<), 60054(<)\n{\n\tDrawSync(0);\n\n\tdb.current_buffer ^= 1;\n\tif (db.current_buffer != 0)\n\t{\n\t\tMoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);\n\t\t\/\/TODO: Verify ra += 0x10;! prolly else skip loc_5F3A8 (implemented but should be checked).\n\t}\n\telse\n\t{\n\t\t\/\/loc_5F3A8\n\t\tMoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);\n\t}\n\n\tDrawSync(0);\n\n\treturn;\n}\n\nvoid GPU_BeginScene()\/\/5F0F0(<), 5FDD0(<)\n{\n\tdb.ot = db.order_table[db.current_buffer];\n\tdb.polyptr = (char*)db.poly_buffer[db.current_buffer];\n\tdb.curpolybuf = (char*)db.poly_buffer[db.current_buffer];\n\tdb.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer]) + 26000;\n\tdb.pickup_ot = db.pickup_order_table[db.current_buffer];\n\tClearOTagR(db.order_table[db.current_buffer], db.nOTSize);\n\n\treturn;\n}\n\nint GPU_FlipNoIdle()\/\/5E078(<), 5F264(<)\n{\n#if INTERNAL\n\tif (ProfileDraw)\n\t{\n\t\tProfileRGB(255, 255, 255);\n\t\tProfileAddOT(&db.ot[0]);\n\t}\/\/loc_5E0B0\n#endif\n\n\tDrawSync(0);\/\/TODO confirm retail is sub_6B144 draw sync\n\n#if _INTERNAL\n\tif (ProfileDraw)\n\t{\n\t\tProfileAddDrawOT(&db.ot[0]);\n\t}\/\/loc_5E0D8\n#endif\n\n\tLnFlipFrame = GnLastFrameCount;\n\n\tif (GnLastFrameCount < 2)\n\t{\n\t\t\/\/loc_5E0F4\n\t\tdo\n\t\t{\n\t\t\tVSync(0);\n\t\t\tLnFlipFrame++;\n\t\t} while (LnFlipFrame < 2);\n\t}\n\telse\n\t{\n\t\t\/\/loc_5E120\n\t\tVSync(0);\n\t\tLnFlipFrame++;\n\t}\n\n\t\/\/loc_5E138\n\t\/\/v0 = db.current_buffer;\n\tGnLastFrameCount = 0;\n\tPutDispEnv(&db.disp[db.current_buffer]);\n\tDrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]);\n\n#if INTERNAL\n\tProfileStartCount();\n#endif\n\n\tdb.current_buffer ^= 1;\n\n\treturn LnFlipFrame;\n}\n\nvoid GPU_GetScreenPosition(short* x, short* y)\/\/5F34C, ?\n{\n\t*x = db.disp[0].screen.x;\n\t*y = db.disp[0].screen.y;\n\treturn;\n}\n\n\/* PSX VRAM (H)\n * ----------- 512px\n * | TL | TR | |\n * ----------- v\n * | BL | BR | \n * -----------\n *(W)1024px-->\n * \n *\/\nvoid GPU_ClearVRAM()\/\/5F2D0(<), 5FFB0(<) (F)\n{\n\tRECT r;\n\n\tDrawSync(0);\n\tVSync(0);\n\n\t\/\/Clear TL\n\tr.x = 0;\n\tr.y = 0;\n\tr.w = 512;\n\tr.h = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BL\n\tr.y = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BR\n\tr.x = 512;\n\tclear_a_rect(&r);\n\n\t\/\/Clear TR\n\tr.y = 0;\n\tclear_a_rect(&r);\n\n\tDrawSync(0);\n\tVSync(0);\n\n\treturn;\n}\n\nvoid clear_a_rect(RECT* r)\/\/5F334(<), 60014(<) (F)\n{\n\tClearImage(r, 0, 48, 0);\n\n\treturn;\n}\n\n\/\/@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.\nvoid GPU_FlipToBuffer(int buffer_index)\/\/5F3C8(<), 600A8(<) (F)\n{\n\tDrawSync(0);\n\tVSync(0);\n\n\tbuffer_index &= 1;\n\n\tif (buffer_index)\n\t{\n\t\tPutDispEnv(&db.disp[1]);\n\t\tdb.current_buffer = buffer_index ^ 1;\n\t\tPutDrawEnv(&db.draw[1]);\n\t}\n\telse\n\t{\n\t\tPutDispEnv(&db.disp[0]);\n\t\tdb.current_buffer = buffer_index ^ 1;\n\t\tPutDrawEnv(&db.draw[0]);\n\t}\n\n\treturn;\n}\n\nvoid GPU_EndScene()\/\/5DFDC(<), 5F23C(!)\n{\n#if 0\n\t\/\/int nPolys;\n\t\/\/static int nWorstPolys;\n\n\tlui\t$v0, 0x4EC4\n\tint a0 = &db.polyptr[0];\n\tint v1 = &db.curpolybuf[0];\n\tint v0 = 0x4EC4EC4F;\n\ta0 -= v1;\n\tv0 = a0 * v0;\n\ta0 >>= 31;\n\tv1 = psxtextinfo->u2v2pad;\n\tv0 >>= 4;\n\tv0 -= a0;\n\n\tif (v1 < v0)\n\t{\n\t\tu2v2pad = v0;\n\t}\/\/loc_5E020\n\t\n\t\/\/loc_5E020\n#endif\n\n\tOptimiseOTagR(&db.ot[0], db.nOTSize);\n\n#if 0\n\tnop\n\n\tProfileRGB(-1, -1, -1);\n\n\ta0 = db.nOTSize;\n\tdo_gfx_debug_mode(&db.ot[db.nOTSize - 1]);\n\n\tProfileRGB(0, -1, -1);\n#endif\n\treturn;\n}\n\nlong OptimiseOTagR(unsigned long* ot, int nOTSize)\/\/86CC4(<), 88D08(<)\n{\n\tunsigned long* a1;\n\tunsigned long* a3;\n\tunsigned long v0;\n\tunsigned long* v1;\n\tlong at = 0;\n\n\tif (nOTSize < 8)\n\t{\n\t\treturn 0;\n\t}\n\n\ta1 = &ot[nOTSize - 1];\n\tv1 = &ot[1];\n\tv0 = a1[0];\n\n\t\/\/loc_86CE4\n\tdo\n\t{\n\t\ta1--;\n\n\t\tif ((unsigned long*)v0 == a1)\n\t\t{\n\t\t\ta3 = a1 - 1;\n\t\t\tif (a1 == ot)\n\t\t\t{\n\t\t\t\treturn at;\n\t\t\t}\n\n\t\t\t\/\/loc_86CF4\n\t\t\tdo\n\t\t\t{\n\t\t\t\tv0 = a1[0];\n\t\t\t\ta1--;\n\t\t\t\tif (a1 == v1)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tat++;\n\t\t\t} while ((unsigned long*) v0 == a1);\n\n\t\t\t\/\/loc_86D08\n\t\t\ta3[0] = v0;\n\t\t}\n\t\tv0 = a1[0];\n\t} while (a1 != ot);\n\n\t\/\/loc_86D0C\n\treturn at;\n}\n\nvoid draw_rotate_sprite(long a0, long a1, long a2)\/\/5F134, 5FE14\n{\n\tlong t0;\n\tshort* r_cossinptr;\n\tlong t6;\n\tlong t5;\n\tlong t1;\n\tlong t4;\n\n\tDelRotAng = (DelRotAng - 52) & 0xFFF;\n\tr_cossinptr = &rcossin_tbl[DelRotAng * 2];\n\n\tt6 = ((-a2 \/ 2) * r_cossinptr[0]) \/ 4096;\n\tt5 = ((-a2 \/ 2) * r_cossinptr[1]) \/ 4096;\n\n\t*(long*) &db.polyptr[4] = 0x2C808080;\n\t*(long*) &db.polyptr[12] = 0;\n\t*(long*) &db.polyptr[20] = 0x1303F00;\n\n\tt0 = t6 - t5;\n\ta2 = -t6;\n\tt4 = a2 - t5;\n\ta2 += t5;\n\tt1 = t6 + t5;\n\n\t*(short*) &db.polyptr[8] = t0 + (t0 \/ 2) + a0;\n\t*(short*) &db.polyptr[10] = t5 + t6 + a1;\n\n\t*(short*) &db.polyptr[16] = t4 + (t4 \/ 2) + a0;\n\t*(short*) &db.polyptr[18] = -t5 + t6 + a1;\n\n\n\t*(short*) &db.polyptr[24] = t1 + (t1 \/ 2) + a0;\n\t*(short*) &db.polyptr[26] = (t5 - t6) + a1;\n\n\t*(short*) &db.polyptr[28] = 0x3F;\/\/width\/height of loading cd?\n\t*(short*) &db.polyptr[36] = 0x3F3F;\n\n\t*(short*) &db.polyptr[32] = a2 + (a2 \/ 2) + a0;\n\t*(short*) &db.polyptr[34] = a1 + (-t5 - t6);\n\n\t*(long*) &db.polyptr[0] = db.ot[0] | 0x09000000;\n\tdb.ot[0] = &db.polyptr[0];\n\t\n\tdb.polyptr += 0x28;\/\/sizeof(POLY_F3); * 2?\n\n\t*(long*) &db.polyptr[4] = 0x2C808080;\n\t*(long*) &db.polyptr[8] = 0x780100;\n\t*(long*) &db.polyptr[12] = 0x6800;\n\t*(long*) &db.polyptr[16] = 0x7801FF;\n\n\n\t*(long*) &db.polyptr[20] = 0x13468FF;\n\t*(long*) &db.polyptr[24] = 0xEF0100;\n\t*(short*) &db.polyptr[28] = 0xDF00;\n\t*(long*) &db.polyptr[32] = 0xEF01FF;\n\n\t*(short*) &db.polyptr[36] = 0xDFFF;\n\n\t*(long*) &db.polyptr[0] = db.ot[0] | 0x9000000;\n\tdb.ot[0] = db.polyptr;\n\t\n\tdb.polyptr += 0x28;\n\treturn;\n}\n\nvoid GPU_SetScreenPosition(short x, short y)\/\/5F360(<), 60040(<)\n{\n\tdb.disp[0].screen.x = x;\n\tdb.disp[0].screen.y = y;\n\tdb.disp[1].screen.x = x;\n\tdb.disp[1].screen.y = y;\n\n\treturn;\n}<|endoftext|>"} {"text":"\/*!\n \\mainpage The QtSparql library\n\n \\brief
unstable<\/center>\n\n \\section Introduction\n\n Description<\/b>\n\n QtSparql is a client-side library for accessing RDF stores.\n\n The query language for RDF stores is SPARQL<\/a>.\n\n QtSparql takes in SPARQL queries, forwards them to the selected backend, and\n gives back the results of the query. It can return the results\n asynchronously if the backend supports asynchronous operations.\n\n QtSparql can connect to different backends. Currently the following backends\n exist:\n\n - QTRACKER for accessing Tracker<\/a> over D-Bus\n - QTRACKER_DIRECT for accessing Tracker<\/a> via direct database\n access and D-Bus\n - QSPARQL_ENDPOINT for accessing online RDF stores, e.g., DBpedia<\/a>\n - QVIRTUOSO backend for accessing Virtuoso<\/a>\n\n List of classes QtSparql API provides:<\/b>\n

\n
Class<\/i><\/td>Description<\/i><\/td><\/tr>\n\n
QSparqlConnection<\/b><\/td>\n Interface for accessing an RDF store.<\/td><\/tr>\n\n
QSparqlConnectionOptions<\/b><\/td>\n Encapsulates options given to QSparqlConnection. Some options are used\n only by some drivers.<\/td><\/tr>\n\n
QSparqlError<\/b><\/td>SPARQL\n error information.<\/td><\/tr>\n\n
QSparqlBinding<\/b><\/td>Handles\n a binding between a SPARQL query variable name and the value of the RDF\n node.<\/td><\/tr>\n\n
QSparqlQuery<\/b><\/td>Means of\n executing and manipulating SPARQL statements.<\/td><\/tr>\n\n
QSparqlQueryOptions<\/b><\/td>\n Encapsulates query execution options given to QSparqlConnection::exec(const QSparqlQuery&, const QSparqlQueryOptions&)\n Some options are used only by some drivers.<\/td><\/tr>\n\n
QSparqlQueryModel<\/b><\/td>Read-only data model\n for SPARQL result sets.<\/td><\/tr>\n\n
QSparqlResultRow<\/b><\/td>Encapsulates a row in\n the results of a query.<\/td><\/tr>\n\n
QSparqlResult<\/b><\/td>Abstract\n interface for accessing the results of an executed QSparqlQuery.<\/td><\/tr>\n\n <\/table><\/p>\n\n \\attention The QtSparql library is not yet stable; we make no\n promises about API \/ ABI compatibility!\n\n \\section gettingstarted Getting started\n\n The following code snippets demonstrate how to retrieve data from\n a RDF database using QtSparql.\n\n - Create a QSparqlConnection object specifiying the backend you want to use.\n If necessary, specify the parameters by using QSparqlConnectionOptions and\n passing it to QSparqlConnection.\n\n E.g. to use tracker:\n \\dontinclude simple\/main.cpp\n \\skipline QSparqlConnection\n\n E.g. to use DBpedia:\n \\dontinclude dbpedia\/main.cpp\n \\skip QSparqlConnectionOptions\n \\until QSPARQL_ENDPOINT\n\n - Construct a QSparqlQuery with the SPARQL query string. Specify the query\n type, if needed.\n\n E.g.\n \\dontinclude simple\/main.cpp\n \\skipline QSparqlQuery\n\n or\n\n \\dontinclude iteration\/main.cpp\n \\skip QSparqlQuery insert\n \\until InsertStatement\n\n - Use QSparqlConnection::exec() to execute the query. It returns a\n pointer to QSparqlResult.\n\n E.g.\n \\dontinclude simple\/main.cpp\n \\skipline QSparqlResult\n\n - You can then connect to the QSparqlResult::finished() and\n QSparqlResult::dataReady signals.\n\n - The QSparqlResult can be iterated over by using the following functions:\n QSparqlResult::first(), QSparqlResult::last(), QSparqlResult::next(),\n QSparqlResult::previous(), QSparqlResult::setPos(). The caller is\n responsible for deleting the QSparqlResult.\n\n E.g.\n \\dontinclude simple\/main.cpp\n \\skip result->next\n \\until toString\n\n - Data can be retrieved by using QSparqlResult::value().\n\n The following classes are the most relevant for getting started with QSparql:\n - QSparqlConnection\n - QSparqlQuery\n - QSparqlResult\n - QSparqlQueryModel\n\n \\section querymodels Query models\n\n The QSparqlQueryModel class provides a convienient, read-only, data model for SPARQL results \n which can be used to provide data to view classes such as QTableView.\n\n After creating the model, use QSparqlQueryModel::setQuery() to set the query for the connection,\n header data for the model can also be set using QSparqlQueryModel::setHeaderData().\n\n E.g.\n \\dontinclude querymodel\/main.cpp\n \\skip model;\n \\until setHeaderData\n\n You can then use this in an a view class by using it's setModel() function.\n\n E.g.\n \\dontinclude querymodel\/main.cpp\n \\skip *view\n \\until model\n\n It is also easy to implement custom query models by reimplementing QSparqlQueryModel::data(), see\n the querymodel example for an example of this.\n\n \\section connectionoptions Connection options supported by drivers\n\n QTRACKER_DIRECT driver supports the following connection options:\n - dataReadyInterval (int, default 1), controls the interval for\n emitting the dataReady signal.\n - maxThread (int), sets the maximum number of threads for the\n thread pool to use. If not set a default of number of cores * 2 will\n be used.\n - threadExpiry (int, default 2000), controls the expiry time\n (in milliseconds) of the threads created by the thread pool.\n\n QENDPOINT driver supports the following connection options:\n - hostName (QString)\n - path (QString)\n - port (int)\n - userName (QString)\n - password (QString)\n - networkAccessManager (QNetworkAccessManager*)\n - proxy (const QNetworkProxy&)\n - custom: \"timeout\" (int) (for virtuoso endpoints)\n - custom: \"maxrows\" (int) (for virtuoso endpoints)\n\n QVIRTUOSO driver supports the following connection options:\n - hostName (QString)\n - port (int)\n - userName (QString)\n - password (QString)\n - databaseName (QString)\n\n For setting custom options, use QSparqlConnectionOptions::setOption() and\n give the option name as a string, followed by the value.\n\n Other options can be set using QSparqlConnectionOptions::setOption(), however\n it is preferable to use the convinence functions in QSparqlConnectionOptions,\n as these provide additional error checking.\n\n \\section connectionfeatures Connection features\n\n The following table describes the features supported by each driver. The\n features can be queried with QSparqlConnection::hasFeature().\n\n \n \n \n \n \n \n
<\/td>\n QuerySize<\/th>\n DefaultGraph<\/th>\n AskQueries<\/th>\n ConstructQueries<\/th>\n UpdateQueries<\/th>\n SyncExec<\/th>\n AsyncExec<\/th>\n <\/tr>\n
QTRACKER<\/th>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n <\/tr>\n
QTRACKER_DIRECT<\/th>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n <\/tr>\n
QSPARQL_ENDPOINT<\/th>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n <\/tr>\n
QVIRTUOSO<\/th>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No (*)<\/td>\n No<\/td>\n <\/tr>\n <\/table>\n\n (*) The QVIRTUOSO driver is natively synchronous, but support for syncExec\n directly is not currently implemented.\n\n \\section backendspecific Accessing backend-specific functionalities\n\n QtSparql doesn't offer backend-specific functionalities. For that purpose,\n there are separate add-on libraries, e.g., libqtsparql-tracker-extensions.\n\n*\/\nAdd QTRACKER_DIRECT specific information\/*!\n \\mainpage The QtSparql library\n\n \\brief
unstable<\/center>\n\n \\section Introduction\n\n Description<\/b>\n\n QtSparql is a client-side library for accessing RDF stores.\n\n The query language for RDF stores is SPARQL<\/a>.\n\n QtSparql takes in SPARQL queries, forwards them to the selected backend, and\n gives back the results of the query. It can return the results\n asynchronously if the backend supports asynchronous operations.\n\n QtSparql can connect to different backends. Currently the following backends\n exist:\n\n - QTRACKER for accessing Tracker<\/a> over D-Bus\n - QTRACKER_DIRECT for accessing Tracker<\/a> via direct database\n access and D-Bus. See the \\ref trackerdirectspecific \"specific useage section\"\n for more information\n - QSPARQL_ENDPOINT for accessing online RDF stores, e.g., DBpedia<\/a>\n - QVIRTUOSO backend for accessing Virtuoso<\/a>\n\n List of classes QtSparql API provides:<\/b>\n

\n
Class<\/i><\/td>Description<\/i><\/td><\/tr>\n\n
QSparqlConnection<\/b><\/td>\n Interface for accessing an RDF store.<\/td><\/tr>\n\n
QSparqlConnectionOptions<\/b><\/td>\n Encapsulates options given to QSparqlConnection. Some options are used\n only by some drivers.<\/td><\/tr>\n\n
QSparqlError<\/b><\/td>SPARQL\n error information.<\/td><\/tr>\n\n
QSparqlBinding<\/b><\/td>Handles\n a binding between a SPARQL query variable name and the value of the RDF\n node.<\/td><\/tr>\n\n
QSparqlQuery<\/b><\/td>Means of\n executing and manipulating SPARQL statements.<\/td><\/tr>\n\n
QSparqlQueryOptions<\/b><\/td>\n Encapsulates query execution options given to QSparqlConnection::exec(const QSparqlQuery&, const QSparqlQueryOptions&)\n Some options are used only by some drivers.<\/td><\/tr>\n\n
QSparqlQueryModel<\/b><\/td>Read-only data model\n for SPARQL result sets.<\/td><\/tr>\n\n
QSparqlResultRow<\/b><\/td>Encapsulates a row in\n the results of a query.<\/td><\/tr>\n\n
QSparqlResult<\/b><\/td>Abstract\n interface for accessing the results of an executed QSparqlQuery.<\/td><\/tr>\n\n <\/table><\/p>\n\n \\attention The QtSparql library is not yet stable; we make no\n promises about API \/ ABI compatibility!\n\n \\section gettingstarted Getting started\n\n The following code snippets demonstrate how to retrieve data from\n a RDF database using QtSparql.\n\n - Create a QSparqlConnection object specifiying the backend you want to use.\n If necessary, specify the parameters by using QSparqlConnectionOptions and\n passing it to QSparqlConnection.\n\n E.g. to use tracker:\n \\dontinclude simple\/main.cpp\n \\skipline QSparqlConnection\n\n E.g. to use DBpedia:\n \\dontinclude dbpedia\/main.cpp\n \\skip QSparqlConnectionOptions\n \\until QSPARQL_ENDPOINT\n\n - Construct a QSparqlQuery with the SPARQL query string. Specify the query\n type, if needed.\n\n E.g.\n \\dontinclude simple\/main.cpp\n \\skipline QSparqlQuery\n\n or\n\n \\dontinclude iteration\/main.cpp\n \\skip QSparqlQuery insert\n \\until InsertStatement\n\n - Use QSparqlConnection::exec() to execute the query. It returns a\n pointer to QSparqlResult.\n\n E.g.\n \\dontinclude simple\/main.cpp\n \\skipline QSparqlResult\n\n - You can then connect to the QSparqlResult::finished() and\n QSparqlResult::dataReady signals.\n\n - The QSparqlResult can be iterated over by using the following functions:\n QSparqlResult::first(), QSparqlResult::last(), QSparqlResult::next(),\n QSparqlResult::previous(), QSparqlResult::setPos(). The caller is\n responsible for deleting the QSparqlResult.\n\n E.g.\n \\dontinclude simple\/main.cpp\n \\skip result->next\n \\until toString\n\n - Data can be retrieved by using QSparqlResult::value().\n\n The following classes are the most relevant for getting started with QSparql:\n - QSparqlConnection\n - QSparqlQuery\n - QSparqlResult\n - QSparqlQueryModel\n\n \\section querymodels Query models\n\n The QSparqlQueryModel class provides a convienient, read-only, data model for SPARQL results \n which can be used to provide data to view classes such as QTableView.\n\n After creating the model, use QSparqlQueryModel::setQuery() to set the query for the connection,\n header data for the model can also be set using QSparqlQueryModel::setHeaderData().\n\n E.g.\n \\dontinclude querymodel\/main.cpp\n \\skip model;\n \\until setHeaderData\n\n You can then use this in an a view class by using it's setModel() function.\n\n E.g.\n \\dontinclude querymodel\/main.cpp\n \\skip *view\n \\until model\n\n It is also easy to implement custom query models by reimplementing QSparqlQueryModel::data(), see\n the querymodel example for an example of this.\n\n \\section connectionoptions Connection options supported by drivers\n\n QTRACKER_DIRECT driver supports the following connection options:\n - dataReadyInterval (int, default 1), controls the interval for\n emitting the dataReady signal.\n - maxThread (int), sets the maximum number of threads for the\n thread pool to use. If not set a default of number of cores * 2 will\n be used.\n - threadExpiry (int, default 2000), controls the expiry time\n (in milliseconds) of the threads created by the thread pool.\n\n QENDPOINT driver supports the following connection options:\n - hostName (QString)\n - path (QString)\n - port (int)\n - userName (QString)\n - password (QString)\n - networkAccessManager (QNetworkAccessManager*)\n - proxy (const QNetworkProxy&)\n - custom: \"timeout\" (int) (for virtuoso endpoints)\n - custom: \"maxrows\" (int) (for virtuoso endpoints)\n\n QVIRTUOSO driver supports the following connection options:\n - hostName (QString)\n - port (int)\n - userName (QString)\n - password (QString)\n - databaseName (QString)\n\n For setting custom options, use QSparqlConnectionOptions::setOption() and\n give the option name as a string, followed by the value.\n\n Other options can be set using QSparqlConnectionOptions::setOption(), however\n it is preferable to use the convinence functions in QSparqlConnectionOptions,\n as these provide additional error checking.\n\n \\section connectionfeatures Connection features\n\n The following table describes the QSparclConnection::Feature support of each\n driver. The features can be queried with QSparqlConnection::hasFeature().\n\n \n \n \n \n \n \n
<\/td>\n QuerySize<\/th>\n DefaultGraph<\/th>\n AskQueries<\/th>\n ConstructQueries<\/th>\n UpdateQueries<\/th>\n SyncExec<\/th>\n AsyncExec<\/th>\n <\/tr>\n
QTRACKER<\/th>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n <\/tr>\n
QTRACKER_DIRECT<\/th>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n <\/tr>\n
QSPARQL_ENDPOINT<\/th>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n <\/tr>\n
QVIRTUOSO<\/th>\n Yes<\/td>\n No<\/td>\n Yes<\/td>\n Yes<\/td>\n Yes<\/td>\n No (*)<\/td>\n No<\/td>\n <\/tr>\n <\/table>\n\n (*) The QVIRTUOSO driver is natively synchronous, but support for syncExec\n directly is not currently implemented.\n\n \\section trackerdirectspecific QTRACKER_DIRECT specific useage\n\n There are two ways to use the QTRACKER_DIRECT driver, synchronously using\n QSparqlConnection::syncExec(), and asynchronously using QSparqlConnection::exec().\n The result behaviour is different, and supports different features, depending on\n the method used.\n\n The following table describes the QSparqlResult::Feature support of each method.\n\n \n \n \n \n
<\/td>\n QuerySize<\/th>\n ForwardOnly<\/th>\n Sync<\/th>\n <\/tr>\n
exec()<\/th>\n Yes<\/td>\n No<\/td>\n No<\/td>\n <\/tr>\n
syncExec()<\/th>\n No<\/td>\n Yes<\/td>\n Yes<\/td>\n <\/tr>\n <\/table>\n\n When using synchronous execution, it is important to fully use the results returned\n before making another query, either synchronously or asynchronously, by using\n QSparqlResult::next until it returns false. If you fail to do this, any new results\n that may have been added after your original query will not be included in any subsequent\n queries you make.\n\n \\section backendspecific Accessing backend-specific functionalities\n\n QtSparql doesn't offer backend-specific functionalities. For that purpose,\n there are separate add-on libraries, e.g., libqtsparql-tracker-extensions.\n\n*\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012-2015 Dano Pernis\n\/\/ See LICENSE for details\n\n#include \"ssa.h\"\n\nnamespace hcc {\nnamespace ssa {\nnamespace {\n\nstruct congruence_classes {\n std::map classes;\n\n std::function replacer()\n {\n return [&](argument& arg) {\n if (!arg.is_reg()) {\n return;\n }\n\n auto it = classes.find(arg);\n if (it != classes.end()) {\n arg = it->second;\n }\n };\n }\n};\n\n\/\/ Implements \"Method I\" from paper by Sreedhar et al.\n\/\/ \"Translating Out of Static Single Assignment Form\"\n\/\/ FIXME copies are not parallel\nvoid naive_copy_insertion(subroutine& s, congruence_classes& cc)\n{\n \/\/ worklist of MOV instructions to be inserted at the end of basic block,\n \/\/ indexed by basic block\n std::map worklist;\n\n \/\/ pass 1: fill worklist and insert primed copy\n s.for_each_bb([&](basic_block& bb) {\n for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e; ++i) {\n if (i->type != instruction_type::PHI)\n continue;\n\n auto arg = i->arguments.begin();\n\n \/\/ invent a new primed name\n const auto base = s.create_reg();\n s.add_debug(base, \"phi_dst_reg\", *arg);\n\n \/\/ insert MOV after PHI\n bb.instructions.insert(++decltype(i)(i),\n instruction(instruction_type::MOV, {*arg, base}));\n cc.classes.emplace(base, base);\n cc.classes.emplace(*arg, base);\n\n \/\/ rename PHI's dest\n *arg++ = base;\n\n while (arg != i->arguments.end()) {\n auto label = *arg++;\n auto value = *arg;\n\n const auto name = s.create_reg();\n s.add_debug(name, \"phi_src_reg\", base);\n s.add_debug(name, \"phi_src_label\", label);\n\n \/\/ insert MOV into worklist\n worklist[label.get_label()].emplace_back(\n instruction(instruction_type::MOV, {name, value}));\n cc.classes.emplace(name, base);\n\n \/\/ rename PHI's src\n *arg++ = name;\n }\n }\n });\n\n \/\/ pass 2: paste instructions from worklist at the end of respective basic block\n s.for_each_bb([&](basic_block& bb) {\n bb.instructions.splice(--bb.instructions.end(), worklist[bb.name]);\n });\n}\n\n\/\/ live(x) ... set of statements were x is live\n\/\/ live(a) intersects live(b) ... def(a) in live(b) or def(b) in live(a)\n\/\/ V(x) ... V(b) = V(a) if b <- a\n\/\/ V(b) = b otherwise\n\/\/ a interfere b ... live(a) intersects live(b) and V(a) != V(b)\nbool interfere(const argument& a, const argument& b, subroutine& s)\n{\n assert(a.is_reg() && b.is_reg());\n\n bool def_a_in_live_b = false;\n bool def_b_in_live_a = false;\n bool live_a = false;\n bool live_b = false;\n std::map V; \/\/ value of variable\n\n \/\/ TODO investigate if domtree is really needed\n \/\/ TODO live ranges are probably overestimated at the end\n\n s.for_each_bb_in_domtree_preorder([&](basic_block& block) {\n for (auto& instr : block.instructions) {\n \/\/ live ranges\n instr.def_apply([&](argument& def) {\n if (def == a) {\n live_a = true;\n if (live_b)\n def_a_in_live_b = true;\n } else if (def == b) {\n live_b = true;\n if (live_a)\n def_b_in_live_a = true;\n }\n });\n\n \/\/ values\n if (instr.type == instruction_type::MOV) {\n auto s0 = instr.arguments[0].save_fast();\n auto s1 = instr.arguments[1].save_fast();\n V[std::move(s0)] = V[std::move(s1)];\n } else {\n instr.def_apply([&](argument& arg) {\n auto s0 = arg.save_fast();\n auto s1 = instr.save_fast();\n V[std::move(s0)] = std::move(s1);\n });\n }\n }\n });\n\n const bool intersect = def_a_in_live_b || def_b_in_live_a;\n auto sa = a.save_fast();\n auto sb = b.save_fast();\n const bool differ_in_value = V.at(sa) != V.at(sb);\n return intersect && differ_in_value;\n}\n\n} \/\/ namespace {\n\n\/\/ Inspired by paper\n\/\/ \"Revisiting Out-of-SSA Translation for Correctness, Code Quality, and Efficiency\"\nvoid subroutine::ssa_deconstruct()\n{\n recompute_dominance();\n\n congruence_classes cc;\n naive_copy_insertion(*this, cc);\n\n \/\/ incidental classes, rising from the code\n for_each_bb([&](basic_block& bb) {\n for (auto& instr : bb.instructions) {\n if (instr.type == instruction_type::MOV) {\n auto& dest = instr.arguments[0];\n auto& src = instr.arguments[1];\n const bool has_src_class = cc.classes.count(src) > 0;\n const bool has_dest_class = cc.classes.count(dest) > 0;\n if (has_src_class && has_dest_class && cc.classes.at(src) == cc.classes.at(dest))\n continue;\n\n if (src.is_reg() && dest.is_reg()) {\n if (!interfere(src, dest, *this)) {\n if (!has_src_class && !has_dest_class) {\n const auto r = create_reg();\n add_debug(r, \"congruence_class\");\n cc.classes.emplace(src, r);\n cc.classes.emplace(dest, r);\n } else if (has_src_class && has_dest_class) {\n auto keep_class = cc.classes.at(src);\n auto remove_class = cc.classes.at(dest);\n for (auto& kv : cc.classes) {\n if (kv.second == remove_class)\n kv.second = keep_class;\n }\n }\n }\n }\n }\n }\n });\n\n \/\/ pass 2: remove phis, replace names, remove nop moves\n \/\/ FIXME materialize parallel moves here, do not add them in the first place\n for_each_bb([&](basic_block& bb) {\n for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e;) {\n if (i->type == instruction_type::PHI) {\n i = bb.instructions.erase(i);\n } else {\n i->def_apply(cc.replacer());\n i->use_apply(cc.replacer());\n if (i->type == instruction_type::MOV && i->arguments[0] == i->arguments[1]) {\n i = bb.instructions.erase(i);\n } else {\n ++i;\n }\n }\n }\n });\n}\n\n} \/\/ namespace ssa {\n} \/\/ namespace hcc {\nOptimize interference computation\/\/ Copyright (c) 2012-2015 Dano Pernis\n\/\/ See LICENSE for details\n\n#include \"ssa.h\"\n\nnamespace hcc {\nnamespace ssa {\nnamespace {\n\nstruct congruence_classes {\n std::map classes;\n\n std::function replacer()\n {\n return [&](argument& arg) {\n if (!arg.is_reg()) {\n return;\n }\n\n auto it = classes.find(arg);\n if (it != classes.end()) {\n arg = it->second;\n }\n };\n }\n};\n\n\/\/ Implements \"Method I\" from paper by Sreedhar et al.\n\/\/ \"Translating Out of Static Single Assignment Form\"\n\/\/ FIXME copies are not parallel\nvoid naive_copy_insertion(subroutine& s, congruence_classes& cc)\n{\n \/\/ worklist of MOV instructions to be inserted at the end of basic block,\n \/\/ indexed by basic block\n std::map worklist;\n\n \/\/ pass 1: fill worklist and insert primed copy\n s.for_each_bb([&](basic_block& bb) {\n for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e; ++i) {\n if (i->type != instruction_type::PHI)\n continue;\n\n auto arg = i->arguments.begin();\n\n \/\/ invent a new primed name\n const auto base = s.create_reg();\n s.add_debug(base, \"phi_dst_reg\", *arg);\n\n \/\/ insert MOV after PHI\n bb.instructions.insert(++decltype(i)(i),\n instruction(instruction_type::MOV, {*arg, base}));\n cc.classes.emplace(base, base);\n cc.classes.emplace(*arg, base);\n\n \/\/ rename PHI's dest\n *arg++ = base;\n\n while (arg != i->arguments.end()) {\n auto label = *arg++;\n auto value = *arg;\n\n const auto name = s.create_reg();\n s.add_debug(name, \"phi_src_reg\", base);\n s.add_debug(name, \"phi_src_label\", label);\n\n \/\/ insert MOV into worklist\n worklist[label.get_label()].emplace_back(\n instruction(instruction_type::MOV, {name, value}));\n cc.classes.emplace(name, base);\n\n \/\/ rename PHI's src\n *arg++ = name;\n }\n }\n });\n\n \/\/ pass 2: paste instructions from worklist at the end of respective basic block\n s.for_each_bb([&](basic_block& bb) {\n bb.instructions.splice(--bb.instructions.end(), worklist[bb.name]);\n });\n}\n\n\/\/ Determine if two registers *a* and *b* interfere in subroutine *s*\n\/\/\n\/\/ Interfering registers have intersecting live ranges and different values:\n\/\/\n\/\/ live(x) ... set of statements where x is live\n\/\/ live(a) intersects live(b) ... def(a) in live(b) or def(b) in live(a)\n\/\/ V(x) ... V(b) = V(a) if b <- a\n\/\/ V(b) = b otherwise\n\/\/ a interfere b ... live(a) intersects live(b) and V(a) != V(b)\nbool interfere(const reg& a, const reg& b, subroutine& s)\n{\n bool def_a_in_live_b = false;\n bool def_b_in_live_a = false;\n bool live_a = false;\n bool live_b = false;\n\n \/\/ At this point, code is still in SSA, so value of each register\n \/\/ is determined solely by its defining instruction. What is more,\n \/\/ we can use pointer here because nothing gets reallocated.\n \/\/ TODO use const *s* to prove that pointer usage is indeed safe.\n std::map value;\n\n \/\/ TODO investigate if domtree is really needed\n \/\/ TODO live ranges are probably overestimated at the end\n\n s.for_each_bb_in_domtree_preorder([&](basic_block& block) {\n for (auto& instr : block.instructions) {\n \/\/ live ranges\n instr.def_apply([&](argument& def) {\n assert (def.is_reg());\n if (def.get_reg() == a) {\n live_a = true;\n if (live_b)\n def_a_in_live_b = true;\n } else if (def == b) {\n live_b = true;\n if (live_a)\n def_b_in_live_a = true;\n }\n });\n\n \/\/ values\n if (instr.type == instruction_type::MOV) {\n if (instr.arguments[1].is_reg()) {\n value.emplace(instr.arguments[0].get_reg(),\n value.at(instr.arguments[1].get_reg()));\n } else {\n value.emplace(instr.arguments[0].get_reg(), &instr);\n }\n } else {\n instr.def_apply([&](argument& arg) {\n assert (arg.is_reg());\n value.emplace(arg.get_reg(), &instr);\n });\n }\n }\n });\n\n const bool intersect = def_a_in_live_b || def_b_in_live_a;\n const bool differ_in_value = value.at(a) != value.at(b);\n return intersect && differ_in_value;\n}\n\n} \/\/ namespace {\n\n\/\/ Inspired by paper\n\/\/ \"Revisiting Out-of-SSA Translation for Correctness, Code Quality, and Efficiency\"\nvoid subroutine::ssa_deconstruct()\n{\n recompute_dominance();\n\n congruence_classes cc;\n naive_copy_insertion(*this, cc);\n\n \/\/ incidental classes, rising from the code\n for_each_bb([&](basic_block& bb) {\n for (auto& instr : bb.instructions) {\n if (instr.type == instruction_type::MOV) {\n auto& dest = instr.arguments[0];\n auto& src = instr.arguments[1];\n const bool has_src_class = cc.classes.count(src) > 0;\n const bool has_dest_class = cc.classes.count(dest) > 0;\n if (has_src_class && has_dest_class && cc.classes.at(src) == cc.classes.at(dest))\n continue;\n\n if (src.is_reg() && dest.is_reg()) {\n if (!interfere(src.get_reg(), dest.get_reg(), *this)) {\n if (!has_src_class && !has_dest_class) {\n const auto r = create_reg();\n add_debug(r, \"congruence_class\");\n cc.classes.emplace(src, r);\n cc.classes.emplace(dest, r);\n } else if (has_src_class && has_dest_class) {\n auto keep_class = cc.classes.at(src);\n auto remove_class = cc.classes.at(dest);\n for (auto& kv : cc.classes) {\n if (kv.second == remove_class)\n kv.second = keep_class;\n }\n }\n }\n }\n }\n }\n });\n\n \/\/ pass 2: remove phis, replace names, remove nop moves\n \/\/ FIXME materialize parallel moves here, do not add them in the first place\n for_each_bb([&](basic_block& bb) {\n for (auto i = bb.instructions.begin(), e = bb.instructions.end(); i != e;) {\n if (i->type == instruction_type::PHI) {\n i = bb.instructions.erase(i);\n } else {\n i->def_apply(cc.replacer());\n i->use_apply(cc.replacer());\n if (i->type == instruction_type::MOV && i->arguments[0] == i->arguments[1]) {\n i = bb.instructions.erase(i);\n } else {\n ++i;\n }\n }\n }\n });\n}\n\n} \/\/ namespace ssa {\n} \/\/ namespace hcc {\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 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 \n#include \n#include \n\n#include \"class_names.h\"\n#include \"common_action_mocks.h\"\n#include \"i_dbg_object_factory_mock.h\"\n#include \"i_eval_coordinator_mock.h\"\n#include \"string_evaluator.h\"\n#include \"type_signature.h\"\n\nusing google_cloud_debugger::ConvertStringToWCharPtr;\nusing google_cloud_debugger::DbgObject;\nusing google_cloud_debugger::StringEvaluator;\nusing google_cloud_debugger::TypeSignature;\nusing std::string;\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::SetArgPointee;\nusing ::testing::SetArrayArgument;\n\nnamespace google_cloud_debugger_test {\n\n\/\/ Test Fixture for DbgString.\nclass StringEvaluatorTest : public ::testing::Test {\n protected:\n virtual void SetUp() {}\n\n \/\/ Sets up IEvalCoordinator for mock call.\n virtual void SetUpEvalCoordinator() {\n EXPECT_CALL(eval_coordinator_mock_, CreateEval(_))\n .Times(1)\n .WillRepeatedly(\n DoAll(SetArgPointee<0>(&debug_eval_mock_), Return(S_OK)));\n\n EXPECT_CALL(eval_coordinator_mock_, WaitForEval(_, &debug_eval_mock_, _))\n .Times(1)\n .WillRepeatedly(\n DoAll(SetArgPointee<2>(&debug_string_mock_), Return(S_OK)));\n\n EXPECT_CALL(debug_eval_mock_, NewString(_))\n .Times(1)\n .WillRepeatedly(Return(S_OK));\n }\n\n \/\/ Sets up object factory for object creation.\n virtual void SetUpObjFactory() {\n EXPECT_CALL(object_factory_mock_,\n CreateDbgObject(&debug_string_mock_, _, _, _))\n .Times(1)\n .WillRepeatedly(Return(S_OK));\n }\n\n \/\/ Mock of IEvalCoordinator used for evaluate.\n IEvalCoordinatorMock eval_coordinator_mock_;\n\n \/\/ Mock used for object creation.\n IDbgObjectFactoryMock object_factory_mock_;\n\n \/\/ Mock eval returned by IEvalCoordinatorMock.\n ICorDebugEvalMock debug_eval_mock_;\n\n \/\/ Debug String returned by IEvalCoordinatorMock.\n ICorDebugStringValueMock debug_string_mock_;\n\n \/\/ Content of the string.\n string string_content_ = \"String Content\";\n};\n\n\/\/ Tests Compile function of DbgString.\n\/\/ This function returns S_OK without anywork.\nTEST_F(StringEvaluatorTest, Compile) {\n StringEvaluator evaluator(string_content_);\n EXPECT_EQ(evaluator.Compile(nullptr, nullptr, nullptr), S_OK);\n}\n\n\/\/ Tests that GetStaticType returns string type.\nTEST_F(StringEvaluatorTest, GetStaticType) {\n StringEvaluator evaluator(string_content_);\n TypeSignature type_sig = evaluator.GetStaticType();\n\n EXPECT_EQ(type_sig.cor_type, CorElementType::ELEMENT_TYPE_STRING);\n EXPECT_EQ(type_sig.type_name, google_cloud_debugger::kStringClassName);\n}\n\n\/\/ Tests that Evaluate function creates a string.\nTEST_F(StringEvaluatorTest, Evaluate) {\n StringEvaluator evaluator(string_content_);\n\n SetUpEvalCoordinator();\n SetUpObjFactory();\n\n std::shared_ptr result;\n std::ostringstream err_stream;\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream),\n S_OK);\n}\n\n\/\/ Tests that error cases for Evaluate function.\nTEST_F(StringEvaluatorTest, EvaluateError) {\n StringEvaluator evaluator(string_content_);\n\n std::shared_ptr result;\n std::ostringstream err_stream;\n \/\/ Null tests.\n EXPECT_EQ(evaluator.Evaluate(nullptr, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream),\n E_INVALIDARG);\n EXPECT_EQ(\n evaluator.Evaluate(&result, nullptr, &object_factory_mock_, &err_stream),\n E_INVALIDARG);\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, nullptr,\n &err_stream),\n E_INVALIDARG);\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, nullptr),\n E_INVALIDARG);\n\n {\n \/\/ Tests that Evaluate fails if we cannot create ICorDebugEval.\n EXPECT_CALL(eval_coordinator_mock_, CreateEval(_))\n .Times(1)\n .WillRepeatedly(Return(E_ACCESSDENIED));\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream),\n E_ACCESSDENIED);\n }\n\n {\n \/\/ Tests that Evaluate fails if we cannot Object Factory fails.\n SetUpEvalCoordinator();\n EXPECT_CALL(object_factory_mock_,\n CreateDbgObject(&debug_string_mock_, _, _, _))\n .Times(1)\n .WillRepeatedly(Return(CORDBG_E_PROCESS_TERMINATED));\n\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream),\n CORDBG_E_PROCESS_TERMINATED);\n }\n}\n\n} \/\/ namespace google_cloud_debugger_test\nAddress PR comments\/\/ Copyright 2018 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 \n#include \n#include \n\n#include \"class_names.h\"\n#include \"common_action_mocks.h\"\n#include \"dbg_string.h\"\n#include \"i_dbg_object_factory_mock.h\"\n#include \"i_eval_coordinator_mock.h\"\n#include \"string_evaluator.h\"\n#include \"type_signature.h\"\n#include \"error_messages.h\"\n\nusing google_cloud_debugger::ConvertStringToWCharPtr;\nusing google_cloud_debugger::DbgObject;\nusing google_cloud_debugger::DbgString;\nusing google_cloud_debugger::StringEvaluator;\nusing google_cloud_debugger::TypeSignature;\nusing std::string;\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::SetArgPointee;\nusing ::testing::SetArrayArgument;\n\nnamespace google_cloud_debugger_test {\n\n\/\/ Test Fixture for StringEvaluator.\nclass StringEvaluatorTest : public ::testing::Test {\n protected:\n virtual void SetUp() {}\n\n \/\/ Sets up IEvalCoordinator for mock call.\n virtual void SetUpEvalCoordinator() {\n EXPECT_CALL(eval_coordinator_mock_, CreateEval(_))\n .Times(1)\n .WillRepeatedly(\n DoAll(SetArgPointee<0>(&debug_eval_mock_), Return(S_OK)));\n\n EXPECT_CALL(eval_coordinator_mock_, WaitForEval(_, &debug_eval_mock_, _))\n .Times(1)\n .WillRepeatedly(\n DoAll(SetArgPointee<2>(&debug_string_mock_), Return(S_OK)));\n\n EXPECT_CALL(debug_eval_mock_, NewString(_))\n .Times(1)\n .WillRepeatedly(Return(S_OK));\n }\n\n \/\/ Sets up object factory for object creation.\n virtual void SetUpObjFactory() {\n EXPECT_CALL(object_factory_mock_,\n CreateDbgObject(&debug_string_mock_, _, _, _))\n .Times(1)\n .WillRepeatedly(Return(S_OK));\n }\n\n \/\/ Mock of IEvalCoordinator used for evaluate.\n IEvalCoordinatorMock eval_coordinator_mock_;\n\n \/\/ Mock used for object creation.\n IDbgObjectFactoryMock object_factory_mock_;\n\n \/\/ Mock eval returned by IEvalCoordinatorMock.\n ICorDebugEvalMock debug_eval_mock_;\n\n \/\/ Debug String returned by IEvalCoordinatorMock.\n ICorDebugStringValueMock debug_string_mock_;\n\n \/\/ Content of the string.\n string string_content_ = \"String Content\";\n\n \/\/ Error stream.\n std::ostringstream err_stream_;\n};\n\n\/\/ Tests Compile function of DbgString.\n\/\/ This function returns S_OK without anywork.\nTEST_F(StringEvaluatorTest, Compile) {\n StringEvaluator evaluator(string_content_);\n EXPECT_EQ(evaluator.Compile(nullptr, nullptr, nullptr), S_OK);\n}\n\n\/\/ Tests that GetStaticType returns string type.\nTEST_F(StringEvaluatorTest, GetStaticType) {\n StringEvaluator evaluator(string_content_);\n TypeSignature type_sig = evaluator.GetStaticType();\n\n EXPECT_EQ(type_sig.cor_type, CorElementType::ELEMENT_TYPE_STRING);\n EXPECT_EQ(type_sig.type_name, google_cloud_debugger::kStringClassName);\n}\n\n\/\/ Tests that Evaluate function creates a string.\nTEST_F(StringEvaluatorTest, Evaluate) {\n StringEvaluator evaluator(string_content_);\n\n SetUpEvalCoordinator();\n SetUpObjFactory();\n\n std::shared_ptr result;\n std::ostringstream err_stream;\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream),\n S_OK);\n}\n\n\/\/ Tests null error cases for Evaluate function.\nTEST_F(StringEvaluatorTest, EvaluateError) {\n StringEvaluator evaluator(string_content_);\n std::shared_ptr result;\n\n EXPECT_EQ(evaluator.Evaluate(nullptr, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream_),\n E_INVALIDARG);\n EXPECT_EQ(\n evaluator.Evaluate(&result, nullptr, &object_factory_mock_, &err_stream_),\n E_INVALIDARG);\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_, nullptr,\n &err_stream_),\n E_INVALIDARG);\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, nullptr),\n E_INVALIDARG);\n}\n\n\/\/ Tests that Evaluate fails if we cannot create ICorDebugEval.\nTEST_F(StringEvaluatorTest, EvaluateErrorEvalCoordinator) {\n StringEvaluator evaluator(string_content_);\n std::shared_ptr result;\n\n EXPECT_CALL(eval_coordinator_mock_, CreateEval(_))\n .Times(1)\n .WillRepeatedly(Return(E_ACCESSDENIED));\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream_),\n E_ACCESSDENIED);\n EXPECT_EQ(err_stream_.str(), google_cloud_debugger::kFailedEvalCreation.c_str());\n}\n\n\/\/ Tests that Evaluate fails if the IDbgObjectFactory cannot create\n\/\/ a new object.\nTEST_F(StringEvaluatorTest, EvaluateErrorObjCreation) {\n StringEvaluator evaluator(string_content_);\n std::shared_ptr result;\n\n SetUpEvalCoordinator();\n EXPECT_CALL(object_factory_mock_,\n CreateDbgObject(&debug_string_mock_, _, _, _))\n .Times(1)\n .WillRepeatedly(Return(CORDBG_E_PROCESS_TERMINATED));\n\n EXPECT_EQ(evaluator.Evaluate(&result, &eval_coordinator_mock_,\n &object_factory_mock_, &err_stream_),\n CORDBG_E_PROCESS_TERMINATED);\n EXPECT_EQ(err_stream_.str(), google_cloud_debugger::kFailedToCreateDbgObject.c_str());\n}\n\n} \/\/ namespace google_cloud_debugger_test\n<|endoftext|>"} {"text":"\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\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#ifndef RESEMBLA_ELIMINATOR_HPP\n#define RESEMBLA_ELIMINATOR_HPP\n\n#include \n#include \n#include \n\n#include \"string_util.hpp\"\n\nnamespace resembla {\n\ntemplate\nstruct Eliminator\n{\n using size_type = typename string_type::size_type;\n using symbol_type = typename string_type::value_type;\n using distance_type = int;\n\n Eliminator(string_type const& pattern = string_type())\n {\n init(pattern);\n }\n\n void init(string_type const& pattern)\n {\n this->pattern = pattern;\n if(pattern.empty()){\n return;\n }\n\n pattern_length = pattern.size();\n block_size = ((pattern_length - 1) >> bit_offset()) + 1;\n rest_bits = pattern_length - (block_size - 1) * bit_width();\n sink = bitvector_type{1} << (rest_bits - 1);\n\n constructPM();\n zeroes.resize(block_size, 0);\n work.resize(block_size);\n }\n\n void operator()(std::vector& candidates, size_type k)\n {\n using index_distance = std::pair;\n\n \/\/ calculate scores\n std::vector work(candidates.size());\n for(size_type i = 0; i < work.size(); ++i){\n work[i].first = i;\n work[i].second = -distance(candidates[i]);\n }\n\n \/\/ sort partially to obtain top-k elements\n std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),\n [](const index_distance& a, const index_distance& b) -> bool{\n return a.second > b.second;\n });\n\n \/\/ ensure that work[i].first < work[j].first if i < j < k\n std::partial_sort(std::begin(work), std::begin(work) + k, std::begin(work) + k,\n [](const index_distance& a, const index_distance& b) -> bool{\n return a.first < b.first;\n });\n#ifdef DEBUG\n std::cerr << \"narrow \" << work.size() << \" strings\" << std::endl;\n for(size_type i = 0; i < k; ++i){\n std::cerr << cast_string(candidates[work[i].first]) << \": \" << work[i].second << std::endl;\n }\n#endif\n\n \/\/ sort original list\n for(size_type i = 0; i < k; ++i){\n std::swap(candidates[i], candidates[work[i].first]);\n }\n candidates.erase(std::begin(candidates) + k, std::end(candidates));\n }\n\nprotected:\n string_type pattern;\n size_type pattern_length;\n size_type block_size;\n size_type rest_bits;\n bitvector_type sink;\n\n std::vector>> PM;\n std::vector zeroes;\n\n struct WorkData\n {\n bitvector_type D0;\n bitvector_type HP;\n bitvector_type HN;\n bitvector_type VP;\n bitvector_type VN;\n\n void reset()\n {\n D0 = HP = HN = VN = 0;\n VP = ~(bitvector_type{0});\n }\n };\n mutable std::vector work;\n\n template static constexpr int bit_width()\n {\n return 8 * sizeof(Integer);\n }\n\n static constexpr int bit_offset(int w)\n {\n return w < 2 ? 0 : (bit_offset(w >> 1) + 1);\n }\n\n template static constexpr int bit_offset()\n {\n return bit_offset(bit_width());\n }\n\n template\n const value_type& find_value(const std::vector>& data,\n const key_type c, const value_type& default_value) const\n {\n size_type l = 0, r = data.size();\n while(r - l > 8){\n auto i = (l + r) \/ 2;\n if(data[i].first < c){\n l = i + 1;\n }\n else if(data[i].first > c){\n r = i;\n }\n else{\n return data[i].second;\n }\n }\n for(size_type i = l; i < r; ++i){\n if(data[i].first == c){\n return data[i].second;\n }\n }\n return default_value;\n }\n\n void constructPM()\n {\n std::map> PM_work;\n for(size_type i = 0; i < block_size - 1; ++i){\n for(size_type j = 0; j < bit_width(); ++j){\n if(PM_work[pattern[i * bit_width() + j]].empty()){\n PM_work[pattern[i * bit_width() + j]].resize(block_size, 0);\n }\n PM_work[pattern[i * bit_width() + j]][i] |= bitvector_type{1} << j;\n }\n }\n for(size_type i = 0; i < rest_bits; ++i){\n if(PM_work[pattern[(block_size - 1) * bit_width() + i]].empty()){\n PM_work[pattern[(block_size - 1) * bit_width() + i]].resize(block_size, 0);\n }\n PM_work[pattern[(block_size - 1) * bit_width() + i]].back() |= bitvector_type{1} << i;\n }\n\n PM.clear();\n for(const auto& p: PM_work){\n PM.push_back(p);\n }\n }\n\n distance_type distance_sp(string_type const &text) const\n {\n auto& w = work.front();\n w.reset();\n for(size_type i = 0; i < pattern_length; ++i){\n w.VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n auto X = find_value(PM, c, zeroes).front() | w.VN;\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = (w.HP << 1) | 1;\n w.VP = (w.HN << 1) | ~(X | w.D0);\n w.VN = X & w.D0;\n\n if(w.HP & sink){\n ++D;\n }\n else if(w.HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance_lp(string_type const &text) const\n {\n constexpr bitvector_type msb = bitvector_type{1} << (bit_width() - 1);\n\n for(auto& w: work){\n w.reset();\n }\n for(size_type i = 0; i < rest_bits; ++i){\n work.back().VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n const auto& PMc = find_value(PM, c, zeroes);\n for(size_type r = 0; r < block_size; ++r){\n auto& w = work[r];\n auto X = PMc[r];\n if(r > 0 && (work[r - 1].HN & msb)){\n X |= 1;\n }\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = w.HP << 1;\n if(r == 0 || work[r - 1].HP & msb){\n X |= 1;\n }\n w.VP = (w.HN << 1) | ~(X | w.D0);\n if(r > 0 && (work[r - 1].HN & msb)){\n w.VP |= 1;\n }\n w.VN = X & w.D0;\n }\n\n if(work.back().HP & sink){\n ++D;\n }\n else if(work.back().HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance(string_type const &text) const\n {\n if(text.empty()){\n return pattern_length;\n }\n else if(pattern_length == 0){\n return text.size();\n }\n\n if(block_size == 1){\n return distance_sp(text);\n }\n else{\n return distance_lp(text);\n }\n }\n};\n\n}\n#endif\nadd heuristics\/*\nResembla: Word-based Japanese similar sentence search library\nhttps:\/\/github.com\/tuem\/resembla\n\nCopyright 2017 Takashi Uemura\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#ifndef RESEMBLA_ELIMINATOR_HPP\n#define RESEMBLA_ELIMINATOR_HPP\n\n#include \n#include \n#include \n\n#include \"string_util.hpp\"\n\nnamespace resembla {\n\ntemplate\nstruct Eliminator\n{\n using size_type = typename string_type::size_type;\n using symbol_type = typename string_type::value_type;\n using distance_type = int;\n\n Eliminator(string_type const& pattern = string_type())\n {\n init(pattern);\n }\n\n void init(string_type const& pattern)\n {\n this->pattern = pattern;\n if(pattern.empty()){\n return;\n }\n\n pattern_length = pattern.size();\n block_size = ((pattern_length - 1) >> bit_offset()) + 1;\n rest_bits = pattern_length - (block_size - 1) * bit_width();\n sink = bitvector_type{1} << (rest_bits - 1);\n\n constructPM();\n zeroes.resize(block_size, 0);\n work.resize(block_size);\n }\n\n void operator()(std::vector& candidates, size_type k)\n {\n using index_distance = std::pair;\n\n \/\/ calculate scores\n std::vector work(candidates.size());\n for(size_type i = 0; i < work.size(); ++i){\n work[i].first = i;\n work[i].second = -distance(candidates[i]);\n }\n\n \/\/ sort partially to obtain top-k elements\n std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),\n [](const index_distance& a, const index_distance& b) -> bool{\n return a.second > b.second;\n });\n\n \/\/ ensure that work[i].first < work[j].first if i < j < k\n std::partial_sort(std::begin(work), std::begin(work) + k, std::begin(work) + k,\n [](const index_distance& a, const index_distance& b) -> bool{\n return a.first < b.first;\n });\n#ifdef DEBUG\n std::cerr << \"narrow \" << work.size() << \" strings\" << std::endl;\n for(size_type i = 0; i < k; ++i){\n std::cerr << cast_string(candidates[work[i].first]) << \": \" << work[i].second << std::endl;\n }\n#endif\n\n \/\/ sort original list\n for(size_type i = 0; i < k; ++i){\n std::swap(candidates[i], candidates[work[i].first]);\n }\n candidates.erase(std::begin(candidates) + k, std::end(candidates));\n }\n\nprotected:\n string_type pattern;\n size_type pattern_length;\n symbol_type c_min, c_max;\n size_type block_size;\n size_type rest_bits;\n bitvector_type sink;\n\n std::vector>> PM;\n std::vector zeroes;\n\n struct WorkData\n {\n bitvector_type D0;\n bitvector_type HP;\n bitvector_type HN;\n bitvector_type VP;\n bitvector_type VN;\n\n void reset()\n {\n D0 = HP = HN = VN = 0;\n VP = ~(bitvector_type{0});\n }\n };\n mutable std::vector work;\n\n template static constexpr int bit_width()\n {\n return 8 * sizeof(Integer);\n }\n\n static constexpr int bit_offset(int w)\n {\n return w < 2 ? 0 : (bit_offset(w >> 1) + 1);\n }\n\n template static constexpr int bit_offset()\n {\n return bit_offset(bit_width());\n }\n\n template\n const value_type& find_value(const std::vector>& data,\n const key_type c, const value_type& default_value) const\n {\n if(c < c_min || c_max < c){\n return default_value;\n }\n else if(c == c_min){\n return PM.front().second;\n }\n else if(c == c_max){\n return PM.back().second;\n }\n\n size_type l = 1, r = data.size() - 1;\n while(r - l > 8){\n auto i = (l + r) \/ 2;\n if(data[i].first < c){\n l = i + 1;\n }\n else if(data[i].first > c){\n r = i;\n }\n else{\n return data[i].second;\n }\n }\n\n for(size_type i = l; i < r; ++i){\n if(data[i].first == c){\n return data[i].second;\n }\n }\n\n return default_value;\n }\n\n void constructPM()\n {\n std::map> PM_work;\n for(size_type i = 0; i < block_size - 1; ++i){\n for(size_type j = 0; j < bit_width(); ++j){\n if(PM_work[pattern[i * bit_width() + j]].empty()){\n PM_work[pattern[i * bit_width() + j]].resize(block_size, 0);\n }\n PM_work[pattern[i * bit_width() + j]][i] |= bitvector_type{1} << j;\n }\n }\n for(size_type i = 0; i < rest_bits; ++i){\n if(PM_work[pattern[(block_size - 1) * bit_width() + i]].empty()){\n PM_work[pattern[(block_size - 1) * bit_width() + i]].resize(block_size, 0);\n }\n PM_work[pattern[(block_size - 1) * bit_width() + i]].back() |= bitvector_type{1} << i;\n }\n\n PM.clear();\n for(const auto& p: PM_work){\n PM.push_back(p);\n }\n c_min = PM.front().first;\n c_max = PM.back().first;\n }\n\n distance_type distance_sp(string_type const &text) const\n {\n auto& w = work.front();\n w.reset();\n for(size_type i = 0; i < pattern_length; ++i){\n w.VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n auto X = find_value(PM, c, zeroes).front() | w.VN;\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = (w.HP << 1) | 1;\n w.VP = (w.HN << 1) | ~(X | w.D0);\n w.VN = X & w.D0;\n\n if(w.HP & sink){\n ++D;\n }\n else if(w.HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance_lp(string_type const &text) const\n {\n constexpr bitvector_type msb = bitvector_type{1} << (bit_width() - 1);\n\n for(auto& w: work){\n w.reset();\n }\n for(size_type i = 0; i < rest_bits; ++i){\n work.back().VP |= bitvector_type{1} << i;\n }\n\n distance_type D = pattern_length;\n for(auto c: text){\n const auto& PMc = find_value(PM, c, zeroes);\n for(size_type r = 0; r < block_size; ++r){\n auto& w = work[r];\n auto X = PMc[r];\n if(r > 0 && (work[r - 1].HN & msb)){\n X |= 1;\n }\n\n w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;\n w.HP = w.VN | ~(w.VP | w.D0);\n w.HN = w.VP & w.D0;\n\n X = w.HP << 1;\n if(r == 0 || work[r - 1].HP & msb){\n X |= 1;\n }\n w.VP = (w.HN << 1) | ~(X | w.D0);\n if(r > 0 && (work[r - 1].HN & msb)){\n w.VP |= 1;\n }\n w.VN = X & w.D0;\n }\n\n if(work.back().HP & sink){\n ++D;\n }\n else if(work.back().HN & sink){\n --D;\n }\n }\n return D;\n }\n\n distance_type distance(string_type const &text) const\n {\n if(text.empty()){\n return pattern_length;\n }\n else if(pattern_length == 0){\n return text.size();\n }\n\n if(block_size == 1){\n return distance_sp(text);\n }\n else{\n return distance_lp(text);\n }\n }\n};\n\n}\n#endif\n<|endoftext|>"} {"text":"\/\/ Convert DMD CodeView debug information to PDB files\r\n\/\/ Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved\r\n\/\/\r\n\/\/ License for redistribution is given by the Artistic License 2.0\r\n\/\/ see file LICENSE for further details\r\n\r\n#include \r\n\r\n#include \"symutil.h\"\r\n#include \"demangle.h\"\r\n\r\nextern \"C\" {\r\n#include \"mscvpdb.h\"\r\n}\r\n\r\n#include \r\n\r\nchar dotReplacementChar = '@';\r\nbool demangleSymbols = true;\r\nbool useTypedefEnum = false;\r\n\r\nint dsym2c(const BYTE* p, int len, char* cname, int maxclen)\r\n{\r\n\tconst BYTE* beg = p;\r\n\tconst BYTE* end = p + len;\r\n\tint zlen, zpos, cpos = 0;\r\n\r\n\t\/\/ decompress symbol\r\n\twhile (p < end)\r\n\t{\r\n\t\tint ch = *p++;\r\n\t\tif(ch == 0)\r\n\t\t\tbreak;\r\n\t\tif ((ch & 0xc0) == 0xc0)\r\n\t\t{\r\n\t\t\tzlen = (ch & 0x7) + 1;\r\n\t\t\tzpos = ((ch >> 3) & 7) + 1; \/\/ + zlen;\r\n\t\t\tif (zpos > cpos)\r\n\t\t\t\tbreak;\r\n\t\t\tif (cpos + zlen >= maxclen)\r\n\t\t\t\tbreak;\r\n\t\t\tfor (int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n\t\telse if (ch >= 0x80)\r\n\t\t{\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tint ch2 = *p++;\r\n\t\t\tzlen = (ch2 & 0x7f) | ((ch & 0x38) << 4);\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tint ch3 = *p++;\r\n\t\t\tzpos = (ch3 & 0x7f) | ((ch & 7) << 7);\r\n\t\t\tif (zpos > cpos)\r\n\t\t\t\tbreak;\r\n\t\t\tif (cpos + zlen >= maxclen)\r\n\t\t\t\tbreak;\r\n\t\t\tfor(int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n#if 0\r\n\t\tif (ch == 0x80)\r\n\t\t{\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tzlen = *p++ & 0x7f;\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tzpos = *p++ & 0x7f;\r\n\t\t\tif (zpos > cpos)\r\n\t\t\t\tbreak;\r\n\t\t\tfor(int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n\t\telse if (ch > 0x80)\r\n\t\t{\r\n\t\t\tzlen = (ch & 0x7) + 1;\r\n\t\t\tzpos = ((ch >> 3) & 0xf) - 7; \/\/ + zlen;\r\n\t\t\tfor(int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n#endif\r\n\t\telse\r\n\t\t\tcname[cpos++] = ch;\r\n\t}\r\n\tif (p < end)\r\n\t{\r\n\t\t\/\/ decompression failed, assume it's containing UTF8 encoded characters\r\n\t\tcpos = min(maxclen, len);\r\n\t\tmemcpy(cname, beg, cpos);\r\n\t}\r\n\tcname[cpos] = 0;\r\n\tif(demangleSymbols)\r\n\t\tif (cname[0] == '_' && cname[1] == 'D' && isdigit(cname[2]))\r\n\t\t\td_demangle(cname, cname, maxclen, true);\r\n\r\n#if 1\r\n\tfor(int i = 0; i < cpos; i++)\r\n\t\tif (cname[i] == '.')\r\n\t\t\tcname[i] = dotReplacementChar;\r\n#endif\r\n\r\n\treturn cpos;\r\n}\r\n\r\nint pstrlen(const BYTE* &p)\r\n{\r\n\tint len = *p++;\r\n\tif(len == 0xff && *p == 0)\r\n\t{\r\n\t\tlen = p[1] | (p[2] << 8);\r\n\t\tp += 3;\r\n\t}\r\n\treturn len;\r\n}\r\n\r\nint pstrmemlen(const BYTE* p)\r\n{\r\n\tconst BYTE* q = p;\r\n\tint len = pstrlen(p);\r\n\treturn len + (p - q);\r\n}\r\n\r\nint dstrlen(const BYTE* &p, bool cstr)\r\n{\r\n\tif(cstr)\r\n\t\treturn strlen((const char*)p);\r\n\treturn pstrlen(p);\r\n}\r\n\r\nchar* p2c(const BYTE* p, int idx)\r\n{\r\n\tstatic char cname[4][2560];\r\n\tint len = pstrlen(p);\r\n\r\n#if 1\r\n\tmemcpy(cname[idx], p, len);\r\n\tcname[idx][len] = 0;\r\n#else\r\n\tdsym2c(p, len, cname[idx], 2560);\r\n#endif\r\n\treturn cname[idx];\r\n}\r\n\r\nchar* p2c(const p_string& p, int idx)\r\n{\r\n\treturn p2c(&p.namelen, idx);\r\n}\r\n\r\nint c2p(const char* c, BYTE* p)\r\n{\r\n\tBYTE* q = p;\r\n\tint len = strlen(c);\r\n\tif(len > 255)\r\n\t{\r\n\t\t*p++ = 0xff;\r\n\t\t*p++ = 0;\r\n\t\t*p++ = len & 0xff;\r\n\t\t*p++ = len >> 8;\r\n\t}\r\n\telse\r\n\t\t*p++ = len;\r\n\tmemcpy(p, c, len);\r\n\treturn p + len - q;\r\n}\r\n\r\nint c2p(const char* c, p_string& p)\r\n{\r\n\treturn c2p(c, &p.namelen);\r\n}\r\n\r\nint p2ccpy(char* p, const BYTE* s)\r\n{\r\n\tint len = pstrlen(s);\r\n\tmemcpy(p, s, len);\r\n\tp[len] = 0;\r\n\treturn len + 1;\r\n}\r\n\r\nint pstrcpy(BYTE* p, const BYTE* s)\r\n{\r\n\tconst BYTE* src = s;\r\n\tint len = pstrlen(s);\r\n\tfor(int i = 0; i <= s - src; i++)\r\n\t\t*p++ = src[i];\r\n\r\n\tfor(int i = 0; i < len; i++)\r\n\t\tif (s[i] == '.')\r\n\t\t{\r\n\t\t\t\/\/p[i++] = ':';\r\n\t\t\tp[i] = dotReplacementChar;\r\n\t\t}\r\n\t\telse\r\n\t\t\tp[i] = s[i];\r\n\treturn len + src - s; \/\/ *(BYTE*) memcpy (p, s, *s + 1) + 1;\r\n}\r\n\r\nint dmemcmp(const void* v1, const void* v2, int len)\r\n{\r\n\tconst BYTE* p1 = (const BYTE*) v1;\r\n\tconst BYTE* p2 = (const BYTE*) v2;\r\n\tfor(int i = 0; i < len; i++)\r\n\t{\r\n\t\tint b1 = p1[i];\r\n\t\tint b2 = p2[i];\r\n\t\tif(b1 == '.')\r\n\t\t\tb1 = dotReplacementChar;\r\n\t\tif(b2 == '.')\r\n\t\t\tb2 = dotReplacementChar;\r\n\t\tif(b1 != b2)\r\n\t\t\treturn b2 - b1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint pstrcpy(p_string& p, const p_string& s)\r\n{\r\n\treturn *(BYTE*) memcpy (&p, &s, s.namelen + 1) + 1;\r\n}\r\n\r\nint pstrcmp(const BYTE* p1, const BYTE* p2)\r\n{\r\n\tint len1 = pstrlen(p1);\r\n\tint len2 = pstrlen(p2);\r\n\tif (len1 != len2)\r\n\t\treturn len2 - len1;\r\n\treturn dmemcmp(p1, p2, len1);\r\n}\r\n\r\nbool p2ccmp(const BYTE* pp, const char* cp)\r\n{\r\n\tint len = strlen(cp);\r\n\tint plen = pstrlen(pp);\r\n\tif (len != plen)\r\n\t\treturn false;\r\n\treturn dmemcmp(pp, cp, len) == 0;\r\n}\r\n\r\nbool p2ccmp(const p_string& pp, const char* cp)\r\n{\r\n\treturn p2ccmp(&pp.namelen, cp);\r\n}\r\n\r\nbool dstrcmp(const BYTE* s1, bool cstr1, const BYTE* s2, bool cstr2)\r\n{\r\n\tint len1 = dstrlen(s1, cstr1);\r\n\tint len2 = dstrlen(s2, cstr2);\r\n\tif(len1 != len2)\r\n\t\treturn false;\r\n\treturn dmemcmp(s1, s2, len1) == 0;\r\n}\r\n\r\nint pstrcpy_v(bool v3, BYTE* d, const BYTE* s)\r\n{\r\n\tif (!v3)\r\n\t\treturn pstrcpy(d, s);\r\n\r\n\tint len = pstrlen(s);\r\n\tint clen = dsym2c(s, len, (char*) d, kMaxNameLen) + 1;\r\n\r\n\treturn clen;\r\n}\r\n\r\nint cstrcpy_v(bool v3, BYTE* d, const char* s)\r\n{\r\n\tint len = strlen(s);\r\n\tif(!v3)\r\n\t{\r\n\t\tassert(len < 256);\r\n\t\t*d++ = len;\r\n\t}\r\n\tlen = (std::min)(len, kMaxNameLen-1);\r\n\r\n\tmemcpy(d, s, len + 1);\r\n\td[len] = '\\0';\r\n\r\n\tfor(int i = 0; i < len; i++)\r\n\t\tif (d[i] == '.')\r\n\t\t\td[i] = dotReplacementChar;\r\n\r\n\treturn len + 1;\r\n}\r\n\r\nDo not crash when handling anonymous entities\/\/ Convert DMD CodeView debug information to PDB files\r\n\/\/ Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved\r\n\/\/\r\n\/\/ License for redistribution is given by the Artistic License 2.0\r\n\/\/ see file LICENSE for further details\r\n\r\n#include \r\n\r\n#include \"symutil.h\"\r\n#include \"demangle.h\"\r\n\r\nextern \"C\" {\r\n#include \"mscvpdb.h\"\r\n}\r\n\r\n#include \r\n\r\nchar dotReplacementChar = '@';\r\nbool demangleSymbols = true;\r\nbool useTypedefEnum = false;\r\n\r\nint dsym2c(const BYTE* p, int len, char* cname, int maxclen)\r\n{\r\n\tconst BYTE* beg = p;\r\n\tconst BYTE* end = p + len;\r\n\tint zlen, zpos, cpos = 0;\r\n\r\n\t\/\/ decompress symbol\r\n\twhile (p < end)\r\n\t{\r\n\t\tint ch = *p++;\r\n\t\tif(ch == 0)\r\n\t\t\tbreak;\r\n\t\tif ((ch & 0xc0) == 0xc0)\r\n\t\t{\r\n\t\t\tzlen = (ch & 0x7) + 1;\r\n\t\t\tzpos = ((ch >> 3) & 7) + 1; \/\/ + zlen;\r\n\t\t\tif (zpos > cpos)\r\n\t\t\t\tbreak;\r\n\t\t\tif (cpos + zlen >= maxclen)\r\n\t\t\t\tbreak;\r\n\t\t\tfor (int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n\t\telse if (ch >= 0x80)\r\n\t\t{\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tint ch2 = *p++;\r\n\t\t\tzlen = (ch2 & 0x7f) | ((ch & 0x38) << 4);\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tint ch3 = *p++;\r\n\t\t\tzpos = (ch3 & 0x7f) | ((ch & 7) << 7);\r\n\t\t\tif (zpos > cpos)\r\n\t\t\t\tbreak;\r\n\t\t\tif (cpos + zlen >= maxclen)\r\n\t\t\t\tbreak;\r\n\t\t\tfor(int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n#if 0\r\n\t\tif (ch == 0x80)\r\n\t\t{\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tzlen = *p++ & 0x7f;\r\n\t\t\tif (p >= end)\r\n\t\t\t\tbreak;\r\n\t\t\tzpos = *p++ & 0x7f;\r\n\t\t\tif (zpos > cpos)\r\n\t\t\t\tbreak;\r\n\t\t\tfor(int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n\t\telse if (ch > 0x80)\r\n\t\t{\r\n\t\t\tzlen = (ch & 0x7) + 1;\r\n\t\t\tzpos = ((ch >> 3) & 0xf) - 7; \/\/ + zlen;\r\n\t\t\tfor(int z = 0; z < zlen; z++)\r\n\t\t\t\tcname[cpos + z] = cname[cpos - zpos + z];\r\n\t\t\tcpos += zlen;\r\n\t\t}\r\n#endif\r\n\t\telse\r\n\t\t\tcname[cpos++] = ch;\r\n\t}\r\n\tif (p < end)\r\n\t{\r\n\t\t\/\/ decompression failed, assume it's containing UTF8 encoded characters\r\n\t\tcpos = min(maxclen, len);\r\n\t\tmemcpy(cname, beg, cpos);\r\n\t}\r\n\tcname[cpos] = 0;\r\n\tif(demangleSymbols)\r\n\t\tif (cname[0] == '_' && cname[1] == 'D' && isdigit(cname[2]))\r\n\t\t\td_demangle(cname, cname, maxclen, true);\r\n\r\n#if 1\r\n\tfor(int i = 0; i < cpos; i++)\r\n\t\tif (cname[i] == '.')\r\n\t\t\tcname[i] = dotReplacementChar;\r\n#endif\r\n\r\n\treturn cpos;\r\n}\r\n\r\nint pstrlen(const BYTE* &p)\r\n{\r\n\tint len = *p++;\r\n\tif(len == 0xff && *p == 0)\r\n\t{\r\n\t\tlen = p[1] | (p[2] << 8);\r\n\t\tp += 3;\r\n\t}\r\n\treturn len;\r\n}\r\n\r\nint pstrmemlen(const BYTE* p)\r\n{\r\n\tconst BYTE* q = p;\r\n\tint len = pstrlen(p);\r\n\treturn len + (p - q);\r\n}\r\n\r\nint dstrlen(const BYTE* &p, bool cstr)\r\n{\r\n\tif(cstr)\r\n\t\treturn strlen((const char*)p);\r\n\treturn pstrlen(p);\r\n}\r\n\r\nchar* p2c(const BYTE* p, int idx)\r\n{\r\n\tstatic char cname[4][2560];\r\n\tint len = pstrlen(p);\r\n\r\n#if 1\r\n\tmemcpy(cname[idx], p, len);\r\n\tcname[idx][len] = 0;\r\n#else\r\n\tdsym2c(p, len, cname[idx], 2560);\r\n#endif\r\n\treturn cname[idx];\r\n}\r\n\r\nchar* p2c(const p_string& p, int idx)\r\n{\r\n\treturn p2c(&p.namelen, idx);\r\n}\r\n\r\nint c2p(const char* c, BYTE* p)\r\n{\r\n\tBYTE* q = p;\r\n\tint len = strlen(c);\r\n\tif(len > 255)\r\n\t{\r\n\t\t*p++ = 0xff;\r\n\t\t*p++ = 0;\r\n\t\t*p++ = len & 0xff;\r\n\t\t*p++ = len >> 8;\r\n\t}\r\n\telse\r\n\t\t*p++ = len;\r\n\tmemcpy(p, c, len);\r\n\treturn p + len - q;\r\n}\r\n\r\nint c2p(const char* c, p_string& p)\r\n{\r\n\treturn c2p(c, &p.namelen);\r\n}\r\n\r\nint p2ccpy(char* p, const BYTE* s)\r\n{\r\n\tint len = pstrlen(s);\r\n\tmemcpy(p, s, len);\r\n\tp[len] = 0;\r\n\treturn len + 1;\r\n}\r\n\r\nint pstrcpy(BYTE* p, const BYTE* s)\r\n{\r\n\tconst BYTE* src = s;\r\n\tint len = pstrlen(s);\r\n\tfor(int i = 0; i <= s - src; i++)\r\n\t\t*p++ = src[i];\r\n\r\n\tfor(int i = 0; i < len; i++)\r\n\t\tif (s[i] == '.')\r\n\t\t{\r\n\t\t\t\/\/p[i++] = ':';\r\n\t\t\tp[i] = dotReplacementChar;\r\n\t\t}\r\n\t\telse\r\n\t\t\tp[i] = s[i];\r\n\treturn len + src - s; \/\/ *(BYTE*) memcpy (p, s, *s + 1) + 1;\r\n}\r\n\r\nint dmemcmp(const void* v1, const void* v2, int len)\r\n{\r\n\tconst BYTE* p1 = (const BYTE*) v1;\r\n\tconst BYTE* p2 = (const BYTE*) v2;\r\n\tfor(int i = 0; i < len; i++)\r\n\t{\r\n\t\tint b1 = p1[i];\r\n\t\tint b2 = p2[i];\r\n\t\tif(b1 == '.')\r\n\t\t\tb1 = dotReplacementChar;\r\n\t\tif(b2 == '.')\r\n\t\t\tb2 = dotReplacementChar;\r\n\t\tif(b1 != b2)\r\n\t\t\treturn b2 - b1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint pstrcpy(p_string& p, const p_string& s)\r\n{\r\n\treturn *(BYTE*) memcpy (&p, &s, s.namelen + 1) + 1;\r\n}\r\n\r\nint pstrcmp(const BYTE* p1, const BYTE* p2)\r\n{\r\n\tint len1 = pstrlen(p1);\r\n\tint len2 = pstrlen(p2);\r\n\tif (len1 != len2)\r\n\t\treturn len2 - len1;\r\n\treturn dmemcmp(p1, p2, len1);\r\n}\r\n\r\nbool p2ccmp(const BYTE* pp, const char* cp)\r\n{\r\n\tint len = strlen(cp);\r\n\tint plen = pstrlen(pp);\r\n\tif (len != plen)\r\n\t\treturn false;\r\n\treturn dmemcmp(pp, cp, len) == 0;\r\n}\r\n\r\nbool p2ccmp(const p_string& pp, const char* cp)\r\n{\r\n\treturn p2ccmp(&pp.namelen, cp);\r\n}\r\n\r\nbool dstrcmp(const BYTE* s1, bool cstr1, const BYTE* s2, bool cstr2)\r\n{\r\n\tint len1 = dstrlen(s1, cstr1);\r\n\tint len2 = dstrlen(s2, cstr2);\r\n\tif(len1 != len2)\r\n\t\treturn false;\r\n\treturn dmemcmp(s1, s2, len1) == 0;\r\n}\r\n\r\nint pstrcpy_v(bool v3, BYTE* d, const BYTE* s)\r\n{\r\n\tif (!v3)\r\n\t\treturn pstrcpy(d, s);\r\n\r\n\tint len = pstrlen(s);\r\n\tint clen = dsym2c(s, len, (char*) d, kMaxNameLen) + 1;\r\n\r\n\treturn clen;\r\n}\r\n\r\nint cstrcpy_v(bool v3, BYTE* d, const char* s)\r\n{\r\n\t\/\/ Process absent names as empty ones\r\n\tif (s == NULL)\r\n\t\ts = \"\";\r\n\r\n\tint len = strlen(s);\r\n\tif(!v3)\r\n\t{\r\n\t\tassert(len < 256);\r\n\t\t*d++ = len;\r\n\t}\r\n\tlen = (std::min)(len, kMaxNameLen-1);\r\n\r\n\tmemcpy(d, s, len + 1);\r\n\td[len] = '\\0';\r\n\r\n\tfor(int i = 0; i < len; i++)\r\n\t\tif (d[i] == '.')\r\n\t\t\td[i] = dotReplacementChar;\r\n\r\n\treturn len + 1;\r\n}\r\n\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n\nEigen::MatrixXd matrixSqrt(const Eigen::MatrixXd & M)\n{\n SM_ASSERT_EQ(std::runtime_error, M.rows(), M.cols(), \"The matrix must be square\");\n Eigen::MatrixXd sqrtM;\n\n Eigen::ComputationInfo result = sm::eigen::computeMatrixSqrt(M, sqrtM);\n SM_ASSERT_EQ(std::runtime_error, result, Eigen::Success, \"The matrix square root was not successful\")\n return sqrtM;\n}\n\nvoid exportEigen()\n{\n boost::python::def(\"computeMatrixSqrt\", &matrixSqrt);\n}\nFixed a compilation error in the python interface#include \n#include \n#include \n\n\nEigen::MatrixXd matrixSqrt(const Eigen::MatrixXd & M)\n{\n SM_ASSERT_EQ(std::runtime_error, M.rows(), M.cols(), \"The matrix must be square\");\n Eigen::MatrixXd sqrtM;\n\n \/*Eigen::ComputationInfo result =*\/ sm::eigen::computeMatrixSqrt(M, sqrtM);\n \/\/SM_ASSERT_EQ(std::runtime_error, result, Eigen::Success, \"The matrix square root was not successful\")\n return sqrtM;\n}\n\nvoid exportEigen()\n{\n boost::python::def(\"computeMatrixSqrt\", &matrixSqrt);\n}\n<|endoftext|>"} {"text":"#pragma once\n\nnamespace svgren{\n\nstruct SubSurface{\n\tstd::uint8_t* data; \/\/RGBA premultiplied alpha\n\tunsigned stride;\n\tunsigned width;\n\tunsigned height;\n\t\n\tunsigned posx;\n\tunsigned posy;\n};\n\n}\nstuff#pragma once\n\nnamespace svgren{\n\nstruct SubSurface{\n\tstd::uint8_t* data; \/\/RGBA premultiplied alpha\n\tunsigned stride;\n\t\n\tunsigned width;\n\tunsigned height;\n\t\n\t\/\/position of subsurface on the canvas\n\tunsigned posx;\n\tunsigned posy;\n};\n\n}\n<|endoftext|>"} {"text":"Measurement jacobians<|endoftext|>"} {"text":"indexcodec: Add extensive comments<|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 \"net\/base\/cert_status_flags.h\"\n\n#include \"base\/logging.h\"\n#include \"net\/base\/net_errors.h\"\n\nnamespace net {\n\nint MapNetErrorToCertStatus(int error) {\n switch (error) {\n case ERR_CERT_COMMON_NAME_INVALID:\n return CERT_STATUS_COMMON_NAME_INVALID;\n case ERR_CERT_DATE_INVALID:\n return CERT_STATUS_DATE_INVALID;\n case ERR_CERT_AUTHORITY_INVALID:\n return CERT_STATUS_AUTHORITY_INVALID;\n case ERR_CERT_NO_REVOCATION_MECHANISM:\n return CERT_STATUS_NO_REVOCATION_MECHANISM;\n case ERR_CERT_UNABLE_TO_CHECK_REVOCATION:\n return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;\n case ERR_CERT_REVOKED:\n return CERT_STATUS_REVOKED;\n \/\/ We added the ERR_CERT_CONTAINS_ERRORS error code when we were using\n \/\/ WinInet, but we never figured out how it differs from ERR_CERT_INVALID.\n \/\/ We should not use ERR_CERT_CONTAINS_ERRORS in new code.\n case ERR_CERT_CONTAINS_ERRORS:\n NOTREACHED();\n \/\/ Falls through.\n case ERR_CERT_INVALID:\n return CERT_STATUS_INVALID;\n case ERR_CERT_WEAK_SIGNATURE_ALGORITHM:\n return CERT_STATUS_WEAK_SIGNATURE_ALGORITHM;\n default:\n return 0;\n }\n}\n\nint MapCertStatusToNetError(int cert_status) {\n \/\/ A certificate may have multiple errors. We report the most\n \/\/ serious error.\n\n \/\/ Unrecoverable errors\n if (cert_status & CERT_STATUS_INVALID)\n return ERR_CERT_INVALID;\n if (cert_status & CERT_STATUS_REVOKED)\n return ERR_CERT_REVOKED;\n\n \/\/ Recoverable errors\n if (cert_status & CERT_STATUS_AUTHORITY_INVALID)\n return ERR_CERT_AUTHORITY_INVALID;\n if (cert_status & CERT_STATUS_COMMON_NAME_INVALID)\n return ERR_CERT_COMMON_NAME_INVALID;\n if (cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM)\n return ERR_CERT_WEAK_SIGNATURE_ALGORITHM;\n if (cert_status & CERT_STATUS_DATE_INVALID)\n return ERR_CERT_DATE_INVALID;\n\n \/\/ Unknown status. Give it the benefit of the doubt.\n if (cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION)\n return ERR_CERT_UNABLE_TO_CHECK_REVOCATION;\n if (cert_status & CERT_STATUS_NO_REVOCATION_MECHANISM)\n return ERR_CERT_NO_REVOCATION_MECHANISM;\n\n NOTREACHED();\n return ERR_UNEXPECTED;\n}\n\n} \/\/ namespace net\nConsider \"certificate revoked\" as the most serious certificate error.\/\/ 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 \"net\/base\/cert_status_flags.h\"\n\n#include \"base\/logging.h\"\n#include \"net\/base\/net_errors.h\"\n\nnamespace net {\n\nint MapNetErrorToCertStatus(int error) {\n switch (error) {\n case ERR_CERT_COMMON_NAME_INVALID:\n return CERT_STATUS_COMMON_NAME_INVALID;\n case ERR_CERT_DATE_INVALID:\n return CERT_STATUS_DATE_INVALID;\n case ERR_CERT_AUTHORITY_INVALID:\n return CERT_STATUS_AUTHORITY_INVALID;\n case ERR_CERT_NO_REVOCATION_MECHANISM:\n return CERT_STATUS_NO_REVOCATION_MECHANISM;\n case ERR_CERT_UNABLE_TO_CHECK_REVOCATION:\n return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;\n case ERR_CERT_REVOKED:\n return CERT_STATUS_REVOKED;\n \/\/ We added the ERR_CERT_CONTAINS_ERRORS error code when we were using\n \/\/ WinInet, but we never figured out how it differs from ERR_CERT_INVALID.\n \/\/ We should not use ERR_CERT_CONTAINS_ERRORS in new code.\n case ERR_CERT_CONTAINS_ERRORS:\n NOTREACHED();\n \/\/ Falls through.\n case ERR_CERT_INVALID:\n return CERT_STATUS_INVALID;\n case ERR_CERT_WEAK_SIGNATURE_ALGORITHM:\n return CERT_STATUS_WEAK_SIGNATURE_ALGORITHM;\n default:\n return 0;\n }\n}\n\nint MapCertStatusToNetError(int cert_status) {\n \/\/ A certificate may have multiple errors. We report the most\n \/\/ serious error.\n\n \/\/ Unrecoverable errors\n if (cert_status & CERT_STATUS_REVOKED)\n return ERR_CERT_REVOKED;\n if (cert_status & CERT_STATUS_INVALID)\n return ERR_CERT_INVALID;\n\n \/\/ Recoverable errors\n if (cert_status & CERT_STATUS_AUTHORITY_INVALID)\n return ERR_CERT_AUTHORITY_INVALID;\n if (cert_status & CERT_STATUS_COMMON_NAME_INVALID)\n return ERR_CERT_COMMON_NAME_INVALID;\n if (cert_status & CERT_STATUS_WEAK_SIGNATURE_ALGORITHM)\n return ERR_CERT_WEAK_SIGNATURE_ALGORITHM;\n if (cert_status & CERT_STATUS_DATE_INVALID)\n return ERR_CERT_DATE_INVALID;\n\n \/\/ Unknown status. Give it the benefit of the doubt.\n if (cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION)\n return ERR_CERT_UNABLE_TO_CHECK_REVOCATION;\n if (cert_status & CERT_STATUS_NO_REVOCATION_MECHANISM)\n return ERR_CERT_NO_REVOCATION_MECHANISM;\n\n NOTREACHED();\n return ERR_UNEXPECTED;\n}\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace json_spirit;\n\nnamespace cucumber {\nnamespace internal {\n\n\n\/*\n * Responses\n *\/\n\n\nvoid SuccessResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nFailureResponse::FailureResponse(const std::string & message, const std::string & exceptionType) :\n message(message),\n exceptionType(exceptionType) {\n}\n\nconst std::string FailureResponse::getMessage() const {\n return message;\n}\n\nconst std::string FailureResponse::getExceptionType() const {\n return exceptionType;\n}\n\nvoid FailureResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nPendingResponse::PendingResponse(const std::string & message) :\n message(message) {\n}\n\nconst std::string PendingResponse::getMessage() const {\n return message;\n}\n\nvoid PendingResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nStepMatchesResponse::StepMatchesResponse(const std::vector & matchingSteps)\n : matchingSteps(matchingSteps) {\n}\n\nconst std::vector& StepMatchesResponse::getMatchingSteps() const {\n return matchingSteps;\n}\n\nvoid StepMatchesResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nSnippetTextResponse::SnippetTextResponse(const std::string & stepSnippet) :\n stepSnippet(stepSnippet) {\n}\n\nconst std::string SnippetTextResponse::getStepSnippet() const {\n return stepSnippet;\n}\n\nvoid SnippetTextResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\n\n\/*\n * Command decoders\n *\/\n\n\nclass CommandDecoder {\npublic:\n virtual ~CommandDecoder() { }\n virtual boost::shared_ptr decode(const mValue & jsonArgs) const = 0;\n};\n\n\nclass ScenarioDecoder : public CommandDecoder {\nprotected:\n CukeEngine::tags_type getTags(const mValue & jsonArgs) const {\n CukeEngine::tags_type tags;\n if (!jsonArgs.is_null()) {\n const mArray & jsonTags = jsonArgs.get_obj().find(\"tags\")->second.get_array();\n for (mArray::const_iterator i = jsonTags.begin(); i != jsonTags.end(); ++i) {\n tags.push_back(i->get_str());\n }\n }\n return tags;\n }\n};\n\n\nclass BeginScenarioDecoder : public ScenarioDecoder {\npublic:\n boost::shared_ptr decode(const mValue & jsonArgs) const {\n return boost::make_shared(getTags(jsonArgs));\n }\n};\n\n\nclass EndScenarioDecoder : public ScenarioDecoder {\npublic:\n boost::shared_ptr decode(const mValue & jsonArgs) const {\n return boost::make_shared(getTags(jsonArgs));\n }\n};\n\n\nclass StepMatchesDecoder : public CommandDecoder {\npublic:\n boost::shared_ptr decode(const mValue & jsonArgs) const {\n mObject stepMatchesArgs(jsonArgs.get_obj());\n const std::string & nameToMatch(stepMatchesArgs[\"name_to_match\"].get_str());\n return boost::make_shared(nameToMatch);\n }\n};\n\n\nclass InvokeDecoder : public CommandDecoder {\npublic:\n boost::shared_ptr decode(const mValue & jsonArgs) const {\n mObject invokeParams(jsonArgs.get_obj());\n\n CukeEngine::invoke_args_type args;\n CukeEngine::invoke_table_type tableArg;\n const std::string & id(invokeParams[\"id\"].get_str());\n fillInvokeArgs(invokeParams, args, tableArg);\n return boost::make_shared(id, args, tableArg);\n }\n\nprivate:\n void fillInvokeArgs(\n const mObject & invokeParams,\n CukeEngine::invoke_args_type & args,\n CukeEngine::invoke_table_type & tableArg) const {\n const mArray & jsonArgs(invokeParams.find(\"args\")->second.get_array());\n for (mArray::const_iterator i = jsonArgs.begin(); i != jsonArgs.end(); ++i) {\n if (i->type() == str_type) {\n args.push_back(i->get_str());\n } else if (i->type() == array_type) {\n fillTableArg(i->get_array(), tableArg);\n }\n }\n }\n\n void fillTableArg(const mArray & jsonTableArg, CukeEngine::invoke_table_type & tableArg) const {\n typedef mArray::size_type size_type;\n size_type rows = jsonTableArg.size();\n if (rows > 0) {\n size_type columns = jsonTableArg[0].get_array().size();\n tableArg.resize(boost::extents[rows][columns]);\n for (size_type i = 0; i < rows; ++i) {\n const mArray & jsonRow(jsonTableArg[i].get_array());\n if (jsonRow.size() == columns) {\n for (size_type j = 0; j < columns; ++j) {\n tableArg[i][j] = jsonRow[j].get_str();\n }\n } else {\n \/\/ TODO: Invalid row\n }\n }\n } else {\n \/\/ TODO: Invalid table (no column specified)\n }\n }\n};\n\n\nclass SnippetTextDecoder : public CommandDecoder {\npublic:\n boost::shared_ptr decode(const mValue & jsonArgs) const {\n mObject snippetTextArgs(jsonArgs.get_obj());\n const std::string & stepKeyword(snippetTextArgs[\"step_keyword\"].get_str());\n const std::string & stepName(snippetTextArgs[\"step_name\"].get_str());\n const std::string & multilineArgClass(snippetTextArgs[\"multiline_arg_class\"].get_str());\n return boost::make_shared(stepKeyword, stepName, multilineArgClass);\n }\n};\n\nstatic const std::map > commandDecodersMap =\n boost::assign::map_list_of >\n (\"begin_scenario\", boost::make_shared< BeginScenarioDecoder >())\n (\"end_scenario\" , boost::make_shared< EndScenarioDecoder >())\n (\"step_matches\" , boost::make_shared< StepMatchesDecoder >())\n (\"invoke\" , boost::make_shared< InvokeDecoder >())\n (\"snippet_text\" , boost::make_shared< SnippetTextDecoder >());\n\n\nJsonSpiritWireMessageCodec::JsonSpiritWireMessageCodec() {};\n\nboost::shared_ptr JsonSpiritWireMessageCodec::decode(const std::string &request) const {\n std::istringstream is(request);\n mValue json;\n try {\n read_stream(is, json);\n mArray & jsonRequest = json.get_array();\n mValue & jsonCommand = jsonRequest[0];\n\n const std::map >::const_iterator\n commandDecoder = commandDecodersMap.find(jsonCommand.get_str());\n if (commandDecoder != commandDecodersMap.end()\n && commandDecoder->second) {\n mValue jsonArgs;\n if (jsonRequest.size() > 1) {\n jsonArgs = jsonRequest[1];\n }\n return commandDecoder->second->decode(jsonArgs);\n }\n } catch (...) {\n \/\/ LOG Error decoding wire protocol command\n }\n return boost::make_shared();\n}\n\nnamespace {\n\n class WireResponseEncoder : public WireResponseVisitor {\n private:\n mArray jsonOutput;\n\n void success(const mValue *detail = 0) {\n output(\"success\", detail);\n }\n\n void fail(const mValue *detail = 0) {\n output(\"fail\", detail);\n }\n\n void output(const char *responseType, const mValue *detail = 0) {\n jsonOutput.push_back(responseType);\n if (detail == 0 || detail->is_null()) {\n return;\n }\n jsonOutput.push_back(*detail);\n }\n\n public:\n std::string encode(const WireResponse& response) {\n jsonOutput.clear();\n response.accept(*this);\n const mValue v(jsonOutput);\n return write_string(v, false);\n }\n\n void visit(const SuccessResponse& \/*response*\/) {\n success();\n }\n\n void visit(const FailureResponse& response) {\n mObject detailObject;\n if (!response.getMessage().empty()) {\n detailObject[\"message\"] = response.getMessage();\n }\n if (!response.getExceptionType().empty()) {\n detailObject[\"exception\"] = response.getExceptionType();\n }\n if (detailObject.empty()) {\n fail();\n } else {\n const mValue detail(detailObject);\n fail(&detail);\n }\n }\n\n void visit(const PendingResponse& response) {\n mValue jsonReponse(response.getMessage());\n output(\"pending\", &jsonReponse);\n }\n\n void visit(const StepMatchesResponse& response) {\n mArray jsonMatches;\n BOOST_FOREACH(StepMatch m, response.getMatchingSteps()) {\n mObject jsonM;\n jsonM[\"id\"] = m.id;\n mArray jsonArgs;\n BOOST_FOREACH(StepMatchArg ma, m.args) {\n mObject jsonMa;\n jsonMa[\"val\"] = ma.value;\n jsonMa[\"pos\"] = ma.position;\n jsonArgs.push_back(jsonMa);\n }\n jsonM[\"args\"] = jsonArgs;\n if (!m.source.empty()) {\n jsonM[\"source\"] = m.source;;\n }\n if (!m.regexp.empty()) {\n jsonM[\"regexp\"] = m.regexp;\n }\n jsonMatches.push_back(jsonM);\n }\n mValue jsonReponse(jsonMatches);\n output(\"success\", &jsonReponse);\n }\n\n void visit(const SnippetTextResponse& response) {\n mValue jsonReponse(response.getStepSnippet());\n success(&jsonReponse);\n }\n };\n\n}\n\nconst std::string JsonSpiritWireMessageCodec::encode(const WireResponse& response) const {\n try {\n WireResponseEncoder encoder;\n return encoder.encode(response);\n } catch (...) {\n throw WireMessageCodecException(\"Error decoding wire protocol response\");\n }\n}\n\nWireProtocolHandler::WireProtocolHandler(const WireMessageCodec& codec, CukeEngine& engine) :\n codec(codec),\n engine(engine) {\n}\n\nstd::string WireProtocolHandler::handle(const std::string &request) const {\n std::string response;\n \/\/ LOG request\n try {\n boost::shared_ptr command = codec.decode(request);\n boost::shared_ptr wireResponse = command->run(engine);\n response = codec.encode(*wireResponse);\n } catch (...) {\n response = \"[\\\"fail\\\"]\";\n }\n \/\/ LOG response\n return response;\n}\n\n}\n}\nReplace CommandDecoder base class for function pointer#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace json_spirit;\n\nnamespace cucumber {\nnamespace internal {\n\n\n\/*\n * Responses\n *\/\n\n\nvoid SuccessResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nFailureResponse::FailureResponse(const std::string & message, const std::string & exceptionType) :\n message(message),\n exceptionType(exceptionType) {\n}\n\nconst std::string FailureResponse::getMessage() const {\n return message;\n}\n\nconst std::string FailureResponse::getExceptionType() const {\n return exceptionType;\n}\n\nvoid FailureResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nPendingResponse::PendingResponse(const std::string & message) :\n message(message) {\n}\n\nconst std::string PendingResponse::getMessage() const {\n return message;\n}\n\nvoid PendingResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nStepMatchesResponse::StepMatchesResponse(const std::vector & matchingSteps)\n : matchingSteps(matchingSteps) {\n}\n\nconst std::vector& StepMatchesResponse::getMatchingSteps() const {\n return matchingSteps;\n}\n\nvoid StepMatchesResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\nSnippetTextResponse::SnippetTextResponse(const std::string & stepSnippet) :\n stepSnippet(stepSnippet) {\n}\n\nconst std::string SnippetTextResponse::getStepSnippet() const {\n return stepSnippet;\n}\n\nvoid SnippetTextResponse::accept(WireResponseVisitor& visitor) const {\n visitor.visit(*this);\n}\n\n\n\/*\n * Command decoders\n *\/\n\n\nnamespace {\n typedef boost::shared_ptr (*CommandDecoder)(const mValue& jsonArgs);\n\n CukeEngine::tags_type getScenarioTags(const mValue& jsonArgs) {\n CukeEngine::tags_type tags;\n if (!jsonArgs.is_null()) {\n const mArray & jsonTags = jsonArgs.get_obj().find(\"tags\")->second.get_array();\n for (mArray::const_iterator i = jsonTags.begin(); i != jsonTags.end(); ++i) {\n tags.push_back(i->get_str());\n }\n }\n return tags;\n }\n\n boost::shared_ptr BeginScenarioDecoder(const mValue& jsonArgs) {\n return boost::make_shared(getScenarioTags(jsonArgs));\n }\n\n boost::shared_ptr EndScenarioDecoder(const mValue& jsonArgs) {\n return boost::make_shared(getScenarioTags(jsonArgs));\n }\n\n boost::shared_ptr StepMatchesDecoder(const mValue& jsonArgs) {\n mObject stepMatchesArgs(jsonArgs.get_obj());\n const std::string& nameToMatch(stepMatchesArgs[\"name_to_match\"].get_str());\n return boost::make_shared(nameToMatch);\n }\n\n void fillTableArg(const mArray& jsonTableArg, CukeEngine::invoke_table_type& tableArg) {\n typedef mArray::size_type size_type;\n size_type rows = jsonTableArg.size();\n if (rows > 0) {\n size_type columns = jsonTableArg[0].get_array().size();\n tableArg.resize(boost::extents[rows][columns]);\n for (size_type i = 0; i < rows; ++i) {\n const mArray & jsonRow(jsonTableArg[i].get_array());\n if (jsonRow.size() == columns) {\n for (size_type j = 0; j < columns; ++j) {\n tableArg[i][j] = jsonRow[j].get_str();\n }\n } else {\n \/\/ TODO: Invalid row\n }\n }\n } else {\n \/\/ TODO: Invalid table (no column specified)\n }\n }\n\n void fillInvokeArgs(\n const mObject& invokeParams,\n CukeEngine::invoke_args_type& args,\n CukeEngine::invoke_table_type& tableArg) {\n const mArray & jsonArgs(invokeParams.find(\"args\")->second.get_array());\n for (mArray::const_iterator i = jsonArgs.begin(); i != jsonArgs.end(); ++i) {\n if (i->type() == str_type) {\n args.push_back(i->get_str());\n } else if (i->type() == array_type) {\n fillTableArg(i->get_array(), tableArg);\n }\n }\n }\n\n boost::shared_ptr InvokeDecoder(const mValue& jsonArgs) {\n mObject invokeParams(jsonArgs.get_obj());\n\n CukeEngine::invoke_args_type args;\n CukeEngine::invoke_table_type tableArg;\n const std::string & id(invokeParams[\"id\"].get_str());\n fillInvokeArgs(invokeParams, args, tableArg);\n return boost::make_shared(id, args, tableArg);\n }\n\n boost::shared_ptr SnippetTextDecoder(const mValue& jsonArgs) {\n mObject snippetTextArgs(jsonArgs.get_obj());\n const std::string & stepKeyword(snippetTextArgs[\"step_keyword\"].get_str());\n const std::string & stepName(snippetTextArgs[\"step_name\"].get_str());\n const std::string & multilineArgClass(snippetTextArgs[\"multiline_arg_class\"].get_str());\n return boost::make_shared(stepKeyword, stepName, multilineArgClass);\n }\n}\n\nstatic const std::map commandDecodersMap =\n boost::assign::map_list_of\n (\"begin_scenario\", BeginScenarioDecoder)\n (\"end_scenario\" , EndScenarioDecoder )\n (\"step_matches\" , StepMatchesDecoder )\n (\"invoke\" , InvokeDecoder )\n (\"snippet_text\" , SnippetTextDecoder )\n ;\n\n\nJsonSpiritWireMessageCodec::JsonSpiritWireMessageCodec() {};\n\nboost::shared_ptr JsonSpiritWireMessageCodec::decode(const std::string &request) const {\n std::istringstream is(request);\n mValue json;\n try {\n read_stream(is, json);\n mArray & jsonRequest = json.get_array();\n mValue & jsonCommand = jsonRequest[0];\n\n const std::map::const_iterator\n commandDecoder = commandDecodersMap.find(jsonCommand.get_str());\n if (commandDecoder != commandDecodersMap.end()\n && commandDecoder->second) {\n mValue jsonArgs;\n if (jsonRequest.size() > 1) {\n jsonArgs = jsonRequest[1];\n }\n return commandDecoder->second(jsonArgs);\n }\n } catch (...) {\n \/\/ LOG Error decoding wire protocol command\n }\n return boost::make_shared();\n}\n\nnamespace {\n\n class WireResponseEncoder : public WireResponseVisitor {\n private:\n mArray jsonOutput;\n\n void success(const mValue *detail = 0) {\n output(\"success\", detail);\n }\n\n void fail(const mValue *detail = 0) {\n output(\"fail\", detail);\n }\n\n void output(const char *responseType, const mValue *detail = 0) {\n jsonOutput.push_back(responseType);\n if (detail == 0 || detail->is_null()) {\n return;\n }\n jsonOutput.push_back(*detail);\n }\n\n public:\n std::string encode(const WireResponse& response) {\n jsonOutput.clear();\n response.accept(*this);\n const mValue v(jsonOutput);\n return write_string(v, false);\n }\n\n void visit(const SuccessResponse& \/*response*\/) {\n success();\n }\n\n void visit(const FailureResponse& response) {\n mObject detailObject;\n if (!response.getMessage().empty()) {\n detailObject[\"message\"] = response.getMessage();\n }\n if (!response.getExceptionType().empty()) {\n detailObject[\"exception\"] = response.getExceptionType();\n }\n if (detailObject.empty()) {\n fail();\n } else {\n const mValue detail(detailObject);\n fail(&detail);\n }\n }\n\n void visit(const PendingResponse& response) {\n mValue jsonReponse(response.getMessage());\n output(\"pending\", &jsonReponse);\n }\n\n void visit(const StepMatchesResponse& response) {\n mArray jsonMatches;\n BOOST_FOREACH(StepMatch m, response.getMatchingSteps()) {\n mObject jsonM;\n jsonM[\"id\"] = m.id;\n mArray jsonArgs;\n BOOST_FOREACH(StepMatchArg ma, m.args) {\n mObject jsonMa;\n jsonMa[\"val\"] = ma.value;\n jsonMa[\"pos\"] = ma.position;\n jsonArgs.push_back(jsonMa);\n }\n jsonM[\"args\"] = jsonArgs;\n if (!m.source.empty()) {\n jsonM[\"source\"] = m.source;;\n }\n if (!m.regexp.empty()) {\n jsonM[\"regexp\"] = m.regexp;\n }\n jsonMatches.push_back(jsonM);\n }\n mValue jsonReponse(jsonMatches);\n output(\"success\", &jsonReponse);\n }\n\n void visit(const SnippetTextResponse& response) {\n mValue jsonReponse(response.getStepSnippet());\n success(&jsonReponse);\n }\n };\n\n}\n\nconst std::string JsonSpiritWireMessageCodec::encode(const WireResponse& response) const {\n try {\n WireResponseEncoder encoder;\n return encoder.encode(response);\n } catch (...) {\n throw WireMessageCodecException(\"Error decoding wire protocol response\");\n }\n}\n\nWireProtocolHandler::WireProtocolHandler(const WireMessageCodec& codec, CukeEngine& engine) :\n codec(codec),\n engine(engine) {\n}\n\nstd::string WireProtocolHandler::handle(const std::string &request) const {\n std::string response;\n \/\/ LOG request\n try {\n boost::shared_ptr command = codec.decode(request);\n boost::shared_ptr wireResponse = command->run(engine);\n response = codec.encode(*wireResponse);\n } catch (...) {\n response = \"[\\\"fail\\\"]\";\n }\n \/\/ LOG response\n return response;\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkColorFilter.h\"\n#include \"SkColorSpaceXformCanvas.h\"\n#include \"SkColorSpaceXformer.h\"\n#include \"SkGradientShader.h\"\n#include \"SkImage_Base.h\"\n#include \"SkMakeUnique.h\"\n#include \"SkNoDrawCanvas.h\"\n#include \"SkSurface.h\"\n\nclass SkColorSpaceXformCanvas : public SkNoDrawCanvas {\npublic:\n SkColorSpaceXformCanvas(SkCanvas* target,\n std::unique_ptr xformer)\n : SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize()))\n , fTarget(target)\n , fXformer(std::move(xformer))\n {\n \/\/ Set the matrix and clip to match |fTarget|. Otherwise, we'll answer queries for\n \/\/ bounds\/matrix differently than |fTarget| would.\n SkCanvas::onClipRect(SkRect::MakeFromIRect(fTarget->getDeviceClipBounds()),\n SkClipOp::kIntersect, kHard_ClipEdgeStyle);\n SkCanvas::setMatrix(fTarget->getTotalMatrix());\n }\n\n SkImageInfo onImageInfo() const override {\n return fTarget->imageInfo();\n }\n\n void onDrawPaint(const SkPaint& paint) override {\n fTarget->drawPaint(fXformer->apply(paint));\n }\n\n void onDrawRect(const SkRect& rect, const SkPaint& paint) override {\n fTarget->drawRect(rect, fXformer->apply(paint));\n }\n void onDrawOval(const SkRect& oval, const SkPaint& paint) override {\n fTarget->drawOval(oval, fXformer->apply(paint));\n }\n void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {\n fTarget->drawRRect(rrect, fXformer->apply(paint));\n }\n void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override {\n fTarget->drawDRRect(outer, inner, fXformer->apply(paint));\n }\n void onDrawPath(const SkPath& path, const SkPaint& paint) override {\n fTarget->drawPath(path, fXformer->apply(paint));\n }\n void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter,\n const SkPaint& paint) override {\n fTarget->drawArc(oval, start, sweep, useCenter, fXformer->apply(paint));\n }\n void onDrawRegion(const SkRegion& region, const SkPaint& paint) override {\n fTarget->drawRegion(region, fXformer->apply(paint));\n }\n void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4],\n SkBlendMode mode, const SkPaint& paint) override {\n SkColor xformed[4];\n if (colors) {\n fXformer->apply(xformed, colors, 4);\n colors = xformed;\n }\n\n fTarget->drawPatch(cubics, colors, texs, mode, fXformer->apply(paint));\n }\n void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts,\n const SkPaint& paint) override {\n fTarget->drawPoints(mode, count, pts, fXformer->apply(paint));\n }\n void onDrawVerticesObject(const SkVertices* vertices, SkBlendMode mode,\n const SkPaint& paint) override {\n sk_sp copy;\n if (vertices->hasColors()) {\n int count = vertices->vertexCount();\n SkSTArray<8, SkColor> xformed(count);\n fXformer->apply(xformed.begin(), vertices->colors(), count);\n copy = SkVertices::MakeCopy(vertices->mode(), count, vertices->positions(),\n vertices->texCoords(), xformed.begin(),\n vertices->indexCount(), vertices->indices());\n vertices = copy.get();\n }\n\n fTarget->drawVertices(vertices, mode, fXformer->apply(paint));\n }\n\n void onDrawText(const void* ptr, size_t len,\n SkScalar x, SkScalar y,\n const SkPaint& paint) override {\n fTarget->drawText(ptr, len, x, y, fXformer->apply(paint));\n }\n void onDrawPosText(const void* ptr, size_t len,\n const SkPoint* xys,\n const SkPaint& paint) override {\n fTarget->drawPosText(ptr, len, xys, fXformer->apply(paint));\n }\n void onDrawPosTextH(const void* ptr, size_t len,\n const SkScalar* xs, SkScalar y,\n const SkPaint& paint) override {\n fTarget->drawPosTextH(ptr, len, xs, y, fXformer->apply(paint));\n }\n void onDrawTextOnPath(const void* ptr, size_t len,\n const SkPath& path, const SkMatrix* matrix,\n const SkPaint& paint) override {\n fTarget->drawTextOnPath(ptr, len, path, matrix, fXformer->apply(paint));\n }\n void onDrawTextRSXform(const void* ptr, size_t len,\n const SkRSXform* xforms, const SkRect* cull,\n const SkPaint& paint) override {\n fTarget->drawTextRSXform(ptr, len, xforms, cull, fXformer->apply(paint));\n }\n void onDrawTextBlob(const SkTextBlob* blob,\n SkScalar x, SkScalar y,\n const SkPaint& paint) override {\n fTarget->drawTextBlob(blob, x, y, fXformer->apply(paint));\n }\n\n void onDrawImage(const SkImage* img,\n SkScalar l, SkScalar t,\n const SkPaint* paint) override {\n fTarget->drawImage(fXformer->apply(img).get(),\n l, t,\n fXformer->apply(paint));\n }\n void onDrawImageRect(const SkImage* img,\n const SkRect* src, const SkRect& dst,\n const SkPaint* paint, SrcRectConstraint constraint) override {\n fTarget->drawImageRect(fXformer->apply(img).get(),\n src ? *src : dst, dst,\n fXformer->apply(paint), constraint);\n }\n void onDrawImageNine(const SkImage* img,\n const SkIRect& center, const SkRect& dst,\n const SkPaint* paint) override {\n fTarget->drawImageNine(fXformer->apply(img).get(),\n center, dst,\n fXformer->apply(paint));\n }\n void onDrawImageLattice(const SkImage* img,\n const Lattice& lattice, const SkRect& dst,\n const SkPaint* paint) override {\n fTarget->drawImageLattice(fXformer->apply(img).get(),\n lattice, dst,\n fXformer->apply(paint));\n }\n void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex,\n const SkColor* colors, int count, SkBlendMode mode,\n const SkRect* cull, const SkPaint* paint) override {\n SkSTArray<8, SkColor> xformed;\n if (colors) {\n xformed.reset(count);\n fXformer->apply(xformed.begin(), colors, count);\n colors = xformed.begin();\n }\n\n fTarget->drawAtlas(fXformer->apply(atlas).get(), xforms, tex, colors, count, mode, cull,\n fXformer->apply(paint));\n }\n\n void onDrawBitmap(const SkBitmap& bitmap,\n SkScalar l, SkScalar t,\n const SkPaint* paint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImage(image.get(), l, t, paint);\n }\n }\n void onDrawBitmapRect(const SkBitmap& bitmap,\n const SkRect* src, const SkRect& dst,\n const SkPaint* paint, SrcRectConstraint constraint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImageRect(image.get(), src, dst, paint, constraint);\n }\n }\n void onDrawBitmapNine(const SkBitmap& bitmap,\n const SkIRect& center, const SkRect& dst,\n const SkPaint* paint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImageNine(image.get(), center, dst, paint);\n }\n }\n void onDrawBitmapLattice(const SkBitmap& bitmap,\n const Lattice& lattice, const SkRect& dst,\n const SkPaint* paint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImageLattice(image.get(), lattice, dst, paint);\n }\n }\n\n \/\/ TODO: May not be ideal to unfurl pictures.\n void onDrawPicture(const SkPicture* pic,\n const SkMatrix* matrix,\n const SkPaint* paint) override {\n SkCanvas::onDrawPicture(pic, matrix, fXformer->apply(paint));\n }\n void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {\n SkCanvas::onDrawDrawable(drawable, matrix);\n }\n\n SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override {\n fTarget->saveLayer({\n rec.fBounds,\n fXformer->apply(rec.fPaint),\n rec.fBackdrop, \/\/ TODO: this is an image filter\n rec.fSaveLayerFlags,\n });\n return kNoLayer_SaveLayerStrategy;\n }\n\n \/\/ Everything from here on should be uninteresting strictly proxied state-change calls.\n void willSave() override { fTarget->save(); }\n void willRestore() override { fTarget->restore(); }\n\n void didConcat (const SkMatrix& m) override { fTarget->concat (m); }\n void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); }\n\n void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override {\n SkCanvas::onClipRect(clip, op, style);\n fTarget->clipRect(clip, op, style);\n }\n void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override {\n SkCanvas::onClipRRect(clip, op, style);\n fTarget->clipRRect(clip, op, style);\n }\n void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override {\n SkCanvas::onClipPath(clip, op, style);\n fTarget->clipPath(clip, op, style);\n }\n void onClipRegion(const SkRegion& clip, SkClipOp op) override {\n SkCanvas::onClipRegion(clip, op);\n fTarget->clipRegion(clip, op);\n }\n\n void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override {\n fTarget->drawAnnotation(rect, key, val);\n }\n\n sk_sp onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override {\n return fTarget->makeSurface(info, &props);\n }\n\n SkISize getBaseLayerSize() const override { return fTarget->getBaseLayerSize(); }\n SkRect onGetLocalClipBounds() const override { return fTarget->getLocalClipBounds(); }\n SkIRect onGetDeviceClipBounds() const override { return fTarget->getDeviceClipBounds(); }\n bool isClipEmpty() const override { return fTarget->isClipEmpty(); }\n bool isClipRect() const override { return fTarget->isClipRect(); }\n bool onPeekPixels(SkPixmap* pixmap) override { return fTarget->peekPixels(pixmap); }\n bool onAccessTopLayerPixels(SkPixmap* pixmap) override {\n SkImageInfo info;\n size_t rowBytes;\n SkIPoint* origin = nullptr;\n void* addr = fTarget->accessTopLayerPixels(&info, &rowBytes, origin);\n if (addr) {\n *pixmap = SkPixmap(info, addr, rowBytes);\n return true;\n }\n return false;\n }\n\n bool onGetProps(SkSurfaceProps* props) const override { return fTarget->getProps(props); }\n void onFlush() override { return fTarget->flush(); }\n\nprivate:\n SkCanvas* fTarget;\n std::unique_ptr fXformer;\n};\n\nstd::unique_ptr SkCreateColorSpaceXformCanvas(SkCanvas* target,\n sk_sp targetCS) {\n std::unique_ptr xformer = SkColorSpaceXformer::Make(std::move(targetCS));\n if (!xformer) {\n return nullptr;\n }\n\n return skstd::make_unique(target, std::move(xformer));\n}\navoid deprecated SkRect::MakeFromIRect\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkColorFilter.h\"\n#include \"SkColorSpaceXformCanvas.h\"\n#include \"SkColorSpaceXformer.h\"\n#include \"SkGradientShader.h\"\n#include \"SkImage_Base.h\"\n#include \"SkMakeUnique.h\"\n#include \"SkNoDrawCanvas.h\"\n#include \"SkSurface.h\"\n\nclass SkColorSpaceXformCanvas : public SkNoDrawCanvas {\npublic:\n SkColorSpaceXformCanvas(SkCanvas* target,\n std::unique_ptr xformer)\n : SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize()))\n , fTarget(target)\n , fXformer(std::move(xformer))\n {\n \/\/ Set the matrix and clip to match |fTarget|. Otherwise, we'll answer queries for\n \/\/ bounds\/matrix differently than |fTarget| would.\n SkCanvas::onClipRect(SkRect::Make(fTarget->getDeviceClipBounds()),\n SkClipOp::kIntersect, kHard_ClipEdgeStyle);\n SkCanvas::setMatrix(fTarget->getTotalMatrix());\n }\n\n SkImageInfo onImageInfo() const override {\n return fTarget->imageInfo();\n }\n\n void onDrawPaint(const SkPaint& paint) override {\n fTarget->drawPaint(fXformer->apply(paint));\n }\n\n void onDrawRect(const SkRect& rect, const SkPaint& paint) override {\n fTarget->drawRect(rect, fXformer->apply(paint));\n }\n void onDrawOval(const SkRect& oval, const SkPaint& paint) override {\n fTarget->drawOval(oval, fXformer->apply(paint));\n }\n void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {\n fTarget->drawRRect(rrect, fXformer->apply(paint));\n }\n void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override {\n fTarget->drawDRRect(outer, inner, fXformer->apply(paint));\n }\n void onDrawPath(const SkPath& path, const SkPaint& paint) override {\n fTarget->drawPath(path, fXformer->apply(paint));\n }\n void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter,\n const SkPaint& paint) override {\n fTarget->drawArc(oval, start, sweep, useCenter, fXformer->apply(paint));\n }\n void onDrawRegion(const SkRegion& region, const SkPaint& paint) override {\n fTarget->drawRegion(region, fXformer->apply(paint));\n }\n void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4],\n SkBlendMode mode, const SkPaint& paint) override {\n SkColor xformed[4];\n if (colors) {\n fXformer->apply(xformed, colors, 4);\n colors = xformed;\n }\n\n fTarget->drawPatch(cubics, colors, texs, mode, fXformer->apply(paint));\n }\n void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts,\n const SkPaint& paint) override {\n fTarget->drawPoints(mode, count, pts, fXformer->apply(paint));\n }\n void onDrawVerticesObject(const SkVertices* vertices, SkBlendMode mode,\n const SkPaint& paint) override {\n sk_sp copy;\n if (vertices->hasColors()) {\n int count = vertices->vertexCount();\n SkSTArray<8, SkColor> xformed(count);\n fXformer->apply(xformed.begin(), vertices->colors(), count);\n copy = SkVertices::MakeCopy(vertices->mode(), count, vertices->positions(),\n vertices->texCoords(), xformed.begin(),\n vertices->indexCount(), vertices->indices());\n vertices = copy.get();\n }\n\n fTarget->drawVertices(vertices, mode, fXformer->apply(paint));\n }\n\n void onDrawText(const void* ptr, size_t len,\n SkScalar x, SkScalar y,\n const SkPaint& paint) override {\n fTarget->drawText(ptr, len, x, y, fXformer->apply(paint));\n }\n void onDrawPosText(const void* ptr, size_t len,\n const SkPoint* xys,\n const SkPaint& paint) override {\n fTarget->drawPosText(ptr, len, xys, fXformer->apply(paint));\n }\n void onDrawPosTextH(const void* ptr, size_t len,\n const SkScalar* xs, SkScalar y,\n const SkPaint& paint) override {\n fTarget->drawPosTextH(ptr, len, xs, y, fXformer->apply(paint));\n }\n void onDrawTextOnPath(const void* ptr, size_t len,\n const SkPath& path, const SkMatrix* matrix,\n const SkPaint& paint) override {\n fTarget->drawTextOnPath(ptr, len, path, matrix, fXformer->apply(paint));\n }\n void onDrawTextRSXform(const void* ptr, size_t len,\n const SkRSXform* xforms, const SkRect* cull,\n const SkPaint& paint) override {\n fTarget->drawTextRSXform(ptr, len, xforms, cull, fXformer->apply(paint));\n }\n void onDrawTextBlob(const SkTextBlob* blob,\n SkScalar x, SkScalar y,\n const SkPaint& paint) override {\n fTarget->drawTextBlob(blob, x, y, fXformer->apply(paint));\n }\n\n void onDrawImage(const SkImage* img,\n SkScalar l, SkScalar t,\n const SkPaint* paint) override {\n fTarget->drawImage(fXformer->apply(img).get(),\n l, t,\n fXformer->apply(paint));\n }\n void onDrawImageRect(const SkImage* img,\n const SkRect* src, const SkRect& dst,\n const SkPaint* paint, SrcRectConstraint constraint) override {\n fTarget->drawImageRect(fXformer->apply(img).get(),\n src ? *src : dst, dst,\n fXformer->apply(paint), constraint);\n }\n void onDrawImageNine(const SkImage* img,\n const SkIRect& center, const SkRect& dst,\n const SkPaint* paint) override {\n fTarget->drawImageNine(fXformer->apply(img).get(),\n center, dst,\n fXformer->apply(paint));\n }\n void onDrawImageLattice(const SkImage* img,\n const Lattice& lattice, const SkRect& dst,\n const SkPaint* paint) override {\n fTarget->drawImageLattice(fXformer->apply(img).get(),\n lattice, dst,\n fXformer->apply(paint));\n }\n void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex,\n const SkColor* colors, int count, SkBlendMode mode,\n const SkRect* cull, const SkPaint* paint) override {\n SkSTArray<8, SkColor> xformed;\n if (colors) {\n xformed.reset(count);\n fXformer->apply(xformed.begin(), colors, count);\n colors = xformed.begin();\n }\n\n fTarget->drawAtlas(fXformer->apply(atlas).get(), xforms, tex, colors, count, mode, cull,\n fXformer->apply(paint));\n }\n\n void onDrawBitmap(const SkBitmap& bitmap,\n SkScalar l, SkScalar t,\n const SkPaint* paint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImage(image.get(), l, t, paint);\n }\n }\n void onDrawBitmapRect(const SkBitmap& bitmap,\n const SkRect* src, const SkRect& dst,\n const SkPaint* paint, SrcRectConstraint constraint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImageRect(image.get(), src, dst, paint, constraint);\n }\n }\n void onDrawBitmapNine(const SkBitmap& bitmap,\n const SkIRect& center, const SkRect& dst,\n const SkPaint* paint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImageNine(image.get(), center, dst, paint);\n }\n }\n void onDrawBitmapLattice(const SkBitmap& bitmap,\n const Lattice& lattice, const SkRect& dst,\n const SkPaint* paint) override {\n if (auto image = SkImage::MakeFromBitmap(bitmap)) {\n this->onDrawImageLattice(image.get(), lattice, dst, paint);\n }\n }\n\n \/\/ TODO: May not be ideal to unfurl pictures.\n void onDrawPicture(const SkPicture* pic,\n const SkMatrix* matrix,\n const SkPaint* paint) override {\n SkCanvas::onDrawPicture(pic, matrix, fXformer->apply(paint));\n }\n void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {\n SkCanvas::onDrawDrawable(drawable, matrix);\n }\n\n SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override {\n fTarget->saveLayer({\n rec.fBounds,\n fXformer->apply(rec.fPaint),\n rec.fBackdrop, \/\/ TODO: this is an image filter\n rec.fSaveLayerFlags,\n });\n return kNoLayer_SaveLayerStrategy;\n }\n\n \/\/ Everything from here on should be uninteresting strictly proxied state-change calls.\n void willSave() override { fTarget->save(); }\n void willRestore() override { fTarget->restore(); }\n\n void didConcat (const SkMatrix& m) override { fTarget->concat (m); }\n void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); }\n\n void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override {\n SkCanvas::onClipRect(clip, op, style);\n fTarget->clipRect(clip, op, style);\n }\n void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override {\n SkCanvas::onClipRRect(clip, op, style);\n fTarget->clipRRect(clip, op, style);\n }\n void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override {\n SkCanvas::onClipPath(clip, op, style);\n fTarget->clipPath(clip, op, style);\n }\n void onClipRegion(const SkRegion& clip, SkClipOp op) override {\n SkCanvas::onClipRegion(clip, op);\n fTarget->clipRegion(clip, op);\n }\n\n void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override {\n fTarget->drawAnnotation(rect, key, val);\n }\n\n sk_sp onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override {\n return fTarget->makeSurface(info, &props);\n }\n\n SkISize getBaseLayerSize() const override { return fTarget->getBaseLayerSize(); }\n SkRect onGetLocalClipBounds() const override { return fTarget->getLocalClipBounds(); }\n SkIRect onGetDeviceClipBounds() const override { return fTarget->getDeviceClipBounds(); }\n bool isClipEmpty() const override { return fTarget->isClipEmpty(); }\n bool isClipRect() const override { return fTarget->isClipRect(); }\n bool onPeekPixels(SkPixmap* pixmap) override { return fTarget->peekPixels(pixmap); }\n bool onAccessTopLayerPixels(SkPixmap* pixmap) override {\n SkImageInfo info;\n size_t rowBytes;\n SkIPoint* origin = nullptr;\n void* addr = fTarget->accessTopLayerPixels(&info, &rowBytes, origin);\n if (addr) {\n *pixmap = SkPixmap(info, addr, rowBytes);\n return true;\n }\n return false;\n }\n\n bool onGetProps(SkSurfaceProps* props) const override { return fTarget->getProps(props); }\n void onFlush() override { return fTarget->flush(); }\n\nprivate:\n SkCanvas* fTarget;\n std::unique_ptr fXformer;\n};\n\nstd::unique_ptr SkCreateColorSpaceXformCanvas(SkCanvas* target,\n sk_sp targetCS) {\n std::unique_ptr xformer = SkColorSpaceXformer::Make(std::move(targetCS));\n if (!xformer) {\n return nullptr;\n }\n\n return skstd::make_unique(target, std::move(xformer));\n}\n<|endoftext|>"} {"text":"\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"$Id$\"\n\/*\nCOPYING CONDITIONS NOTICE:\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of version 2 of the GNU General Public License as\n published by the Free Software Foundation, and provided that the\n following conditions are met:\n\n * Redistributions of source code must retain this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below).\n\n * Redistributions in binary form must reproduce this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below) in the documentation and\/or other materials\n provided with the distribution.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\nCOPYRIGHT NOTICE:\n\n TokuDB, Tokutek Fractal Tree Indexing Library.\n Copyright (C) 2007-2013 Tokutek, Inc.\n\nDISCLAIMER:\n\n This program 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 General Public License for more details.\n\nUNIVERSITY PATENT NOTICE:\n\n The technology is licensed by the Massachusetts Institute of\n Technology, Rutgers State University of New Jersey, and the Research\n Foundation of State University of New York at Stony Brook under\n United States of America Serial No. 11\/760379 and to the patents\n and\/or patent applications resulting from it.\n\nPATENT MARKING NOTICE:\n\n This software is covered by US Patent No. 8,185,551.\n This software is covered by US Patent No. 8,489,638.\n\nPATENT RIGHTS GRANT:\n\n \"THIS IMPLEMENTATION\" means the copyrightable works distributed by\n Tokutek as part of the Fractal Tree project.\n\n \"PATENT CLAIMS\" means the claims of patents that are owned or\n licensable by Tokutek, both currently or in the future; and that in\n the absence of this license would be infringed by THIS\n IMPLEMENTATION or by using or running THIS IMPLEMENTATION.\n\n \"PATENT CHALLENGE\" shall mean a challenge to the validity,\n patentability, enforceability and\/or non-infringement of any of the\n PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.\n\n Tokutek hereby grants to you, for the term and geographical scope of\n the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,\n irrevocable (except as stated in this section) patent license to\n make, have made, use, offer to sell, sell, import, transfer, and\n otherwise run, modify, and propagate the contents of THIS\n IMPLEMENTATION, where such license applies only to the PATENT\n CLAIMS. This grant does not include claims that would be infringed\n only as a consequence of further modifications of THIS\n IMPLEMENTATION. If you or your agent or licensee institute or order\n or agree to the institution of patent litigation against any entity\n (including a cross-claim or counterclaim in a lawsuit) alleging that\n THIS IMPLEMENTATION constitutes direct or contributory patent\n infringement, or inducement of patent infringement, then any rights\n granted to you under this License shall terminate as of the date\n such litigation is filed. If you or your agent or exclusive\n licensee institute or order or agree to the institution of a PATENT\n CHALLENGE, then Tokutek may terminate any rights granted to you\n under this License.\n*\/\n\n#ident \"Copyright (c) 2007-2013 Tokutek Inc. All rights reserved.\"\n#ident \"The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11\/760379 and to the patents and\/or patent applications resulting from it.\"\n\n\/\/ Create a lot of dirty nodes, kick off a checkpoint, and close the environment.\n\/\/ Measure the time it takes to close the environment since we are speeding up that\n\/\/ function.\n\n#include \"test.h\"\n#include \n#include \n\n\/\/ Insert max_rows key\/val pairs into the db\nstatic void do_inserts(DB_ENV *env, DB *db, uint64_t max_rows, size_t val_size) {\n char val_data[val_size]; memset(val_data, 0, val_size);\n int r;\n DB_TXN *txn = nullptr;\n r = env->txn_begin(env, nullptr, &txn, 0);\n CKERR(r);\n\n for (uint64_t i = 1; i <= max_rows; i++) {\n \/\/ pick a sequential key but it does not matter for this test.\n uint64_t k[2] = {\n htobe64(i), random64(),\n };\n DBT key = { .data = k, .size = sizeof k };\n DBT val = { .data = val_data, .size = (uint32_t) val_size };\n r = db->put(db, txn, &key, &val, 0);\n CKERR(r);\n\n if ((i % 1000) == 0) {\n if (verbose)\n fprintf(stderr, \"put %\" PRIu64 \"\\n\", i);\n r = txn->commit(txn, 0);\n CKERR(r);\n r = env->txn_begin(env, nullptr, &txn, 0);\n CKERR(r);\n }\n }\n\n r = txn->commit(txn, 0);\n CKERR(r);\n}\n\n\/\/ Create a cache with a lot of dirty nodes, kick off a checkpoint, and measure the time to\n\/\/ close the environment.\nstatic void big_shutdown(void) {\n int r;\n\n DB_ENV *env = nullptr;\n r = db_env_create(&env, 0);\n CKERR(r);\n r = env->set_cachesize(env, 8, 0, 1);\n CKERR(r);\n r = env->open(env, TOKU_TEST_FILENAME,\n DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE,\n S_IRWXU+S_IRWXG+S_IRWXO);\n CKERR(r);\n\n DB *db = nullptr;\n r = db_create(&db, env, 0);\n CKERR(r);\n r = db->open(db, nullptr, \"foo.db\", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO);\n CKERR(r);\n\n do_inserts(env, db, 1000000, 1024);\n\n \/\/ kick the checkpoint thread\n if (verbose)\n fprintf(stderr, \"env->checkpointing_set_period\\n\");\n r = env->checkpointing_set_period(env, 2);\n CKERR(r);\n sleep(3);\n\n if (verbose)\n fprintf(stderr, \"db->close\\n\");\n r = db->close(db, 0);\n CKERR(r);\n\n \/\/ measure the shutdown time\n uint64_t tstart = toku_current_time_microsec();\n if (verbose)\n fprintf(stderr, \"env->close\\n\");\n r = env->close(env, 0);\n CKERR(r);\n uint64_t tend = toku_current_time_microsec();\n if (verbose)\n fprintf(stderr, \"env->close complete %\" PRIu64 \" sec\\n\", (tend - tstart)\/1000000);\n}\n\nint test_main (int argc, char *const argv[]) {\n default_parse_args(argc, argv);\n\n \/\/ init the env directory\n toku_os_recursive_delete(TOKU_TEST_FILENAME);\n int r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO);\n CKERR(r);\n\n \/\/ run the test\n big_shutdown();\n\n return 0;\n}\nFT-312 fix centos compile\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"$Id$\"\n\/*\nCOPYING CONDITIONS NOTICE:\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of version 2 of the GNU General Public License as\n published by the Free Software Foundation, and provided that the\n following conditions are met:\n\n * Redistributions of source code must retain this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below).\n\n * Redistributions in binary form must reproduce this COPYING\n CONDITIONS NOTICE, the COPYRIGHT NOTICE (below), the\n DISCLAIMER (below), the UNIVERSITY PATENT NOTICE (below), the\n PATENT MARKING NOTICE (below), and the PATENT RIGHTS\n GRANT (below) in the documentation and\/or other materials\n provided with the distribution.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\nCOPYRIGHT NOTICE:\n\n TokuDB, Tokutek Fractal Tree Indexing Library.\n Copyright (C) 2007-2013 Tokutek, Inc.\n\nDISCLAIMER:\n\n This program 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 General Public License for more details.\n\nUNIVERSITY PATENT NOTICE:\n\n The technology is licensed by the Massachusetts Institute of\n Technology, Rutgers State University of New Jersey, and the Research\n Foundation of State University of New York at Stony Brook under\n United States of America Serial No. 11\/760379 and to the patents\n and\/or patent applications resulting from it.\n\nPATENT MARKING NOTICE:\n\n This software is covered by US Patent No. 8,185,551.\n This software is covered by US Patent No. 8,489,638.\n\nPATENT RIGHTS GRANT:\n\n \"THIS IMPLEMENTATION\" means the copyrightable works distributed by\n Tokutek as part of the Fractal Tree project.\n\n \"PATENT CLAIMS\" means the claims of patents that are owned or\n licensable by Tokutek, both currently or in the future; and that in\n the absence of this license would be infringed by THIS\n IMPLEMENTATION or by using or running THIS IMPLEMENTATION.\n\n \"PATENT CHALLENGE\" shall mean a challenge to the validity,\n patentability, enforceability and\/or non-infringement of any of the\n PATENT CLAIMS or otherwise opposing any of the PATENT CLAIMS.\n\n Tokutek hereby grants to you, for the term and geographical scope of\n the PATENT CLAIMS, a non-exclusive, no-charge, royalty-free,\n irrevocable (except as stated in this section) patent license to\n make, have made, use, offer to sell, sell, import, transfer, and\n otherwise run, modify, and propagate the contents of THIS\n IMPLEMENTATION, where such license applies only to the PATENT\n CLAIMS. This grant does not include claims that would be infringed\n only as a consequence of further modifications of THIS\n IMPLEMENTATION. If you or your agent or licensee institute or order\n or agree to the institution of patent litigation against any entity\n (including a cross-claim or counterclaim in a lawsuit) alleging that\n THIS IMPLEMENTATION constitutes direct or contributory patent\n infringement, or inducement of patent infringement, then any rights\n granted to you under this License shall terminate as of the date\n such litigation is filed. If you or your agent or exclusive\n licensee institute or order or agree to the institution of a PATENT\n CHALLENGE, then Tokutek may terminate any rights granted to you\n under this License.\n*\/\n\n#ident \"Copyright (c) 2007-2013 Tokutek Inc. All rights reserved.\"\n#ident \"The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11\/760379 and to the patents and\/or patent applications resulting from it.\"\n\n\/\/ Create a lot of dirty nodes, kick off a checkpoint, and close the environment.\n\/\/ Measure the time it takes to close the environment since we are speeding up that\n\/\/ function.\n\n#include \"test.h\"\n#include \n#include \n\n#ifndef htobe64\n#define htobe64(x) __bswap_64(x)\n#endif\n\n\/\/ Insert max_rows key\/val pairs into the db\nstatic void do_inserts(DB_ENV *env, DB *db, uint64_t max_rows, size_t val_size) {\n char val_data[val_size]; memset(val_data, 0, val_size);\n int r;\n DB_TXN *txn = nullptr;\n r = env->txn_begin(env, nullptr, &txn, 0);\n CKERR(r);\n\n for (uint64_t i = 1; i <= max_rows; i++) {\n \/\/ pick a sequential key but it does not matter for this test.\n uint64_t k[2] = {\n htobe64(i), random64(),\n };\n DBT key = { .data = k, .size = sizeof k };\n DBT val = { .data = val_data, .size = (uint32_t) val_size };\n r = db->put(db, txn, &key, &val, 0);\n CKERR(r);\n\n if ((i % 1000) == 0) {\n if (verbose)\n fprintf(stderr, \"put %\" PRIu64 \"\\n\", i);\n r = txn->commit(txn, 0);\n CKERR(r);\n r = env->txn_begin(env, nullptr, &txn, 0);\n CKERR(r);\n }\n }\n\n r = txn->commit(txn, 0);\n CKERR(r);\n}\n\n\/\/ Create a cache with a lot of dirty nodes, kick off a checkpoint, and measure the time to\n\/\/ close the environment.\nstatic void big_shutdown(void) {\n int r;\n\n DB_ENV *env = nullptr;\n r = db_env_create(&env, 0);\n CKERR(r);\n r = env->set_cachesize(env, 8, 0, 1);\n CKERR(r);\n r = env->open(env, TOKU_TEST_FILENAME,\n DB_INIT_MPOOL|DB_CREATE|DB_THREAD |DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_TXN|DB_PRIVATE,\n S_IRWXU+S_IRWXG+S_IRWXO);\n CKERR(r);\n\n DB *db = nullptr;\n r = db_create(&db, env, 0);\n CKERR(r);\n r = db->open(db, nullptr, \"foo.db\", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO);\n CKERR(r);\n\n do_inserts(env, db, 1000000, 1024);\n\n \/\/ kick the checkpoint thread\n if (verbose)\n fprintf(stderr, \"env->checkpointing_set_period\\n\");\n r = env->checkpointing_set_period(env, 2);\n CKERR(r);\n sleep(3);\n\n if (verbose)\n fprintf(stderr, \"db->close\\n\");\n r = db->close(db, 0);\n CKERR(r);\n\n \/\/ measure the shutdown time\n uint64_t tstart = toku_current_time_microsec();\n if (verbose)\n fprintf(stderr, \"env->close\\n\");\n r = env->close(env, 0);\n CKERR(r);\n uint64_t tend = toku_current_time_microsec();\n if (verbose)\n fprintf(stderr, \"env->close complete %\" PRIu64 \" sec\\n\", (tend - tstart)\/1000000);\n}\n\nint test_main (int argc, char *const argv[]) {\n default_parse_args(argc, argv);\n\n \/\/ init the env directory\n toku_os_recursive_delete(TOKU_TEST_FILENAME);\n int r = toku_os_mkdir(TOKU_TEST_FILENAME, S_IRWXU+S_IRWXG+S_IRWXO);\n CKERR(r);\n\n \/\/ run the test\n big_shutdown();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nbool Text_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy Text_Proxy\n(\n new osgText::Text,\n \"Text\",\n \"Object Drawable Text\",\n Text_readLocalData,\n Text_writeLocalData\n);\n\nbool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n osgText::Text &text = static_cast(obj);\n bool itAdvanced = false;\n\n\n if (fr.matchSequence(\"font %w\"))\n { \n text.setFont(fr[1].getStr());\n fr += 2;\n itAdvanced = true;\n \n }\n\n if (fr[0].matchWord(\"fontResolution\") || fr[0].matchWord(\"fontSize\"))\n {\n unsigned int width;\n unsigned int height;\n if (fr[1].getUInt(width) && fr[2].getUInt(height))\n {\n text.setFontResolution(width,height);\n fr += 3;\n itAdvanced = true;\n }\n }\n\n if (fr[0].matchWord(\"characterSize\"))\n {\n float height;\n float aspectRatio;\n if (fr[1].getFloat(height) && fr[2].getFloat(aspectRatio))\n {\n text.setCharacterSize(height,aspectRatio);\n fr += 3;\n itAdvanced = true;\n }\n }\n\n if (fr.matchSequence(\"characterSizeMode %w\"))\n {\n std::string str = fr[1].getStr();\n if (str==\"OBJECT_COORDS\") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS);\n else if (str==\"SCREEN_COORDS\") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);\n else if (str==\"OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT\") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);\n }\n\n \/\/ maximum dimentsions of text box.\n if (fr[0].matchWord(\"maximumWidth\"))\n {\n float width;\n if (fr[1].getFloat(width))\n {\n text.setMaximumWidth(width);\n fr += 2;\n itAdvanced = true;\n }\n }\n\n if (fr[0].matchWord(\"maximumHeight\"))\n {\n float height;\n if (fr[1].getFloat(height))\n {\n text.setMaximumHeight(height);\n fr += 2;\n itAdvanced = true;\n }\n }\n\n if (fr.matchSequence(\"alignment %w\"))\n {\n std::string str = fr[1].getStr();\n if (str==\"LEFT_TOP\") text.setAlignment(osgText::Text::LEFT_TOP);\n else if (str==\"LEFT_CENTER\") text.setAlignment(osgText::Text::LEFT_CENTER);\n else if (str==\"LEFT_BOTTOM\") text.setAlignment(osgText::Text::LEFT_BOTTOM);\n else if (str==\"CENTER_TOP\") text.setAlignment(osgText::Text::CENTER_TOP);\n else if (str==\"CENTER_CENTER\") text.setAlignment(osgText::Text::CENTER_CENTER);\n else if (str==\"CENTER_BOTTOM\") text.setAlignment(osgText::Text::CENTER_BOTTOM);\n else if (str==\"RIGHT_TOP\") text.setAlignment(osgText::Text::RIGHT_TOP);\n else if (str==\"RIGHT_CENTER\") text.setAlignment(osgText::Text::RIGHT_CENTER);\n else if (str==\"RIGHT_BOTTOM\") text.setAlignment(osgText::Text::RIGHT_BOTTOM);\n else if (str==\"LEFT_BASE_LINE\") text.setAlignment(osgText::Text::LEFT_BASE_LINE);\n else if (str==\"CENTER_BASE_LINE\") text.setAlignment(osgText::Text::CENTER_BASE_LINE);\n else if (str==\"RIGHT_BASE_LINE\") text.setAlignment(osgText::Text::RIGHT_BASE_LINE);\n else if (str==\"BASE_LINE\") text.setAlignment(osgText::Text::BASE_LINE);\n fr += 2;\n itAdvanced = true;\n }\n \n if (fr.matchSequence(\"axisAlignment %w\"))\n {\n std::string str = fr[1].getStr();\n if (str==\"XY_PLANE\") text.setAxisAlignment(osgText::Text::XY_PLANE);\n else if (str==\"REVERSED_XY_PLANE\") text.setAxisAlignment(osgText::Text::REVERSED_XY_PLANE);\n else if (str==\"XZ_PLANE\") text.setAxisAlignment(osgText::Text::XZ_PLANE);\n else if (str==\"REVERSED_XZ_PLANE\") text.setAxisAlignment(osgText::Text::REVERSED_XZ_PLANE);\n else if (str==\"YZ_PLANE\") text.setAxisAlignment(osgText::Text::YZ_PLANE);\n else if (str==\"REVERSED_YZ_PLANE\") text.setAxisAlignment(osgText::Text::REVERSED_YZ_PLANE);\n else if (str==\"SCREEN\") text.setAxisAlignment(osgText::Text::SCREEN);\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"rotation\"))\n {\n osg::Vec4 rotation;\n if (fr[1].getFloat(rotation.x()) && fr[2].getFloat(rotation.y()) && fr[3].getFloat(rotation.z()) && fr[4].getFloat(rotation.w()))\n {\n text.setRotation(rotation);\n fr += 4;\n itAdvanced = true;\n }\n }\n\n if (fr.matchSequence(\"autoRotateToScreen TRUE\"))\n {\n text.setAutoRotateToScreen(true);\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"autoScaleToLimitScreenSizeToFontResolution TRUE\"))\n {\n text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"layout %w\") && fr[1].getStr())\n {\n std::string str = fr[1].getStr();\n if (str==\"LEFT_TO_RIGHT\") text.setLayout(osgText::Text::LEFT_TO_RIGHT);\n else if (str==\"RIGHT_TO_LEFT\") text.setLayout(osgText::Text::RIGHT_TO_LEFT);\n else if (str==\"VERTICAL\") text.setLayout(osgText::Text::VERTICAL);\n fr += 2;\n itAdvanced = true;\n }\n\n\n \/\/ position\n if (fr[0].matchWord(\"position\"))\n {\n osg::Vec3 p;\n if (fr[1].getFloat(p.x()) && fr[2].getFloat(p.y()) && fr[3].getFloat(p.z()))\n {\n text.setPosition(p);\n fr += 4;\n itAdvanced = true;\n }\n }\n\n \/\/ color\n if (fr[0].matchWord(\"color\"))\n {\n osg::Vec4 c;\n if (fr[1].getFloat(c.x()) && fr[2].getFloat(c.y()) && fr[3].getFloat(c.z()) && fr[4].getFloat(c.w()))\n {\n text.setColor(c);\n fr += 4;\n itAdvanced = true;\n }\n }\n\n \/\/ draw mode\n if (fr[0].matchWord(\"drawMode\"))\n {\n int i;\n if (fr[1].getInt(i)) {\n text.setDrawMode(i);\n fr += 2;\n itAdvanced = true;\n }\n }\n\n \/\/ text\n if (fr.matchSequence(\"text %s\") && fr[1].getStr()) {\n text.setText(std::string(fr[1].getStr()));\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"text %i {\"))\n {\n \/\/ pre 0.9.3 releases..\n int entry = fr[0].getNoNestedBrackets();\n\n int capacity;\n fr[1].getInt(capacity);\n\n osgText::String str;\n str.reserve(capacity);\n\n fr += 3;\n\n while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)\n {\n unsigned int c;\n if (fr[0].getUInt(c))\n {\n ++fr;\n str.push_back(c);\n }\n else\n {\n ++fr;\n }\n }\n\n text.setText(str);\n\n itAdvanced = true;\n ++fr;\n }\n\n return itAdvanced;\n}\n\nbool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n const osgText::Text &text = static_cast(obj);\n\n if (text.getFont())\n {\n fw.indent() << \"font \" << text.getFont()->getFileName() << std::endl;\n }\n\n \/\/ font resolution\n fw.indent() << \"fontResolution \" << text.getFontWidth() << \" \" << text.getFontHeight() << std::endl;\n\n \/\/ charater size.\n fw.indent() << \"characterSize \" << text.getCharacterHeight() << \" \" << text.getCharacterAspectRatio() << std::endl;\n\n fw.indent() << \"characterSizeMode \";\n switch(text.getCharacterSizeMode())\n {\n case osgText::Text::OBJECT_COORDS : fw<<\"OBJECT_COORDS\"<0.0f)\n {\n fw.indent() << \"maximumWidth \" << text.getMaximumWidth() << std::endl;\n }\n \n if (text.getMaximumHeight()>0.0f)\n {\n fw.indent() << \"maximumHeight \" << text.getMaximumHeight() << std::endl;\n }\n \n \/\/ alignment\n fw.indent() << \"alignment \";\n switch(text.getAlignment())\n {\n case osgText::Text::LEFT_TOP: fw << \"LEFT_TOP\" << std::endl; break;\n case osgText::Text::LEFT_CENTER : fw << \"LEFT_CENTER\" << std::endl; break;\n case osgText::Text::LEFT_BOTTOM : fw << \"LEFT_BOTTOM\" << std::endl; break;\n \n case osgText::Text::CENTER_TOP: fw << \"CENTER_TOP\" << std::endl; break;\n case osgText::Text::CENTER_CENTER: fw << \"CENTER_CENTER\" << std::endl; break;\n case osgText::Text::CENTER_BOTTOM: fw << \"CENTER_BOTTOM\" << std::endl; break;\n \n case osgText::Text::RIGHT_TOP: fw << \"RIGHT_TOP\" << std::endl; break;\n case osgText::Text::RIGHT_CENTER: fw << \"RIGHT_CENTER\" << std::endl; break;\n case osgText::Text::RIGHT_BOTTOM: fw << \"RIGHT_BOTTOM\" << std::endl; break;\n \n case osgText::Text::LEFT_BASE_LINE: fw << \"LEFT_BASE_LINE\" << std::endl; break;\n case osgText::Text::CENTER_BASE_LINE:fw << \"CENTER_BASE_LINE\" << std::endl; break;\n case osgText::Text::RIGHT_BASE_LINE: fw << \"RIGHT_BASE_LINE\" << std::endl; break;\n };\n\n\n if (!text.getRotation().zeroRotation())\n {\n fw.indent() << \"rotation \" << text.getRotation() << std::endl;\n }\n\n if (text.getAutoRotateToScreen())\n {\n fw.indent() << \"autoRotateToScreen TRUE\"<< std::endl;\n }\n\n\n \/\/ layout\n fw.indent() << \"layout \";\n switch(text.getLayout())\n {\n case osgText::Text::LEFT_TO_RIGHT: fw << \"LEFT_TO_RIGHT\" << std::endl; break;\n case osgText::Text::RIGHT_TO_LEFT: fw << \"RIGHT_TO_LEFT\" << std::endl; break;\n case osgText::Text::VERTICAL: fw << \"VERTICAL\" << std::endl; break;\n };\n\n\n \/\/ position\n osg::Vec3 p = text.getPosition();\n fw.indent() << \"position \" << p.x() << \" \" << p.y() << \" \" << p.z() << std::endl;\n\n \/\/ color\n osg::Vec4 c = text.getColor();\n fw.indent() << \"color \" << c.x() << \" \" << c.y() << \" \" << c.z() << \" \" << c.w() << std::endl;\n\n \/\/ draw mode\n fw.indent() << \"drawMode \" << text.getDrawMode() << std::endl;\n\n\n \/\/ text\n const osgText::String& textstring = text.getText();\n bool isACString = true;\n osgText::String::const_iterator itr;\n for(itr=textstring.begin();\n itr!=textstring.end() && isACString;\n ++itr)\n {\n if (*itr==0 || *itr>256) isACString=false;\n }\n if (isACString)\n {\n std::string str;\n\n for(itr=textstring.begin();\n itr!=textstring.end();\n ++itr)\n {\n str += (char)(*itr);\n }\n\n \/\/std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));\n \n fw.indent() << \"text \" << fw.wrapString(str) << std::endl;\n }\n else\n {\n \/\/ do it the hardway...output each character as an int\n fw.indent() << \"text \"<Added .osg suppot for new alignment modes#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nbool Text_readLocalData(osg::Object &obj, osgDB::Input &fr);\nbool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw);\n\nosgDB::RegisterDotOsgWrapperProxy Text_Proxy\n(\n new osgText::Text,\n \"Text\",\n \"Object Drawable Text\",\n Text_readLocalData,\n Text_writeLocalData\n);\n\nbool Text_readLocalData(osg::Object &obj, osgDB::Input &fr)\n{\n osgText::Text &text = static_cast(obj);\n bool itAdvanced = false;\n\n\n if (fr.matchSequence(\"font %w\"))\n { \n text.setFont(fr[1].getStr());\n fr += 2;\n itAdvanced = true;\n \n }\n\n if (fr[0].matchWord(\"fontResolution\") || fr[0].matchWord(\"fontSize\"))\n {\n unsigned int width;\n unsigned int height;\n if (fr[1].getUInt(width) && fr[2].getUInt(height))\n {\n text.setFontResolution(width,height);\n fr += 3;\n itAdvanced = true;\n }\n }\n\n if (fr[0].matchWord(\"characterSize\"))\n {\n float height;\n float aspectRatio;\n if (fr[1].getFloat(height) && fr[2].getFloat(aspectRatio))\n {\n text.setCharacterSize(height,aspectRatio);\n fr += 3;\n itAdvanced = true;\n }\n }\n\n if (fr.matchSequence(\"characterSizeMode %w\"))\n {\n std::string str = fr[1].getStr();\n if (str==\"OBJECT_COORDS\") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS);\n else if (str==\"SCREEN_COORDS\") text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);\n else if (str==\"OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT\") text.setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);\n }\n\n \/\/ maximum dimentsions of text box.\n if (fr[0].matchWord(\"maximumWidth\"))\n {\n float width;\n if (fr[1].getFloat(width))\n {\n text.setMaximumWidth(width);\n fr += 2;\n itAdvanced = true;\n }\n }\n\n if (fr[0].matchWord(\"maximumHeight\"))\n {\n float height;\n if (fr[1].getFloat(height))\n {\n text.setMaximumHeight(height);\n fr += 2;\n itAdvanced = true;\n }\n }\n\n if (fr.matchSequence(\"alignment %w\"))\n {\n std::string str = fr[1].getStr();\n if (str==\"LEFT_TOP\") text.setAlignment(osgText::Text::LEFT_TOP);\n else if (str==\"LEFT_CENTER\") text.setAlignment(osgText::Text::LEFT_CENTER);\n else if (str==\"LEFT_BOTTOM\") text.setAlignment(osgText::Text::LEFT_BOTTOM);\n else if (str==\"CENTER_TOP\") text.setAlignment(osgText::Text::CENTER_TOP);\n else if (str==\"CENTER_CENTER\") text.setAlignment(osgText::Text::CENTER_CENTER);\n else if (str==\"CENTER_BOTTOM\") text.setAlignment(osgText::Text::CENTER_BOTTOM);\n else if (str==\"RIGHT_TOP\") text.setAlignment(osgText::Text::RIGHT_TOP);\n else if (str==\"RIGHT_CENTER\") text.setAlignment(osgText::Text::RIGHT_CENTER);\n else if (str==\"RIGHT_BOTTOM\") text.setAlignment(osgText::Text::RIGHT_BOTTOM);\n else if (str==\"LEFT_BASE_LINE\") text.setAlignment(osgText::Text::LEFT_BASE_LINE);\n else if (str==\"CENTER_BASE_LINE\") text.setAlignment(osgText::Text::CENTER_BASE_LINE);\n else if (str==\"RIGHT_BASE_LINE\") text.setAlignment(osgText::Text::RIGHT_BASE_LINE);\n else if (str==\"LEFT_BOTTOM_BASE_LINE\") text.setAlignment(osgText::Text::LEFT_BOTTOM_BASE_LINE);\n else if (str==\"CENTER_BOTTOM_BASE_LINE\") text.setAlignment(osgText::Text::CENTER_BOTTOM_BASE_LINE);\n else if (str==\"RIGHT_BOTTOM_BASE_LINE\") text.setAlignment(osgText::Text::RIGHT_BOTTOM_BASE_LINE);\n else if (str==\"BASE_LINE\") text.setAlignment(osgText::Text::BASE_LINE);\n fr += 2;\n itAdvanced = true;\n }\n \n if (fr.matchSequence(\"axisAlignment %w\"))\n {\n std::string str = fr[1].getStr();\n if (str==\"XY_PLANE\") text.setAxisAlignment(osgText::Text::XY_PLANE);\n else if (str==\"REVERSED_XY_PLANE\") text.setAxisAlignment(osgText::Text::REVERSED_XY_PLANE);\n else if (str==\"XZ_PLANE\") text.setAxisAlignment(osgText::Text::XZ_PLANE);\n else if (str==\"REVERSED_XZ_PLANE\") text.setAxisAlignment(osgText::Text::REVERSED_XZ_PLANE);\n else if (str==\"YZ_PLANE\") text.setAxisAlignment(osgText::Text::YZ_PLANE);\n else if (str==\"REVERSED_YZ_PLANE\") text.setAxisAlignment(osgText::Text::REVERSED_YZ_PLANE);\n else if (str==\"SCREEN\") text.setAxisAlignment(osgText::Text::SCREEN);\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"rotation\"))\n {\n osg::Vec4 rotation;\n if (fr[1].getFloat(rotation.x()) && fr[2].getFloat(rotation.y()) && fr[3].getFloat(rotation.z()) && fr[4].getFloat(rotation.w()))\n {\n text.setRotation(rotation);\n fr += 4;\n itAdvanced = true;\n }\n }\n\n if (fr.matchSequence(\"autoRotateToScreen TRUE\"))\n {\n text.setAutoRotateToScreen(true);\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"autoScaleToLimitScreenSizeToFontResolution TRUE\"))\n {\n text.setCharacterSizeMode(osgText::Text::SCREEN_COORDS);\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"layout %w\") && fr[1].getStr())\n {\n std::string str = fr[1].getStr();\n if (str==\"LEFT_TO_RIGHT\") text.setLayout(osgText::Text::LEFT_TO_RIGHT);\n else if (str==\"RIGHT_TO_LEFT\") text.setLayout(osgText::Text::RIGHT_TO_LEFT);\n else if (str==\"VERTICAL\") text.setLayout(osgText::Text::VERTICAL);\n fr += 2;\n itAdvanced = true;\n }\n\n\n \/\/ position\n if (fr[0].matchWord(\"position\"))\n {\n osg::Vec3 p;\n if (fr[1].getFloat(p.x()) && fr[2].getFloat(p.y()) && fr[3].getFloat(p.z()))\n {\n text.setPosition(p);\n fr += 4;\n itAdvanced = true;\n }\n }\n\n \/\/ color\n if (fr[0].matchWord(\"color\"))\n {\n osg::Vec4 c;\n if (fr[1].getFloat(c.x()) && fr[2].getFloat(c.y()) && fr[3].getFloat(c.z()) && fr[4].getFloat(c.w()))\n {\n text.setColor(c);\n fr += 4;\n itAdvanced = true;\n }\n }\n\n \/\/ draw mode\n if (fr[0].matchWord(\"drawMode\"))\n {\n int i;\n if (fr[1].getInt(i)) {\n text.setDrawMode(i);\n fr += 2;\n itAdvanced = true;\n }\n }\n\n \/\/ text\n if (fr.matchSequence(\"text %s\") && fr[1].getStr()) {\n text.setText(std::string(fr[1].getStr()));\n fr += 2;\n itAdvanced = true;\n }\n\n if (fr.matchSequence(\"text %i {\"))\n {\n \/\/ pre 0.9.3 releases..\n int entry = fr[0].getNoNestedBrackets();\n\n int capacity;\n fr[1].getInt(capacity);\n\n osgText::String str;\n str.reserve(capacity);\n\n fr += 3;\n\n while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)\n {\n unsigned int c;\n if (fr[0].getUInt(c))\n {\n ++fr;\n str.push_back(c);\n }\n else\n {\n ++fr;\n }\n }\n\n text.setText(str);\n\n itAdvanced = true;\n ++fr;\n }\n\n return itAdvanced;\n}\n\nbool Text_writeLocalData(const osg::Object &obj, osgDB::Output &fw)\n{\n const osgText::Text &text = static_cast(obj);\n\n if (text.getFont())\n {\n fw.indent() << \"font \" << text.getFont()->getFileName() << std::endl;\n }\n\n \/\/ font resolution\n fw.indent() << \"fontResolution \" << text.getFontWidth() << \" \" << text.getFontHeight() << std::endl;\n\n \/\/ charater size.\n fw.indent() << \"characterSize \" << text.getCharacterHeight() << \" \" << text.getCharacterAspectRatio() << std::endl;\n\n fw.indent() << \"characterSizeMode \";\n switch(text.getCharacterSizeMode())\n {\n case osgText::Text::OBJECT_COORDS : fw<<\"OBJECT_COORDS\"<0.0f)\n {\n fw.indent() << \"maximumWidth \" << text.getMaximumWidth() << std::endl;\n }\n \n if (text.getMaximumHeight()>0.0f)\n {\n fw.indent() << \"maximumHeight \" << text.getMaximumHeight() << std::endl;\n }\n \n \/\/ alignment\n fw.indent() << \"alignment \";\n switch(text.getAlignment())\n {\n case osgText::Text::LEFT_TOP: fw << \"LEFT_TOP\" << std::endl; break;\n case osgText::Text::LEFT_CENTER : fw << \"LEFT_CENTER\" << std::endl; break;\n case osgText::Text::LEFT_BOTTOM : fw << \"LEFT_BOTTOM\" << std::endl; break;\n \n case osgText::Text::CENTER_TOP: fw << \"CENTER_TOP\" << std::endl; break;\n case osgText::Text::CENTER_CENTER: fw << \"CENTER_CENTER\" << std::endl; break;\n case osgText::Text::CENTER_BOTTOM: fw << \"CENTER_BOTTOM\" << std::endl; break;\n \n case osgText::Text::RIGHT_TOP: fw << \"RIGHT_TOP\" << std::endl; break;\n case osgText::Text::RIGHT_CENTER: fw << \"RIGHT_CENTER\" << std::endl; break;\n case osgText::Text::RIGHT_BOTTOM: fw << \"RIGHT_BOTTOM\" << std::endl; break;\n \n case osgText::Text::LEFT_BASE_LINE: fw << \"LEFT_BASE_LINE\" << std::endl; break;\n case osgText::Text::CENTER_BASE_LINE:fw << \"CENTER_BASE_LINE\" << std::endl; break;\n case osgText::Text::RIGHT_BASE_LINE: fw << \"RIGHT_BASE_LINE\" << std::endl; break;\n \n case osgText::Text::LEFT_BOTTOM_BASE_LINE: fw << \"LEFT_BOTTOM_BASE_LINE\" << std::endl; break;\n case osgText::Text::CENTER_BOTTOM_BASE_LINE:fw << \"CENTER_BOTTOM_BASE_LINE\" << std::endl; break;\n case osgText::Text::RIGHT_BOTTOM_BASE_LINE: fw << \"RIGHT_BOTTOM_BASE_LINE\" << std::endl; break;\n };\n\n\n if (!text.getRotation().zeroRotation())\n {\n fw.indent() << \"rotation \" << text.getRotation() << std::endl;\n }\n\n if (text.getAutoRotateToScreen())\n {\n fw.indent() << \"autoRotateToScreen TRUE\"<< std::endl;\n }\n\n\n \/\/ layout\n fw.indent() << \"layout \";\n switch(text.getLayout())\n {\n case osgText::Text::LEFT_TO_RIGHT: fw << \"LEFT_TO_RIGHT\" << std::endl; break;\n case osgText::Text::RIGHT_TO_LEFT: fw << \"RIGHT_TO_LEFT\" << std::endl; break;\n case osgText::Text::VERTICAL: fw << \"VERTICAL\" << std::endl; break;\n };\n\n\n \/\/ position\n osg::Vec3 p = text.getPosition();\n fw.indent() << \"position \" << p.x() << \" \" << p.y() << \" \" << p.z() << std::endl;\n\n \/\/ color\n osg::Vec4 c = text.getColor();\n fw.indent() << \"color \" << c.x() << \" \" << c.y() << \" \" << c.z() << \" \" << c.w() << std::endl;\n\n \/\/ draw mode\n fw.indent() << \"drawMode \" << text.getDrawMode() << std::endl;\n\n\n \/\/ text\n const osgText::String& textstring = text.getText();\n bool isACString = true;\n osgText::String::const_iterator itr;\n for(itr=textstring.begin();\n itr!=textstring.end() && isACString;\n ++itr)\n {\n if (*itr==0 || *itr>256) isACString=false;\n }\n if (isACString)\n {\n std::string str;\n\n for(itr=textstring.begin();\n itr!=textstring.end();\n ++itr)\n {\n str += (char)(*itr);\n }\n\n \/\/std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));\n \n fw.indent() << \"text \" << fw.wrapString(str) << std::endl;\n }\n else\n {\n \/\/ do it the hardway...output each character as an int\n fw.indent() << \"text \"<"} {"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\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace Producer;\nusing namespace osgProducer;\n\n\nclass RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback\n{\npublic:\n\n RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):\n _cameraGroup(cameraGroup),\n _sceneHandler(sceneHandler) {}\n \n virtual void operator()( const Producer::RenderSurface & rs)\n {\n \n osg::Timer timer;\n osg::Timer_t start_t = timer.tick();\n \n if (_cameraGroup->getRealizeCallback())\n {\n (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);\n }\n else if (_sceneHandler) _sceneHandler->init();\n\n osg::Timer_t end_t = timer.tick();\n double time = timer.delta_m(start_t,end_t);\n osg::notify(osg::INFO) << \"Time to init = \"<addCommandLineOption(\"-c \",\"Specify camera config file\");\n }\n\n std::string filename;\n if (arguments.read(\"-c\",filename)) return findCameraConfigFile(filename);\n\n char *ptr;\n if( (ptr = getenv( \"PRODUCER_CAMERA_CONFIG_FILE\" )) )\n {\n osg::notify(osg::DEBUG_INFO) << \"PRODUCER_CAMERA_CONFIG_FILE(\"<setMaxNumberOfGraphicsContexts( getNumberOfCameras() );\n\n}\n\nvoid OsgCameraGroup::setSceneData( osg::Node *scene ) \n{ \n if (_scene_data==scene) return;\n\n if (_scene_decorator.valid() && _scene_data.valid())\n {\n _scene_decorator->removeChild(_scene_data.get());\n }\n \n _scene_data = scene; \n \n if (_scene_decorator.valid() && _scene_data.valid())\n {\n _scene_decorator->addChild(scene);\n }\n \n setUpSceneViewsWithData();\n}\n \nvoid OsgCameraGroup::setSceneDecorator( osg::Group* decorator)\n{\n if (_scene_decorator==decorator) return;\n\n _scene_decorator = decorator;\n\n if (_scene_data.valid() && decorator) \n {\n decorator->addChild(_scene_data.get());\n }\n setUpSceneViewsWithData();\n}\n\n \nvoid OsgCameraGroup::setUpSceneViewsWithData()\n{\n for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )\n {\n if (_scene_decorator.valid())\n {\n (*p)->setSceneData( _scene_decorator.get() );\n }\n else if (_scene_data.valid())\n {\n (*p)->setSceneData( _scene_data.get() );\n }\n else\n {\n (*p)->setSceneData( 0 );\n }\n \n (*p)->setFrameStamp( _frameStamp.get() );\n (*p)->setGlobalStateSet( _global_stateset.get() );\n (*p)->setBackgroundColor( _background_color );\n (*p)->setLODScale( _LODScale );\n (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );\n (*p)->getState()->reset();\n }\n}\n\n\nvoid OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )\n{\n _frameStamp = fs;\n setUpSceneViewsWithData();\n}\n\n\nvoid OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset ) \n{ \n _global_stateset = sset; \n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) \n{\n _background_color = backgroundColor;\n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::setLODScale( float scale )\n{\n \/\/ need to set a local variable?\n _LODScale = scale;\n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)\n{\n \/\/ need to set a local variable?\n _fusionDistanceMode = mode;\n _fusionDistanceValue = value;\n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::advance()\n{\n if( !_initialized ) return;\n CameraGroup::advance(); \n}\n\nbool OsgCameraGroup::realize( ThreadingModel thread_model )\n{\n if( _realized ) return _realized;\n _thread_model = thread_model;\n return realize();\n}\n\n\n\/\/ small visitor to check for the existance of particle systems,\n\/\/ which currently arn't thread safe, so we would need to disable\n\/\/ multithreading of cull and draw.\nclass SearchForParticleNodes : public osg::NodeVisitor\n{\npublic:\n SearchForParticleNodes():\n osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),\n _foundParticles(false) \n {\n }\n \n virtual void apply(osg::Node& node)\n {\n if (strcmp(node.libraryName(),\"osgParticle\")==0) _foundParticles = true;\n if (!_foundParticles) traverse(node);\n }\n \n \n bool _foundParticles;\n};\n\nbool OsgCameraGroup::realize()\n{\n if( _initialized ) return _realized;\n\n if (!_ds) _ds = osg::DisplaySettings::instance();\n\n _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );\n \n _shvec.clear();\n \n osg::Node* node = getTopMostSceneData();\n if (node)\n {\n \/\/ traverse the scene graphs gathering the requirements of the OpenGL buffers.\n osgUtil::DisplayRequirementsVisitor drv;\n drv.setDisplaySettings(_ds.get());\n node->accept(drv);\n }\n \n unsigned int numMultiSamples = 0;\n\n #ifdef __sgi\n \/\/ switch on anti-aliasing by default, just in case we have an Onyx :-)\n numMultiSamples = 4;\n #endif\n\n \/\/ set up each render stage to clear the appropriate buffers.\n GLbitfield clear_mask=0;\n if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;\n if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;\n if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;\n\n for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )\n {\n Producer::Camera *cam = _cfg->getCamera(i);\n \n \/\/ create the scene handler.\n osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());\n sh->setDefaults();\n sh->getState()->setContextID(i);\n\n _shvec.push_back( sh );\n cam->setSceneHandler( sh );\n \n \/\/ set up the clear mask.\n osgUtil::RenderStage *stage = sh->getRenderStage();\n if (stage) stage->setClearMask(clear_mask);\n\n \/\/ set the realize callback.\n Producer::RenderSurface* rs = cam->getRenderSurface();\n rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));\n \n \/\/ set up the visual chooser.\n if (_ds.valid() || numMultiSamples!=0)\n {\n \n Producer::VisualChooser* rs_vc = rs->getVisualChooser();\n if (!rs_vc)\n {\n rs_vc = new Producer::VisualChooser;\n rs_vc->setSimpleConfiguration();\n rs->setVisualChooser(rs_vc);\n }\n if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();\n if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());\n if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());\n\n rs_vc->setDepthSize(24);\n\n if (numMultiSamples)\n {\n #if defined( GLX_SAMPLES_SGIS )\n rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);\n #endif\n #if defined( GLX_SAMPLES_BUFFER_SGIS )\n rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);\n #endif\n }\n } \n }\n\n if( _global_stateset == NULL && _shvec.size() > 0 )\n {\n SceneHandlerList::iterator p = _shvec.begin();\n _global_stateset = (*p)->getGlobalStateSet();\n }\n\n setUpSceneViewsWithData();\n \n if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)\n {\n SearchForParticleNodes sfpn;\n getTopMostSceneData()->accept(sfpn);\n if (sfpn._foundParticles)\n {\n osg::notify(osg::INFO)<<\"Warning: disabling multi-threading of cull and draw\"<getNumberOfCameras()>=1)\n {\n Producer::Camera *cam = _cfg->getCamera(0);\n matrix.set(cam->getViewMatrix());\n }\n return matrix;\n}\n\nvoid OsgCameraGroup::frame()\n{\n osg::Node* node = getTopMostSceneData();\n if (node) node->getBound();\n\n CameraGroup::frame();\n _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );\n}\n\nAdded a setting of OsgCameraGroup::_applicateUsage to ApplicationUsage::instance() by default.\/* -*-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\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace Producer;\nusing namespace osgProducer;\n\n\nclass RenderSurfaceRealizeCallback : public Producer::RenderSurface::Callback\n{\npublic:\n\n RenderSurfaceRealizeCallback(OsgCameraGroup* cameraGroup,OsgSceneHandler* sceneHandler):\n _cameraGroup(cameraGroup),\n _sceneHandler(sceneHandler) {}\n \n virtual void operator()( const Producer::RenderSurface & rs)\n {\n \n osg::Timer timer;\n osg::Timer_t start_t = timer.tick();\n \n if (_cameraGroup->getRealizeCallback())\n {\n (*(_cameraGroup->getRealizeCallback()))(*_cameraGroup,*_sceneHandler,rs);\n }\n else if (_sceneHandler) _sceneHandler->init();\n\n osg::Timer_t end_t = timer.tick();\n double time = timer.delta_m(start_t,end_t);\n osg::notify(osg::INFO) << \"Time to init = \"<addCommandLineOption(\"-c \",\"Specify camera config file\");\n }\n\n std::string filename;\n if (arguments.read(\"-c\",filename)) return findCameraConfigFile(filename);\n\n char *ptr;\n if( (ptr = getenv( \"PRODUCER_CAMERA_CONFIG_FILE\" )) )\n {\n osg::notify(osg::DEBUG_INFO) << \"PRODUCER_CAMERA_CONFIG_FILE(\"<setMaxNumberOfGraphicsContexts( getNumberOfCameras() );\n \n _applicationUsage = osg::ApplicationUsage::instance();\n}\n\nvoid OsgCameraGroup::setSceneData( osg::Node *scene ) \n{ \n if (_scene_data==scene) return;\n\n if (_scene_decorator.valid() && _scene_data.valid())\n {\n _scene_decorator->removeChild(_scene_data.get());\n }\n \n _scene_data = scene; \n \n if (_scene_decorator.valid() && _scene_data.valid())\n {\n _scene_decorator->addChild(scene);\n }\n \n setUpSceneViewsWithData();\n}\n \nvoid OsgCameraGroup::setSceneDecorator( osg::Group* decorator)\n{\n if (_scene_decorator==decorator) return;\n\n _scene_decorator = decorator;\n\n if (_scene_data.valid() && decorator) \n {\n decorator->addChild(_scene_data.get());\n }\n setUpSceneViewsWithData();\n}\n\n \nvoid OsgCameraGroup::setUpSceneViewsWithData()\n{\n for(SceneHandlerList::iterator p = _shvec.begin(); p != _shvec.end(); p++ )\n {\n if (_scene_decorator.valid())\n {\n (*p)->setSceneData( _scene_decorator.get() );\n }\n else if (_scene_data.valid())\n {\n (*p)->setSceneData( _scene_data.get() );\n }\n else\n {\n (*p)->setSceneData( 0 );\n }\n \n (*p)->setFrameStamp( _frameStamp.get() );\n (*p)->setGlobalStateSet( _global_stateset.get() );\n (*p)->setBackgroundColor( _background_color );\n (*p)->setLODScale( _LODScale );\n (*p)->setFusionDistance( _fusionDistanceMode, _fusionDistanceValue );\n (*p)->getState()->reset();\n }\n}\n\n\nvoid OsgCameraGroup::setFrameStamp( osg::FrameStamp* fs )\n{\n _frameStamp = fs;\n setUpSceneViewsWithData();\n}\n\n\nvoid OsgCameraGroup::setGlobalStateSet( osg::StateSet *sset ) \n{ \n _global_stateset = sset; \n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::setBackgroundColor( const osg::Vec4& backgroundColor ) \n{\n _background_color = backgroundColor;\n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::setLODScale( float scale )\n{\n \/\/ need to set a local variable?\n _LODScale = scale;\n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::setFusionDistance( osgUtil::SceneView::FusionDistanceMode mode,float value)\n{\n \/\/ need to set a local variable?\n _fusionDistanceMode = mode;\n _fusionDistanceValue = value;\n setUpSceneViewsWithData();\n}\n\nvoid OsgCameraGroup::advance()\n{\n if( !_initialized ) return;\n CameraGroup::advance(); \n}\n\nbool OsgCameraGroup::realize( ThreadingModel thread_model )\n{\n if( _realized ) return _realized;\n _thread_model = thread_model;\n return realize();\n}\n\n\n\/\/ small visitor to check for the existance of particle systems,\n\/\/ which currently arn't thread safe, so we would need to disable\n\/\/ multithreading of cull and draw.\nclass SearchForParticleNodes : public osg::NodeVisitor\n{\npublic:\n SearchForParticleNodes():\n osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),\n _foundParticles(false) \n {\n }\n \n virtual void apply(osg::Node& node)\n {\n if (strcmp(node.libraryName(),\"osgParticle\")==0) _foundParticles = true;\n if (!_foundParticles) traverse(node);\n }\n \n \n bool _foundParticles;\n};\n\nbool OsgCameraGroup::realize()\n{\n if( _initialized ) return _realized;\n\n if (!_ds) _ds = osg::DisplaySettings::instance();\n\n _ds->setMaxNumberOfGraphicsContexts( _cfg->getNumberOfCameras() );\n \n _shvec.clear();\n \n osg::Node* node = getTopMostSceneData();\n if (node)\n {\n \/\/ traverse the scene graphs gathering the requirements of the OpenGL buffers.\n osgUtil::DisplayRequirementsVisitor drv;\n drv.setDisplaySettings(_ds.get());\n node->accept(drv);\n }\n \n unsigned int numMultiSamples = 0;\n\n #ifdef __sgi\n \/\/ switch on anti-aliasing by default, just in case we have an Onyx :-)\n numMultiSamples = 4;\n #endif\n\n \/\/ set up each render stage to clear the appropriate buffers.\n GLbitfield clear_mask=0;\n if (_ds->getRGB()) clear_mask |= GL_COLOR_BUFFER_BIT;\n if (_ds->getDepthBuffer()) clear_mask |= GL_DEPTH_BUFFER_BIT;\n if (_ds->getStencilBuffer()) clear_mask |= GL_STENCIL_BUFFER_BIT;\n\n for( unsigned int i = 0; i < _cfg->getNumberOfCameras(); i++ )\n {\n Producer::Camera *cam = _cfg->getCamera(i);\n \n \/\/ create the scene handler.\n osgProducer::OsgSceneHandler *sh = new osgProducer::OsgSceneHandler(_ds.get());\n sh->setDefaults();\n sh->getState()->setContextID(i);\n\n _shvec.push_back( sh );\n cam->setSceneHandler( sh );\n \n \/\/ set up the clear mask.\n osgUtil::RenderStage *stage = sh->getRenderStage();\n if (stage) stage->setClearMask(clear_mask);\n\n \/\/ set the realize callback.\n Producer::RenderSurface* rs = cam->getRenderSurface();\n rs->setRealizeCallback( new RenderSurfaceRealizeCallback(this, sh));\n \n \/\/ set up the visual chooser.\n if (_ds.valid() || numMultiSamples!=0)\n {\n \n Producer::VisualChooser* rs_vc = rs->getVisualChooser();\n if (!rs_vc)\n {\n rs_vc = new Producer::VisualChooser;\n rs_vc->setSimpleConfiguration();\n rs->setVisualChooser(rs_vc);\n }\n if (_ds->getStereo() && _ds->getStereoMode()==osg::DisplaySettings::QUAD_BUFFER) rs_vc->useStereo();\n if (_ds->getStencilBuffer()) rs_vc->setStencilSize(_ds->getMinimumNumStencilBits());\n if (_ds->getAlphaBuffer()) rs_vc->setAlphaSize(_ds->getMinimumNumAlphaBits());\n\n rs_vc->setDepthSize(24);\n\n if (numMultiSamples)\n {\n #if defined( GLX_SAMPLES_SGIS )\n rs_vc->addExtendedAttribute( GLX_SAMPLES_SGIS, numMultiSamples);\n #endif\n #if defined( GLX_SAMPLES_BUFFER_SGIS )\n rs_vc->addExtendedAttribute( GLX_SAMPLES_BUFFER_SGIS, 1);\n #endif\n }\n } \n }\n\n if( _global_stateset == NULL && _shvec.size() > 0 )\n {\n SceneHandlerList::iterator p = _shvec.begin();\n _global_stateset = (*p)->getGlobalStateSet();\n }\n\n setUpSceneViewsWithData();\n \n if (getTopMostSceneData() && _thread_model!=Producer::CameraGroup::SingleThreaded)\n {\n SearchForParticleNodes sfpn;\n getTopMostSceneData()->accept(sfpn);\n if (sfpn._foundParticles)\n {\n osg::notify(osg::INFO)<<\"Warning: disabling multi-threading of cull and draw\"<getNumberOfCameras()>=1)\n {\n Producer::Camera *cam = _cfg->getCamera(0);\n matrix.set(cam->getViewMatrix());\n }\n return matrix;\n}\n\nvoid OsgCameraGroup::frame()\n{\n osg::Node* node = getTopMostSceneData();\n if (node) node->getBound();\n\n CameraGroup::frame();\n _frameStamp->setFrameNumber( _frameStamp->getFrameNumber() + 1 );\n}\n\n<|endoftext|>"} {"text":"\n#include \"ui_sc_editor.h\"\n\n#include \n\nnamespace ImGui\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid FillRect(ImVec2 pos, ImVec2 size, unsigned int color)\n{\n\tImGuiWindow* window = GetCurrentWindow();\n\tImVec2 currentPos = window->Pos + pos;\n window->DrawList->AddRectFilled(currentPos, currentPos + size, color, 0.0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfloat GetTextWidth(const char* textStart, const char* textEnd)\n{\n\tImVec2 size = CalcTextSize(textStart, textEnd);\n\treturn size.x; \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nImVec2 GetRelativeMousePos()\n{\n const ImGuiState* g = GImGui;\n ImGuiWindow* window = GetCurrentWindow();\n ImVec2 pos = g->IO.MousePos - window->Pos;\n ImVec2 zero = ImVec2(0.0f, 0.0f);\n return ImClamp(pos, zero, window->Size);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool IsFocusWindowKeyDown(int key, bool repeat)\n{\n\tif (!GetWindowIsFocused())\n\t\treturn false;\n\n \/\/ImGuiState& g = GImGui;\n \/\/ImGuiWindow* window = GetCurrentWindow();\n\n \/\/ Only send keyboard events to selected window\n\n \/\/if (g.FocusedWindow != window)\n \/\/ return false;\n\n return IsKeyPressed(key, repeat);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid GetWindowRect(ImGuiWindow* window, ImVec2* pos, ImVec2* size)\n{\n *pos = window->Pos;\n *size = window->Size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SetWindowRect(ImGuiWindow* window, const ImVec2 pos, const ImVec2 size)\n{\n window->PosFloat = pos;\n window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);\n window->Size = size;\n window->SizeFull = size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool IsActiveWindow(ImGuiWindow* window)\n{\n const ImGuiState* g = GImGui;\n return g->FocusedWindow == window;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nImScEditor* ScInputText(const char* label, float xSize, float ySize, void (*callback)(void*), void* userData)\n{\n ImGuiWindow* window = GetCurrentWindow();\n const ImGuiID id = window->GetID(label);\n\n (void)callback;\n (void)userData;\n\n ImGui::BeginChild(\"Log\");\n\n\tImGuiStorage* storage = GetStateStorage();\n\tScEditor* editor = (ScEditor*)storage->GetVoidPtr(id);\n\n\tif (!editor)\n\t{\n\t\t(void)xSize;\n\t\t(void)ySize;\n\t\teditor = ScEditor_create((int)xSize, (int)ySize);\n\t\tstorage->SetVoidPtr(id, (void*)editor);\n\t}\n\n\tImScEditor* editorInterface = ScEditor_getInterface(editor);\n\n\t\/\/float textSize = ImGui::GetTextLineHeightWithSpacing() - 1;\n\t\/\/ TODO: Remove hardcoded value, ask scintilla\n\tfloat textSize = 26;\n\n\tScEditor_resize(editor, 0, 0, (int)window->Size.x - 20, (int)window->Size.y); \n\n\tint lineCount = (int)editorInterface->SendCommand(SCI_GETLINECOUNT, 0, 0);\n\n\teditorInterface->HandleInput();\n\n\tImGuiListClipper clipper(lineCount, textSize);\n\n\t\/\/ImVec2 pos = window->DC.CursorPos;\n\n ScEditor_setDrawList(GetWindowDrawList());\n ScEditor_setFont(GetWindowFont());\n\tScEditor_setPos(0.0f, 0.0f);\n\n\t\/\/int currentPos = (int)editorInterface->SendCommand(SCN_GETTOPLINE, 0, 0);\n\n\t\/\/float scrollPos = ImGui::GetScrollPosY();\n\t\n\t\/\/int iPos = (int)(((int)ImGui::GetScrollPosY()) \/ (int)(textSize)); \n\n\t\/\/if (currentPos != iPos)\n\t\/\/{\n\teditorInterface->ScrollTo(clipper.DisplayStart);\n\t\/\/}\n\n\t\/\/printf(\"current pos in scintilla %d - pos sent %d\\n\", newPos, iPos);\n\n\tclipper.End();\n\n ImGui::EndChild();\n\t\n\treturn editorInterface;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n}\n\nRemoved usage of GetWindowIsFocused (deprecated)\n#include \"ui_sc_editor.h\"\n\n#include \n\nnamespace ImGui\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid FillRect(ImVec2 pos, ImVec2 size, unsigned int color)\n{\n\tImGuiWindow* window = GetCurrentWindow();\n\tImVec2 currentPos = window->Pos + pos;\n window->DrawList->AddRectFilled(currentPos, currentPos + size, color, 0.0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfloat GetTextWidth(const char* textStart, const char* textEnd)\n{\n\tImVec2 size = CalcTextSize(textStart, textEnd);\n\treturn size.x; \n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nImVec2 GetRelativeMousePos()\n{\n const ImGuiState* g = GImGui;\n ImGuiWindow* window = GetCurrentWindow();\n ImVec2 pos = g->IO.MousePos - window->Pos;\n ImVec2 zero = ImVec2(0.0f, 0.0f);\n return ImClamp(pos, zero, window->Size);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool IsFocusWindowKeyDown(int key, bool repeat)\n{\n\tif (!IsWindowFocused())\n\t\treturn false;\n\n\t\/\/if (!GetWindowIsFocused())\n\t\/\/\treturn false;\n\n \/\/ImGuiState& g = GImGui;\n \/\/ImGuiWindow* window = GetCurrentWindow();\n\n \/\/ Only send keyboard events to selected window\n\n \/\/if (g.FocusedWindow != window)\n \/\/ return false;\n\n return IsKeyPressed(key, repeat);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid GetWindowRect(ImGuiWindow* window, ImVec2* pos, ImVec2* size)\n{\n *pos = window->Pos;\n *size = window->Size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SetWindowRect(ImGuiWindow* window, const ImVec2 pos, const ImVec2 size)\n{\n window->PosFloat = pos;\n window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y);\n window->Size = size;\n window->SizeFull = size;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool IsActiveWindow(ImGuiWindow* window)\n{\n const ImGuiState* g = GImGui;\n return g->FocusedWindow == window;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nImScEditor* ScInputText(const char* label, float xSize, float ySize, void (*callback)(void*), void* userData)\n{\n ImGuiWindow* window = GetCurrentWindow();\n const ImGuiID id = window->GetID(label);\n\n (void)callback;\n (void)userData;\n\n \/\/ImGui::BeginChild(\"Log\");\n\n\tImGuiStorage* storage = GetStateStorage();\n\tScEditor* editor = (ScEditor*)storage->GetVoidPtr(id);\n\n\tif (!editor)\n\t{\n\t\t(void)xSize;\n\t\t(void)ySize;\n\t\teditor = ScEditor_create((int)xSize, (int)ySize);\n\t\tstorage->SetVoidPtr(id, (void*)editor);\n\t}\n\n\tImScEditor* editorInterface = ScEditor_getInterface(editor);\n\n\t\/\/float textSize = ImGui::GetTextLineHeightWithSpacing() - 1;\n\t\/\/ TODO: Remove hardcoded value, ask scintilla\n\tfloat textSize = 26;\n\n\tScEditor_resize(editor, 0, 0, (int)window->Size.x - 20, (int)window->Size.y); \n\n\tint lineCount = (int)editorInterface->SendCommand(SCI_GETLINECOUNT, 0, 0);\n\n\teditorInterface->HandleInput();\n\n\tImGuiListClipper clipper(lineCount, textSize);\n\n\t\/\/ImVec2 pos = window->DC.CursorPos;\n\n ScEditor_setDrawList(GetWindowDrawList());\n ScEditor_setFont(GetWindowFont());\n\tScEditor_setPos(0.0f, 14.0f);\n\n\t\/\/int currentPos = (int)editorInterface->SendCommand(SCN_GETTOPLINE, 0, 0);\n\n\t\/\/float scrollPos = ImGui::GetScrollPosY();\n\t\n\t\/\/int iPos = (int)(((int)ImGui::GetScrollPosY()) \/ (int)(textSize)); \n\n\t\/\/if (currentPos != iPos)\n\t\/\/{\n\teditorInterface->ScrollTo(clipper.DisplayStart);\n\t\/\/}\n\n\t\/\/printf(\"current pos in scintilla %d - pos sent %d\\n\", newPos, iPos);\n\n\tclipper.End();\n\n \/\/ImGui::EndChild();\n\t\n\treturn editorInterface;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n}\n\n<|endoftext|>"} {"text":"\/**\n * projectM -- Milkdrop-esque visualisation SDK\n * Copyright (C)2003-2007 projectM 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n * See 'LICENSE.txt' included within this release\n *\n *\/\n\/**\n * $Id$\n *\n * Beat detection class. Takes decompressed sound buffers and returns\n * various characteristics\n *\n * $Log$\n *\n *\/\n\n#ifndef _BEAT_DETECT_H\n#define _BEAT_DETECT_H\n\n#include \"PCM.hpp\"\n\nclass BeatDetect\n{\n\tpublic:\n\t\t\/** Vars *\/\n\t\tfloat beat_buffer[32][80],\n\t\tbeat_instant[32],\n\t\tbeat_history[32];\n\t\tfloat beat_val[32],\n\t\tbeat_att[32],\n\t\tbeat_variance[32];\n\t\tint beat_buffer_pos;\n\t\tfloat vol_buffer[80],\n\t\tvol_instant,\n\t\tvol_history;\n\n\t\tfloat treb ;\n\t\tfloat mid ;\n\t\tfloat bass ;\n\t\tfloat vol_old ;\n\t\tfloat beat_sensitivity;\n\t\tfloat treb_att ;\n\t\tfloat mid_att ;\n\t\tfloat bass_att ;\n\t\tfloat vol;\n\n\t\tPCM *pcm;\n\n\t\t\/** Methods *\/\n\t\tDLLEXPORT BeatDetect(PCM *pcm);\n\t\tDLLEXPORT ~BeatDetect();\n\t\tvoid initBeatDetect();\n\t\tvoid reset();\n\t\tvoid detectFromSamples();\n\t\tvoid getBeatVals ( float *vdataL, float *vdataR );\n\n};\n\n#endif \/** !_BEAT_DETECT_H *\/\nremoved DLLEXPORT from beatdetect (was it necessary?)\/**\n * projectM -- Milkdrop-esque visualisation SDK\n * Copyright (C)2003-2007 projectM 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n * See 'LICENSE.txt' included within this release\n *\n *\/\n\/**\n * $Id$\n *\n * Beat detection class. Takes decompressed sound buffers and returns\n * various characteristics\n *\n * $Log$\n *\n *\/\n\n#ifndef _BEAT_DETECT_H\n#define _BEAT_DETECT_H\n\n#include \"PCM.hpp\"\n\nclass BeatDetect\n{\n\tpublic:\n\t\t\/** Vars *\/\n\t\tfloat beat_buffer[32][80],\n\t\tbeat_instant[32],\n\t\tbeat_history[32];\n\t\tfloat beat_val[32],\n\t\tbeat_att[32],\n\t\tbeat_variance[32];\n\t\tint beat_buffer_pos;\n\t\tfloat vol_buffer[80],\n\t\tvol_instant,\n\t\tvol_history;\n\n\t\tfloat treb ;\n\t\tfloat mid ;\n\t\tfloat bass ;\n\t\tfloat vol_old ;\n\t\tfloat beat_sensitivity;\n\t\tfloat treb_att ;\n\t\tfloat mid_att ;\n\t\tfloat bass_att ;\n\t\tfloat vol;\n\n\t\tPCM *pcm;\n\n\t\t\/** Methods *\/\n\t\tBeatDetect(PCM *pcm);\n\t\t~BeatDetect();\n\t\tvoid initBeatDetect();\n\t\tvoid reset();\n\t\tvoid detectFromSamples();\n\t\tvoid getBeatVals ( float *vdataL, float *vdataR );\n\n};\n\n#endif \/** !_BEAT_DETECT_H *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: exprnode.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 17:41: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#define _NTSDK \/\/ wg. HUGE_VAL MH\n#define HUGE_VAL HUGE\n#include \n\n#include \n#include \"sbcomp.hxx\"\n#include \"expr.hxx\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, SbiToken t, SbiExprNode* r )\n{\n BaseInit( p );\n\n pLeft = l;\n pRight = r;\n eTok = t;\n nVal = 0;\n eType = SbxVARIANT; \/\/ Nodes sind immer Variant\n eNodeType = SbxNODE;\n bComposite= TRUE;\n}\n\nSbiExprNode::SbiExprNode( SbiParser* p, double n, SbxDataType t )\n{\n BaseInit( p );\n\n eType = t;\n eNodeType = SbxNUMVAL;\n nVal = n;\n}\n\nSbiExprNode::SbiExprNode( SbiParser* p, const String& rVal )\n{\n BaseInit( p );\n\n eType = SbxSTRING;\n eNodeType = SbxSTRVAL;\n aStrVal = rVal;\n}\n\nSbiExprNode::SbiExprNode( SbiParser* p, const SbiSymDef& r, SbxDataType t, SbiExprList* l )\n{\n BaseInit( p );\n\n eType = ( t == SbxVARIANT ) ? r.GetType() : t;\n eNodeType = SbxVARVAL;\n aVar.pDef = (SbiSymDef*) &r;\n aVar.pPar = l;\n aVar.pNext= NULL;\n\n \/\/ Funktionsergebnisse sind nie starr\n bComposite= BOOL( aVar.pDef->GetProcDef() != NULL );\n}\n\n\/\/ #120061 TypeOf\nSbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, USHORT nId )\n{\n BaseInit( p );\n\n pLeft = l;\n eType = SbxBOOL;\n eNodeType = SbxTYPEOF;\n nTypeStrId = nId;\n}\n\n\n\/\/ AB: 17.12.95, Hilfsfunktion fuer Ctor fuer einheitliche Initialisierung\nvoid SbiExprNode::BaseInit( SbiParser* p )\n{\n pGen = &p->aGen;\n eTok = NIL;\n pLeft = NULL;\n pRight = NULL;\n pWithParent = NULL;\n bComposite = FALSE;\n bError = FALSE;\n}\n\nSbiExprNode::~SbiExprNode()\n{\n delete pLeft;\n delete pRight;\n if( IsVariable() )\n {\n delete aVar.pPar;\n delete aVar.pNext;\n }\n}\n\nSbiSymDef* SbiExprNode::GetVar()\n{\n if( eNodeType == SbxVARVAL )\n return aVar.pDef;\n else\n return NULL;\n}\n\nSbiSymDef* SbiExprNode::GetRealVar()\n{\n SbiExprNode* p = GetRealNode();\n if( p )\n return p->GetVar();\n else\n return NULL;\n}\n\n\/\/ AB: 18.12.95\nSbiExprNode* SbiExprNode::GetRealNode()\n{\n if( eNodeType == SbxVARVAL )\n {\n SbiExprNode* p = this;\n while( p->aVar.pNext )\n p = p->aVar.pNext;\n return p;\n }\n else\n return NULL;\n}\n\n\/\/ Diese Methode setzt den Typ um, falls er in den Integer-Bereich hineinpasst\n\nBOOL SbiExprNode::IsIntConst()\n{\n if( eNodeType == SbxNUMVAL )\n {\n if( eType >= SbxINTEGER && eType <= SbxDOUBLE )\n {\n double n;\n if( nVal >= SbxMININT && nVal <= SbxMAXINT && modf( nVal, &n ) == 0 )\n {\n nVal = (double) (short) nVal;\n eType = SbxINTEGER;\n return TRUE;\n }\n }\n }\n return FALSE;\n}\n\nBOOL SbiExprNode::IsNumber()\n{\n return BOOL( eNodeType == SbxNUMVAL );\n}\n\nBOOL SbiExprNode::IsString()\n{\n return BOOL( eNodeType == SbxSTRVAL );\n}\n\nBOOL SbiExprNode::IsVariable()\n{\n return BOOL( eNodeType == SbxVARVAL );\n}\n\nBOOL SbiExprNode::IsLvalue()\n{\n return IsVariable();\n}\n\n\/\/ Ermitteln der Tiefe eines Baumes\n\nshort SbiExprNode::GetDepth()\n{\n if( IsOperand() ) return 0;\n else\n {\n short d1 = pLeft->GetDepth();\n short d2 = pRight->GetDepth();\n return( (d1 < d2 ) ? d2 : d1 ) + 1;\n }\n}\n\n\n\/\/ Abgleich eines Baumes:\n\/\/ 1. Constant Folding\n\/\/ 2. Typabgleich\n\/\/ 3. Umwandlung der Operanden in Strings\n\/\/ 4. Hochziehen der Composite- und Error-Bits\n\nvoid SbiExprNode::Optimize()\n{\n FoldConstants();\n CollectBits();\n}\n\n\/\/ Hochziehen der Composite- und Fehlerbits\n\nvoid SbiExprNode::CollectBits()\n{\n if( pLeft )\n {\n pLeft->CollectBits();\n bError |= pLeft->bError;\n bComposite |= pLeft->bComposite;\n }\n if( pRight )\n {\n pRight->CollectBits();\n bError |= pRight->bError;\n bComposite |= pRight->bComposite;\n }\n}\n\n\/\/ Kann ein Zweig umgeformt werden, wird TRUE zurueckgeliefert. In diesem\n\/\/ Fall ist das Ergebnis im linken Zweig.\n\nvoid SbiExprNode::FoldConstants()\n{\n if( IsOperand() ) return;\n pLeft->FoldConstants();\n if( pRight )\n {\n pRight->FoldConstants();\n if( pLeft->IsConstant() && pRight->IsConstant()\n && pLeft->eNodeType == pRight->eNodeType )\n {\n CollectBits();\n if( eTok == CAT )\n \/\/ CAT verbindet auch zwei Zahlen miteinander!\n eType = SbxSTRING;\n if( pLeft->eType == SbxSTRING )\n \/\/ Kein Type Mismatch!\n eType = SbxSTRING;\n if( eType == SbxSTRING )\n {\n String rl( pLeft->GetString() );\n String rr( pRight->GetString() );\n delete pLeft; pLeft = NULL;\n delete pRight; pRight = NULL;\n bComposite = FALSE;\n if( eTok == PLUS || eTok == CAT )\n {\n eTok = CAT;\n \/\/ Verkettung:\n aStrVal = rl;\n aStrVal += rr;\n eType = SbxSTRING;\n eNodeType = SbxSTRVAL;\n }\n else\n {\n eType = SbxDOUBLE;\n eNodeType = SbxNUMVAL;\n StringCompare eRes = rr.CompareTo( rl );\n switch( eTok )\n {\n case EQ:\n nVal = ( eRes == COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;\n break;\n case NE:\n nVal = ( eRes != COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;\n break;\n case LT:\n nVal = ( eRes == COMPARE_LESS ) ? SbxTRUE : SbxFALSE;\n break;\n case GT:\n nVal = ( eRes == COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;\n break;\n case LE:\n nVal = ( eRes != COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;\n break;\n case GE:\n nVal = ( eRes != COMPARE_LESS ) ? SbxTRUE : SbxFALSE;\n break;\n default:\n pGen->GetParser()->Error( SbERR_CONVERSION );\n bError = TRUE;\n }\n }\n }\n else\n {\n double nl = pLeft->nVal;\n double nr = pRight->nVal;\n long ll = 0, lr = 0;\n long llMod = 0, lrMod = 0;\n if( ( eTok >= AND && eTok <= IMP )\n || eTok == IDIV || eTok == MOD )\n {\n \/\/ Integer-Operationen\n BOOL err = FALSE;\n if( nl > SbxMAXLNG ) err = TRUE, nl = SbxMAXLNG;\n else\n if( nl < SbxMINLNG ) err = TRUE, nl = SbxMINLNG;\n if( nr > SbxMAXLNG ) err = TRUE, nr = SbxMAXLNG;\n else\n if( nr < SbxMINLNG ) err = TRUE, nr = SbxMINLNG;\n ll = (long) nl; lr = (long) nr;\n llMod = (long) (nl < 0 ? nl - 0.5 : nl + 0.5);\n lrMod = (long) (nr < 0 ? nr - 0.5 : nr + 0.5);\n if( err )\n {\n pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );\n bError = TRUE;\n }\n }\n BOOL bBothInt = BOOL( pLeft->eType < SbxSINGLE\n && pRight->eType < SbxSINGLE );\n delete pLeft; pLeft = NULL;\n delete pRight; pRight = NULL;\n nVal = 0;\n eType = SbxDOUBLE;\n eNodeType = SbxNUMVAL;\n bComposite = FALSE;\n BOOL bCheckType = FALSE;\n switch( eTok )\n {\n case EXPON:\n nVal = pow( nl, nr ); break;\n case MUL:\n bCheckType = TRUE;\n nVal = nl * nr; break;\n case DIV:\n if( !nr )\n {\n pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;\n bError = TRUE;\n } else nVal = nl \/ nr;\n break;\n case PLUS:\n bCheckType = TRUE;\n nVal = nl + nr; break;\n case MINUS:\n bCheckType = TRUE;\n nVal = nl - nr; break;\n case EQ:\n nVal = ( nl == nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case NE:\n nVal = ( nl != nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case LT:\n nVal = ( nl < nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case GT:\n nVal = ( nl > nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case LE:\n nVal = ( nl <= nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case GE:\n nVal = ( nl >= nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case IDIV:\n if( !lr )\n {\n pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;\n bError = TRUE;\n } else nVal = ll \/ lr;\n eType = SbxLONG; break;\n case MOD:\n if( !lr )\n {\n pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;\n bError = TRUE;\n } else nVal = llMod % lrMod;\n eType = SbxLONG; break;\n case AND:\n nVal = (double) ( ll & lr ); eType = SbxLONG; break;\n case OR:\n nVal = (double) ( ll | lr ); eType = SbxLONG; break;\n case XOR:\n nVal = (double) ( ll ^ lr ); eType = SbxLONG; break;\n case EQV:\n nVal = (double) ( ~ll ^ lr ); eType = SbxLONG; break;\n case IMP:\n nVal = (double) ( ~ll | lr ); eType = SbxLONG; break;\n default: break;\n }\n\n if( !::rtl::math::isFinite( nVal ) )\n pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );\n\n \/\/ Den Datentyp wiederherstellen, um Rundungsfehler\n \/\/ zu killen\n if( bCheckType && bBothInt\n && nVal >= SbxMINLNG && nVal <= SbxMAXLNG )\n {\n \/\/ NK-Stellen weg\n long n = (long) nVal;\n nVal = n;\n eType = ( n >= SbxMININT && n <= SbxMAXINT )\n ? SbxINTEGER : SbxLONG;\n }\n }\n }\n }\n else if( pLeft->IsNumber() )\n {\n nVal = pLeft->nVal;\n delete pLeft;\n pLeft = NULL;\n eType = SbxDOUBLE;\n eNodeType = SbxNUMVAL;\n bComposite = FALSE;\n switch( eTok )\n {\n case NEG:\n nVal = -nVal; break;\n case NOT: {\n \/\/ Integer-Operation!\n BOOL err = FALSE;\n if( nVal > SbxMAXLNG ) err = TRUE, nVal = SbxMAXLNG;\n else\n if( nVal < SbxMINLNG ) err = TRUE, nVal = SbxMINLNG;\n if( err )\n {\n pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );\n bError = TRUE;\n }\n nVal = (double) ~((long) nVal);\n eType = SbxLONG;\n } break;\n default: break;\n }\n }\n if( eNodeType == SbxNUMVAL )\n {\n \/\/ Evtl auf INTEGER falten (wg. besserem Opcode)?\n if( eType == SbxSINGLE || eType == SbxDOUBLE )\n {\n double x;\n if( nVal >= SbxMINLNG && nVal <= SbxMAXLNG\n && !modf( nVal, &x ) )\n eType = SbxLONG;\n }\n if( eType == SbxLONG && nVal >= SbxMININT && nVal <= SbxMAXINT )\n eType = SbxINTEGER;\n }\n}\n\n\nINTEGRATION: CWS pchfix02 (1.14.24); FILE MERGED 2006\/09\/01 17:17:02 kaib 1.14.24.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: exprnode.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 10:02:02 $\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_basic.hxx\"\n\n#define _NTSDK \/\/ wg. HUGE_VAL MH\n#define HUGE_VAL HUGE\n#include \n\n#include \n#include \"sbcomp.hxx\"\n#include \"expr.hxx\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, SbiToken t, SbiExprNode* r )\n{\n BaseInit( p );\n\n pLeft = l;\n pRight = r;\n eTok = t;\n nVal = 0;\n eType = SbxVARIANT; \/\/ Nodes sind immer Variant\n eNodeType = SbxNODE;\n bComposite= TRUE;\n}\n\nSbiExprNode::SbiExprNode( SbiParser* p, double n, SbxDataType t )\n{\n BaseInit( p );\n\n eType = t;\n eNodeType = SbxNUMVAL;\n nVal = n;\n}\n\nSbiExprNode::SbiExprNode( SbiParser* p, const String& rVal )\n{\n BaseInit( p );\n\n eType = SbxSTRING;\n eNodeType = SbxSTRVAL;\n aStrVal = rVal;\n}\n\nSbiExprNode::SbiExprNode( SbiParser* p, const SbiSymDef& r, SbxDataType t, SbiExprList* l )\n{\n BaseInit( p );\n\n eType = ( t == SbxVARIANT ) ? r.GetType() : t;\n eNodeType = SbxVARVAL;\n aVar.pDef = (SbiSymDef*) &r;\n aVar.pPar = l;\n aVar.pNext= NULL;\n\n \/\/ Funktionsergebnisse sind nie starr\n bComposite= BOOL( aVar.pDef->GetProcDef() != NULL );\n}\n\n\/\/ #120061 TypeOf\nSbiExprNode::SbiExprNode( SbiParser* p, SbiExprNode* l, USHORT nId )\n{\n BaseInit( p );\n\n pLeft = l;\n eType = SbxBOOL;\n eNodeType = SbxTYPEOF;\n nTypeStrId = nId;\n}\n\n\n\/\/ AB: 17.12.95, Hilfsfunktion fuer Ctor fuer einheitliche Initialisierung\nvoid SbiExprNode::BaseInit( SbiParser* p )\n{\n pGen = &p->aGen;\n eTok = NIL;\n pLeft = NULL;\n pRight = NULL;\n pWithParent = NULL;\n bComposite = FALSE;\n bError = FALSE;\n}\n\nSbiExprNode::~SbiExprNode()\n{\n delete pLeft;\n delete pRight;\n if( IsVariable() )\n {\n delete aVar.pPar;\n delete aVar.pNext;\n }\n}\n\nSbiSymDef* SbiExprNode::GetVar()\n{\n if( eNodeType == SbxVARVAL )\n return aVar.pDef;\n else\n return NULL;\n}\n\nSbiSymDef* SbiExprNode::GetRealVar()\n{\n SbiExprNode* p = GetRealNode();\n if( p )\n return p->GetVar();\n else\n return NULL;\n}\n\n\/\/ AB: 18.12.95\nSbiExprNode* SbiExprNode::GetRealNode()\n{\n if( eNodeType == SbxVARVAL )\n {\n SbiExprNode* p = this;\n while( p->aVar.pNext )\n p = p->aVar.pNext;\n return p;\n }\n else\n return NULL;\n}\n\n\/\/ Diese Methode setzt den Typ um, falls er in den Integer-Bereich hineinpasst\n\nBOOL SbiExprNode::IsIntConst()\n{\n if( eNodeType == SbxNUMVAL )\n {\n if( eType >= SbxINTEGER && eType <= SbxDOUBLE )\n {\n double n;\n if( nVal >= SbxMININT && nVal <= SbxMAXINT && modf( nVal, &n ) == 0 )\n {\n nVal = (double) (short) nVal;\n eType = SbxINTEGER;\n return TRUE;\n }\n }\n }\n return FALSE;\n}\n\nBOOL SbiExprNode::IsNumber()\n{\n return BOOL( eNodeType == SbxNUMVAL );\n}\n\nBOOL SbiExprNode::IsString()\n{\n return BOOL( eNodeType == SbxSTRVAL );\n}\n\nBOOL SbiExprNode::IsVariable()\n{\n return BOOL( eNodeType == SbxVARVAL );\n}\n\nBOOL SbiExprNode::IsLvalue()\n{\n return IsVariable();\n}\n\n\/\/ Ermitteln der Tiefe eines Baumes\n\nshort SbiExprNode::GetDepth()\n{\n if( IsOperand() ) return 0;\n else\n {\n short d1 = pLeft->GetDepth();\n short d2 = pRight->GetDepth();\n return( (d1 < d2 ) ? d2 : d1 ) + 1;\n }\n}\n\n\n\/\/ Abgleich eines Baumes:\n\/\/ 1. Constant Folding\n\/\/ 2. Typabgleich\n\/\/ 3. Umwandlung der Operanden in Strings\n\/\/ 4. Hochziehen der Composite- und Error-Bits\n\nvoid SbiExprNode::Optimize()\n{\n FoldConstants();\n CollectBits();\n}\n\n\/\/ Hochziehen der Composite- und Fehlerbits\n\nvoid SbiExprNode::CollectBits()\n{\n if( pLeft )\n {\n pLeft->CollectBits();\n bError |= pLeft->bError;\n bComposite |= pLeft->bComposite;\n }\n if( pRight )\n {\n pRight->CollectBits();\n bError |= pRight->bError;\n bComposite |= pRight->bComposite;\n }\n}\n\n\/\/ Kann ein Zweig umgeformt werden, wird TRUE zurueckgeliefert. In diesem\n\/\/ Fall ist das Ergebnis im linken Zweig.\n\nvoid SbiExprNode::FoldConstants()\n{\n if( IsOperand() ) return;\n pLeft->FoldConstants();\n if( pRight )\n {\n pRight->FoldConstants();\n if( pLeft->IsConstant() && pRight->IsConstant()\n && pLeft->eNodeType == pRight->eNodeType )\n {\n CollectBits();\n if( eTok == CAT )\n \/\/ CAT verbindet auch zwei Zahlen miteinander!\n eType = SbxSTRING;\n if( pLeft->eType == SbxSTRING )\n \/\/ Kein Type Mismatch!\n eType = SbxSTRING;\n if( eType == SbxSTRING )\n {\n String rl( pLeft->GetString() );\n String rr( pRight->GetString() );\n delete pLeft; pLeft = NULL;\n delete pRight; pRight = NULL;\n bComposite = FALSE;\n if( eTok == PLUS || eTok == CAT )\n {\n eTok = CAT;\n \/\/ Verkettung:\n aStrVal = rl;\n aStrVal += rr;\n eType = SbxSTRING;\n eNodeType = SbxSTRVAL;\n }\n else\n {\n eType = SbxDOUBLE;\n eNodeType = SbxNUMVAL;\n StringCompare eRes = rr.CompareTo( rl );\n switch( eTok )\n {\n case EQ:\n nVal = ( eRes == COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;\n break;\n case NE:\n nVal = ( eRes != COMPARE_EQUAL ) ? SbxTRUE : SbxFALSE;\n break;\n case LT:\n nVal = ( eRes == COMPARE_LESS ) ? SbxTRUE : SbxFALSE;\n break;\n case GT:\n nVal = ( eRes == COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;\n break;\n case LE:\n nVal = ( eRes != COMPARE_GREATER ) ? SbxTRUE : SbxFALSE;\n break;\n case GE:\n nVal = ( eRes != COMPARE_LESS ) ? SbxTRUE : SbxFALSE;\n break;\n default:\n pGen->GetParser()->Error( SbERR_CONVERSION );\n bError = TRUE;\n }\n }\n }\n else\n {\n double nl = pLeft->nVal;\n double nr = pRight->nVal;\n long ll = 0, lr = 0;\n long llMod = 0, lrMod = 0;\n if( ( eTok >= AND && eTok <= IMP )\n || eTok == IDIV || eTok == MOD )\n {\n \/\/ Integer-Operationen\n BOOL err = FALSE;\n if( nl > SbxMAXLNG ) err = TRUE, nl = SbxMAXLNG;\n else\n if( nl < SbxMINLNG ) err = TRUE, nl = SbxMINLNG;\n if( nr > SbxMAXLNG ) err = TRUE, nr = SbxMAXLNG;\n else\n if( nr < SbxMINLNG ) err = TRUE, nr = SbxMINLNG;\n ll = (long) nl; lr = (long) nr;\n llMod = (long) (nl < 0 ? nl - 0.5 : nl + 0.5);\n lrMod = (long) (nr < 0 ? nr - 0.5 : nr + 0.5);\n if( err )\n {\n pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );\n bError = TRUE;\n }\n }\n BOOL bBothInt = BOOL( pLeft->eType < SbxSINGLE\n && pRight->eType < SbxSINGLE );\n delete pLeft; pLeft = NULL;\n delete pRight; pRight = NULL;\n nVal = 0;\n eType = SbxDOUBLE;\n eNodeType = SbxNUMVAL;\n bComposite = FALSE;\n BOOL bCheckType = FALSE;\n switch( eTok )\n {\n case EXPON:\n nVal = pow( nl, nr ); break;\n case MUL:\n bCheckType = TRUE;\n nVal = nl * nr; break;\n case DIV:\n if( !nr )\n {\n pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;\n bError = TRUE;\n } else nVal = nl \/ nr;\n break;\n case PLUS:\n bCheckType = TRUE;\n nVal = nl + nr; break;\n case MINUS:\n bCheckType = TRUE;\n nVal = nl - nr; break;\n case EQ:\n nVal = ( nl == nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case NE:\n nVal = ( nl != nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case LT:\n nVal = ( nl < nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case GT:\n nVal = ( nl > nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case LE:\n nVal = ( nl <= nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case GE:\n nVal = ( nl >= nr ) ? SbxTRUE : SbxFALSE;\n eType = SbxINTEGER; break;\n case IDIV:\n if( !lr )\n {\n pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;\n bError = TRUE;\n } else nVal = ll \/ lr;\n eType = SbxLONG; break;\n case MOD:\n if( !lr )\n {\n pGen->GetParser()->Error( SbERR_ZERODIV ); nVal = HUGE_VAL;\n bError = TRUE;\n } else nVal = llMod % lrMod;\n eType = SbxLONG; break;\n case AND:\n nVal = (double) ( ll & lr ); eType = SbxLONG; break;\n case OR:\n nVal = (double) ( ll | lr ); eType = SbxLONG; break;\n case XOR:\n nVal = (double) ( ll ^ lr ); eType = SbxLONG; break;\n case EQV:\n nVal = (double) ( ~ll ^ lr ); eType = SbxLONG; break;\n case IMP:\n nVal = (double) ( ~ll | lr ); eType = SbxLONG; break;\n default: break;\n }\n\n if( !::rtl::math::isFinite( nVal ) )\n pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );\n\n \/\/ Den Datentyp wiederherstellen, um Rundungsfehler\n \/\/ zu killen\n if( bCheckType && bBothInt\n && nVal >= SbxMINLNG && nVal <= SbxMAXLNG )\n {\n \/\/ NK-Stellen weg\n long n = (long) nVal;\n nVal = n;\n eType = ( n >= SbxMININT && n <= SbxMAXINT )\n ? SbxINTEGER : SbxLONG;\n }\n }\n }\n }\n else if( pLeft->IsNumber() )\n {\n nVal = pLeft->nVal;\n delete pLeft;\n pLeft = NULL;\n eType = SbxDOUBLE;\n eNodeType = SbxNUMVAL;\n bComposite = FALSE;\n switch( eTok )\n {\n case NEG:\n nVal = -nVal; break;\n case NOT: {\n \/\/ Integer-Operation!\n BOOL err = FALSE;\n if( nVal > SbxMAXLNG ) err = TRUE, nVal = SbxMAXLNG;\n else\n if( nVal < SbxMINLNG ) err = TRUE, nVal = SbxMINLNG;\n if( err )\n {\n pGen->GetParser()->Error( SbERR_MATH_OVERFLOW );\n bError = TRUE;\n }\n nVal = (double) ~((long) nVal);\n eType = SbxLONG;\n } break;\n default: break;\n }\n }\n if( eNodeType == SbxNUMVAL )\n {\n \/\/ Evtl auf INTEGER falten (wg. besserem Opcode)?\n if( eType == SbxSINGLE || eType == SbxDOUBLE )\n {\n double x;\n if( nVal >= SbxMINLNG && nVal <= SbxMAXLNG\n && !modf( nVal, &x ) )\n eType = SbxLONG;\n }\n if( eType == SbxLONG && nVal >= SbxMININT && nVal <= SbxMAXINT )\n eType = SbxINTEGER;\n }\n}\n\n\n<|endoftext|>"} {"text":"\/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n * Copyright Projet JRL-Japan, 2009\n *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n *\n * File: CoMFreezer.cpp\n * Project: SOT\n * Author: Pierre Gergondet\n *\n * Version control\n * ===============\n *\n * $Id$\n *\n * Description\n * ============\n *\n *\n * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*\/\n\n#include \n#include \n#include \n\n\nusing namespace dynamicgraph;\nusing namespace sot;\n\nDYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CoMFreezer, \"CoMFreezer\");\n\nCoMFreezer::CoMFreezer(const std::string & name)\n : Entity(name)\n , m_lastCoM(3)\n , m_previousPGInProcess(false)\n , m_lastStopTime(-1)\n\n , CoMRefSIN(NULL, \"CoMFreezer(\"+name+\")::input(vector)::CoMRef\")\n , PGInProcessSIN(NULL, \"CoMFreezer(\"+name+\")::input(bool)::PGInProcess\")\n , freezedCoMSOUT(boost::bind(&CoMFreezer::computeFreezedCoM, this, _1, _2),\n CoMRefSIN << PGInProcessSIN,\n \"CoMFreezer(\"+name+\")::output(vector)::freezedCoM\")\n{\n sotDEBUGIN(5);\n\n signalRegistration( CoMRefSIN << PGInProcessSIN << freezedCoMSOUT );\n\n sotDEBUGOUT(5);\n}\n\nCoMFreezer::~CoMFreezer(void)\n{\n sotDEBUGIN(5);\n sotDEBUGOUT(5);\n return;\n}\n\nml::Vector & CoMFreezer::computeFreezedCoM(ml::Vector & freezedCoM, const int & time)\n{\n sotDEBUGIN(15);\n\n unsigned PGInProcess = PGInProcessSIN(time); \n if(PGInProcess) \/* CoM unfreezed *\/\n {\n m_lastCoM = CoMRefSIN(time);\n m_previousPGInProcess = PGInProcess;\n }\n else\n {\n if(m_previousPGInProcess) \/* pg.inprocess switch from 1 to 0 *\/\n {\n m_lastStopTime = time;\n m_lastCoM = CoMRefSIN(time);\n m_previousPGInProcess = PGInProcess;\n }\n else if(time < m_lastStopTime + 200) \/* keep updating for 1s *\/\n {\n m_lastCoM = CoMRefSIN(time);\n }\n }\n\n freezedCoM = m_lastCoM;\n\n sotDEBUGOUT(15);\n\n if(m_lastStopTime < 0)\n {\n m_lastCoM = CoMRefSIN(time);\n m_lastStopTime = time;\n freezedCoM = m_lastCoM;\n return freezedCoM;\n }\n\n\n return m_lastCoM;\n}\n\nvoid CoMFreezer::display(std::ostream & os) const\n{\n os << \"CoMFreezer \" << getName() << \".\" << std::endl;\n}\nRemove warnings (during conversion unsigned -> bool)\/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n * Copyright Projet JRL-Japan, 2009\n *+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n *\n * File: CoMFreezer.cpp\n * Project: SOT\n * Author: Pierre Gergondet\n *\n * Version control\n * ===============\n *\n * $Id$\n *\n * Description\n * ============\n *\n *\n * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*\/\n\n#include \n#include \n#include \n\n\nusing namespace dynamicgraph;\nusing namespace sot;\n\nDYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CoMFreezer, \"CoMFreezer\");\n\nCoMFreezer::CoMFreezer(const std::string & name)\n : Entity(name)\n , m_lastCoM(3)\n , m_previousPGInProcess(false)\n , m_lastStopTime(-1)\n\n , CoMRefSIN(NULL, \"CoMFreezer(\"+name+\")::input(vector)::CoMRef\")\n , PGInProcessSIN(NULL, \"CoMFreezer(\"+name+\")::input(bool)::PGInProcess\")\n , freezedCoMSOUT(boost::bind(&CoMFreezer::computeFreezedCoM, this, _1, _2),\n CoMRefSIN << PGInProcessSIN,\n \"CoMFreezer(\"+name+\")::output(vector)::freezedCoM\")\n{\n sotDEBUGIN(5);\n\n signalRegistration( CoMRefSIN << PGInProcessSIN << freezedCoMSOUT );\n\n sotDEBUGOUT(5);\n}\n\nCoMFreezer::~CoMFreezer(void)\n{\n sotDEBUGIN(5);\n sotDEBUGOUT(5);\n return;\n}\n\nml::Vector & CoMFreezer::computeFreezedCoM(ml::Vector & freezedCoM, const int & time)\n{\n sotDEBUGIN(15);\n\n unsigned PGInProcess = PGInProcessSIN(time); \n if(PGInProcess) \/* CoM unfreezed *\/\n {\n m_lastCoM = CoMRefSIN(time);\n m_previousPGInProcess = (PGInProcess == 0);\n }\n else\n {\n if(m_previousPGInProcess) \/* pg.inprocess switch from 1 to 0 *\/\n {\n m_lastStopTime = time;\n m_lastCoM = CoMRefSIN(time);\n m_previousPGInProcess = (PGInProcess == 0);\n }\n else if(time < m_lastStopTime + 200) \/* keep updating for 1s *\/\n {\n m_lastCoM = CoMRefSIN(time);\n }\n }\n\n freezedCoM = m_lastCoM;\n\n sotDEBUGOUT(15);\n\n if(m_lastStopTime < 0)\n {\n m_lastCoM = CoMRefSIN(time);\n m_lastStopTime = time;\n freezedCoM = m_lastCoM;\n return freezedCoM;\n }\n\n\n return m_lastCoM;\n}\n\nvoid CoMFreezer::display(std::ostream & os) const\n{\n os << \"CoMFreezer \" << getName() << \".\" << std::endl;\n}\n<|endoftext|>"} {"text":"\/* \n * Copyright 2009 The VOTCA Development Team (http:\/\/www.votca.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\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid + interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n\n string in_file, out_file, grid, fitgrid, comment, type, boundaries;\n Spline *spline;\n Table in, out, der;\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.\")\n (\"type\", po::value(&type)->default_value(\"akima\"), \"[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.\")\n (\"fitgrid\", po::value(&fitgrid), \"specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.\")\n (\"nocut\", \"Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.\")\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\")\n (\"help\", \"options file for coarse graining\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n\n if(!(vm.count(\"grid\") || vm.count(\"fitgrid\"))) {\n cout << \"Need grid for interpolation or fitgrid for fit.\\n\";\n return 1;\n }\n\n if((!vm.count(\"grid\")) && vm.count(\"fitgrid\")) {\n cout << \"Need a grid for fitting as well.\\n\";\n return 1;\n }\n\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n\n \n in.Load(in_file);\n\n if (vm.count(\"type\")) {\n if(type==\"cubic\") {\n spline = new CubicSpline();\n }\n else if(type==\"akima\") {\n spline = new AkimaSpline();\n }\n else if(type==\"linear\") {\n spline = new LinSpline();\n }\n else {\n throw std::runtime_error(\"unknown type\");\n }\n }\n spline->setBC(Spline::splineNormal);\n \n\n if (vm.count(\"boundaries\")) {\n if(boundaries==\"periodic\") {\n spline->setBC(Spline::splinePeriodic);\n }\n if(boundaries==\"derivativezero\") {\n spline->setBC(Spline::splineDerivativeZero);\n }\n \/\/default: normal\n }\n\n\n \/\/ in case fit is specified\n if (vm.count(\"fitgrid\")) {\n Tokenizer tok(fitgrid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in fitgrid, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing \" << type << \" fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n\n \/\/ cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut)\n ub::vector x_copy;\n ub::vector y_copy;\n if (!vm.count(\"nocut\")) {\n \/\/ determine vector size\n int minindex=-1, maxindex;\n for (int i=0; i(maxindex-minindex+1);\n y_copy = ub::zero_vector(maxindex-minindex+1);\n for (int i=minindex; i<=maxindex; i++) {\n x_copy(i-minindex) = in.x(i);\n y_copy(i-minindex) = in.y(i);\n }\n }\n\n \/\/ fitting\n spline->GenerateGrid(sp_min, sp_max, sp_step);\n if (vm.count(\"nocut\")) {\n spline->Fit(in.x(), in.y());\n } else {\n spline->Fit(x_copy, y_copy);\n }\n } else {\n \/\/ otherwise do interpolation (default = cubic)\n spline->Interpolate(in.x(), in.y());\n }\n\n \n out.GenerateGridSpacing(min, max, step);\n spline->Calculate(out.x(), out.y());\n \n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) \/\/ fix for precison errors\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n\n spline->CalculateDerivative(der.x(), der.y());\n\n der.Save(vm[\"derivative\"].as());\n }\n\n delete spline;\n return 0;\n}\n\nerror handling in csg_resample\/* \n * Copyright 2009 The VOTCA Development Team (http:\/\/www.votca.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\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"version.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nusing namespace votca::csg;\nusing namespace votca::tools;\n\nvoid help_text()\n{\n votca::csg::HelpTextHeader(\"csg_resample\");\n cout << \"Change grid + interval of any sort of table files.\\n\"\n \"Mainly called internally by inverse script, can also be\\n\"\n \"used to manually prepare input files for coarse-grained\\n\"\n \"simulations.\\n\\n\"; \n}\n\nvoid check_option(po::options_description &desc, po::variables_map &vm, const string &option)\n{\n if(!vm.count(option)) {\n cout << \"csg_resample \\n\\n\"; \n cout << desc << endl << \"parameter \" << option << \" is not specified\\n\";\n exit(1);\n }\n}\n\nint main(int argc, char** argv)\n{\n\n string in_file, out_file, grid, fitgrid, comment, type, boundaries;\n Spline *spline;\n Table in, out, der;\n \/\/ program options\n po::options_description desc(\"Allowed options\"); \n \n desc.add_options()\n (\"in\", po::value(&in_file), \"table to read\")\n (\"out\", po::value(&out_file), \"table to write\")\n (\"derivative\", po::value(), \"table to write\")\n (\"grid\", po::value(&grid), \"new grid spacing (min:step:max). If 'grid' is specified only, interpolation is performed.\")\n (\"type\", po::value(&type)->default_value(\"akima\"), \"[cubic|akima|linear]. If option is not specified, the default type 'akima' is assumed.\")\n (\"fitgrid\", po::value(&fitgrid), \"specify fit grid (min:step:max). If 'grid' and 'fitgrid' are specified, a fit is performed.\")\n (\"nocut\", \"Option for fitgrid: Normally, values out of fitgrid boundaries are cut off. If they shouldn't, choose --nocut.\")\n (\"comment\", po::value(&comment), \"store a comment in the output table\")\n (\"boundaries\", po::value(&boundaries), \"(natural|periodic|derivativezero) sets boundary conditions\")\n (\"help\", \"options file for coarse graining\");\n \n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm); \n po::notify(vm);\n }\n catch(po::error err) {\n cout << \"error parsing command line: \" << err.what() << endl;\n return -1;\n }\n \n \/\/ does the user want help?\n if (vm.count(\"help\")) {\n help_text();\n cout << desc << endl;\n return 0;\n }\n \n check_option(desc, vm, \"in\");\n check_option(desc, vm, \"out\");\n\n if(!(vm.count(\"grid\") || vm.count(\"fitgrid\"))) {\n cout << \"Need grid for interpolation or fitgrid for fit.\\n\";\n return 1;\n }\n\n if((!vm.count(\"grid\")) && vm.count(\"fitgrid\")) {\n cout << \"Need a grid for fitting as well.\\n\";\n return 1;\n }\n\n \n double min, max, step;\n {\n Tokenizer tok(grid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format, use min:step:max\\n\";\n return 1; \n }\n min = boost::lexical_cast(toks[0]);\n step = boost::lexical_cast(toks[1]);\n max = boost::lexical_cast(toks[2]);\n }\n\n \n in.Load(in_file);\n\n if (vm.count(\"type\")) {\n if(type==\"cubic\") {\n spline = new CubicSpline();\n }\n else if(type==\"akima\") {\n spline = new AkimaSpline();\n }\n else if(type==\"linear\") {\n spline = new LinSpline();\n }\n else {\n throw std::runtime_error(\"unknown type\");\n }\n }\n spline->setBC(Spline::splineNormal);\n \n\n if (vm.count(\"boundaries\")) {\n if(boundaries==\"periodic\") {\n spline->setBC(Spline::splinePeriodic);\n }\n if(boundaries==\"derivativezero\") {\n spline->setBC(Spline::splineDerivativeZero);\n }\n \/\/default: normal\n }\n\n\n \/\/ in case fit is specified\n if (vm.count(\"fitgrid\")) {\n Tokenizer tok(fitgrid, \":\");\n vector toks;\n tok.ToVector(toks);\n if(toks.size()!=3) {\n cout << \"wrong range format in fitgrid, use min:step:max\\n\";\n return 1; \n }\n double sp_min, sp_max, sp_step;\n sp_min = boost::lexical_cast(toks[0]);\n sp_step = boost::lexical_cast(toks[1]);\n sp_max = boost::lexical_cast(toks[2]);\n cout << \"doing \" << type << \" fit \" << sp_min << \":\" << sp_step << \":\" << sp_max << endl;\n\n \/\/ cut off any values out of fitgrid boundaries (exception: do nothing in case of --nocut)\n ub::vector x_copy;\n ub::vector y_copy;\n if (!vm.count(\"nocut\")) {\n \/\/ determine vector size\n int minindex=-1, maxindex;\n for (int i=0; i(maxindex-minindex+1);\n y_copy = ub::zero_vector(maxindex-minindex+1);\n for (int i=minindex; i<=maxindex; i++) {\n x_copy(i-minindex) = in.x(i);\n y_copy(i-minindex) = in.y(i);\n }\n }\n\n \/\/ fitting\n spline->GenerateGrid(sp_min, sp_max, sp_step);\n try {\n if (vm.count(\"nocut\")) {\n spline->Fit(in.x(), in.y());\n } else {\n spline->Fit(x_copy, y_copy);\n } \n } catch (const char* message) {\n if(message=\"qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n } \n else if(message=\"constrained_qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data for fit, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while fitting.\");\n }\n } else {\n \/\/ otherwise do interpolation (default = cubic)\n try {\n spline->Interpolate(in.x(), in.y());\n } catch (const char* message) {\n if(message=\"qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else if(message=\"constrained_qrsolve_zero_column_in_matrix\") {\n throw std::runtime_error(\"error in Linalg::linalg_constrained_qrsolve : Not enough data, please adjust grid (zero row in fit matrix)\");\n }\n else throw std::runtime_error(\"Unknown error in csg_resample while interpolating.\");\n }\n }\n\n \n out.GenerateGridSpacing(min, max, step);\n spline->Calculate(out.x(), out.y());\n \n \n \/\/store a comment line\n if (vm.count(\"comment\")){\n out.set_comment(comment);\n }\n out.y() = out.y();\n out.flags() = ub::scalar_vector(out.flags().size(), 'o');\n\n int i=0;\n for(i=0; out.x(i) < in.x(0) && i= out.x(i) || fabs(in.x(j)-out.x(i) ) < 1e-12) \/\/ fix for precison errors\n break; \n if(in.size() == j) break;\n out.flags(i) = in.flags(j);\n }\n \n out.Save(out_file);\n \n if (vm.count(\"derivative\")) {\n der.GenerateGridSpacing(min, max, step);\n der.flags() = ub::scalar_vector(der.flags().size(), 'o');\n\n spline->CalculateDerivative(der.x(), der.y());\n\n der.Save(vm[\"derivative\"].as());\n }\n\n delete spline;\n return 0;\n}\n\n<|endoftext|>"} {"text":"#ifndef TURBO_TOOLSET_INTRINSIC_HPP\n#define TURBO_TOOLSET_INTRINSIC_HPP\n\n#include \n#include \n\nnamespace turbo {\nnamespace toolset {\n\nconstexpr int uint32_digits()\n{\n return std::numeric_limits::digits;\n}\n\nconstexpr int uint64_digits()\n{\n return std::numeric_limits::digits;\n}\n\nconstexpr std::uint32_t pow_2_to_31()\n{\n return 1U << 31;\n}\n\ninline std::uint32_t count_leading_zero(std::uint32_t input)\n{\n#if defined( _WIN32) && defined(_MSC_VER)\n std::uint32_t result = 0U;\n return (_BitScanReverse(result&, input) == 0) ? uint32_digits() : uint32_digits() - result + 1U;\n#elif defined(__GNUC__) || defined(__clang__)\n return (input == 0U) ? uint32_digits() : __builtin_clz(input);\n#else\n std::uint32_t count = 0U;\n while (count < uint32_digits() && (input & pow_2_to_31()) != pow_2_to_31())\n {\n\tinput = input << 1;\n\t++count;\n }\n return count;\n#endif\n}\n\ninline std::uint64_t count_leading_zero(std::uint64_t input)\n{\n#if defined( _WIN32) && defined(_MSC_VER)\n std::uint64_t result = 0U;\n return (_BitScanReverse64(result&, input) == 0) ? uint64_digits() : uint64_digits() - result + 1U;\n#else\n std::uint32_t high_result = count_leading_zero(static_cast((input & 0xFFFFFFFF00000000) >> uint32_digits()));\n return (high_result != uint32_digits()) ? high_result : count_leading_zero(static_cast(input & 0x00000000FFFFFFFF)) + uint32_digits();\n#endif\n}\n\n} \/\/ namespace toolset\n} \/\/ namespace turbo\n\n#endif\n\noverloading count_leading_zero for std::uint8_t and std::uint16_t#ifndef TURBO_TOOLSET_INTRINSIC_HPP\n#define TURBO_TOOLSET_INTRINSIC_HPP\n\n#include \n#include \n\nnamespace turbo {\nnamespace toolset {\n\nconstexpr int uint32_digits()\n{\n return std::numeric_limits::digits;\n}\n\nconstexpr int uint64_digits()\n{\n return std::numeric_limits::digits;\n}\n\nconstexpr std::uint32_t pow_2_to_31()\n{\n return 1U << 31;\n}\n\ninline std::uint32_t count_leading_zero(std::uint32_t input)\n{\n#if defined( _WIN32) && defined(_MSC_VER)\n std::uint32_t result = 0U;\n return (_BitScanReverse(result&, input) == 0) ? uint32_digits() : uint32_digits() - result + 1U;\n#elif defined(__GNUC__) || defined(__clang__)\n return (input == 0U) ? uint32_digits() : __builtin_clz(input);\n#else\n std::uint32_t count = 0U;\n while (count < uint32_digits() && (input & pow_2_to_31()) != pow_2_to_31())\n {\n\tinput = input << 1;\n\t++count;\n }\n return count;\n#endif\n}\n\ninline std::uint64_t count_leading_zero(std::uint64_t input)\n{\n#if defined( _WIN32) && defined(_MSC_VER)\n std::uint64_t result = 0U;\n return (_BitScanReverse64(result&, input) == 0) ? uint64_digits() : uint64_digits() - result + 1U;\n#else\n std::uint32_t high_result = count_leading_zero(static_cast((input & 0xFFFFFFFF00000000) >> uint32_digits()));\n return (high_result != uint32_digits())\n\t ? high_result\n\t : count_leading_zero(static_cast(input & 0x00000000FFFFFFFF)) + uint32_digits();\n#endif\n}\n\ninline std::uint32_t count_leading_zero(std::uint8_t input)\n{\n return count_leading_zero(static_cast(input))\n\t + std::numeric_limits::digits\n\t - std::numeric_limits::digits;\n}\n\ninline std::uint32_t count_leading_zero(std::uint16_t input)\n{\n return count_leading_zero(static_cast(input))\n\t + std::numeric_limits::digits\n\t - std::numeric_limits::digits;\n}\n\n} \/\/ namespace toolset\n} \/\/ namespace turbo\n\n#endif\n\n<|endoftext|>"} {"text":"include DYLD_LIBRARY_PATH on macOS for run\/dbg<|endoftext|>"} {"text":"#include \"common\/Clock.h\"\n\n#include \"rgw_log.h\"\n#include \"rgw_acl.h\"\n#include \"rgw_access.h\"\n\n#define DOUT_SUBSYS rgw\n\nstatic rgw_bucket log_bucket(RGW_LOG_POOL_NAME);\n\nstatic void set_param_str(struct req_state *s, const char *name, string& str)\n{\n const char *p = s->env->get(name);\n if (p)\n str = p;\n}\n\nstring render_log_object_name(const string& format,\n\t\t\t struct tm *dt, int64_t bucket_id, const string& bucket_name)\n{\n string o;\n for (unsigned i=0; itm_year + 1900);\n\tbreak;\n case 'y':\n\tsprintf(buf, \"%.2d\", dt->tm_year % 100);\n\tbreak;\n case 'm':\n\tsprintf(buf, \"%.2d\", dt->tm_mon + 1);\n\tbreak;\n case 'd':\n\tsprintf(buf, \"%.2d\", dt->tm_mday);\n\tbreak;\n case 'H':\n\tsprintf(buf, \"%.2d\", dt->tm_hour);\n\tbreak;\n case 'I':\n\tsprintf(buf, \"%.2d\", (dt->tm_hour % 12) + 1);\n\tbreak;\n case 'k':\n\tsprintf(buf, \"%d\", dt->tm_hour);\n\tbreak;\n case 'l':\n\tsprintf(buf, \"%d\", (dt->tm_hour % 12) + 1);\n\tbreak;\n case 'M':\n\tsprintf(buf, \"%.2d\", dt->tm_min);\n\tbreak;\n\n case 'i':\n\tsprintf(buf, \"%lld\", (long long)bucket_id);\n\tbreak;\n case 'n':\n\to += bucket_name;\n\tcontinue;\n default:\n\t\/\/ unknown code\n\tsprintf(buf, \"%%%c\", format[i]);\n\tbreak;\n }\n o += buf;\n continue;\n }\n o += format[i];\n }\n return o;\n}\n\nint rgw_log_op(struct req_state *s)\n{\n struct rgw_log_entry entry;\n uint64_t bucket_id;\n\n if (!s->should_log)\n return 0;\n\n if (!s->bucket_name) {\n dout(0) << \"nothing to log for operation\" << dendl;\n return -EINVAL;\n }\n if (s->err.ret == -ERR_NO_SUCH_BUCKET) {\n if (!g_conf->rgw_log_nonexistent_bucket) {\n dout(0) << \"bucket \" << s->bucket << \" doesn't exist, not logging\" << dendl;\n return 0;\n }\n bucket_id = 0;\n } else {\n bucket_id = s->bucket.bucket_id;\n }\n entry.bucket = s->bucket_name;\n\n if (s->object)\n entry.obj = s->object;\n else\n entry.obj = \"-\";\n\n entry.obj_size = s->obj_size;\n\n if (g_conf->rgw_remote_addr_param.length())\n set_param_str(s, g_conf->rgw_remote_addr_param.c_str(), entry.remote_addr);\n else\n set_param_str(s, \"REMOTE_ADDR\", entry.remote_addr); \n set_param_str(s, \"HTTP_USER_AGENT\", entry.user_agent);\n set_param_str(s, \"HTTP_REFERRER\", entry.referrer);\n set_param_str(s, \"REQUEST_URI\", entry.uri);\n set_param_str(s, \"REQUEST_METHOD\", entry.op);\n\n entry.user = s->user.user_id;\n if (s->acl)\n entry.object_owner = s->acl->get_owner().get_id();\n entry.bucket_owner = s->bucket_owner;\n\n entry.time = s->time;\n entry.total_time = ceph_clock_now(g_ceph_context) - s->time;\n entry.bytes_sent = s->bytes_sent;\n entry.bytes_received = s->bytes_received;\n if (s->err.http_ret) {\n char buf[16];\n snprintf(buf, sizeof(buf), \"%d\", s->err.http_ret);\n entry.http_status = buf;\n } else\n entry.http_status = \"200\"; \/\/ default\n\n entry.error_code = s->err.s3_code;\n entry.bucket_id = bucket_id;\n\n bufferlist bl;\n ::encode(entry, bl);\n\n struct tm bdt;\n time_t t = entry.time.sec();\n if (g_conf->rgw_log_object_name_utc)\n gmtime_r(&t, &bdt);\n else\n localtime_r(&t, &bdt);\n \n string oid = render_log_object_name(g_conf->rgw_log_object_name, &bdt,\n\t\t\t\t s->bucket.bucket_id, entry.bucket.c_str());\n\n rgw_obj obj(log_bucket, oid);\n\n int ret = rgwstore->append_async(obj, bl.length(), bl);\n if (ret == -ENOENT) {\n string id;\n map attrs;\n ret = rgwstore->create_bucket(id, log_bucket, attrs, true);\n if (ret < 0)\n goto done;\n \/\/ retry\n ret = rgwstore->append_async(obj, bl.length(), bl);\n }\ndone:\n if (ret < 0)\n dout(0) << \"failed to log entry\" << dendl;\n\n return ret;\n}\n\nint rgw_log_intent(struct req_state *s, rgw_obj& obj, RGWIntentEvent intent)\n{\n rgw_bucket intent_log_bucket(RGW_INTENT_LOG_POOL_NAME);\n\n rgw_intent_log_entry entry;\n entry.obj = obj;\n entry.intent = (uint32_t)intent;\n entry.op_time = s->time;\n\n struct tm bdt;\n time_t t = entry.op_time.sec();\n if (g_conf->rgw_intent_log_object_name_utc)\n gmtime_r(&t, &bdt);\n else\n localtime_r(&t, &bdt);\n\n char buf[obj.bucket.name.size() + 16];\n sprintf(buf, \"%.4d-%.2d-%.2d-%lld-%s\", (bdt.tm_year+1900), (bdt.tm_mon+1), bdt.tm_mday,\n\t (long long)s->bucket.bucket_id, obj.bucket.name.c_str());\n string oid(buf);\n rgw_obj log_obj(intent_log_bucket, oid);\n\n bufferlist bl;\n ::encode(entry, bl);\n\n int ret = rgwstore->append_async(log_obj, bl.length(), bl);\n if (ret == -ENOENT) {\n string id;\n map attrs;\n ret = rgwstore->create_bucket(id, intent_log_bucket, attrs, true);\n if (ret < 0)\n goto done;\n ret = rgwstore->append_async(log_obj, bl.length(), bl);\n }\n\ndone:\n return ret;\n}\nrgw: don't log entries with bad utf8#include \"common\/Clock.h\"\n#include \"common\/utf8.h\"\n\n#include \"rgw_log.h\"\n#include \"rgw_acl.h\"\n#include \"rgw_access.h\"\n\n#define DOUT_SUBSYS rgw\n\nstatic rgw_bucket log_bucket(RGW_LOG_POOL_NAME);\n\nstatic void set_param_str(struct req_state *s, const char *name, string& str)\n{\n const char *p = s->env->get(name);\n if (p)\n str = p;\n}\n\nstring render_log_object_name(const string& format,\n\t\t\t struct tm *dt, int64_t bucket_id, const string& bucket_name)\n{\n string o;\n for (unsigned i=0; itm_year + 1900);\n\tbreak;\n case 'y':\n\tsprintf(buf, \"%.2d\", dt->tm_year % 100);\n\tbreak;\n case 'm':\n\tsprintf(buf, \"%.2d\", dt->tm_mon + 1);\n\tbreak;\n case 'd':\n\tsprintf(buf, \"%.2d\", dt->tm_mday);\n\tbreak;\n case 'H':\n\tsprintf(buf, \"%.2d\", dt->tm_hour);\n\tbreak;\n case 'I':\n\tsprintf(buf, \"%.2d\", (dt->tm_hour % 12) + 1);\n\tbreak;\n case 'k':\n\tsprintf(buf, \"%d\", dt->tm_hour);\n\tbreak;\n case 'l':\n\tsprintf(buf, \"%d\", (dt->tm_hour % 12) + 1);\n\tbreak;\n case 'M':\n\tsprintf(buf, \"%.2d\", dt->tm_min);\n\tbreak;\n\n case 'i':\n\tsprintf(buf, \"%lld\", (long long)bucket_id);\n\tbreak;\n case 'n':\n\to += bucket_name;\n\tcontinue;\n default:\n\t\/\/ unknown code\n\tsprintf(buf, \"%%%c\", format[i]);\n\tbreak;\n }\n o += buf;\n continue;\n }\n o += format[i];\n }\n return o;\n}\n\nint rgw_log_op(struct req_state *s)\n{\n struct rgw_log_entry entry;\n uint64_t bucket_id;\n\n if (!s->should_log)\n return 0;\n\n if (!s->bucket_name) {\n dout(0) << \"nothing to log for operation\" << dendl;\n return -EINVAL;\n }\n if (s->err.ret == -ERR_NO_SUCH_BUCKET) {\n if (!g_conf->rgw_log_nonexistent_bucket) {\n dout(0) << \"bucket \" << s->bucket << \" doesn't exist, not logging\" << dendl;\n return 0;\n }\n bucket_id = 0;\n } else {\n bucket_id = s->bucket.bucket_id;\n }\n entry.bucket = s->bucket_name;\n\n if (check_utf8(s->bucket_name, entry.bucket.size()) != 0) {\n dout(0) << \"not logging op on bucket with non-utf8 name\" << dendl;\n return 0;\n }\n\n if (s->object)\n entry.obj = s->object;\n else\n entry.obj = \"-\";\n\n entry.obj_size = s->obj_size;\n\n if (g_conf->rgw_remote_addr_param.length())\n set_param_str(s, g_conf->rgw_remote_addr_param.c_str(), entry.remote_addr);\n else\n set_param_str(s, \"REMOTE_ADDR\", entry.remote_addr); \n set_param_str(s, \"HTTP_USER_AGENT\", entry.user_agent);\n set_param_str(s, \"HTTP_REFERRER\", entry.referrer);\n set_param_str(s, \"REQUEST_URI\", entry.uri);\n set_param_str(s, \"REQUEST_METHOD\", entry.op);\n\n entry.user = s->user.user_id;\n if (s->acl)\n entry.object_owner = s->acl->get_owner().get_id();\n entry.bucket_owner = s->bucket_owner;\n\n entry.time = s->time;\n entry.total_time = ceph_clock_now(g_ceph_context) - s->time;\n entry.bytes_sent = s->bytes_sent;\n entry.bytes_received = s->bytes_received;\n if (s->err.http_ret) {\n char buf[16];\n snprintf(buf, sizeof(buf), \"%d\", s->err.http_ret);\n entry.http_status = buf;\n } else\n entry.http_status = \"200\"; \/\/ default\n\n entry.error_code = s->err.s3_code;\n entry.bucket_id = bucket_id;\n\n bufferlist bl;\n ::encode(entry, bl);\n\n struct tm bdt;\n time_t t = entry.time.sec();\n if (g_conf->rgw_log_object_name_utc)\n gmtime_r(&t, &bdt);\n else\n localtime_r(&t, &bdt);\n \n string oid = render_log_object_name(g_conf->rgw_log_object_name, &bdt,\n\t\t\t\t s->bucket.bucket_id, entry.bucket.c_str());\n\n rgw_obj obj(log_bucket, oid);\n\n int ret = rgwstore->append_async(obj, bl.length(), bl);\n if (ret == -ENOENT) {\n string id;\n map attrs;\n ret = rgwstore->create_bucket(id, log_bucket, attrs, true);\n if (ret < 0)\n goto done;\n \/\/ retry\n ret = rgwstore->append_async(obj, bl.length(), bl);\n }\ndone:\n if (ret < 0)\n dout(0) << \"failed to log entry\" << dendl;\n\n return ret;\n}\n\nint rgw_log_intent(struct req_state *s, rgw_obj& obj, RGWIntentEvent intent)\n{\n rgw_bucket intent_log_bucket(RGW_INTENT_LOG_POOL_NAME);\n\n rgw_intent_log_entry entry;\n entry.obj = obj;\n entry.intent = (uint32_t)intent;\n entry.op_time = s->time;\n\n struct tm bdt;\n time_t t = entry.op_time.sec();\n if (g_conf->rgw_intent_log_object_name_utc)\n gmtime_r(&t, &bdt);\n else\n localtime_r(&t, &bdt);\n\n char buf[obj.bucket.name.size() + 16];\n sprintf(buf, \"%.4d-%.2d-%.2d-%lld-%s\", (bdt.tm_year+1900), (bdt.tm_mon+1), bdt.tm_mday,\n\t (long long)s->bucket.bucket_id, obj.bucket.name.c_str());\n string oid(buf);\n rgw_obj log_obj(intent_log_bucket, oid);\n\n bufferlist bl;\n ::encode(entry, bl);\n\n int ret = rgwstore->append_async(log_obj, bl.length(), bl);\n if (ret == -ENOENT) {\n string id;\n map attrs;\n ret = rgwstore->create_bucket(id, intent_log_bucket, attrs, true);\n if (ret < 0)\n goto done;\n ret = rgwstore->append_async(log_obj, bl.length(), bl);\n }\n\ndone:\n return ret;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2021 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Filter.hxx\"\n#include \"CompletionHandler.hxx\"\n#include \"lib\/openssl\/Name.hxx\"\n#include \"lib\/openssl\/UniqueX509.hxx\"\n#include \"FifoBufferBio.hxx\"\n#include \"fs\/ThreadSocketFilter.hxx\"\n#include \"memory\/fb_pool.hxx\"\n#include \"memory\/SliceFifoBuffer.hxx\"\n#include \"util\/AllocatedArray.hxx\"\n#include \"util\/AllocatedString.hxx\"\n\n#include \n#include \n\n#include \n#include \n\nclass SslFilter final : public ThreadSocketFilterHandler,\n\t\t\tSslCompletionHandler {\n\t\/**\n\t * Buffers which can be accessed from within the thread without\n\t * holding locks. These will be copied to\/from the according\n\t * #thread_socket_filter buffers.\n\t *\/\n\tSliceFifoBuffer encrypted_input, decrypted_input,\n\t\tplain_output, encrypted_output;\n\n\tconst UniqueSSL ssl;\n\n\tbool handshaking = true;\n\n\tAllocatedArray alpn_selected;\n\npublic:\n\tAllocatedString peer_subject, peer_issuer_subject;\n\n\tSslFilter(UniqueSSL &&_ssl)\n\t\t:ssl(std::move(_ssl)) {\n\t\tSSL_set_bio(ssl.get(),\n\t\t\t NewFifoBufferBio(encrypted_input),\n\t\t\t NewFifoBufferBio(encrypted_output));\n\n\t\tSetSslCompletionHandler(*ssl, *this);\n\t}\n\n\tstd::span GetAlpnSelected() const noexcept {\n\t\treturn {alpn_selected.data(), alpn_selected.size()};\n\t}\n\nprivate:\n\t\/**\n\t * Called from inside Run() right after the handshake has\n\t * completed. This is used to collect some data for our\n\t * public getters.\n\t *\/\n\tvoid PostHandshake() noexcept;\n\n\tvoid Encrypt();\n\n\t\/* virtual methods from class ThreadSocketFilterHandler *\/\n\tvoid PreRun(ThreadSocketFilterInternal &f) noexcept override;\n\tvoid Run(ThreadSocketFilterInternal &f) override;\n\tvoid PostRun(ThreadSocketFilterInternal &f) noexcept override;\n\tvoid CancelRun(ThreadSocketFilterInternal &f) noexcept override;\n\n\t\/* virtual methods from class SslCompletionHandler *\/\n\tvoid OnSslCompletion() noexcept override {\n\t\tScheduleRun();\n\t}\n};\n\nstatic std::runtime_error\nMakeSslError()\n{\n\tunsigned long error = ERR_get_error();\n\tchar buffer[120];\n\treturn std::runtime_error(ERR_error_string(error, buffer));\n}\n\nstatic AllocatedString\nformat_subject_name(X509 *cert)\n{\n\treturn ToString(X509_get_subject_name(cert));\n}\n\nstatic AllocatedString\nformat_issuer_subject_name(X509 *cert)\n{\n\treturn ToString(X509_get_issuer_name(cert));\n}\n\n[[gnu::pure]]\nstatic bool\nis_ssl_error(SSL *ssl, int ret)\n{\n\tif (ret == 0)\n\t\t\/* this is always an error according to the documentation of\n\t\t SSL_read(), SSL_write() and SSL_do_handshake() *\/\n\t\treturn true;\n\n\tswitch (SSL_get_error(ssl, ret)) {\n\tcase SSL_ERROR_NONE:\n\tcase SSL_ERROR_WANT_READ:\n\tcase SSL_ERROR_WANT_WRITE:\n\tcase SSL_ERROR_WANT_CONNECT:\n\tcase SSL_ERROR_WANT_ACCEPT:\n\tcase SSL_ERROR_WANT_X509_LOOKUP:\n\t\treturn false;\n\n\tdefault:\n\t\treturn true;\n\t}\n}\n\nstatic void\nCheckThrowSslError(SSL *ssl, int result)\n{\n\tif (is_ssl_error(ssl, result))\n\t\tthrow MakeSslError();\n}\n\ninline void\nSslFilter::PostHandshake() noexcept\n{\n\tconst unsigned char *alpn_data;\n\tunsigned int alpn_length;\n\tSSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length);\n\tif (alpn_length > 0)\n\t\talpn_selected = ConstBuffer(alpn_data,\n\t\t\t\t\t\t\t alpn_length);\n\n\tUniqueX509 cert(SSL_get_peer_certificate(ssl.get()));\n\tif (cert != nullptr) {\n\t\tpeer_subject = format_subject_name(cert.get());\n\t\tpeer_issuer_subject = format_issuer_subject_name(cert.get());\n\t}\n}\n\nenum class SslDecryptResult {\n\tSUCCESS,\n\n\t\/**\n\t * More encrypted_input data is required.\n\t *\/\n\tMORE,\n\n\tCLOSE_NOTIFY_ALERT,\n};\n\nstatic SslDecryptResult\nssl_decrypt(SSL *ssl, ForeignFifoBuffer &buffer)\n{\n\t\/* SSL_read() must be called repeatedly until there is no more\n\t data (or until the buffer is full) *\/\n\n\twhile (true) {\n\t\tauto w = buffer.Write();\n\t\tif (w.empty())\n\t\t\treturn SslDecryptResult::SUCCESS;\n\n\t\tint result = SSL_read(ssl, w.data(), w.size());\n\t\tif (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ)\n\t\t\treturn SslDecryptResult::MORE;\n\n\t\tif (result <= 0) {\n\t\t\tif (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN)\n\t\t\t\t\/* got a \"close notify\" alert from the peer *\/\n\t\t\t\treturn SslDecryptResult::CLOSE_NOTIFY_ALERT;\n\n\t\t\tCheckThrowSslError(ssl, result);\n\t\t\treturn SslDecryptResult::SUCCESS;\n\t\t}\n\n\t\tbuffer.Append(result);\n\t}\n}\n\nstatic void\nssl_encrypt(SSL *ssl, ForeignFifoBuffer &buffer)\n{\n\t\/* SSL_write() must be called repeatedly until there is no more\n\t data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes\n\t only the current incomplete record, and additional data which\n\t has been submitted more recently will only be considered in the\n\t next SSL_write() call *\/\n\n\twhile (true) {\n\t\tauto r = buffer.Read();\n\t\tif (r.empty())\n\t\t\treturn;\n\n\t\tint result = SSL_write(ssl, r.data(), r.size());\n\t\tif (result <= 0) {\n\t\t\tCheckThrowSslError(ssl, result);\n\t\t\treturn;\n\t\t}\n\n\t\tbuffer.Consume(result);\n\t}\n}\n\ninline void\nSslFilter::Encrypt()\n{\n\tssl_encrypt(ssl.get(), plain_output);\n}\n\n\/*\n * thread_socket_filter_handler\n *\n *\/\n\nvoid\nSslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept\n{\n\tif (f.IsIdle()) {\n\t\tdecrypted_input.AllocateIfNull(fb_pool_get());\n\t\tencrypted_output.AllocateIfNull(fb_pool_get());\n\t}\n}\n\nvoid\nSslFilter::Run(ThreadSocketFilterInternal &f)\n{\n\t\/* copy input (and output to make room for more output) *\/\n\n\t{\n\t\tstd::unique_lock lock(f.mutex);\n\n\t\tif (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) {\n\t\t\t\/* retry, let PreRun() allocate the missing buffer *\/\n\t\t\tf.again = true;\n\t\t\treturn;\n\t\t}\n\n\t\tf.decrypted_input.MoveFromAllowNull(decrypted_input);\n\n\t\tplain_output.MoveFromAllowNull(f.plain_output);\n\t\tencrypted_input.MoveFromAllowSrcNull(f.encrypted_input);\n\n\t\tf.encrypted_output.MoveFromAllowNull(encrypted_output);\n\n\t\tif (decrypted_input.IsNull() || encrypted_output.IsNull()) {\n\t\t\t\/* retry, let PreRun() allocate the missing buffer *\/\n\t\t\tf.again = true;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/* let OpenSSL work *\/\n\n\tERR_clear_error();\n\n\tif (handshaking) [[unlikely]] {\n\t\tint result = SSL_do_handshake(ssl.get());\n\t\tif (result == 1) {\n\t\t\thandshaking = false;\n\t\t\tPostHandshake();\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tCheckThrowSslError(ssl.get(), result);\n\t\t\t\t\/* flush the encrypted_output buffer, because it may\n\t\t\t\t contain a \"TLS alert\" *\/\n\t\t\t} catch (...) {\n\t\t\t\tconst std::lock_guard lock(f.mutex);\n\t\t\t\tf.encrypted_output.MoveFromAllowNull(encrypted_output);\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!handshaking) [[likely]] {\n\t\tEncrypt();\n\n\t\tswitch (ssl_decrypt(ssl.get(), decrypted_input)) {\n\t\tcase SslDecryptResult::SUCCESS:\n\t\t\tbreak;\n\n\t\tcase SslDecryptResult::MORE:\n\t\t\tif (encrypted_input.IsDefinedAndFull())\n\t\t\t\tthrow std::runtime_error(\"SSL encrypted_input buffer is full\");\n\n\t\t\tbreak;\n\n\t\tcase SslDecryptResult::CLOSE_NOTIFY_ALERT:\n\t\t\t{\n\t\t\t\tstd::unique_lock lock(f.mutex);\n\t\t\t\tf.input_eof = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/* copy output *\/\n\n\t{\n\t\tstd::unique_lock lock(f.mutex);\n\n\t\tf.decrypted_input.MoveFromAllowNull(decrypted_input);\n\t\tf.encrypted_output.MoveFromAllowNull(encrypted_output);\n\t\tf.drained = plain_output.empty() && encrypted_output.empty();\n\n\t\tif (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty())\n\t\t\t\/* there's more data to be decrypted and we\n\t\t\t still have room in the destination buffer,\n\t\t\t so let's run again *\/\n\t\t\tf.again = true;\n\n\t\tif (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() &&\n\t\t !encrypted_output.IsDefinedAndFull())\n\t\t\t\/* there's more data, and we're ready to handle it: try\n\t\t\t again *\/\n\t\t\tf.again = true;\n\n\t\tf.handshaking = handshaking;\n\t}\n}\n\nvoid\nSslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept\n{\n\tif (f.IsIdle()) {\n\t\tplain_output.FreeIfEmpty();\n\t\tencrypted_input.FreeIfEmpty();\n\t\tdecrypted_input.FreeIfEmpty();\n\t\tencrypted_output.FreeIfEmpty();\n\t}\n}\n\nvoid\nSslFilter::CancelRun(ThreadSocketFilterInternal &) noexcept\n{\n\tif (cancel_ptr)\n\t\t\/* cancel the CertCache::Apply() call *\/\n\t\tcancel_ptr.Cancel();\n}\n\n\/*\n * constructor\n *\n *\/\n\nstd::unique_ptr\nssl_filter_new(UniqueSSL &&ssl) noexcept\n{\n\treturn std::make_unique(std::move(ssl));\n}\n\nSslFilter &\nssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept\n{\n\treturn static_cast(tsfh);\n}\n\nconst SslFilter *\nssl_filter_cast_from(const SocketFilter *socket_filter) noexcept\n{\n\tconst auto *tsf = dynamic_cast(socket_filter);\n\tif (tsf == nullptr)\n\t\treturn nullptr;\n\n\treturn dynamic_cast(&tsf->GetHandler());\n}\n\nstd::span\nssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept\n{\n\treturn ssl.GetAlpnSelected();\n}\n\nconst char *\nssl_filter_get_peer_subject(const SslFilter &ssl) noexcept\n{\n\treturn ssl.peer_subject.c_str();\n}\n\nconst char *\nssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept\n{\n\treturn ssl.peer_issuer_subject.c_str();\n}\nssl\/Filter: use std::span\/*\n * Copyright 2007-2021 CM4all GmbH\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Filter.hxx\"\n#include \"CompletionHandler.hxx\"\n#include \"lib\/openssl\/Name.hxx\"\n#include \"lib\/openssl\/UniqueX509.hxx\"\n#include \"FifoBufferBio.hxx\"\n#include \"fs\/ThreadSocketFilter.hxx\"\n#include \"memory\/fb_pool.hxx\"\n#include \"memory\/SliceFifoBuffer.hxx\"\n#include \"util\/AllocatedArray.hxx\"\n#include \"util\/AllocatedString.hxx\"\n\n#include \n#include \n\n#include \n#include \n\nclass SslFilter final : public ThreadSocketFilterHandler,\n\t\t\tSslCompletionHandler {\n\t\/**\n\t * Buffers which can be accessed from within the thread without\n\t * holding locks. These will be copied to\/from the according\n\t * #thread_socket_filter buffers.\n\t *\/\n\tSliceFifoBuffer encrypted_input, decrypted_input,\n\t\tplain_output, encrypted_output;\n\n\tconst UniqueSSL ssl;\n\n\tbool handshaking = true;\n\n\tAllocatedArray alpn_selected;\n\npublic:\n\tAllocatedString peer_subject, peer_issuer_subject;\n\n\tSslFilter(UniqueSSL &&_ssl)\n\t\t:ssl(std::move(_ssl)) {\n\t\tSSL_set_bio(ssl.get(),\n\t\t\t NewFifoBufferBio(encrypted_input),\n\t\t\t NewFifoBufferBio(encrypted_output));\n\n\t\tSetSslCompletionHandler(*ssl, *this);\n\t}\n\n\tstd::span GetAlpnSelected() const noexcept {\n\t\treturn {alpn_selected.data(), alpn_selected.size()};\n\t}\n\nprivate:\n\t\/**\n\t * Called from inside Run() right after the handshake has\n\t * completed. This is used to collect some data for our\n\t * public getters.\n\t *\/\n\tvoid PostHandshake() noexcept;\n\n\tvoid Encrypt();\n\n\t\/* virtual methods from class ThreadSocketFilterHandler *\/\n\tvoid PreRun(ThreadSocketFilterInternal &f) noexcept override;\n\tvoid Run(ThreadSocketFilterInternal &f) override;\n\tvoid PostRun(ThreadSocketFilterInternal &f) noexcept override;\n\tvoid CancelRun(ThreadSocketFilterInternal &f) noexcept override;\n\n\t\/* virtual methods from class SslCompletionHandler *\/\n\tvoid OnSslCompletion() noexcept override {\n\t\tScheduleRun();\n\t}\n};\n\nstatic std::runtime_error\nMakeSslError()\n{\n\tunsigned long error = ERR_get_error();\n\tchar buffer[120];\n\treturn std::runtime_error(ERR_error_string(error, buffer));\n}\n\nstatic AllocatedString\nformat_subject_name(X509 *cert)\n{\n\treturn ToString(X509_get_subject_name(cert));\n}\n\nstatic AllocatedString\nformat_issuer_subject_name(X509 *cert)\n{\n\treturn ToString(X509_get_issuer_name(cert));\n}\n\n[[gnu::pure]]\nstatic bool\nis_ssl_error(SSL *ssl, int ret)\n{\n\tif (ret == 0)\n\t\t\/* this is always an error according to the documentation of\n\t\t SSL_read(), SSL_write() and SSL_do_handshake() *\/\n\t\treturn true;\n\n\tswitch (SSL_get_error(ssl, ret)) {\n\tcase SSL_ERROR_NONE:\n\tcase SSL_ERROR_WANT_READ:\n\tcase SSL_ERROR_WANT_WRITE:\n\tcase SSL_ERROR_WANT_CONNECT:\n\tcase SSL_ERROR_WANT_ACCEPT:\n\tcase SSL_ERROR_WANT_X509_LOOKUP:\n\t\treturn false;\n\n\tdefault:\n\t\treturn true;\n\t}\n}\n\nstatic void\nCheckThrowSslError(SSL *ssl, int result)\n{\n\tif (is_ssl_error(ssl, result))\n\t\tthrow MakeSslError();\n}\n\ninline void\nSslFilter::PostHandshake() noexcept\n{\n\tconst unsigned char *alpn_data;\n\tunsigned int alpn_length;\n\tSSL_get0_alpn_selected(ssl.get(), &alpn_data, &alpn_length);\n\tif (alpn_length > 0)\n\t\talpn_selected = std::span(alpn_data,\n\t\t\t\t\t\t\t alpn_length);\n\n\tUniqueX509 cert(SSL_get_peer_certificate(ssl.get()));\n\tif (cert != nullptr) {\n\t\tpeer_subject = format_subject_name(cert.get());\n\t\tpeer_issuer_subject = format_issuer_subject_name(cert.get());\n\t}\n}\n\nenum class SslDecryptResult {\n\tSUCCESS,\n\n\t\/**\n\t * More encrypted_input data is required.\n\t *\/\n\tMORE,\n\n\tCLOSE_NOTIFY_ALERT,\n};\n\nstatic SslDecryptResult\nssl_decrypt(SSL *ssl, ForeignFifoBuffer &buffer)\n{\n\t\/* SSL_read() must be called repeatedly until there is no more\n\t data (or until the buffer is full) *\/\n\n\twhile (true) {\n\t\tauto w = buffer.Write();\n\t\tif (w.empty())\n\t\t\treturn SslDecryptResult::SUCCESS;\n\n\t\tint result = SSL_read(ssl, w.data(), w.size());\n\t\tif (result < 0 && SSL_get_error(ssl, result) == SSL_ERROR_WANT_READ)\n\t\t\treturn SslDecryptResult::MORE;\n\n\t\tif (result <= 0) {\n\t\t\tif (SSL_get_error(ssl, result) == SSL_ERROR_ZERO_RETURN)\n\t\t\t\t\/* got a \"close notify\" alert from the peer *\/\n\t\t\t\treturn SslDecryptResult::CLOSE_NOTIFY_ALERT;\n\n\t\t\tCheckThrowSslError(ssl, result);\n\t\t\treturn SslDecryptResult::SUCCESS;\n\t\t}\n\n\t\tbuffer.Append(result);\n\t}\n}\n\nstatic void\nssl_encrypt(SSL *ssl, ForeignFifoBuffer &buffer)\n{\n\t\/* SSL_write() must be called repeatedly until there is no more\n\t data; with SSL_MODE_ENABLE_PARTIAL_WRITE, SSL_write() finishes\n\t only the current incomplete record, and additional data which\n\t has been submitted more recently will only be considered in the\n\t next SSL_write() call *\/\n\n\twhile (true) {\n\t\tauto r = buffer.Read();\n\t\tif (r.empty())\n\t\t\treturn;\n\n\t\tint result = SSL_write(ssl, r.data(), r.size());\n\t\tif (result <= 0) {\n\t\t\tCheckThrowSslError(ssl, result);\n\t\t\treturn;\n\t\t}\n\n\t\tbuffer.Consume(result);\n\t}\n}\n\ninline void\nSslFilter::Encrypt()\n{\n\tssl_encrypt(ssl.get(), plain_output);\n}\n\n\/*\n * thread_socket_filter_handler\n *\n *\/\n\nvoid\nSslFilter::PreRun(ThreadSocketFilterInternal &f) noexcept\n{\n\tif (f.IsIdle()) {\n\t\tdecrypted_input.AllocateIfNull(fb_pool_get());\n\t\tencrypted_output.AllocateIfNull(fb_pool_get());\n\t}\n}\n\nvoid\nSslFilter::Run(ThreadSocketFilterInternal &f)\n{\n\t\/* copy input (and output to make room for more output) *\/\n\n\t{\n\t\tstd::unique_lock lock(f.mutex);\n\n\t\tif (f.decrypted_input.IsNull() || f.encrypted_output.IsNull()) {\n\t\t\t\/* retry, let PreRun() allocate the missing buffer *\/\n\t\t\tf.again = true;\n\t\t\treturn;\n\t\t}\n\n\t\tf.decrypted_input.MoveFromAllowNull(decrypted_input);\n\n\t\tplain_output.MoveFromAllowNull(f.plain_output);\n\t\tencrypted_input.MoveFromAllowSrcNull(f.encrypted_input);\n\n\t\tf.encrypted_output.MoveFromAllowNull(encrypted_output);\n\n\t\tif (decrypted_input.IsNull() || encrypted_output.IsNull()) {\n\t\t\t\/* retry, let PreRun() allocate the missing buffer *\/\n\t\t\tf.again = true;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/* let OpenSSL work *\/\n\n\tERR_clear_error();\n\n\tif (handshaking) [[unlikely]] {\n\t\tint result = SSL_do_handshake(ssl.get());\n\t\tif (result == 1) {\n\t\t\thandshaking = false;\n\t\t\tPostHandshake();\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tCheckThrowSslError(ssl.get(), result);\n\t\t\t\t\/* flush the encrypted_output buffer, because it may\n\t\t\t\t contain a \"TLS alert\" *\/\n\t\t\t} catch (...) {\n\t\t\t\tconst std::lock_guard lock(f.mutex);\n\t\t\t\tf.encrypted_output.MoveFromAllowNull(encrypted_output);\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!handshaking) [[likely]] {\n\t\tEncrypt();\n\n\t\tswitch (ssl_decrypt(ssl.get(), decrypted_input)) {\n\t\tcase SslDecryptResult::SUCCESS:\n\t\t\tbreak;\n\n\t\tcase SslDecryptResult::MORE:\n\t\t\tif (encrypted_input.IsDefinedAndFull())\n\t\t\t\tthrow std::runtime_error(\"SSL encrypted_input buffer is full\");\n\n\t\t\tbreak;\n\n\t\tcase SslDecryptResult::CLOSE_NOTIFY_ALERT:\n\t\t\t{\n\t\t\t\tstd::unique_lock lock(f.mutex);\n\t\t\t\tf.input_eof = true;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/* copy output *\/\n\n\t{\n\t\tstd::unique_lock lock(f.mutex);\n\n\t\tf.decrypted_input.MoveFromAllowNull(decrypted_input);\n\t\tf.encrypted_output.MoveFromAllowNull(encrypted_output);\n\t\tf.drained = plain_output.empty() && encrypted_output.empty();\n\n\t\tif (!decrypted_input.IsDefinedAndFull() && !f.encrypted_input.empty())\n\t\t\t\/* there's more data to be decrypted and we\n\t\t\t still have room in the destination buffer,\n\t\t\t so let's run again *\/\n\t\t\tf.again = true;\n\n\t\tif (!f.plain_output.empty() && !plain_output.IsDefinedAndFull() &&\n\t\t !encrypted_output.IsDefinedAndFull())\n\t\t\t\/* there's more data, and we're ready to handle it: try\n\t\t\t again *\/\n\t\t\tf.again = true;\n\n\t\tf.handshaking = handshaking;\n\t}\n}\n\nvoid\nSslFilter::PostRun(ThreadSocketFilterInternal &f) noexcept\n{\n\tif (f.IsIdle()) {\n\t\tplain_output.FreeIfEmpty();\n\t\tencrypted_input.FreeIfEmpty();\n\t\tdecrypted_input.FreeIfEmpty();\n\t\tencrypted_output.FreeIfEmpty();\n\t}\n}\n\nvoid\nSslFilter::CancelRun(ThreadSocketFilterInternal &) noexcept\n{\n\tif (cancel_ptr)\n\t\t\/* cancel the CertCache::Apply() call *\/\n\t\tcancel_ptr.Cancel();\n}\n\n\/*\n * constructor\n *\n *\/\n\nstd::unique_ptr\nssl_filter_new(UniqueSSL &&ssl) noexcept\n{\n\treturn std::make_unique(std::move(ssl));\n}\n\nSslFilter &\nssl_filter_cast_from(ThreadSocketFilterHandler &tsfh) noexcept\n{\n\treturn static_cast(tsfh);\n}\n\nconst SslFilter *\nssl_filter_cast_from(const SocketFilter *socket_filter) noexcept\n{\n\tconst auto *tsf = dynamic_cast(socket_filter);\n\tif (tsf == nullptr)\n\t\treturn nullptr;\n\n\treturn dynamic_cast(&tsf->GetHandler());\n}\n\nstd::span\nssl_filter_get_alpn_selected(const SslFilter &ssl) noexcept\n{\n\treturn ssl.GetAlpnSelected();\n}\n\nconst char *\nssl_filter_get_peer_subject(const SslFilter &ssl) noexcept\n{\n\treturn ssl.peer_subject.c_str();\n}\n\nconst char *\nssl_filter_get_peer_issuer_subject(const SslFilter &ssl) noexcept\n{\n\treturn ssl.peer_issuer_subject.c_str();\n}\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#include \n#include \n\n#include \"Model.hpp\"\n\ntypedef void (Implementation::Model::*OneArgMethod) (\n const Abstract::Point& coordinates\n);\n\ntypedef void (Implementation::Model::*TwoArgsMethod) (\n const Abstract::Point& coordinates,\n int change\n);\n\ntypedef void (Implementation::Model::*MultiArgsMethod) (\n const Abstract::Point& coordinates,\n int mass,\n int direction,\n int team,\n int instruction\n);\n\ntemplate\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n Func model_method,\n int arg1,\n int arg2\n) {\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(arg1, arg2), Exception\n );\n}\n\ntemplate<>\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n OneArgMethod model_method,\n int arg1,\n int arg2\n) {\n Abstract::Point coordinates(arg1, arg2);\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(coordinates), Exception\n );\n}\n\ntemplate<>\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n TwoArgsMethod model_method,\n int arg1,\n int arg2\n) {\n Abstract::Point coordinates(arg1, arg2);\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(coordinates, 0), Exception\n );\n}\n\ntemplate<>\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n MultiArgsMethod model_method,\n int arg1,\n int arg2\n) {\n Abstract::Point coordinates(arg1, arg2);\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(\n coordinates,\n DEFAULT_MASS,\n 0,\n 0,\n 0\n ),\n Exception\n );\n}\n\n\/\/ \"dead\" test: attempt to do something with dead bacterium\ntemplate\nstatic void deadTest(\n Implementation::Model* model,\n Func model_method\n) {\n model->kill(0, 0);\n checkModelMethodForThrow(\n model,\n model_method,\n 0,\n 0\n );\n}\n\ntemplate\nstatic void checkErrorHandling(\n Implementation::Model* model,\n Func model_method,\n bool dead_test\n) {\n \/\/ Range errors: test all combinations of\n \/\/ \"wrong\" (outside of correct range) arguments.\n \/\/ This solution works for coordinates and non-coordinates\n \/\/ methods of Model. (< 0, = 0, > MAX)\n int wrong_args[] = {-1, 0, MIN_WIDTH};\n BOOST_FOREACH (int arg1, wrong_args) {\n BOOST_FOREACH (int arg2, wrong_args) {\n if ((arg1 != 0) || (arg2 != 0)) {\n \/\/ (0, 0) is correct\n checkModelMethodForThrow(\n model,\n model_method,\n arg1,\n arg2\n );\n }\n }\n }\n if (dead_test) {\n \/\/ \"dead\" error\n \/\/ (attempt to do something with dead bacterium)\n deadTest(model, model_method);\n }\n}\n\nstatic Abstract::Point createInBaseCoordinates(\n Implementation::Model* model\n) {\n Abstract::Point coordinates(0, 0);\n model->createNewByCoordinates(\n coordinates,\n DEFAULT_MASS,\n 0,\n 0,\n 0\n );\n return coordinates;\n}\n\nstatic Implementation::Model* createBaseModel(\n int bacteria = 0,\n int teams = 1\n) {\n Implementation::Model* model =\n Abstract::makeModel(\n MIN_WIDTH,\n MIN_HEIGHT,\n bacteria,\n teams\n );\n return model;\n}\n\nBOOST_AUTO_TEST_CASE (bacteria_number_test) {\n Implementation::Model* model = createBaseModel();\n int bacteria_number = model->getBacteriaNumber(0);\n BOOST_REQUIRE(bacteria_number == 0);\n createInBaseCoordinates(model);\n bacteria_number = model->getBacteriaNumber(0);\n BOOST_REQUIRE(bacteria_number == 1);\n \/\/ range errors\n BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);\n BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_instruction_test) {\n Implementation::Model* model = createBaseModel(1, 1);\n int instruction = model->getInstruction(0, 0);\n BOOST_REQUIRE(instruction == 0);\n checkErrorHandling(\n model,\n &Implementation::Model::getInstruction,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n Abstract::Point derived_coordinates = model->getCoordinates(0, 0);\n BOOST_REQUIRE(derived_coordinates == coordinates);\n checkErrorHandling(\n model,\n &Implementation::Model::getCoordinates,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_direction_test) {\n Implementation::Model* model = createBaseModel();\n createInBaseCoordinates(model);\n int direction = model->getDirection(0, 0);\n BOOST_REQUIRE(direction == Abstract::LEFT);\n checkErrorHandling(\n model,\n &Implementation::Model::getDirection,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_mass_test) {\n Implementation::Model* model = createBaseModel(1, 1);\n int mass = model->getMass(0, 0);\n BOOST_REQUIRE(mass == DEFAULT_MASS);\n checkErrorHandling(\n model,\n &Implementation::Model::getMass,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (height_test) {\n Implementation::Model* model = createBaseModel();\n BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (width_test) {\n Implementation::Model* model = createBaseModel();\n BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (kill_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n model->kill(0, 0);\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::EMPTY);\n \/\/ error handling checks\n createInBaseCoordinates(model);\n \/\/ FIXME test doesn't work correctly without this function call.\n \/\/ The solution is to use set instead of vector in model.\n model->clearBeforeMove(0);\n checkErrorHandling(\n model,\n &Implementation::Model::kill,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (create_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::BACTERIUM);\n checkErrorHandling(\n model,\n &Implementation::Model::createNewByCoordinates,\n false\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n int test_val = 1;\n model->changeMassByCoordinates(coordinates, test_val);\n int new_mass = model->getMassByCoordinates(coordinates);\n BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));\n model->changeMassByCoordinates(coordinates, -test_val);\n new_mass = model->getMassByCoordinates(coordinates);\n BOOST_REQUIRE(new_mass == DEFAULT_MASS);\n checkErrorHandling(\n model,\n &Implementation::Model::changeMassByCoordinates,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (kill_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n model->killByCoordinates(coordinates);\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::EMPTY);\n checkErrorHandling(\n model,\n &Implementation::Model::killByCoordinates,\n false\n );\n delete model;\n}\nModel tests: add isAlive() check to kill_test\/*\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#include \n#include \n\n#include \"Model.hpp\"\n\ntypedef void (Implementation::Model::*OneArgMethod) (\n const Abstract::Point& coordinates\n);\n\ntypedef void (Implementation::Model::*TwoArgsMethod) (\n const Abstract::Point& coordinates,\n int change\n);\n\ntypedef void (Implementation::Model::*MultiArgsMethod) (\n const Abstract::Point& coordinates,\n int mass,\n int direction,\n int team,\n int instruction\n);\n\ntemplate\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n Func model_method,\n int arg1,\n int arg2\n) {\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(arg1, arg2), Exception\n );\n}\n\ntemplate<>\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n OneArgMethod model_method,\n int arg1,\n int arg2\n) {\n Abstract::Point coordinates(arg1, arg2);\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(coordinates), Exception\n );\n}\n\ntemplate<>\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n TwoArgsMethod model_method,\n int arg1,\n int arg2\n) {\n Abstract::Point coordinates(arg1, arg2);\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(coordinates, 0), Exception\n );\n}\n\ntemplate<>\nvoid checkModelMethodForThrow(\n Implementation::Model* model,\n MultiArgsMethod model_method,\n int arg1,\n int arg2\n) {\n Abstract::Point coordinates(arg1, arg2);\n BOOST_REQUIRE_THROW(\n ((*model).*model_method)(\n coordinates,\n DEFAULT_MASS,\n 0,\n 0,\n 0\n ),\n Exception\n );\n}\n\n\/\/ \"dead\" test: attempt to do something with dead bacterium\ntemplate\nstatic void deadTest(\n Implementation::Model* model,\n Func model_method\n) {\n model->kill(0, 0);\n checkModelMethodForThrow(\n model,\n model_method,\n 0,\n 0\n );\n}\n\ntemplate\nstatic void checkErrorHandling(\n Implementation::Model* model,\n Func model_method,\n bool dead_test\n) {\n \/\/ Range errors: test all combinations of\n \/\/ \"wrong\" (outside of correct range) arguments.\n \/\/ This solution works for coordinates and non-coordinates\n \/\/ methods of Model. (< 0, = 0, > MAX)\n int wrong_args[] = {-1, 0, MIN_WIDTH};\n BOOST_FOREACH (int arg1, wrong_args) {\n BOOST_FOREACH (int arg2, wrong_args) {\n if ((arg1 != 0) || (arg2 != 0)) {\n \/\/ (0, 0) is correct\n checkModelMethodForThrow(\n model,\n model_method,\n arg1,\n arg2\n );\n }\n }\n }\n if (dead_test) {\n \/\/ \"dead\" error\n \/\/ (attempt to do something with dead bacterium)\n deadTest(model, model_method);\n }\n}\n\nstatic Abstract::Point createInBaseCoordinates(\n Implementation::Model* model\n) {\n Abstract::Point coordinates(0, 0);\n model->createNewByCoordinates(\n coordinates,\n DEFAULT_MASS,\n 0,\n 0,\n 0\n );\n return coordinates;\n}\n\nstatic Implementation::Model* createBaseModel(\n int bacteria = 0,\n int teams = 1\n) {\n Implementation::Model* model =\n Abstract::makeModel(\n MIN_WIDTH,\n MIN_HEIGHT,\n bacteria,\n teams\n );\n return model;\n}\n\nBOOST_AUTO_TEST_CASE (bacteria_number_test) {\n Implementation::Model* model = createBaseModel();\n int bacteria_number = model->getBacteriaNumber(0);\n BOOST_REQUIRE(bacteria_number == 0);\n createInBaseCoordinates(model);\n bacteria_number = model->getBacteriaNumber(0);\n BOOST_REQUIRE(bacteria_number == 1);\n \/\/ range errors\n BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);\n BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_instruction_test) {\n Implementation::Model* model = createBaseModel(1, 1);\n int instruction = model->getInstruction(0, 0);\n BOOST_REQUIRE(instruction == 0);\n checkErrorHandling(\n model,\n &Implementation::Model::getInstruction,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n Abstract::Point derived_coordinates = model->getCoordinates(0, 0);\n BOOST_REQUIRE(derived_coordinates == coordinates);\n checkErrorHandling(\n model,\n &Implementation::Model::getCoordinates,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_direction_test) {\n Implementation::Model* model = createBaseModel();\n createInBaseCoordinates(model);\n int direction = model->getDirection(0, 0);\n BOOST_REQUIRE(direction == Abstract::LEFT);\n checkErrorHandling(\n model,\n &Implementation::Model::getDirection,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (get_mass_test) {\n Implementation::Model* model = createBaseModel(1, 1);\n int mass = model->getMass(0, 0);\n BOOST_REQUIRE(mass == DEFAULT_MASS);\n checkErrorHandling(\n model,\n &Implementation::Model::getMass,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (height_test) {\n Implementation::Model* model = createBaseModel();\n BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (width_test) {\n Implementation::Model* model = createBaseModel();\n BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (kill_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n model->kill(0, 0);\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::EMPTY);\n BOOST_REQUIRE(model->isAlive(0, 0) == false);\n \/\/ error handling checks\n createInBaseCoordinates(model);\n \/\/ FIXME test doesn't work correctly without this function call.\n \/\/ The solution is to use set instead of vector in model.\n model->clearBeforeMove(0);\n checkErrorHandling(\n model,\n &Implementation::Model::kill,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (create_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::BACTERIUM);\n checkErrorHandling(\n model,\n &Implementation::Model::createNewByCoordinates,\n false\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n int test_val = 1;\n model->changeMassByCoordinates(coordinates, test_val);\n int new_mass = model->getMassByCoordinates(coordinates);\n BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));\n model->changeMassByCoordinates(coordinates, -test_val);\n new_mass = model->getMassByCoordinates(coordinates);\n BOOST_REQUIRE(new_mass == DEFAULT_MASS);\n checkErrorHandling(\n model,\n &Implementation::Model::changeMassByCoordinates,\n true\n );\n delete model;\n}\n\nBOOST_AUTO_TEST_CASE (kill_coordinates_test) {\n Implementation::Model* model = createBaseModel();\n Abstract::Point coordinates = createInBaseCoordinates(model);\n model->killByCoordinates(coordinates);\n Abstract::CellState state = model->cellState(coordinates);\n BOOST_REQUIRE(state == Abstract::EMPTY);\n checkErrorHandling(\n model,\n &Implementation::Model::killByCoordinates,\n false\n );\n delete model;\n}\n<|endoftext|>"} {"text":"\/*\n * This file is part of WinSparkle (http:\/\/winsparkle.org)\n *\n * Copyright (C) 2009 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 \"threads.h\"\n#include \"error.h\"\n\n#include \n#include \n\nnamespace winsparkle\n{\n\n\/*--------------------------------------------------------------------------*\n Helpers\n *--------------------------------------------------------------------------*\/\n\nnamespace\n{\n\n\/\/ Sets thread's name for the debugger\nvoid SetThreadName(DWORD threadId, const char *name)\n{\n#ifdef _MSC_VER\n \/\/ This code is copied verbatim from MSDN, see\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/xcb2z8hs%28VS.100%29.aspx\n\n #define MS_VC_EXCEPTION 0x406D1388\n\n #pragma pack(push,8)\n typedef struct tagTHREADNAME_INFO\n {\n DWORD dwType; \/\/ Must be 0x1000.\n LPCSTR szName; \/\/ Pointer to name (in user addr space).\n DWORD dwThreadID; \/\/ Thread ID (-1=caller thread).\n DWORD dwFlags; \/\/ Reserved for future use, must be zero.\n } THREADNAME_INFO;\n #pragma pack(pop)\n\n Sleep(10);\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = name;\n info.dwThreadID = threadId;\n info.dwFlags = 0;\n\n __try\n {\n RaiseException\n (\n MS_VC_EXCEPTION,\n 0,\n sizeof(info) \/ sizeof(ULONG_PTR),\n (ULONG_PTR*)&info\n );\n }\n __except(EXCEPTION_EXECUTE_HANDLER)\n {\n }\n#endif \/\/ _MSC_VER\n}\n\n} \/\/ anonymous namespace\n\n\n\/*--------------------------------------------------------------------------*\n Thread class\n *--------------------------------------------------------------------------*\/\n\nThread::Thread(const char *name)\n : m_handle(NULL), m_id(0), m_signalEvent(NULL)\n{\n m_handle = (HANDLE)_beginthreadex\n (\n NULL, \/\/ default security\n 0, \/\/ default stack size\n &Thread::ThreadEntryPoint,\n this, \/\/ arguments\n CREATE_SUSPENDED,\n &m_id \/\/ thread ID\n );\n\n if ( !m_handle )\n throw Win32Exception();\n}\n\n\nThread::~Thread()\n{\n if ( m_handle )\n CloseHandle(m_handle);\n}\n\n\n\/*static*\/ unsigned __stdcall Thread::ThreadEntryPoint(void *data)\n{\n Thread *thread = reinterpret_cast(data);\n thread->Run();\n\n if ( !thread->IsJoinable() )\n delete thread;\n\n\treturn 0;\n}\n\n\nvoid Thread::Start()\n{\n if ( !m_handle )\n throw Win32Exception();\n\n m_signalEvent = CreateEvent\n (\n NULL, \/\/ default security attributes\n FALSE, \/\/ auto-reset\n FALSE, \/\/ initially non-signaled\n NULL \/\/ anonymous\n );\n if ( !m_signalEvent )\n throw Win32Exception();\n\n if ( ResumeThread(m_handle) == (DWORD)-1 )\n {\n CloseHandle(m_signalEvent);\n m_signalEvent = NULL;\n throw Win32Exception();\n }\n\n \/\/ Wait until Run() signals that it is fully initialized.\n WaitForSingleObject(m_signalEvent, INFINITE);\n CloseHandle(m_signalEvent);\n m_signalEvent = NULL;\n}\n\n\nvoid Thread::SignalReady()\n{\n SetEvent(m_signalEvent);\n}\n\n} \/\/ namespace winsparkle\nForgot to actually set thread's name in ctor.\/*\n * This file is part of WinSparkle (http:\/\/winsparkle.org)\n *\n * Copyright (C) 2009 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 \"threads.h\"\n#include \"error.h\"\n\n#include \n#include \n\nnamespace winsparkle\n{\n\n\/*--------------------------------------------------------------------------*\n Helpers\n *--------------------------------------------------------------------------*\/\n\nnamespace\n{\n\n\/\/ Sets thread's name for the debugger\nvoid SetThreadName(DWORD threadId, const char *name)\n{\n#ifdef _MSC_VER\n \/\/ This code is copied verbatim from MSDN, see\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/xcb2z8hs%28VS.100%29.aspx\n\n #define MS_VC_EXCEPTION 0x406D1388\n\n #pragma pack(push,8)\n typedef struct tagTHREADNAME_INFO\n {\n DWORD dwType; \/\/ Must be 0x1000.\n LPCSTR szName; \/\/ Pointer to name (in user addr space).\n DWORD dwThreadID; \/\/ Thread ID (-1=caller thread).\n DWORD dwFlags; \/\/ Reserved for future use, must be zero.\n } THREADNAME_INFO;\n #pragma pack(pop)\n\n Sleep(10);\n THREADNAME_INFO info;\n info.dwType = 0x1000;\n info.szName = name;\n info.dwThreadID = threadId;\n info.dwFlags = 0;\n\n __try\n {\n RaiseException\n (\n MS_VC_EXCEPTION,\n 0,\n sizeof(info) \/ sizeof(ULONG_PTR),\n (ULONG_PTR*)&info\n );\n }\n __except(EXCEPTION_EXECUTE_HANDLER)\n {\n }\n#endif \/\/ _MSC_VER\n}\n\n} \/\/ anonymous namespace\n\n\n\/*--------------------------------------------------------------------------*\n Thread class\n *--------------------------------------------------------------------------*\/\n\nThread::Thread(const char *name)\n : m_handle(NULL), m_id(0), m_signalEvent(NULL)\n{\n m_handle = (HANDLE)_beginthreadex\n (\n NULL, \/\/ default security\n 0, \/\/ default stack size\n &Thread::ThreadEntryPoint,\n this, \/\/ arguments\n CREATE_SUSPENDED,\n &m_id \/\/ thread ID\n );\n\n if ( !m_handle )\n throw Win32Exception();\n\n SetThreadName(m_id, name);\n}\n\n\nThread::~Thread()\n{\n if ( m_handle )\n CloseHandle(m_handle);\n}\n\n\n\/*static*\/ unsigned __stdcall Thread::ThreadEntryPoint(void *data)\n{\n Thread *thread = reinterpret_cast(data);\n thread->Run();\n\n if ( !thread->IsJoinable() )\n delete thread;\n\n\treturn 0;\n}\n\n\nvoid Thread::Start()\n{\n if ( !m_handle )\n throw Win32Exception();\n\n m_signalEvent = CreateEvent\n (\n NULL, \/\/ default security attributes\n FALSE, \/\/ auto-reset\n FALSE, \/\/ initially non-signaled\n NULL \/\/ anonymous\n );\n if ( !m_signalEvent )\n throw Win32Exception();\n\n if ( ResumeThread(m_handle) == (DWORD)-1 )\n {\n CloseHandle(m_signalEvent);\n m_signalEvent = NULL;\n throw Win32Exception();\n }\n\n \/\/ Wait until Run() signals that it is fully initialized.\n WaitForSingleObject(m_signalEvent, INFINITE);\n CloseHandle(m_signalEvent);\n m_signalEvent = NULL;\n}\n\n\nvoid Thread::SignalReady()\n{\n SetEvent(m_signalEvent);\n}\n\n} \/\/ namespace winsparkle\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"QtAwesome.h\"\n#include \"utils\/utils.h\"\n#include \"seafile-applet.h\"\n#include \"rpc\/rpc-client.h\"\n#include \"rpc\/local-repo.h\"\n#include \"download-repo-dialog.h\"\n#include \"clone-tasks-dialog.h\"\n#include \"cloud-view.h\"\n#include \"repo-item.h\"\n#include \"repo-item-delegate.h\"\n#include \"repo-tree-model.h\"\n#include \"repo-tree-view.h\"\n#include \"repo-detail-dialog.h\"\n\nRepoTreeView::RepoTreeView(CloudView *cloud_view, QWidget *parent)\n : QTreeView(parent),\n cloud_view_(cloud_view)\n{\n header()->hide();\n createActions();\n\n \/\/ We draw the indicator ourselves\n setIndentation(0);\n \/\/ We handle the click oursevles\n setExpandsOnDoubleClick(false);\n\n connect(this, SIGNAL(clicked(const QModelIndex&)),\n this, SLOT(onItemClicked(const QModelIndex&)));\n\n connect(this, SIGNAL(doubleClicked(const QModelIndex&)),\n this, SLOT(onItemDoubleClicked(const QModelIndex&)));\n}\n\nvoid RepoTreeView::contextMenuEvent(QContextMenuEvent *event)\n{\n QPoint pos = event->pos();\n QModelIndex index = indexAt(pos);\n if (!index.isValid()) {\n \/\/ Not clicked at a repo item\n return;\n }\n\n QStandardItem *item = getRepoItem(index);\n if (!item || item->type() != REPO_ITEM_TYPE) {\n return;\n }\n updateRepoActions();\n QMenu *menu = prepareContextMenu((RepoItem *)item);\n pos = viewport()->mapToGlobal(pos);\n menu->exec(pos);\n}\n\nQMenu* RepoTreeView::prepareContextMenu(const RepoItem *item)\n{\n QMenu *menu = new QMenu(this);\n if (item->localRepo().isValid()) {\n menu->addAction(open_local_folder_action_);\n }\n\n if (item->repoDownloadable()) {\n menu->addAction(download_action_);\n }\n\n menu->addAction(view_on_web_action_);\n\n if (item->localRepo().isValid()) {\n menu->addSeparator();\n menu->addAction(toggle_auto_sync_action_);\n menu->addAction(sync_now_action_);\n menu->addSeparator();\n }\n\n menu->addAction(show_detail_action_);\n\n if (item->cloneTask().isCancelable()) {\n menu->addAction(cancel_download_action_);\n }\n if (item->localRepo().isValid()) {\n menu->addAction(unsync_action_);\n }\n\n return menu;\n}\n\nvoid RepoTreeView::updateRepoActions()\n{\n RepoItem *item = NULL;\n QItemSelection selected = selectionModel()->selection();\n QModelIndexList indexes = selected.indexes();\n if (indexes.size() != 0) {\n const QModelIndex& index = indexes.at(0);\n QStandardItem *it = ((RepoTreeModel *)model())->itemFromIndex(index);\n if (it && it->type() == REPO_ITEM_TYPE) {\n item = (RepoItem *)it;\n }\n }\n\n if (!item) {\n \/\/ No repo item is selected\n download_action_->setEnabled(false);\n sync_now_action_->setEnabled(false);\n open_local_folder_action_->setEnabled(false);\n unsync_action_->setEnabled(false);\n toggle_auto_sync_action_->setEnabled(false);\n view_on_web_action_->setEnabled(false);\n show_detail_action_->setEnabled(false);\n return;\n }\n\n LocalRepo r;\n seafApplet->rpcClient()->getLocalRepo(item->repo().id, &r);\n item->setLocalRepo(r);\n\n if (item->localRepo().isValid()) {\n const LocalRepo& local_repo = item->localRepo();\n download_action_->setEnabled(false);\n\n sync_now_action_->setEnabled(true);\n sync_now_action_->setData(QVariant::fromValue(local_repo));\n\n open_local_folder_action_->setData(QVariant::fromValue(local_repo));\n open_local_folder_action_->setEnabled(true);\n\n unsync_action_->setData(QVariant::fromValue(local_repo));\n unsync_action_->setEnabled(true);\n\n toggle_auto_sync_action_->setData(QVariant::fromValue(local_repo));\n toggle_auto_sync_action_->setEnabled(true);\n if (local_repo.auto_sync) {\n toggle_auto_sync_action_->setText(tr(\"Disable auto sync\"));\n toggle_auto_sync_action_->setToolTip(tr(\"Disable auto sync\"));\n toggle_auto_sync_action_->setIcon(QIcon(\":\/images\/pause.png\"));\n } else {\n toggle_auto_sync_action_->setText(tr(\"Enable auto sync\"));\n toggle_auto_sync_action_->setToolTip(tr(\"Enable auto sync\"));\n toggle_auto_sync_action_->setIcon(QIcon(\":\/images\/play.png\"));\n }\n\n } else {\n if (item->repoDownloadable()) {\n download_action_->setEnabled(true);\n download_action_->setData(QVariant::fromValue(item->repo()));\n } else {\n download_action_->setEnabled(false);\n }\n\n sync_now_action_->setEnabled(false);\n\n open_local_folder_action_->setEnabled(false);\n unsync_action_->setEnabled(false);\n toggle_auto_sync_action_->setEnabled(false);\n }\n\n view_on_web_action_->setEnabled(true);\n view_on_web_action_->setData(item->repo().id);\n show_detail_action_->setEnabled(true);\n show_detail_action_->setData(QVariant::fromValue(item->repo()));\n\n if (item->cloneTask().isCancelable()) {\n cancel_download_action_->setEnabled(true);\n cancel_download_action_->setData(QVariant::fromValue(item->repo()));\n } else {\n cancel_download_action_->setEnabled(false);\n }\n}\n\nQStandardItem* RepoTreeView::getRepoItem(const QModelIndex &index) const\n{\n if (!index.isValid()) {\n return NULL;\n }\n const RepoTreeModel *model = (const RepoTreeModel*)index.model();\n QStandardItem *item = model->itemFromIndex(index);\n if (item->type() != REPO_ITEM_TYPE &&\n item->type() != REPO_CATEGORY_TYPE) {\n return NULL;\n }\n return item;\n}\n\nvoid RepoTreeView::createActions()\n{\n show_detail_action_ = new QAction(tr(\"&Show details\"), this);\n show_detail_action_->setIcon(QIcon(\":\/images\/info.png\"));\n show_detail_action_->setStatusTip(tr(\"Download this library\"));\n show_detail_action_->setIconVisibleInMenu(true);\n connect(show_detail_action_, SIGNAL(triggered()), this, SLOT(showRepoDetail()));\n\n download_action_ = new QAction(tr(\"&Download this library\"), this);\n download_action_->setIcon(QIcon(\":\/images\/download.png\"));\n download_action_->setStatusTip(tr(\"Download this library\"));\n download_action_->setIconVisibleInMenu(true);\n connect(download_action_, SIGNAL(triggered()), this, SLOT(downloadRepo()));\n\n sync_now_action_ = new QAction(tr(\"&Sync now\"), this);\n sync_now_action_->setIcon(QIcon(\":\/images\/sync_now.png\"));\n sync_now_action_->setStatusTip(tr(\"Sync this library immediately\"));\n sync_now_action_->setIconVisibleInMenu(true);\n connect(sync_now_action_, SIGNAL(triggered()), this, SLOT(syncRepoImmediately()));\n\n cancel_download_action_ = new QAction(tr(\"&Cancel download\"), this);\n cancel_download_action_->setIcon(QIcon(\":\/images\/remove.png\"));\n cancel_download_action_->setStatusTip(tr(\"Cancel download of this library\"));\n cancel_download_action_->setIconVisibleInMenu(true);\n connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(cancelDownload()));\n\n open_local_folder_action_ = new QAction(tr(\"&Open folder\"), this);\n open_local_folder_action_->setIcon(QIcon(\":\/images\/folder-open.png\"));\n open_local_folder_action_->setStatusTip(tr(\"open local folder\"));\n open_local_folder_action_->setIconVisibleInMenu(true);\n connect(open_local_folder_action_, SIGNAL(triggered()), this, SLOT(openLocalFolder()));\n\n unsync_action_ = new QAction(tr(\"&Unsync\"), this);\n unsync_action_->setStatusTip(tr(\"unsync this library\"));\n unsync_action_->setIcon(QIcon(\":\/images\/minus.png\"));\n unsync_action_->setIconVisibleInMenu(true);\n connect(unsync_action_, SIGNAL(triggered()), this, SLOT(unsyncRepo()));\n\n toggle_auto_sync_action_ = new QAction(tr(\"Enable auto sync\"), this);\n toggle_auto_sync_action_->setStatusTip(tr(\"Enable auto sync\"));\n toggle_auto_sync_action_->setIconVisibleInMenu(true);\n connect(toggle_auto_sync_action_, SIGNAL(triggered()), this, SLOT(toggleRepoAutoSync()));\n\n view_on_web_action_ = new QAction(tr(\"&View on cloud\"), this);\n view_on_web_action_->setIcon(QIcon(\":\/images\/cloud.png\"));\n view_on_web_action_->setStatusTip(tr(\"view this library on seahub\"));\n view_on_web_action_->setIconVisibleInMenu(true);\n\n connect(view_on_web_action_, SIGNAL(triggered()), this, SLOT(viewRepoOnWeb()));\n}\n\nvoid RepoTreeView::downloadRepo()\n{\n ServerRepo repo = qvariant_cast(download_action_->data());\n DownloadRepoDialog dialog(cloud_view_->currentAccount(), repo, this);\n\n updateRepoActions();\n}\n\nvoid RepoTreeView::showRepoDetail()\n{\n ServerRepo repo = qvariant_cast(show_detail_action_->data());\n RepoDetailDialog dialog(repo, this);\n dialog.exec();\n}\n\nvoid RepoTreeView::openLocalFolder()\n{\n LocalRepo repo = qvariant_cast(open_local_folder_action_->data());\n QDesktopServices::openUrl(QUrl::fromLocalFile(repo.worktree));\n}\n\nvoid RepoTreeView::toggleRepoAutoSync()\n{\n LocalRepo repo = qvariant_cast(toggle_auto_sync_action_->data());\n\n seafApplet->rpcClient()->setRepoAutoSync(repo.id, !repo.auto_sync);\n\n updateRepoActions();\n}\n\nvoid RepoTreeView::unsyncRepo()\n{\n LocalRepo repo = qvariant_cast(toggle_auto_sync_action_->data());\n\n QString question = tr(\"Are you sure to unsync library \\\"%1\\\"?\").arg(repo.name);\n\n if (QMessageBox::question(this,\n tr(SEAFILE_CLIENT_BRAND),\n question,\n QMessageBox::Ok | QMessageBox::Cancel,\n QMessageBox::Cancel) != QMessageBox::Ok) {\n return;\n }\n\n if (seafApplet->rpcClient()->unsync(repo.id) < 0) {\n QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),\n tr(\"Failed to unsync library \\\"%1\\\"\").arg(repo.name),\n QMessageBox::Ok);\n }\n\n updateRepoActions();\n}\n\nvoid RepoTreeView::onItemClicked(const QModelIndex& index)\n{\n QStandardItem *item = getRepoItem(index);\n if (!item) {\n return;\n }\n if (item->type() == REPO_ITEM_TYPE) {\n return;\n } else {\n \/\/ A repo category item\n if (isExpanded(index)) {\n collapse(index);\n } else {\n expand(index);\n }\n }\n}\n\nvoid RepoTreeView::onItemDoubleClicked(const QModelIndex& index)\n{\n QStandardItem *item = getRepoItem(index);\n if (!item) {\n return;\n }\n if (item->type() == REPO_ITEM_TYPE) {\n RepoItem *it = (RepoItem *)item;\n const LocalRepo& local_repo = it->localRepo();\n if (local_repo.isValid()) {\n QDesktopServices::openUrl(QUrl::fromLocalFile(local_repo.worktree));\n }\n }\n}\n\nvoid RepoTreeView::viewRepoOnWeb()\n{\n QString repo_id = view_on_web_action_->data().toString();\n const Account& account = cloud_view_->currentAccount();\n if (account.isValid()) {\n QUrl url = account.serverUrl;\n url.setPath(url.path() + \"\/repo\/\" + repo_id);\n QDesktopServices::openUrl(url);\n }\n}\n\nbool RepoTreeView::viewportEvent(QEvent *event)\n{\n if (event->type() != QEvent::ToolTip && event->type() != QEvent::WhatsThis) {\n return QTreeView::viewportEvent(event);\n }\n\n QPoint global_pos = QCursor::pos();\n QPoint viewport_pos = viewport()->mapFromGlobal(global_pos);\n QModelIndex index = indexAt(viewport_pos);\n if (!index.isValid()) {\n return true;\n }\n\n QStandardItem *item = getRepoItem(index);\n if (!item) {\n return true;\n }\n\n QRect item_rect = visualRect(index);\n if (item->type() == REPO_ITEM_TYPE) {\n showRepoItemToolTip((RepoItem *)item, global_pos, item_rect);\n } else {\n showRepoCategoryItemToolTip((RepoCategoryItem *)item, global_pos, item_rect);\n }\n\n return true;\n}\n\nvoid RepoTreeView::showRepoItemToolTip(const RepoItem *item,\n const QPoint& pos,\n const QRect& rect)\n{\n RepoItemDelegate *delegate = (RepoItemDelegate *)itemDelegate();\n delegate->showRepoItemToolTip(item, pos, viewport(), rect);\n}\n\nvoid RepoTreeView::showRepoCategoryItemToolTip(const RepoCategoryItem *item,\n const QPoint& pos,\n const QRect& rect)\n{\n QToolTip::showText(pos, item->name(), viewport(), rect);\n \/\/ QToolTip::showText(pos, item->name());\n}\n\nstd::vector RepoTreeView::getToolBarActions()\n{\n std::vector actions;\n\n actions.push_back(download_action_);\n actions.push_back(open_local_folder_action_);\n actions.push_back(view_on_web_action_);\n actions.push_back(show_detail_action_);\n return actions;\n}\n\nvoid RepoTreeView::selectionChanged(const QItemSelection &selected,\n const QItemSelection &deselected)\n{\n updateRepoActions();\n}\n\nvoid RepoTreeView::hideEvent(QHideEvent *event)\n{\n download_action_->setEnabled(false);\n open_local_folder_action_->setEnabled(false);\n unsync_action_->setEnabled(false);\n toggle_auto_sync_action_->setEnabled(false);\n view_on_web_action_->setEnabled(false);\n show_detail_action_->setEnabled(false);\n}\n\nvoid RepoTreeView::showEvent(QShowEvent *event)\n{\n updateRepoActions();\n}\n\nvoid RepoTreeView::syncRepoImmediately()\n{\n LocalRepo repo = qvariant_cast(sync_now_action_->data());\n\n seafApplet->rpcClient()->syncRepoImmediately(repo.id);\n}\n\nvoid RepoTreeView::cancelDownload()\n{\n ServerRepo repo = qvariant_cast(cancel_download_action_->data());\n\n QString error;\n if (seafApplet->rpcClient()->cancelCloneTask(repo.id, &error) < 0) {\n QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),\n tr(\"Failed to cancel this task:\\n\\n %1\").arg(error),\n QMessageBox::Ok);\n } else {\n QMessageBox::information(this, tr(SEAFILE_CLIENT_BRAND),\n tr(\"The download has been canceled\"),\n QMessageBox::Ok);\n }\n}\nfixed a bug#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"QtAwesome.h\"\n#include \"utils\/utils.h\"\n#include \"seafile-applet.h\"\n#include \"rpc\/rpc-client.h\"\n#include \"rpc\/local-repo.h\"\n#include \"download-repo-dialog.h\"\n#include \"clone-tasks-dialog.h\"\n#include \"cloud-view.h\"\n#include \"repo-item.h\"\n#include \"repo-item-delegate.h\"\n#include \"repo-tree-model.h\"\n#include \"repo-tree-view.h\"\n#include \"repo-detail-dialog.h\"\n\nRepoTreeView::RepoTreeView(CloudView *cloud_view, QWidget *parent)\n : QTreeView(parent),\n cloud_view_(cloud_view)\n{\n header()->hide();\n createActions();\n\n \/\/ We draw the indicator ourselves\n setIndentation(0);\n \/\/ We handle the click oursevles\n setExpandsOnDoubleClick(false);\n\n connect(this, SIGNAL(clicked(const QModelIndex&)),\n this, SLOT(onItemClicked(const QModelIndex&)));\n\n connect(this, SIGNAL(doubleClicked(const QModelIndex&)),\n this, SLOT(onItemDoubleClicked(const QModelIndex&)));\n}\n\nvoid RepoTreeView::contextMenuEvent(QContextMenuEvent *event)\n{\n QPoint pos = event->pos();\n QModelIndex index = indexAt(pos);\n if (!index.isValid()) {\n \/\/ Not clicked at a repo item\n return;\n }\n\n QStandardItem *item = getRepoItem(index);\n if (!item || item->type() != REPO_ITEM_TYPE) {\n return;\n }\n updateRepoActions();\n QMenu *menu = prepareContextMenu((RepoItem *)item);\n pos = viewport()->mapToGlobal(pos);\n menu->exec(pos);\n}\n\nQMenu* RepoTreeView::prepareContextMenu(const RepoItem *item)\n{\n QMenu *menu = new QMenu(this);\n if (item->localRepo().isValid()) {\n menu->addAction(open_local_folder_action_);\n }\n\n if (item->repoDownloadable()) {\n menu->addAction(download_action_);\n }\n\n menu->addAction(view_on_web_action_);\n\n if (item->localRepo().isValid()) {\n menu->addSeparator();\n menu->addAction(toggle_auto_sync_action_);\n menu->addAction(sync_now_action_);\n menu->addSeparator();\n }\n\n menu->addAction(show_detail_action_);\n\n if (item->cloneTask().isCancelable()) {\n menu->addAction(cancel_download_action_);\n }\n if (item->localRepo().isValid()) {\n menu->addAction(unsync_action_);\n }\n\n return menu;\n}\n\nvoid RepoTreeView::updateRepoActions()\n{\n RepoItem *item = NULL;\n QItemSelection selected = selectionModel()->selection();\n QModelIndexList indexes = selected.indexes();\n if (indexes.size() != 0) {\n const QModelIndex& index = indexes.at(0);\n QStandardItem *it = ((RepoTreeModel *)model())->itemFromIndex(index);\n if (it && it->type() == REPO_ITEM_TYPE) {\n item = (RepoItem *)it;\n }\n }\n\n if (!item) {\n \/\/ No repo item is selected\n download_action_->setEnabled(false);\n sync_now_action_->setEnabled(false);\n open_local_folder_action_->setEnabled(false);\n unsync_action_->setEnabled(false);\n toggle_auto_sync_action_->setEnabled(false);\n view_on_web_action_->setEnabled(false);\n show_detail_action_->setEnabled(false);\n return;\n }\n\n LocalRepo r;\n seafApplet->rpcClient()->getLocalRepo(item->repo().id, &r);\n item->setLocalRepo(r);\n\n if (item->localRepo().isValid()) {\n const LocalRepo& local_repo = item->localRepo();\n download_action_->setEnabled(false);\n\n sync_now_action_->setEnabled(true);\n sync_now_action_->setData(QVariant::fromValue(local_repo));\n\n open_local_folder_action_->setData(QVariant::fromValue(local_repo));\n open_local_folder_action_->setEnabled(true);\n\n unsync_action_->setData(QVariant::fromValue(local_repo));\n unsync_action_->setEnabled(true);\n\n toggle_auto_sync_action_->setData(QVariant::fromValue(local_repo));\n toggle_auto_sync_action_->setEnabled(true);\n if (local_repo.auto_sync) {\n toggle_auto_sync_action_->setText(tr(\"Disable auto sync\"));\n toggle_auto_sync_action_->setToolTip(tr(\"Disable auto sync\"));\n toggle_auto_sync_action_->setIcon(QIcon(\":\/images\/pause.png\"));\n } else {\n toggle_auto_sync_action_->setText(tr(\"Enable auto sync\"));\n toggle_auto_sync_action_->setToolTip(tr(\"Enable auto sync\"));\n toggle_auto_sync_action_->setIcon(QIcon(\":\/images\/play.png\"));\n }\n\n } else {\n if (item->repoDownloadable()) {\n download_action_->setEnabled(true);\n download_action_->setData(QVariant::fromValue(item->repo()));\n } else {\n download_action_->setEnabled(false);\n }\n\n sync_now_action_->setEnabled(false);\n\n open_local_folder_action_->setEnabled(false);\n unsync_action_->setEnabled(false);\n toggle_auto_sync_action_->setEnabled(false);\n }\n\n view_on_web_action_->setEnabled(true);\n view_on_web_action_->setData(item->repo().id);\n show_detail_action_->setEnabled(true);\n show_detail_action_->setData(QVariant::fromValue(item->repo()));\n\n if (item->cloneTask().isCancelable()) {\n cancel_download_action_->setEnabled(true);\n cancel_download_action_->setData(QVariant::fromValue(item->repo()));\n } else {\n cancel_download_action_->setEnabled(false);\n }\n}\n\nQStandardItem* RepoTreeView::getRepoItem(const QModelIndex &index) const\n{\n if (!index.isValid()) {\n return NULL;\n }\n const RepoTreeModel *model = (const RepoTreeModel*)index.model();\n QStandardItem *item = model->itemFromIndex(index);\n if (item->type() != REPO_ITEM_TYPE &&\n item->type() != REPO_CATEGORY_TYPE) {\n return NULL;\n }\n return item;\n}\n\nvoid RepoTreeView::createActions()\n{\n show_detail_action_ = new QAction(tr(\"&Show details\"), this);\n show_detail_action_->setIcon(QIcon(\":\/images\/info.png\"));\n show_detail_action_->setStatusTip(tr(\"Download this library\"));\n show_detail_action_->setIconVisibleInMenu(true);\n connect(show_detail_action_, SIGNAL(triggered()), this, SLOT(showRepoDetail()));\n\n download_action_ = new QAction(tr(\"&Download this library\"), this);\n download_action_->setIcon(QIcon(\":\/images\/download.png\"));\n download_action_->setStatusTip(tr(\"Download this library\"));\n download_action_->setIconVisibleInMenu(true);\n connect(download_action_, SIGNAL(triggered()), this, SLOT(downloadRepo()));\n\n sync_now_action_ = new QAction(tr(\"&Sync now\"), this);\n sync_now_action_->setIcon(QIcon(\":\/images\/sync_now.png\"));\n sync_now_action_->setStatusTip(tr(\"Sync this library immediately\"));\n sync_now_action_->setIconVisibleInMenu(true);\n connect(sync_now_action_, SIGNAL(triggered()), this, SLOT(syncRepoImmediately()));\n\n cancel_download_action_ = new QAction(tr(\"&Cancel download\"), this);\n cancel_download_action_->setIcon(QIcon(\":\/images\/remove.png\"));\n cancel_download_action_->setStatusTip(tr(\"Cancel download of this library\"));\n cancel_download_action_->setIconVisibleInMenu(true);\n connect(cancel_download_action_, SIGNAL(triggered()), this, SLOT(cancelDownload()));\n\n open_local_folder_action_ = new QAction(tr(\"&Open folder\"), this);\n open_local_folder_action_->setIcon(QIcon(\":\/images\/folder-open.png\"));\n open_local_folder_action_->setStatusTip(tr(\"open local folder\"));\n open_local_folder_action_->setIconVisibleInMenu(true);\n connect(open_local_folder_action_, SIGNAL(triggered()), this, SLOT(openLocalFolder()));\n\n unsync_action_ = new QAction(tr(\"&Unsync\"), this);\n unsync_action_->setStatusTip(tr(\"unsync this library\"));\n unsync_action_->setIcon(QIcon(\":\/images\/minus.png\"));\n unsync_action_->setIconVisibleInMenu(true);\n connect(unsync_action_, SIGNAL(triggered()), this, SLOT(unsyncRepo()));\n\n toggle_auto_sync_action_ = new QAction(tr(\"Enable auto sync\"), this);\n toggle_auto_sync_action_->setStatusTip(tr(\"Enable auto sync\"));\n toggle_auto_sync_action_->setIconVisibleInMenu(true);\n connect(toggle_auto_sync_action_, SIGNAL(triggered()), this, SLOT(toggleRepoAutoSync()));\n\n view_on_web_action_ = new QAction(tr(\"&View on cloud\"), this);\n view_on_web_action_->setIcon(QIcon(\":\/images\/cloud.png\"));\n view_on_web_action_->setStatusTip(tr(\"view this library on seahub\"));\n view_on_web_action_->setIconVisibleInMenu(true);\n\n connect(view_on_web_action_, SIGNAL(triggered()), this, SLOT(viewRepoOnWeb()));\n}\n\nvoid RepoTreeView::downloadRepo()\n{\n ServerRepo repo = qvariant_cast(download_action_->data());\n DownloadRepoDialog dialog(cloud_view_->currentAccount(), repo, this);\n\n dialog.exec();\n\n updateRepoActions();\n}\n\nvoid RepoTreeView::showRepoDetail()\n{\n ServerRepo repo = qvariant_cast(show_detail_action_->data());\n RepoDetailDialog dialog(repo, this);\n dialog.exec();\n}\n\nvoid RepoTreeView::openLocalFolder()\n{\n LocalRepo repo = qvariant_cast(open_local_folder_action_->data());\n QDesktopServices::openUrl(QUrl::fromLocalFile(repo.worktree));\n}\n\nvoid RepoTreeView::toggleRepoAutoSync()\n{\n LocalRepo repo = qvariant_cast(toggle_auto_sync_action_->data());\n\n seafApplet->rpcClient()->setRepoAutoSync(repo.id, !repo.auto_sync);\n\n updateRepoActions();\n}\n\nvoid RepoTreeView::unsyncRepo()\n{\n LocalRepo repo = qvariant_cast(toggle_auto_sync_action_->data());\n\n QString question = tr(\"Are you sure to unsync library \\\"%1\\\"?\").arg(repo.name);\n\n if (QMessageBox::question(this,\n tr(SEAFILE_CLIENT_BRAND),\n question,\n QMessageBox::Ok | QMessageBox::Cancel,\n QMessageBox::Cancel) != QMessageBox::Ok) {\n return;\n }\n\n if (seafApplet->rpcClient()->unsync(repo.id) < 0) {\n QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),\n tr(\"Failed to unsync library \\\"%1\\\"\").arg(repo.name),\n QMessageBox::Ok);\n }\n\n updateRepoActions();\n}\n\nvoid RepoTreeView::onItemClicked(const QModelIndex& index)\n{\n QStandardItem *item = getRepoItem(index);\n if (!item) {\n return;\n }\n if (item->type() == REPO_ITEM_TYPE) {\n return;\n } else {\n \/\/ A repo category item\n if (isExpanded(index)) {\n collapse(index);\n } else {\n expand(index);\n }\n }\n}\n\nvoid RepoTreeView::onItemDoubleClicked(const QModelIndex& index)\n{\n QStandardItem *item = getRepoItem(index);\n if (!item) {\n return;\n }\n if (item->type() == REPO_ITEM_TYPE) {\n RepoItem *it = (RepoItem *)item;\n const LocalRepo& local_repo = it->localRepo();\n if (local_repo.isValid()) {\n QDesktopServices::openUrl(QUrl::fromLocalFile(local_repo.worktree));\n }\n }\n}\n\nvoid RepoTreeView::viewRepoOnWeb()\n{\n QString repo_id = view_on_web_action_->data().toString();\n const Account& account = cloud_view_->currentAccount();\n if (account.isValid()) {\n QUrl url = account.serverUrl;\n url.setPath(url.path() + \"\/repo\/\" + repo_id);\n QDesktopServices::openUrl(url);\n }\n}\n\nbool RepoTreeView::viewportEvent(QEvent *event)\n{\n if (event->type() != QEvent::ToolTip && event->type() != QEvent::WhatsThis) {\n return QTreeView::viewportEvent(event);\n }\n\n QPoint global_pos = QCursor::pos();\n QPoint viewport_pos = viewport()->mapFromGlobal(global_pos);\n QModelIndex index = indexAt(viewport_pos);\n if (!index.isValid()) {\n return true;\n }\n\n QStandardItem *item = getRepoItem(index);\n if (!item) {\n return true;\n }\n\n QRect item_rect = visualRect(index);\n if (item->type() == REPO_ITEM_TYPE) {\n showRepoItemToolTip((RepoItem *)item, global_pos, item_rect);\n } else {\n showRepoCategoryItemToolTip((RepoCategoryItem *)item, global_pos, item_rect);\n }\n\n return true;\n}\n\nvoid RepoTreeView::showRepoItemToolTip(const RepoItem *item,\n const QPoint& pos,\n const QRect& rect)\n{\n RepoItemDelegate *delegate = (RepoItemDelegate *)itemDelegate();\n delegate->showRepoItemToolTip(item, pos, viewport(), rect);\n}\n\nvoid RepoTreeView::showRepoCategoryItemToolTip(const RepoCategoryItem *item,\n const QPoint& pos,\n const QRect& rect)\n{\n QToolTip::showText(pos, item->name(), viewport(), rect);\n \/\/ QToolTip::showText(pos, item->name());\n}\n\nstd::vector RepoTreeView::getToolBarActions()\n{\n std::vector actions;\n\n actions.push_back(download_action_);\n actions.push_back(open_local_folder_action_);\n actions.push_back(view_on_web_action_);\n actions.push_back(show_detail_action_);\n return actions;\n}\n\nvoid RepoTreeView::selectionChanged(const QItemSelection &selected,\n const QItemSelection &deselected)\n{\n updateRepoActions();\n}\n\nvoid RepoTreeView::hideEvent(QHideEvent *event)\n{\n download_action_->setEnabled(false);\n open_local_folder_action_->setEnabled(false);\n unsync_action_->setEnabled(false);\n toggle_auto_sync_action_->setEnabled(false);\n view_on_web_action_->setEnabled(false);\n show_detail_action_->setEnabled(false);\n}\n\nvoid RepoTreeView::showEvent(QShowEvent *event)\n{\n updateRepoActions();\n}\n\nvoid RepoTreeView::syncRepoImmediately()\n{\n LocalRepo repo = qvariant_cast(sync_now_action_->data());\n\n seafApplet->rpcClient()->syncRepoImmediately(repo.id);\n}\n\nvoid RepoTreeView::cancelDownload()\n{\n ServerRepo repo = qvariant_cast(cancel_download_action_->data());\n\n QString error;\n if (seafApplet->rpcClient()->cancelCloneTask(repo.id, &error) < 0) {\n QMessageBox::warning(this, tr(SEAFILE_CLIENT_BRAND),\n tr(\"Failed to cancel this task:\\n\\n %1\").arg(error),\n QMessageBox::Ok);\n } else {\n QMessageBox::information(this, tr(SEAFILE_CLIENT_BRAND),\n tr(\"The download has been canceled\"),\n QMessageBox::Ok);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2010-2015 Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef TRIVIAL_ARRAY_HXX\n#define TRIVIAL_ARRAY_HXX\n\n#include \n#include \n\n#include \n\n\/**\n * An array with a maximum size known at compile time. It keeps track\n * of the actual length at runtime. The clear() function needs to be\n * called to initialize the class properly.\n *\/\ntemplate\nclass TrivialArray {\n\ttypedef std::array Array;\n\npublic:\n\ttypedef unsigned size_type;\n\ttypedef T value_type;\n\ttypedef typename Array::iterator iterator;\n\ttypedef typename Array::const_iterator const_iterator;\n\nprotected:\n\tsize_type the_size;\n\tArray data;\n\n\tconstexpr\n\tTrivialArray(size_type _size):the_size(_size) {}\n\npublic:\n\t\/**\n\t * Non-initialising constructor.\n\t *\/\n\tTrivialArray() = default;\n\n\tTrivialArray(size_type _size, const T &value):the_size(_size) {\n\t\tstd::fill(begin(), end(), value);\n\t}\n\n\t\/**\n\t * Initialise the array with values from the iterator range.\n\t *\/\n\ttemplate\n\tTrivialArray(I _begin, I _end):the_size(0) {\n\t\tfor (I i = _begin; i != _end; ++i)\n\t\t\tpush_back(*i);\n\t}\n\n\tconstexpr\n\tsize_type capacity() const { return max; }\n\n\tconstexpr\n\tsize_type max_size() const {\n\t\treturn max;\n\t}\n\n\t\/**\n\t * Forcibly set the specified size, without initialising or\n\t * freeing new\/excess elements.\n\t *\/\n\tvoid resize(size_type new_size) {\n\t\tassert(new_size <= max_size());\n\n\t\tthe_size = new_size;\n\t}\n\n\t\/**\n\t * Returns the number of allocated elements.\n\t *\/\n\tconstexpr\n\tsize_type size() const {\n\t\treturn the_size;\n\t}\n\n\tvoid shrink(size_type _size) {\n\t\tassert(_size <= the_size);\n\n\t\tthe_size = _size;\n\t}\n\n\tconstexpr\n\tbool empty() const {\n\t\treturn the_size == 0;\n\t}\n\n\tconstexpr\n\tbool full() const {\n\t\treturn the_size == max;\n\t}\n\n\t\/**\n\t * Empties this array, but does not destruct its elements.\n\t *\/\n\tvoid clear() {\n\t\tthe_size = 0;\n\t}\n\n\t\/**\n\t * Returns one element. No bounds checking.\n\t *\/\n\tT &operator[](size_type i) {\n\t\tassert(i < size());\n\n\t\treturn data[i];\n\t}\n\n\t\/**\n\t * Returns one constant element. No bounds checking.\n\t *\/\n\tconst T &operator[](size_type i) const {\n\t\tassert(i < size());\n\n\t\treturn data[i];\n\t}\n\n\titerator begin() {\n\t\treturn data.begin();\n\t}\n\n\tconstexpr const_iterator begin() const {\n\t\treturn data.begin();\n\t}\n\n\titerator end() {\n\t\treturn std::next(data.begin(), the_size);\n\t}\n\n\tconstexpr const_iterator end() const {\n\t\treturn std::next(data.begin(), the_size);\n\t}\n\n\tT &last() {\n\t\tassert(the_size > 0);\n\n\t\treturn data[the_size - 1];\n\t}\n\n\tconst T &last() const {\n\t\tassert(the_size > 0);\n\n\t\treturn data[the_size - 1];\n\t}\n\n\tbool contains(const T &value) const {\n\t\treturn std::find(begin(), end(), value) != end();\n\t}\n\n\t\/**\n\t * Return address of start of data segment.\n\t *\/\n\tconst T* raw() const {\n\t\treturn &data[0];\n\t}\n\n\t\/**\n\t * Append an element at the end of the array, increasing the\n\t * length by one. No bounds checking.\n\t *\/\n\tvoid append(const T &value) {\n\t\tassert(!full());\n\n\t\tdata[the_size++] = value;\n\t}\n\n\t\/**\n\t * Increase the length by one and return a pointer to the new\n\t * element, to be modified by the caller. No bounds checking.\n\t *\/\n\tT &append() {\n\t\tassert(!full());\n\n\t\treturn data[the_size++];\n\t}\n\n\t\/**\n\t * Like append(), but checks if the array is already full\n\t * (returns false in this case).\n\t *\/\n\tbool checked_append(const T &value) {\n\t\tif (full())\n\t\t\treturn false;\n\n\t\tappend(value);\n\t\treturn true;\n\t}\n\n\t\/**\n\t * Remove the item at the given index.\n\t *\/\n\tvoid remove(size_type i) {\n\t\tassert(i < size());\n\n\t\tstd::move(std::next(data.begin(), i + 1),\n\t\t\t std::next(data.begin(), size()),\n\t\t\t std::next(data.begin(), i));\n\n\t\t--the_size;\n\t}\n\n\t\/**\n\t * Remove an item by copying the last item over it.\n\t *\/\n\tvoid quick_remove(size_type i) {\n\t\tassert(i < size());\n\n\t\tif (i < size() - 1)\n\t\t\tdata[i] = std::move(data[size() - 1]);\n\n\t\t--the_size;\n\t}\n\n\t\/* STL API emulation *\/\n\n\tvoid push_back(const T &value) {\n\t\tappend(value);\n\t}\n\n\tT &front() {\n\t\tassert(the_size > 0);\n\n\t\treturn data.front();\n\t}\n\n\tconst T &front() const {\n\t\tassert(the_size > 0);\n\n\t\treturn data.front();\n\t}\n\n\tT &back() {\n\t\treturn last();\n\t}\n\n\tconst T &back() const {\n\t\treturn last();\n\t}\n};\n\n#endif\nutil\/TrivialArray: add method insert()\/*\n * Copyright (C) 2010-2015 Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef TRIVIAL_ARRAY_HXX\n#define TRIVIAL_ARRAY_HXX\n\n#include \n#include \n\n#include \n\n\/**\n * An array with a maximum size known at compile time. It keeps track\n * of the actual length at runtime. The clear() function needs to be\n * called to initialize the class properly.\n *\/\ntemplate\nclass TrivialArray {\n\ttypedef std::array Array;\n\npublic:\n\ttypedef unsigned size_type;\n\ttypedef T value_type;\n\ttypedef typename Array::iterator iterator;\n\ttypedef typename Array::const_iterator const_iterator;\n\nprotected:\n\tsize_type the_size;\n\tArray data;\n\n\tconstexpr\n\tTrivialArray(size_type _size):the_size(_size) {}\n\npublic:\n\t\/**\n\t * Non-initialising constructor.\n\t *\/\n\tTrivialArray() = default;\n\n\tTrivialArray(size_type _size, const T &value):the_size(_size) {\n\t\tstd::fill(begin(), end(), value);\n\t}\n\n\t\/**\n\t * Initialise the array with values from the iterator range.\n\t *\/\n\ttemplate\n\tTrivialArray(I _begin, I _end):the_size(0) {\n\t\tfor (I i = _begin; i != _end; ++i)\n\t\t\tpush_back(*i);\n\t}\n\n\tconstexpr\n\tsize_type capacity() const { return max; }\n\n\tconstexpr\n\tsize_type max_size() const {\n\t\treturn max;\n\t}\n\n\t\/**\n\t * Forcibly set the specified size, without initialising or\n\t * freeing new\/excess elements.\n\t *\/\n\tvoid resize(size_type new_size) {\n\t\tassert(new_size <= max_size());\n\n\t\tthe_size = new_size;\n\t}\n\n\t\/**\n\t * Returns the number of allocated elements.\n\t *\/\n\tconstexpr\n\tsize_type size() const {\n\t\treturn the_size;\n\t}\n\n\tvoid shrink(size_type _size) {\n\t\tassert(_size <= the_size);\n\n\t\tthe_size = _size;\n\t}\n\n\tconstexpr\n\tbool empty() const {\n\t\treturn the_size == 0;\n\t}\n\n\tconstexpr\n\tbool full() const {\n\t\treturn the_size == max;\n\t}\n\n\t\/**\n\t * Empties this array, but does not destruct its elements.\n\t *\/\n\tvoid clear() {\n\t\tthe_size = 0;\n\t}\n\n\t\/**\n\t * Returns one element. No bounds checking.\n\t *\/\n\tT &operator[](size_type i) {\n\t\tassert(i < size());\n\n\t\treturn data[i];\n\t}\n\n\t\/**\n\t * Returns one constant element. No bounds checking.\n\t *\/\n\tconst T &operator[](size_type i) const {\n\t\tassert(i < size());\n\n\t\treturn data[i];\n\t}\n\n\titerator begin() {\n\t\treturn data.begin();\n\t}\n\n\tconstexpr const_iterator begin() const {\n\t\treturn data.begin();\n\t}\n\n\titerator end() {\n\t\treturn std::next(data.begin(), the_size);\n\t}\n\n\tconstexpr const_iterator end() const {\n\t\treturn std::next(data.begin(), the_size);\n\t}\n\n\tT &last() {\n\t\tassert(the_size > 0);\n\n\t\treturn data[the_size - 1];\n\t}\n\n\tconst T &last() const {\n\t\tassert(the_size > 0);\n\n\t\treturn data[the_size - 1];\n\t}\n\n\tbool contains(const T &value) const {\n\t\treturn std::find(begin(), end(), value) != end();\n\t}\n\n\t\/**\n\t * Return address of start of data segment.\n\t *\/\n\tconst T* raw() const {\n\t\treturn &data[0];\n\t}\n\n\t\/**\n\t * Append an element at the end of the array, increasing the\n\t * length by one. No bounds checking.\n\t *\/\n\tvoid append(const T &value) {\n\t\tassert(!full());\n\n\t\tdata[the_size++] = value;\n\t}\n\n\t\/**\n\t * Increase the length by one and return a pointer to the new\n\t * element, to be modified by the caller. No bounds checking.\n\t *\/\n\tT &append() {\n\t\tassert(!full());\n\n\t\treturn data[the_size++];\n\t}\n\n\t\/**\n\t * Like append(), but checks if the array is already full\n\t * (returns false in this case).\n\t *\/\n\tbool checked_append(const T &value) {\n\t\tif (full())\n\t\t\treturn false;\n\n\t\tappend(value);\n\t\treturn true;\n\t}\n\n\t\/**\n\t * Remove the item at the given index.\n\t *\/\n\tvoid remove(size_type i) {\n\t\tassert(i < size());\n\n\t\tstd::move(std::next(data.begin(), i + 1),\n\t\t\t std::next(data.begin(), size()),\n\t\t\t std::next(data.begin(), i));\n\n\t\t--the_size;\n\t}\n\n\t\/**\n\t * Remove an item by copying the last item over it.\n\t *\/\n\tvoid quick_remove(size_type i) {\n\t\tassert(i < size());\n\n\t\tif (i < size() - 1)\n\t\t\tdata[i] = std::move(data[size() - 1]);\n\n\t\t--the_size;\n\t}\n\n\ttemplate\n\tvoid insert(size_type i, I _begin, I _end) {\n\t\tsize_type n = std::distance(_begin, _end);\n\t\tassert(the_size + n < capacity());\n\n\t\tauto dest_begin = std::next(begin(), i);\n\t\tauto dest_end = end();\n\t\tthe_size += n;\n\n\t\tstd::move_backward(dest_begin, dest_end, end());\n\t\tstd::copy(_begin, _end, dest_begin);\n\t}\n\n\t\/* STL API emulation *\/\n\n\tvoid push_back(const T &value) {\n\t\tappend(value);\n\t}\n\n\tT &front() {\n\t\tassert(the_size > 0);\n\n\t\treturn data.front();\n\t}\n\n\tconst T &front() const {\n\t\tassert(the_size > 0);\n\n\t\treturn data.front();\n\t}\n\n\tT &back() {\n\t\treturn last();\n\t}\n\n\tconst T &back() const {\n\t\treturn last();\n\t}\n};\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: tabvwsh.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: nn $ $Date: 2000-09-22 18:28:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#if !defined OS2 && !defined WNT\n\/\/#define _BUTTON_HXX\n#endif\n\n#define _SETBRW_HXX\n#define _STACK_HXX\n\/\/#define _STATUS_HXX\n#define _STDMENU_HXX\n#define _TABBAR_HXX\n#define _VCBRW_HXX\n#define _VCTRLS_HXX\n#define _VCSBX_HXX\n#define _VCONT_HXX\n#define _VDRWOBJ_HXX\n\n#define _BASE_DLGS_HXX\n#define _BIGINT_HXX\n#define _CACHESTR_HXX\n#define _CONFIG_HXX\n#define _CURSOR_HXX\n#define _CTRLTOOL_HXX\n#define _DLGCFG_HXX\n#define _DYNARR_HXX\n#define _EXTATTR_HXX\n#define _FILDLG_HXX\n#define _FONTDLG_HXX\n#define _FRM3D_HXX\n#define _INTRO_HXX\n#define _ISETBWR_HXX\n#define _NO_SVRTF_PARSER_HXX\n#define _MACRODLG_HXX\n#define _MODALDLG_HXX\n#define _MOREBUTTON_HXX\n#define _OUTLINER_HXX\n#define _PASSWD_HXX\n\/\/#define _PRNDLG_HXX\n\/\/#define _POLY_HXX\n#define _PVRWIN_HXX\n#define _QUEUE_HXX\n#define _RULER_HXX\n#define _SCRWIN_HXX\n#define _STACK_HXX\n#define _SETBRW_HXX\n#define _STACK_HXX\n\/\/#define _STATUS_HXX\n#define _STDMENU_HXX\n#define _TABBAR_HXX\n#define _VCBRW_HXX\n#define _VCTRLS_HXX\n#define _VCSBX_HXX\n#define _VCONT_HXX\n#define _VDRWOBJ_HXX\n\n#define _SVDXOUT_HXX\n#define _SVDATTR_HXX\n#define _SVDETC_HXX\n#define _SVDIO_HXX\n#define _SVDRAG_HXX\n#define _SVDLAYER_HXX\n\n#define _SFXFILEDLG_HXX\n#define _SFX_MACRO_HXX\n#define _SFXMNUITEM_HXX\n#define _SFXMNUMGR_HXX\n#define _SFXMSGPOOL_HXX\n#define _SFXMULTISEL_HXX\n#define _SFXBASIC_HXX\n#define _SFXSTBMGR_HXX\n\/\/#define _SFXTBXCTRL_HXX\n\/\/#define _SFXTBXMGR_HXX\n\/\/#define _SFXIMGMGR_HXX\n\n#define _SI_DLL_HXX\n#define _SIDLL_HXX\n#define _SI_NOITEMS\n#define _SI_NOOTHERFORMS\n#define _SI_NOSBXCONTROLS\n#define _SINOSBXCONTROLS\n#define _SI_NODRW\n#define _SI_NOCONTROL\n\n#define _SVX_DAILDLL_HXX\n#define _SVX_HYPHEN_HXX\n#define _SVX_IMPGRF_HXX\n#define _SVX_OPTITEMS_HXX\n#define _SVX_OPTGERL_HXX\n#define _SVX_OPTSAVE_HXX\n#define _SVX_OPTSPELL_HXX\n#define _SVX_OPTPATH_HXX\n#define _SVX_OPTLINGU_HXX\n#define _SVX_RULER_HXX\n#define _SVX_RULRITEM_HXX\n#define _SVX_SPLWRAP_HXX\n#define _SVX_SPLDLG_HXX\n#define _SVX_THESDLG_HXX\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"scitems.hxx\"\n#include \n#include \n#include \n#include \n#include \n\n#include \"tabvwsh.hxx\"\n#include \"docsh.hxx\"\n#include \"reffact.hxx\"\n#include \"scresid.hxx\"\n#include \"dwfunctr.hxx\"\n#include \"sc.hrc\" \/\/ -> SID_TOOL_xxx\n#include \"drawattr.hxx\" \/\/ -> SvxDrawToolItem\n\n\n#define ScTabViewShell\n#include \"scslots.hxx\"\n\n#define SearchSettings\n#include \n\nTYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener);\n\nSFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL))\n{\n SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD |\n SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,\n ScResId(RID_OBJECTBAR_TOOLS) );\n\n SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS);\n SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR);\n SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG);\n SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG);\n}\n\nSFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) )\n{\n SFX_VIEW_REGISTRATION(ScDocShell);\n}\n\n\/\/------------------------------------------------------------------\n\n\nold include removed\/*************************************************************************\n *\n * $RCSfile: tabvwsh.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: nn $ $Date: 2000-10-19 18:36:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#if !defined OS2 && !defined WNT\n\/\/#define _BUTTON_HXX\n#endif\n\n#define _SETBRW_HXX\n#define _STACK_HXX\n\/\/#define _STATUS_HXX\n#define _STDMENU_HXX\n#define _TABBAR_HXX\n#define _VCBRW_HXX\n#define _VCTRLS_HXX\n#define _VCSBX_HXX\n#define _VCONT_HXX\n#define _VDRWOBJ_HXX\n\n#define _BASE_DLGS_HXX\n#define _BIGINT_HXX\n#define _CACHESTR_HXX\n#define _CONFIG_HXX\n#define _CURSOR_HXX\n#define _CTRLTOOL_HXX\n#define _DLGCFG_HXX\n#define _DYNARR_HXX\n#define _EXTATTR_HXX\n#define _FILDLG_HXX\n#define _FONTDLG_HXX\n#define _FRM3D_HXX\n#define _INTRO_HXX\n#define _ISETBWR_HXX\n#define _NO_SVRTF_PARSER_HXX\n#define _MACRODLG_HXX\n#define _MODALDLG_HXX\n#define _MOREBUTTON_HXX\n#define _OUTLINER_HXX\n#define _PASSWD_HXX\n\/\/#define _PRNDLG_HXX\n\/\/#define _POLY_HXX\n#define _PVRWIN_HXX\n#define _QUEUE_HXX\n#define _RULER_HXX\n#define _SCRWIN_HXX\n#define _STACK_HXX\n#define _SETBRW_HXX\n#define _STACK_HXX\n\/\/#define _STATUS_HXX\n#define _STDMENU_HXX\n#define _TABBAR_HXX\n#define _VCBRW_HXX\n#define _VCTRLS_HXX\n#define _VCSBX_HXX\n#define _VCONT_HXX\n#define _VDRWOBJ_HXX\n\n#define _SVDXOUT_HXX\n#define _SVDATTR_HXX\n#define _SVDETC_HXX\n#define _SVDIO_HXX\n#define _SVDRAG_HXX\n#define _SVDLAYER_HXX\n\n#define _SFXFILEDLG_HXX\n#define _SFX_MACRO_HXX\n#define _SFXMNUITEM_HXX\n#define _SFXMNUMGR_HXX\n#define _SFXMSGPOOL_HXX\n#define _SFXMULTISEL_HXX\n#define _SFXBASIC_HXX\n#define _SFXSTBMGR_HXX\n\/\/#define _SFXTBXCTRL_HXX\n\/\/#define _SFXTBXMGR_HXX\n\/\/#define _SFXIMGMGR_HXX\n\n#define _SI_DLL_HXX\n#define _SIDLL_HXX\n#define _SI_NOITEMS\n#define _SI_NOOTHERFORMS\n#define _SI_NOSBXCONTROLS\n#define _SINOSBXCONTROLS\n#define _SI_NODRW\n#define _SI_NOCONTROL\n\n#define _SVX_DAILDLL_HXX\n#define _SVX_HYPHEN_HXX\n#define _SVX_IMPGRF_HXX\n#define _SVX_OPTITEMS_HXX\n#define _SVX_OPTGERL_HXX\n#define _SVX_OPTSAVE_HXX\n#define _SVX_OPTSPELL_HXX\n#define _SVX_OPTPATH_HXX\n#define _SVX_OPTLINGU_HXX\n#define _SVX_RULER_HXX\n#define _SVX_RULRITEM_HXX\n#define _SVX_SPLWRAP_HXX\n#define _SVX_SPLDLG_HXX\n#define _SVX_THESDLG_HXX\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"scitems.hxx\"\n#include \n#include \n#include \n#include \n\n#include \"tabvwsh.hxx\"\n#include \"docsh.hxx\"\n#include \"reffact.hxx\"\n#include \"scresid.hxx\"\n#include \"dwfunctr.hxx\"\n#include \"sc.hrc\" \/\/ -> SID_TOOL_xxx\n#include \"drawattr.hxx\" \/\/ -> SvxDrawToolItem\n\n\n#define ScTabViewShell\n#include \"scslots.hxx\"\n\n#define SearchSettings\n#include \n\nTYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener);\n\nSFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL))\n{\n SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD |\n SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER,\n ScResId(RID_OBJECTBAR_TOOLS) );\n\n SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS);\n SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR);\n SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId());\n SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG);\n SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG);\n}\n\nSFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) )\n{\n SFX_VIEW_REGISTRATION(ScDocShell);\n}\n\n\/\/------------------------------------------------------------------\n\n\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2011 \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"note.h\"\n\n#include \n#include \n\n#include \n\nNote::Note(QObject *parent)\n: AbstractPimItem(parent)\n{\n \/\/init payload, mimetype, and displayattribute\n commitData();\n}\n\/*\nNote::Note(const Note ¬e)\n: AbstractPimItem(note.getItem())\n{\n m_text = note.m_text;\n m_title = note.m_title;\n m_creationDate = note.m_creationDate;\n}*\/\n\nNote::Note(const Akonadi::Item &item, QObject *parent)\n: AbstractPimItem(item, parent)\n{\n fetchData();\n}\n\nNote::Note(AbstractPimItem &item, QObject* parent)\n: AbstractPimItem(item, parent)\n{\n commitData();\n}\n\n\nbool Note::hasValidPayload()\n{\n if (m_item.hasPayload()) {\n return true;\n }\n return false;\n}\n\n\nvoid Note::commitData()\n{\n m_item.setMimeType(Akonadi::NoteUtils::noteMimeType());\n Akonadi::NoteUtils::NoteMessageWrapper messageWrapper;\n messageWrapper.setTitle(m_title);\n messageWrapper.setText(m_text, m_textIsRich ? Qt::RichText : Qt::PlainText);\n messageWrapper.setCreationDate(m_creationDate);\n messageWrapper.setFrom(QString::fromLatin1( \"NoteTaker@kde4\" )); \/\/FIXME shouldn't be hardcoded\n m_item.setPayload(messageWrapper.message());\n \n Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute();\n eda->setIconName(getIconName());\n eda->setDisplayName(m_title);\n m_item.addAttribute(eda);\n}\n\nvoid Note::fetchData()\n{\n if (m_dataFetched) {\n return;\n }\n \n if ( !hasValidPayload()) {\n kDebug() << \"invalid payload\";\n return;\n }\n \n KMime::Message::Ptr msg = m_item.payload();\n Q_ASSERT(msg.get());\n Akonadi::NoteUtils::NoteMessageWrapper messageWrapper(msg);\n m_textIsRich = messageWrapper.textFormat() == Qt::RichText;\n m_titleIsRich = false;\n m_title = messageWrapper.title();\n m_text = messageWrapper.text();\n m_creationDate = messageWrapper.creationDate();\n\n m_dataFetched = true;\n}\n\n\nQString Note::mimeType()\n{\n Q_ASSERT(AbstractPimItem::mimeType(AbstractPimItem::Note) == Akonadi::NoteUtils::noteMimeType());\n return AbstractPimItem::mimeType(AbstractPimItem::Note);\n}\n\nAbstractPimItem::ItemStatus Note::getStatus() const\n{\n return AbstractPimItem::Later;\n}\n\n\nKDateTime Note::getPrimaryDate()\n{\n return getLastModifiedDate();\n}\n\nQString Note::getIconName()\n{\n return Akonadi::NoteUtils::noteIconName();\n}\n\n\nAbstractPimItem::ItemType Note::itemType()\n{\n return AbstractPimItem::Note;\n}\nset correct application name\/*\n Copyright (c) 2011 \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"note.h\"\n\n#include \n#include \n\n#include \n#include \n\nNote::Note(QObject *parent)\n: AbstractPimItem(parent)\n{\n \/\/init payload, mimetype, and displayattribute\n commitData();\n}\n\/*\nNote::Note(const Note ¬e)\n: AbstractPimItem(note.getItem())\n{\n m_text = note.m_text;\n m_title = note.m_title;\n m_creationDate = note.m_creationDate;\n}*\/\n\nNote::Note(const Akonadi::Item &item, QObject *parent)\n: AbstractPimItem(item, parent)\n{\n fetchData();\n}\n\nNote::Note(AbstractPimItem &item, QObject* parent)\n: AbstractPimItem(item, parent)\n{\n commitData();\n}\n\n\nbool Note::hasValidPayload()\n{\n if (m_item.hasPayload()) {\n return true;\n }\n return false;\n}\n\n\nvoid Note::commitData()\n{\n m_item.setMimeType(Akonadi::NoteUtils::noteMimeType());\n Akonadi::NoteUtils::NoteMessageWrapper messageWrapper;\n messageWrapper.setTitle(m_title);\n messageWrapper.setText(m_text, m_textIsRich ? Qt::RichText : Qt::PlainText);\n messageWrapper.setCreationDate(m_creationDate);\n messageWrapper.setFrom(QCoreApplication::applicationName()+QCoreApplication::applicationVersion());\n m_item.setPayload(messageWrapper.message());\n \n Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute();\n eda->setIconName(getIconName());\n eda->setDisplayName(m_title);\n m_item.addAttribute(eda);\n}\n\nvoid Note::fetchData()\n{\n if (m_dataFetched) {\n return;\n }\n \n if ( !hasValidPayload()) {\n kDebug() << \"invalid payload\";\n return;\n }\n \n KMime::Message::Ptr msg = m_item.payload();\n Q_ASSERT(msg.get());\n Akonadi::NoteUtils::NoteMessageWrapper messageWrapper(msg);\n m_textIsRich = messageWrapper.textFormat() == Qt::RichText;\n m_titleIsRich = false;\n m_title = messageWrapper.title();\n m_text = messageWrapper.text();\n m_creationDate = messageWrapper.creationDate();\n\n m_dataFetched = true;\n}\n\n\nQString Note::mimeType()\n{\n Q_ASSERT(AbstractPimItem::mimeType(AbstractPimItem::Note) == Akonadi::NoteUtils::noteMimeType());\n return AbstractPimItem::mimeType(AbstractPimItem::Note);\n}\n\nAbstractPimItem::ItemStatus Note::getStatus() const\n{\n return AbstractPimItem::Later;\n}\n\n\nKDateTime Note::getPrimaryDate()\n{\n return getLastModifiedDate();\n}\n\nQString Note::getIconName()\n{\n return Akonadi::NoteUtils::noteIconName();\n}\n\n\nAbstractPimItem::ItemType Note::itemType()\n{\n return AbstractPimItem::Note;\n}\n<|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 \"modules\/prediction\/prediction.h\"\n\n#include \n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/prediction\/common\/prediction_gflags.h\"\n#include \"modules\/prediction\/container\/container_manager.h\"\n#include \"modules\/prediction\/container\/obstacles\/obstacles_container.h\"\n#include \"modules\/prediction\/container\/pose\/pose_container.h\"\n#include \"modules\/prediction\/evaluator\/evaluator_manager.h\"\n#include \"modules\/prediction\/predictor\/predictor_manager.h\"\n#include \"modules\/prediction\/proto\/prediction_obstacle.pb.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nusing ::apollo::common::ErrorCode;\nusing ::apollo::common::Status;\nusing ::apollo::common::TrajectoryPoint;\nusing ::apollo::common::adapter::AdapterConfig;\nusing ::apollo::common::adapter::AdapterManager;\nusing ::apollo::common::time::Clock;\nusing ::apollo::localization::LocalizationEstimate;\nusing ::apollo::perception::PerceptionObstacle;\nusing ::apollo::perception::PerceptionObstacles;\n\nstd::string Prediction::Name() const {\n return FLAGS_prediction_module_name;\n}\n\nStatus Prediction::Init() {\n \/\/ Load prediction conf\n prediction_conf_.Clear();\n if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,\n &prediction_conf_)) {\n return OnError(\"Unable to load prediction conf file: \" +\n FLAGS_prediction_conf_file);\n } else {\n ADEBUG << \"Prediction config file is loaded into: \"\n << prediction_conf_.ShortDebugString();\n }\n\n adapter_conf_.Clear();\n if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,\n &adapter_conf_)) {\n return OnError(\"Unable to load adapter conf file: \" +\n FLAGS_prediction_adapter_config_filename);\n } else {\n ADEBUG << \"Adapter config file is loaded into: \"\n << adapter_conf_.ShortDebugString();\n }\n\n \/\/ Initialization of all managers\n AdapterManager::Init(adapter_conf_);\n ContainerManager::instance()->Init(adapter_conf_);\n EvaluatorManager::instance()->Init(prediction_conf_);\n PredictorManager::instance()->Init(prediction_conf_);\n\n CHECK(AdapterManager::GetLocalization()) << \"Localization is not ready.\";\n CHECK(AdapterManager::GetPerceptionObstacles()) << \"Perception is not ready.\";\n\n \/\/ Set perception obstacle callback function\n AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);\n \/\/ Set localization callback function\n AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);\n\n return Status::OK();\n}\n\nStatus Prediction::Start() {\n return Status::OK();\n}\n\nvoid Prediction::Stop() {}\n\nvoid Prediction::OnLocalization(const LocalizationEstimate& localization) {\n ObstaclesContainer* obstacles_container = dynamic_cast(\n ContainerManager::instance()->GetContainer(\n AdapterConfig::PERCEPTION_OBSTACLES));\n CHECK_NOTNULL(obstacles_container);\n\n PoseContainer* pose_container = dynamic_cast(\n ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));\n CHECK_NOTNULL(pose_container);\n\n pose_container->Insert(localization);\n PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();\n if (pose_ptr != nullptr) {\n obstacles_container->InsertPerceptionObstacle(\n *(pose_ptr), pose_container->GetTimestamp());\n } else {\n ADEBUG << \"Invalid pose found.\";\n }\n\n ADEBUG << \"Received a localization message [\"\n << localization.ShortDebugString() << \"].\";\n}\n\nvoid Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {\n ADEBUG << \"Received a perception message [\"\n << perception_obstacles.ShortDebugString() << \"].\";\n\n double start_timestamp = Clock::NowInSecond();\n ObstaclesContainer* obstacles_container = dynamic_cast(\n ContainerManager::instance()->GetContainer(\n AdapterConfig::PERCEPTION_OBSTACLES));\n CHECK_NOTNULL(obstacles_container);\n obstacles_container->Insert(perception_obstacles);\n EvaluatorManager::instance()->Run(perception_obstacles);\n PredictorManager::instance()->Run(perception_obstacles);\n\n auto prediction_obstacles =\n PredictorManager::instance()->prediction_obstacles();\n prediction_obstacles.set_start_timestamp(start_timestamp);\n prediction_obstacles.set_end_timestamp(Clock::NowInSecond());\n\n Publish(&prediction_obstacles);\n}\n\nStatus Prediction::OnError(const std::string& error_msg) {\n return Status(ErrorCode::PREDICTION_ERROR, error_msg);\n}\n\nbool Prediction::IsValidTrajectoryPoint(\n const TrajectoryPoint& trajectory_point) {\n return (!std::isnan(trajectory_point.path_point().x())) &&\n (!std::isnan(trajectory_point.path_point().y())) &&\n (!std::isnan(trajectory_point.path_point().theta())) &&\n (!std::isnan(trajectory_point.v())) &&\n (!std::isnan(trajectory_point.a())) &&\n (!std::isnan(trajectory_point.relative_time()));\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\nPrediction: added back trajectory point check\/******************************************************************************\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 \"modules\/prediction\/prediction.h\"\n\n#include \n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/prediction\/common\/prediction_gflags.h\"\n#include \"modules\/prediction\/container\/container_manager.h\"\n#include \"modules\/prediction\/container\/obstacles\/obstacles_container.h\"\n#include \"modules\/prediction\/container\/pose\/pose_container.h\"\n#include \"modules\/prediction\/evaluator\/evaluator_manager.h\"\n#include \"modules\/prediction\/predictor\/predictor_manager.h\"\n#include \"modules\/prediction\/proto\/prediction_obstacle.pb.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nusing ::apollo::common::ErrorCode;\nusing ::apollo::common::Status;\nusing ::apollo::common::TrajectoryPoint;\nusing ::apollo::common::adapter::AdapterConfig;\nusing ::apollo::common::adapter::AdapterManager;\nusing ::apollo::common::time::Clock;\nusing ::apollo::localization::LocalizationEstimate;\nusing ::apollo::perception::PerceptionObstacle;\nusing ::apollo::perception::PerceptionObstacles;\n\nstd::string Prediction::Name() const {\n return FLAGS_prediction_module_name;\n}\n\nStatus Prediction::Init() {\n \/\/ Load prediction conf\n prediction_conf_.Clear();\n if (!common::util::GetProtoFromFile(FLAGS_prediction_conf_file,\n &prediction_conf_)) {\n return OnError(\"Unable to load prediction conf file: \" +\n FLAGS_prediction_conf_file);\n } else {\n ADEBUG << \"Prediction config file is loaded into: \"\n << prediction_conf_.ShortDebugString();\n }\n\n adapter_conf_.Clear();\n if (!common::util::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,\n &adapter_conf_)) {\n return OnError(\"Unable to load adapter conf file: \" +\n FLAGS_prediction_adapter_config_filename);\n } else {\n ADEBUG << \"Adapter config file is loaded into: \"\n << adapter_conf_.ShortDebugString();\n }\n\n \/\/ Initialization of all managers\n AdapterManager::Init(adapter_conf_);\n ContainerManager::instance()->Init(adapter_conf_);\n EvaluatorManager::instance()->Init(prediction_conf_);\n PredictorManager::instance()->Init(prediction_conf_);\n\n CHECK(AdapterManager::GetLocalization()) << \"Localization is not ready.\";\n CHECK(AdapterManager::GetPerceptionObstacles()) << \"Perception is not ready.\";\n\n \/\/ Set perception obstacle callback function\n AdapterManager::AddPerceptionObstaclesCallback(&Prediction::RunOnce, this);\n \/\/ Set localization callback function\n AdapterManager::AddLocalizationCallback(&Prediction::OnLocalization, this);\n\n return Status::OK();\n}\n\nStatus Prediction::Start() {\n return Status::OK();\n}\n\nvoid Prediction::Stop() {}\n\nvoid Prediction::OnLocalization(const LocalizationEstimate& localization) {\n ObstaclesContainer* obstacles_container = dynamic_cast(\n ContainerManager::instance()->GetContainer(\n AdapterConfig::PERCEPTION_OBSTACLES));\n CHECK_NOTNULL(obstacles_container);\n\n PoseContainer* pose_container = dynamic_cast(\n ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));\n CHECK_NOTNULL(pose_container);\n\n pose_container->Insert(localization);\n PerceptionObstacle* pose_ptr = pose_container->ToPerceptionObstacle();\n if (pose_ptr != nullptr) {\n obstacles_container->InsertPerceptionObstacle(\n *(pose_ptr), pose_container->GetTimestamp());\n } else {\n ADEBUG << \"Invalid pose found.\";\n }\n\n ADEBUG << \"Received a localization message [\"\n << localization.ShortDebugString() << \"].\";\n}\n\nvoid Prediction::RunOnce(const PerceptionObstacles& perception_obstacles) {\n ADEBUG << \"Received a perception message [\"\n << perception_obstacles.ShortDebugString() << \"].\";\n\n double start_timestamp = Clock::NowInSecond();\n ObstaclesContainer* obstacles_container = dynamic_cast(\n ContainerManager::instance()->GetContainer(\n AdapterConfig::PERCEPTION_OBSTACLES));\n CHECK_NOTNULL(obstacles_container);\n obstacles_container->Insert(perception_obstacles);\n EvaluatorManager::instance()->Run(perception_obstacles);\n PredictorManager::instance()->Run(perception_obstacles);\n\n auto prediction_obstacles =\n PredictorManager::instance()->prediction_obstacles();\n prediction_obstacles.set_start_timestamp(start_timestamp);\n prediction_obstacles.set_end_timestamp(Clock::NowInSecond());\n Publish(&prediction_obstacles);\n for (auto const& prediction_obstacle :\n prediction_obstacles.prediction_obstacle()) {\n for (auto const& trajectory : prediction_obstacle.trajectory()) {\n for (auto const& trajectory_point : trajectory.trajectory_point()) {\n CHECK(IsValidTrajectoryPoint(trajectory_point));\n }\n }\n }\n\n ADEBUG << \"Received a perception message [\"\n << perception_obstacles.ShortDebugString() << \"].\";\n ADEBUG << \"Published a prediction message [\"\n << prediction_obstacles.ShortDebugString() << \"].\";\n}\n\nStatus Prediction::OnError(const std::string& error_msg) {\n return Status(ErrorCode::PREDICTION_ERROR, error_msg);\n}\n\nbool Prediction::IsValidTrajectoryPoint(\n const TrajectoryPoint& trajectory_point) {\n return trajectory_point.has_path_point() &&\n (!std::isnan(trajectory_point.path_point().x())) &&\n (!std::isnan(trajectory_point.path_point().y())) &&\n (!std::isnan(trajectory_point.path_point().theta())) &&\n (!std::isnan(trajectory_point.v())) &&\n (!std::isnan(trajectory_point.a())) &&\n (!std::isnan(trajectory_point.relative_time()));\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/*\n * webrtc-echo - A WebRTC echo server\n * Copyright (C) 2014 Stephan Thamm\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 \"srtp.h\"\n\n#include \n\n#include \"helper.h\"\n\nusing namespace v8;\n\nv8::Persistent Srtp::constructor;\nbool Srtp::initialized = false;\n\nstatic void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {\n\tsrtp_policy_t policy;\n\n\tmemset(&policy, 0, sizeof(policy));\n\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);\n\n\tpolicy.ssrc.type = direction;\n\tpolicy.ssrc.value = 0;\n\n\tpolicy.key = (unsigned char*) key;\n\n\tpolicy.next = NULL;\n\n\tint res = srtp_create(session, &policy);\n\n\tDEBUG(\"creating session \" << res);\n}\n\nSrtp::Srtp(const char *sendKey, const char *recvKey) {\n\tif(!initialized) {\n\t\tDEBUG(\"initializing srtp\");\n\t\tsrtp_init();\n\t\tinitialized = true;\n\t}\n\n\tcreateSession(&_sendSession, sendKey, ssrc_any_outbound);\n\tcreateSession(&_recvSession, recvKey, ssrc_any_inbound);\n}\n\nSrtp::~Srtp() {\n\tsrtp_dealloc(_sendSession);\n\tsrtp_dealloc(_recvSession);\n}\n\nvoid Srtp::init(v8::Handle exports) {\n\t\/\/ Prepare constructor template\n\tLocal tpl = FunctionTemplate::New(New);\n\ttpl->SetClassName(String::NewSymbol(\"Srtp\"));\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\t\/\/ protoype\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtp\", protectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtp\", unprotectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtcp\", protectRtcp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtcp\", unprotectRtcp);\n\tconstructor = Persistent::New(tpl->GetFunction());\n\t\/\/ export\n\texports->Set(String::NewSymbol(\"Srtp\"), constructor);\n}\n\nv8::Handle Srtp::New(const v8::Arguments& args) {\n\tHandleScope scope;\n\n\tif (args.IsConstructCall()) {\n\t\t\/\/ Invoked as constructor: `new MyObject(...)`\n\t\tif(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {\n\t\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffers\")));\n\t\t}\n\n\t\tconst char *sendKey = node::Buffer::Data(args[0]);\n\t\tconst char *recvKey = node::Buffer::Data(args[1]);\n\n\t\tSrtp* obj = new Srtp(sendKey, recvKey);\n\t\tobj->Wrap(args.This());\n\n\t\treturn args.This();\n\t} else {\n\t\t\/\/ Invoked as plain function `MyObject(...)`, turn into construct call.\n\t\tconst int argc = 1;\n\t\tLocal argv[1] = { argv[0] };\n\t\treturn scope.Close(constructor->NewInstance(argc, argv));\n\t}\n}\n\nv8::Handle Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {\n\tHandleScope scope;\n\n\t\/\/ type checking\n\n\tif(!node::Buffer::HasInstance(args[0])) {\n\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffer\")));\n\t}\n\n\t\/\/ copy buffer for result\n\n\tint size = node::Buffer::Length(args[0]);\n\tchar *in_buf = node::Buffer::Data(args[0]);\n\n\tHandle tmp = node::Buffer::New(size + 32)->handle_;\n\tchar *out_buf = node::Buffer::Data(tmp);\n\n\tmemcpy(out_buf, in_buf, size);\n\n\t\/\/ actual crypt stuff\n\n\terr_status_t err = fun(session, out_buf, &size);\n\n\tif(err != err_status_ok) {\n\t\tDEBUG(\"srtp error \" << err);\n\t}\n\n\t\/\/ return slice of the right size\n\n\tHandle slice_v = tmp->Get(String::New(\"slice\")); \n\n\tif(!slice_v->IsFunction()) {\n\t\treturn ThrowException(Exception::Error(String::New(\"Buffer does not have a slice function\")));\n\t}\n\n\tHandle slice_f = v8::Handle::Cast(slice_v);\n\n\tconst int argc = 2;\n\tHandle argv[argc] = {\n\t\tInteger::New(0),\n\t\tInteger::New(size),\n\t};\n\n\tHandle res = slice_f->Call(tmp, argc, argv);\n\n\treturn scope.Close(res);\n}\n\nv8::Handle Srtp::protectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect);\n}\n\nv8::Handle Srtp::unprotectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect);\n}\n\nv8::Handle Srtp::protectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect_rtcp);\n}\n\nv8::Handle Srtp::unprotectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect_rtcp);\n}\n\nDisable srtp replay protection\/*\n * webrtc-echo - A WebRTC echo server\n * Copyright (C) 2014 Stephan Thamm\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 \"srtp.h\"\n\n#include \n\n#include \"helper.h\"\n\nusing namespace v8;\n\nv8::Persistent Srtp::constructor;\nbool Srtp::initialized = false;\n\nstatic void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {\n\tsrtp_policy_t policy;\n\n\tmemset(&policy, 0, sizeof(policy));\n\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);\n\n\tpolicy.ssrc.type = direction;\n\tpolicy.ssrc.value = 0;\n\n\tpolicy.key = (unsigned char*) key;\n\n\tpolicy.window_size = 0;\n\tpolicy.allow_repeat_tx = 1;\n\n\tpolicy.next = NULL;\n\n\tsrtp_create(session, &policy);\n}\n\nSrtp::Srtp(const char *sendKey, const char *recvKey) {\n\tif(!initialized) {\n\t\tDEBUG(\"initializing srtp\");\n\t\tsrtp_init();\n\t\tinitialized = true;\n\t}\n\n\tcreateSession(&_sendSession, sendKey, ssrc_any_outbound);\n\tcreateSession(&_recvSession, recvKey, ssrc_any_inbound);\n}\n\nSrtp::~Srtp() {\n\tsrtp_dealloc(_sendSession);\n\tsrtp_dealloc(_recvSession);\n}\n\nvoid Srtp::init(v8::Handle exports) {\n\t\/\/ Prepare constructor template\n\tLocal tpl = FunctionTemplate::New(New);\n\ttpl->SetClassName(String::NewSymbol(\"Srtp\"));\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\t\/\/ protoype\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtp\", protectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtp\", unprotectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtcp\", protectRtcp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtcp\", unprotectRtcp);\n\tconstructor = Persistent::New(tpl->GetFunction());\n\t\/\/ export\n\texports->Set(String::NewSymbol(\"Srtp\"), constructor);\n}\n\nv8::Handle Srtp::New(const v8::Arguments& args) {\n\tHandleScope scope;\n\n\tif (args.IsConstructCall()) {\n\t\t\/\/ Invoked as constructor: `new MyObject(...)`\n\t\tif(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {\n\t\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffers\")));\n\t\t}\n\n\t\tconst char *sendKey = node::Buffer::Data(args[0]);\n\t\tconst char *recvKey = node::Buffer::Data(args[1]);\n\n\t\tSrtp* obj = new Srtp(sendKey, recvKey);\n\t\tobj->Wrap(args.This());\n\n\t\treturn args.This();\n\t} else {\n\t\t\/\/ Invoked as plain function `MyObject(...)`, turn into construct call.\n\t\tconst int argc = 1;\n\t\tLocal argv[1] = { argv[0] };\n\t\treturn scope.Close(constructor->NewInstance(argc, argv));\n\t}\n}\n\nv8::Handle Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {\n\tHandleScope scope;\n\n\t\/\/ type checking\n\n\tif(!node::Buffer::HasInstance(args[0])) {\n\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffer\")));\n\t}\n\n\t\/\/ copy buffer for result\n\n\tint size = node::Buffer::Length(args[0]);\n\tchar *in_buf = node::Buffer::Data(args[0]);\n\n\tHandle tmp = node::Buffer::New(size + 32)->handle_;\n\tchar *out_buf = node::Buffer::Data(tmp);\n\n\tmemcpy(out_buf, in_buf, size);\n\n\t\/\/ actual crypt stuff\n\n\terr_status_t err = fun(session, out_buf, &size);\n\n\tif(err != err_status_ok) {\n\t\tDEBUG(\"srtp error \" << err);\n\t}\n\n\t\/\/ return slice of the right size\n\n\tHandle slice_v = tmp->Get(String::New(\"slice\")); \n\n\tif(!slice_v->IsFunction()) {\n\t\treturn ThrowException(Exception::Error(String::New(\"Buffer does not have a slice function\")));\n\t}\n\n\tHandle slice_f = v8::Handle::Cast(slice_v);\n\n\tconst int argc = 2;\n\tHandle argv[argc] = {\n\t\tInteger::New(0),\n\t\tInteger::New(size),\n\t};\n\n\tHandle res = slice_f->Call(tmp, argc, argv);\n\n\treturn scope.Close(res);\n}\n\nv8::Handle Srtp::protectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect);\n}\n\nv8::Handle Srtp::unprotectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect);\n}\n\nv8::Handle Srtp::protectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect_rtcp);\n}\n\nv8::Handle Srtp::unprotectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect_rtcp);\n}\n\n<|endoftext|>"} {"text":"\/*\n * webrtc-echo - A WebRTC echo server\n * Copyright (C) 2014 Stephan Thamm\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 \"srtp.h\"\n\n#include \n\n#include \"helper.h\"\n\nusing namespace v8;\n\nv8::Persistent Srtp::constructor;\nbool Srtp::initialized = false;\n\nstatic void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {\n\tsrtp_policy_t policy;\n\n\tmemset(&policy, 0, sizeof(policy));\n\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);\n\n\tpolicy.ssrc.type = direction;\n\tpolicy.ssrc.value = 0;\n\n\tpolicy.key = (unsigned char*) key;\n\n\tpolicy.window_size = 0;\n\tpolicy.allow_repeat_tx = 1;\n\n\tpolicy.next = NULL;\n\n\tsrtp_create(session, &policy);\n}\n\nSrtp::Srtp(const char *sendKey, const char *recvKey) {\n\tif(!initialized) {\n\t\tDEBUG(\"initializing srtp\");\n\t\tsrtp_init();\n\t\tinitialized = true;\n\t}\n\n\tcreateSession(&_sendSession, sendKey, ssrc_any_outbound);\n\tcreateSession(&_recvSession, recvKey, ssrc_any_inbound);\n}\n\nSrtp::~Srtp() {\n\tsrtp_dealloc(_sendSession);\n\tsrtp_dealloc(_recvSession);\n}\n\nvoid Srtp::init(v8::Handle exports) {\n\t\/\/ Prepare constructor template\n\tLocal tpl = FunctionTemplate::New(New);\n\ttpl->SetClassName(String::NewSymbol(\"Srtp\"));\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\t\/\/ protoype\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtp\", protectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtp\", unprotectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtcp\", protectRtcp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtcp\", unprotectRtcp);\n\tconstructor = Persistent::New(tpl->GetFunction());\n\t\/\/ export\n\texports->Set(String::NewSymbol(\"Srtp\"), constructor);\n}\n\nv8::Handle Srtp::New(const v8::Arguments& args) {\n\tHandleScope scope;\n\n\tif (args.IsConstructCall()) {\n\t\t\/\/ Invoked as constructor: `new MyObject(...)`\n\t\tif(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {\n\t\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffers\")));\n\t\t}\n\n\t\tconst char *sendKey = node::Buffer::Data(args[0]);\n\t\tconst char *recvKey = node::Buffer::Data(args[1]);\n\n\t\tSrtp* obj = new Srtp(sendKey, recvKey);\n\t\tobj->Wrap(args.This());\n\n\t\treturn args.This();\n\t} else {\n\t\t\/\/ Invoked as plain function `MyObject(...)`, turn into construct call.\n\t\tconst int argc = 1;\n\t\tLocal argv[1] = { argv[0] };\n\t\treturn scope.Close(constructor->NewInstance(argc, argv));\n\t}\n}\n\nv8::Handle Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {\n\tHandleScope scope;\n\n\t\/\/ type checking\n\n\tif(!node::Buffer::HasInstance(args[0])) {\n\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffer\")));\n\t}\n\n\t\/\/ copy buffer for result\n\n\tint size = node::Buffer::Length(args[0]);\n\tchar *in_buf = node::Buffer::Data(args[0]);\n\n\tHandle tmp = node::Buffer::New(size + 32)->handle_;\n\tchar *out_buf = node::Buffer::Data(tmp);\n\n\tmemcpy(out_buf, in_buf, size);\n\n\t\/\/ actual crypt stuff\n\n\terr_status_t err = fun(session, out_buf, &size);\n\n\tif(err != err_status_ok) {\n\t\tDEBUG(\"srtp error \" << err);\n\t}\n\n\t\/\/ return slice of the right size\n\n\tHandle slice_v = tmp->Get(String::New(\"slice\")); \n\n\tif(!slice_v->IsFunction()) {\n\t\treturn ThrowException(Exception::Error(String::New(\"Buffer does not have a slice function\")));\n\t}\n\n\tHandle slice_f = v8::Handle::Cast(slice_v);\n\n\tconst int argc = 2;\n\tHandle argv[argc] = {\n\t\tInteger::New(0),\n\t\tInteger::New(size),\n\t};\n\n\tHandle res = slice_f->Call(tmp, argc, argv);\n\n\treturn scope.Close(res);\n}\n\nv8::Handle Srtp::protectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect);\n}\n\nv8::Handle Srtp::unprotectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect);\n}\n\nv8::Handle Srtp::protectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect_rtcp);\n}\n\nv8::Handle Srtp::unprotectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect_rtcp);\n}\n\nDo not set window size of srtp to zero\/*\n * webrtc-echo - A WebRTC echo server\n * Copyright (C) 2014 Stephan Thamm\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 \"srtp.h\"\n\n#include \n\n#include \"helper.h\"\n\nusing namespace v8;\n\nv8::Persistent Srtp::constructor;\nbool Srtp::initialized = false;\n\nstatic void createSession(srtp_t *session, const char *key, ssrc_type_t direction) {\n\tsrtp_policy_t policy;\n\n\tmemset(&policy, 0, sizeof(policy));\n\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtp);\n\tcrypto_policy_set_aes_cm_128_hmac_sha1_80(&policy.rtcp);\n\n\tpolicy.ssrc.type = direction;\n\tpolicy.ssrc.value = 0;\n\n\tpolicy.key = (unsigned char*) key;\n\n\t\/\/policy.window_size = 0;\n\tpolicy.allow_repeat_tx = 1;\n\n\tpolicy.next = NULL;\n\n\tsrtp_create(session, &policy);\n}\n\nSrtp::Srtp(const char *sendKey, const char *recvKey) {\n\tif(!initialized) {\n\t\tDEBUG(\"initializing srtp\");\n\t\tsrtp_init();\n\t\tinitialized = true;\n\t}\n\n\tcreateSession(&_sendSession, sendKey, ssrc_any_outbound);\n\tcreateSession(&_recvSession, recvKey, ssrc_any_inbound);\n}\n\nSrtp::~Srtp() {\n\tsrtp_dealloc(_sendSession);\n\tsrtp_dealloc(_recvSession);\n}\n\nvoid Srtp::init(v8::Handle exports) {\n\t\/\/ Prepare constructor template\n\tLocal tpl = FunctionTemplate::New(New);\n\ttpl->SetClassName(String::NewSymbol(\"Srtp\"));\n\ttpl->InstanceTemplate()->SetInternalFieldCount(1);\n\t\/\/ protoype\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtp\", protectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtp\", unprotectRtp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"protectRtcp\", protectRtcp);\n\tNODE_SET_PROTOTYPE_METHOD(tpl, \"unprotectRtcp\", unprotectRtcp);\n\tconstructor = Persistent::New(tpl->GetFunction());\n\t\/\/ export\n\texports->Set(String::NewSymbol(\"Srtp\"), constructor);\n}\n\nv8::Handle Srtp::New(const v8::Arguments& args) {\n\tHandleScope scope;\n\n\tif (args.IsConstructCall()) {\n\t\t\/\/ Invoked as constructor: `new MyObject(...)`\n\t\tif(!node::Buffer::HasInstance(args[0]) || !node::Buffer::HasInstance(args[1])) {\n\t\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffers\")));\n\t\t}\n\n\t\tconst char *sendKey = node::Buffer::Data(args[0]);\n\t\tconst char *recvKey = node::Buffer::Data(args[1]);\n\n\t\tSrtp* obj = new Srtp(sendKey, recvKey);\n\t\tobj->Wrap(args.This());\n\n\t\treturn args.This();\n\t} else {\n\t\t\/\/ Invoked as plain function `MyObject(...)`, turn into construct call.\n\t\tconst int argc = 1;\n\t\tLocal argv[1] = { argv[0] };\n\t\treturn scope.Close(constructor->NewInstance(argc, argv));\n\t}\n}\n\nv8::Handle Srtp::convert(const v8::Arguments& args, srtp_t session, convert_fun fun) {\n\tHandleScope scope;\n\n\t\/\/ type checking\n\n\tif(!node::Buffer::HasInstance(args[0])) {\n\t\treturn ThrowException(Exception::TypeError(String::New(\"Expected buffer\")));\n\t}\n\n\t\/\/ copy buffer for result\n\n\tint size = node::Buffer::Length(args[0]);\n\tchar *in_buf = node::Buffer::Data(args[0]);\n\n\tHandle tmp = node::Buffer::New(size + 32)->handle_;\n\tchar *out_buf = node::Buffer::Data(tmp);\n\n\tmemcpy(out_buf, in_buf, size);\n\n\t\/\/ actual crypt stuff\n\n\terr_status_t err = fun(session, out_buf, &size);\n\n\tif(err != err_status_ok) {\n\t\tDEBUG(\"srtp error \" << err);\n\t}\n\n\t\/\/ return slice of the right size\n\n\tHandle slice_v = tmp->Get(String::New(\"slice\")); \n\n\tif(!slice_v->IsFunction()) {\n\t\treturn ThrowException(Exception::Error(String::New(\"Buffer does not have a slice function\")));\n\t}\n\n\tHandle slice_f = v8::Handle::Cast(slice_v);\n\n\tconst int argc = 2;\n\tHandle argv[argc] = {\n\t\tInteger::New(0),\n\t\tInteger::New(size),\n\t};\n\n\tHandle res = slice_f->Call(tmp, argc, argv);\n\n\treturn scope.Close(res);\n}\n\nv8::Handle Srtp::protectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect);\n}\n\nv8::Handle Srtp::unprotectRtp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect);\n}\n\nv8::Handle Srtp::protectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_sendSession, srtp_protect_rtcp);\n}\n\nv8::Handle Srtp::unprotectRtcp(const v8::Arguments& args) {\n\tSrtp *srtp = node::ObjectWrap::Unwrap(args.This()->ToObject());\n\n\treturn convert(args, srtp->_recvSession, srtp_unprotect_rtcp);\n}\n\n<|endoftext|>"} {"text":"#include \"ompu\/music\/concrete\/context.hpp\"\n#include \"ompu\/music.hpp\"\n\n\nnamespace ompu { namespace music { namespace concrete {\n\nnamespace detail {\n\nbool ContextKeyboard::empty() const noexcept\n{\n return notes_.empty();\n}\n\nvoid ContextKeyboard::on(Note note) noexcept\n{\n notes_.emplace(std::move(note));\n}\n\nvoid ContextKeyboard::off(Note note) noexcept\n{\n notes_.erase(note);\n}\n\nvoid ContextKeyboard::clear()\n{\n notes_.clear();\n}\n\n} \/\/ detail\n\n\nContext::Context()\n : key_(keys::CMaj{})\n{}\n\nvoid Context::set(Key key) noexcept\n{\n key_ = std::move(key);\n}\n\n\nstd::vector\nContext::get_closest_chords(std::size_t const limit) const\n{\n auto const notes = kb_.notes();\n\n std::vector ret;\n ret.reserve(limit);\n\n try {\n for (auto possible_root : notes) {\n auto const root_height = possible_root.height();\n Chord chord{std::move(possible_root)};\n\n for (auto possible_note : notes) {\n if (possible_note.height() == root_height) continue;\n chord.add(std::move(possible_note));\n }\n\n ret.emplace_back(std::move(chord));\n if (ret.size() >= limit) break;\n }\n\n } catch (invalid_chord_error const& e) {\n if (logger_) {\n *logger_ << e.what() << std::endl;\n }\n }\n\n return ret;\n}\n\n\nvoid Context::add(Note note) noexcept\n{\n kb_.on(std::move(note));\n}\n\nvoid Context::remove(Note note) noexcept\n{\n kb_.off(std::move(note));\n}\n\nvoid Context::add_or_remove(bool is_add, Note note) noexcept\n{\n is_add ? kb_.on(std::move(note)) : kb_.off(std::move(note));\n}\n\nvoid Context::clear_notes()\n{\n kb_.clear();\n}\n\n}}} \/\/ ompu\nChord detection: auto shrink buffer#include \"ompu\/music\/concrete\/context.hpp\"\n#include \"ompu\/music.hpp\"\n\n\nnamespace ompu { namespace music { namespace concrete {\n\nnamespace detail {\n\nbool ContextKeyboard::empty() const noexcept\n{\n return notes_.empty();\n}\n\nvoid ContextKeyboard::on(Note note) noexcept\n{\n notes_.emplace(std::move(note));\n}\n\nvoid ContextKeyboard::off(Note note) noexcept\n{\n notes_.erase(note);\n}\n\nvoid ContextKeyboard::clear()\n{\n notes_.clear();\n}\n\n} \/\/ detail\n\n\nContext::Context()\n : key_(keys::CMaj{})\n{}\n\nvoid Context::set(Key key) noexcept\n{\n key_ = std::move(key);\n}\n\n\nstd::vector\nContext::get_closest_chords(std::size_t const limit) const\n{\n auto const notes = kb_.notes();\n\n std::vector ret;\n ret.reserve(limit);\n\n try {\n for (auto possible_root : notes) {\n auto const root_height = possible_root.height();\n Chord chord{std::move(possible_root)};\n\n for (auto possible_note : notes) {\n if (possible_note.height() == root_height) continue;\n chord.add(std::move(possible_note));\n }\n\n ret.emplace_back(std::move(chord));\n if (ret.size() >= limit) break;\n }\n\n } catch (invalid_chord_error const& e) {\n if (logger_) {\n *logger_ << e.what() << std::endl;\n }\n }\n\n ret.shrink_to_fit();\n return ret;\n}\n\n\nvoid Context::add(Note note) noexcept\n{\n kb_.on(std::move(note));\n}\n\nvoid Context::remove(Note note) noexcept\n{\n kb_.off(std::move(note));\n}\n\nvoid Context::add_or_remove(bool is_add, Note note) noexcept\n{\n is_add ? kb_.on(std::move(note)) : kb_.off(std::move(note));\n}\n\nvoid Context::clear_notes()\n{\n kb_.clear();\n}\n\n}}} \/\/ ompu\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n\/* MacLaurin Serie for sin(x), Taylor serie with a = 0\n * sin(x) = (Σn=0, ∞)(((-1 ^ n)\/(2n + 1)!)(x^(2n + 1)) \n \n * As the serie converges, the next term of the sum will be\n * smaller than the last one, and also will be alternating\n * signs between + and -, therefore each iteration aproaches\n * the correct value. We need to get a given number of correct\n * digits, so we must make the last term calculated lesser\n * than the required absolute error. *\/\n\nusing namespace std;\n\ndouble sin(double x, double E);\ndouble maxAbsErr(int cd);\nulong fact(ulong n);\n\nint main(int argc, char* args[]){\n double x;\n int cd;\n\n if(argc > 2){\n x = atof(args[1]);\n cd = atoi(args[2]);\n }else{\n cout << \"Input x and cd:\" << endl;\n cin >> x;\n cin >> cd;\n }\n \n double E = maxAbsErr(cd);\n\n cout << \"sin(\" << x << \") = \" << setprecision(cd) << sin(x, E) \n << \", E = \" << E << \", cd = \" << cd << endl;\n \n return 0;\n}\n\n\/\/sin(x) = (Σn=0, ∞)(((-1 ^ n)\/(2n + 1)!)(x^(2n + 1))\ndouble sin(double x, double E){\n\n double sin = 0.0d, term, last;\n\n int n = 0;\n bool bigger = true;\n while(bigger){\n last = sin;\n term = (pow(-1.0d, n) \/ fact(2*n + 1)) * pow(x, 2*n + 1);\n if(abs(sin + term - last) > E){\n sin += term;\n }else{\n bigger = false;\n }\n n++;\n }\n\n return sin;\n}\n\n\/\/Emax = 1.0 x 10 ^ -cd, asuming c++ uses floor as round method\ndouble maxAbsErr(int cd) {\n return pow(10.0d, -cd);\n}\n\nulong fact(ulong n){\n if(n <= 1) return 1;\n return n * fact(n - 1);\n}\nCleaned up the repository<|endoftext|>"} {"text":"\/*\n * Copyright 2016 - 2021 gary@drinkingtea.net\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 \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"core.hpp\"\n\nnamespace nostalgia::core {\n\nconstexpr auto Scale = 5;\n\nox::Error initGfx(Context *ctx) noexcept {\n\tauto id = new SdlImplData;\n\tctx->setWindowerData(id);\n\tid->window = SDL_CreateWindow(\"nostalgia\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n\t 240 * Scale, 160 * Scale,\n\t SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);\n\tif (id->window == nullptr) {\n\t\treturn OxError(1, SDL_GetError());\n\t}\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\tid->renderer = SDL_GL_CreateContext(id->window);\n\tif (id->renderer == nullptr) {\n\t\treturn OxError(1, SDL_GetError());\n\t}\n\toxReturnError(renderer::init(ctx));\n\treturn OxError(0);\n}\n\nox::Error shutdownGfx(Context *ctx) noexcept {\n\toxReturnError(renderer::shutdown(ctx));\n\tauto id = ctx->windowerData();\n\tSDL_GL_DeleteContext(id->renderer);\n\tSDL_DestroyWindow(id->window);\n\tctx->setWindowerData(nullptr);\n\tdelete id;\n\treturn OxError(0);\n}\n\nint getScreenWidth(Context *ctx) noexcept {\n\tauto id = ctx->windowerData();\n\tint x = 0, y = 0;\n\tSDL_GetWindowSize(id->window, &x, &y);\n\treturn x;\n}\n\nint getScreenHeight(Context *ctx) noexcept {\n\tauto id = ctx->windowerData();\n\tint x = 0, y = 0;\n\tSDL_GetWindowSize(id->window, &x, &y);\n\treturn y;\n}\n\ncommon::Size getScreenSize(Context *ctx) noexcept {\n\tauto id = ctx->windowerData();\n\tint x = 0, y = 0;\n\tSDL_GetWindowSize(id->window, &x, &y);\n\treturn {x, y};\n}\n\n}\n[nostalgia\/core\/sdl] Cleanup\/*\n * Copyright 2016 - 2021 gary@drinkingtea.net\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 \n\n#include \n\n#include \n\n#include \n#include \n\n#include \"core.hpp\"\n\nnamespace nostalgia::core {\n\nconstexpr auto Scale = 5;\n\nox::Error initGfx(Context *ctx) noexcept {\n\tauto id = new SdlImplData;\n\tctx->setWindowerData(id);\n\tid->window = SDL_CreateWindow(\"nostalgia\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\n\t 240 * Scale, 160 * Scale,\n\t SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI);\n\tif (id->window == nullptr) {\n\t\treturn OxError(1, SDL_GetError());\n\t}\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\tid->renderer = SDL_GL_CreateContext(id->window);\n\tif (id->renderer == nullptr) {\n\t\treturn OxError(1, SDL_GetError());\n\t}\n\toxReturnError(renderer::init(ctx));\n\treturn OxError(0);\n}\n\nox::Error shutdownGfx(Context *ctx) noexcept {\n\toxReturnError(renderer::shutdown(ctx));\n\tauto id = ctx->windowerData();\n\tSDL_GL_DeleteContext(id->renderer);\n\tSDL_DestroyWindow(id->window);\n\tctx->setWindowerData(nullptr);\n\tdelete id;\n\treturn OxError(0);\n}\n\nint getScreenWidth(Context *ctx) noexcept {\n\tauto id = ctx->windowerData();\n\tint x = 0, y = 0;\n\tSDL_GetWindowSize(id->window, &x, &y);\n\treturn x;\n}\n\nint getScreenHeight(Context *ctx) noexcept {\n\tauto id = ctx->windowerData();\n\tint x = 0, y = 0;\n\tSDL_GetWindowSize(id->window, &x, &y);\n\treturn y;\n}\n\ncommon::Size getScreenSize(Context *ctx) noexcept {\n\tauto id = ctx->windowerData();\n\tint x = 0, y = 0;\n\tSDL_GetWindowSize(id->window, &x, &y);\n\treturn {x, y};\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define DEBUG 0\n#define MAX_N 5001\n\nunsigned long long sumstb[MAX_N];\nunsigned long long stb[MAX_N];\nunsigned long long sumbts[MAX_N];\nunsigned long long bts[MAX_N];\n\nint n;\n\n\/\/ 0 - small to big, 1 - big to small\nunsigned long long cost[2][MAX_N][MAX_N];\n\nusing namespace std;\n\nclass Mine\n{\npublic:\n int x, w;\n\n Mine(int _x = 0, int _w = 0)\n {\n x = _x;\n w = _w;\n }\n\n void operator=(const Mine &m)\n {\n x = m.x;\n w = m.w;\n }\n};\n\nvector mines(MAX_N);\n\nbool func(const Mine &m1, const Mine &m2)\n{\n return (m1.x < m2.x);\n}\n\ninline long long costFromStoB(int s, int b)\n{\n long long ret = 0;\n\n if (s < b)\n {\n if (0 == s)\n {\n ret = stb[b];\n }\n else\n {\n ret = stb[b] - stb[s] - sumstb[s - 1] * (long long)(mines[b].x - mines[s].x);\n }\n }\n\n return ret;\n}\n\ninline long long costFromBtoS(int s, int b)\n{\n long long ret = 0;\n\n if (s < b)\n {\n if (n - 1 == b)\n {\n ret = bts[s];\n }\n else\n {\n ret = bts[s] - bts[b] - sumbts[b + 1] * (long long)(mines[b].x - mines[s].x);\n }\n }\n\n return ret;\n}\n\nint main()\n{\n\/\/ cout << \"begin\" << endl;\n#if DEBUG\n ifstream inFile;\n inFile.open(\"input.txt\");\n#endif\n\n int k;\n#if DEBUG\n inFile >> n >> k;\n#else\n cin >> n >> k;\n#endif\n\n for (size_t i = 0; i < n; i++)\n {\n int x, w;\n#if DEBUG\n inFile >> x >> w;\n#else\n cin >> x >> w;\n#endif\n\n mines[i].x = x;\n mines[i].w = w;\n }\n\n \/\/ sort\n sort(mines.begin(), mines.begin() + n, func);\n\n \/\/ small to big\n sumstb[0] = mines[0].w;\n for (size_t i = 1; i < n; i++)\n {\n sumstb[i] = mines[i].w + sumstb[i - 1];\n\n stb[i] = stb[i - 1] + sumstb[i - 1] * (mines[i].x - mines[i - 1].x);\n }\n\n \/\/ big to small\n sumbts[n - 1] = mines[n - 1].w;\n for (int i = n - 2; i >= 0; i--)\n {\n sumbts[i] = mines[i].w + sumbts[i + 1];\n\n bts[i] = bts[i + 1] + sumbts[i + 1] * (mines[i + 1].x - mines[i].x);\n }\n\n int tmove = n - k;\n unsigned long long ret = 0;\n\n for (size_t i = 0; i < n; i++)\n {\n for (size_t m = 0; m <= tmove; m++)\n {\n if (0 < i)\n {\n unsigned long long tmp = cost[0][i - 1][m];\n if (0 == tmp)\n {\n tmp = cost[1][i - 1][m];\n }\n else\n {\n if (tmp > cost[1][i - 1][m] && 0 < cost[1][i - 1][m])\n {\n tmp = cost[1][i - 1][m];\n }\n }\n \n if (0 < tmp && (0 == cost[0][i][m] || cost[0][i][m] > tmp))\n {\n cost[0][i][m] = tmp;\n if (tmove == m)\n {\n if (0 == ret || ret > cost[0][i][m])\n {\n ret = cost[0][i][m];\n }\n }\n }\n \n if (0 < tmp && (0 == cost[1][i][m] || cost[1][i][m] > tmp))\n {\n cost[1][i][m] = tmp;\n if (tmove == m)\n {\n if (0 == ret || ret > cost[1][i][m])\n {\n ret = cost[1][i][m];\n }\n }\n }\n }\n\n for (int j = i - 1; j >= 0 && j >= i - m; j--)\n {\n if (0 < m - (i - j) && 0 == cost[1][j][m - (i - j)])\n {\n continue;\n }\n \n if (0 == cost[0][i][m] || cost[0][i][m] > (cost[1][j][m - (i - j)] + costFromStoB(j, i)))\n {\n cost[0][i][m] = cost[1][j][m - (i - j)] + costFromStoB(j, i);\n if (tmove == m)\n {\n if (0 == ret || ret > cost[0][i][m])\n {\n ret = cost[0][i][m];\n }\n }\n }\n }\n\n for (size_t j = i + 1; j < n; j++)\n {\n if (m + j - i > tmove)\n {\n break;\n }\n\n unsigned long long tmp = cost[0][i][m];\n if (0 == tmp)\n {\n tmp = cost[1][i][m];\n }\n else\n {\n if (tmp > cost[1][i][m] && 0 < cost[1][i][m])\n {\n tmp = cost[1][i][m];\n }\n }\n \n if (0 < m && 0 == tmp)\n {\n break;\n }\n\n if (0 == cost[1][j + 1][m + j - i] || cost[1][j + 1][m + j - i] > (tmp + costFromBtoS(i, j)))\n {\n cost[1][j + 1][m + j - i] = tmp + costFromBtoS(i, j);\n if (tmove == m + j - i)\n {\n if (0 == ret || ret > cost[1][j + 1][m + j - i])\n {\n ret = cost[1][j + 1][m + j - i];\n }\n }\n }\n }\n }\n }\n\n cout << ret << endl;\n\n#if DEBUG\n inFile.close();\n#endif\n\n return 0;\n}\n49.64 points#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#define DEBUG 0\n#define MAX_N 5001\n\nunsigned long long sumstb[MAX_N];\nunsigned long long stb[MAX_N];\nunsigned long long sumbts[MAX_N];\nunsigned long long bts[MAX_N];\n\nint n;\n\n\/\/ 0 - small to big, 1 - big to small\nunsigned long long cost[2][MAX_N][MAX_N];\n\nusing namespace std;\n\nclass Mine\n{\npublic:\n int x, w;\n\n Mine(int _x = 0, int _w = 0)\n {\n x = _x;\n w = _w;\n }\n\n void operator=(const Mine &m)\n {\n x = m.x;\n w = m.w;\n }\n};\n\nvector mines(MAX_N);\n\nbool func(const Mine &m1, const Mine &m2)\n{\n return (m1.x < m2.x);\n}\n\ninline long long costFromStoB(int s, int b)\n{\n long long ret = 0;\n\n if (s < b)\n {\n if (0 == s)\n {\n ret = stb[b];\n }\n else\n {\n ret = stb[b] - stb[s] - sumstb[s - 1] * (long long)(mines[b].x - mines[s].x);\n }\n }\n\n return ret;\n}\n\ninline long long costFromBtoS(int s, int b)\n{\n long long ret = 0;\n\n if (s < b)\n {\n if (n - 1 == b)\n {\n ret = bts[s];\n }\n else\n {\n ret = bts[s] - bts[b] - sumbts[b + 1] * (long long)(mines[b].x - mines[s].x);\n }\n }\n\n return ret;\n}\n\nint main()\n{\n#if DEBUG\n ifstream inFile;\n inFile.open(\"input.txt\");\n#endif\n\n int k;\n#if DEBUG\n inFile >> n >> k;\n#else\n cin >> n >> k;\n#endif\n\n for (size_t i = 0; i < n; i++)\n {\n int x, w;\n#if DEBUG\n inFile >> x >> w;\n#else\n cin >> x >> w;\n#endif\n\n mines[i].x = x;\n mines[i].w = w;\n }\n\n \/\/ sort\n sort(mines.begin(), mines.begin() + n, func);\n\n \/\/ small to big\n sumstb[0] = mines[0].w;\n for (size_t i = 1; i < n; i++)\n {\n sumstb[i] = mines[i].w + sumstb[i - 1];\n\n stb[i] = stb[i - 1] + sumstb[i - 1] * (mines[i].x - mines[i - 1].x);\n }\n\n \/\/ big to small\n sumbts[n - 1] = mines[n - 1].w;\n for (int i = n - 2; i >= 0; i--)\n {\n sumbts[i] = mines[i].w + sumbts[i + 1];\n\n bts[i] = bts[i + 1] + sumbts[i + 1] * (mines[i + 1].x - mines[i].x);\n }\n\n int tmove = n - k;\n unsigned long long ret = 0;\n\n for (size_t i = 0; i < n; i++)\n {\n for (size_t m = 0; m <= tmove; m++)\n {\n if (0 < i)\n {\n unsigned long long tmp = cost[0][i - 1][m];\n if (0 == tmp)\n {\n tmp = cost[1][i - 1][m];\n }\n else\n {\n if (tmp > cost[1][i - 1][m] && 0 < cost[1][i - 1][m])\n {\n tmp = cost[1][i - 1][m];\n }\n }\n \n if (0 < tmp && (0 == cost[0][i][m] || cost[0][i][m] > tmp))\n {\n cost[0][i][m] = tmp;\n if (tmove == m)\n {\n if (0 == ret || ret > cost[0][i][m])\n {\n ret = cost[0][i][m];\n }\n }\n }\n \n if (0 < tmp && (0 == cost[1][i][m] || cost[1][i][m] > tmp))\n {\n cost[1][i][m] = tmp;\n if (tmove == m)\n {\n if (0 == ret || ret > cost[1][i][m])\n {\n ret = cost[1][i][m];\n }\n }\n }\n }\n\n for (int j = i - 1; j >= 0 && j >= i - m; j--)\n {\n if (0 < m - (i - j) && 0 == cost[1][j][m - (i - j)])\n {\n continue;\n }\n\n if (0 < ret && ret <= costFromStoB(j, i))\n {\n break;\n }\n \n if (0 == cost[0][i][m] || cost[0][i][m] > (cost[1][j][m - (i - j)] + costFromStoB(j, i)))\n {\n cost[0][i][m] = cost[1][j][m - (i - j)] + costFromStoB(j, i);\n if (tmove == m)\n {\n if (0 == ret || ret > cost[0][i][m])\n {\n ret = cost[0][i][m];\n }\n }\n }\n }\n\n unsigned long long tmp = cost[0][i][m];\n if (0 == tmp)\n {\n tmp = cost[1][i][m];\n }\n else\n {\n if (tmp > cost[1][i][m] && 0 < cost[1][i][m])\n {\n tmp = cost[1][i][m];\n }\n }\n\n for (size_t j = i + 1; j < n; j++)\n {\n if (m + j - i > tmove)\n {\n break;\n }\n \n if (0 < m && 0 == tmp)\n {\n break;\n }\n\n if (0 < ret && (ret <= tmp + costFromBtoS(i, j)))\n {\n break;\n }\n\n if (0 == cost[1][j + 1][m + j - i] || cost[1][j + 1][m + j - i] > (tmp + costFromBtoS(i, j)))\n {\n cost[1][j + 1][m + j - i] = tmp + costFromBtoS(i, j);\n if (tmove == m + j - i)\n {\n if (0 == ret || ret > cost[1][j + 1][m + j - i])\n {\n ret = cost[1][j + 1][m + j - i];\n }\n }\n }\n }\n }\n }\n\n cout << ret << endl;\n\n#if DEBUG\n inFile.close();\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef CXX_CONVERSIONS_HXX\n# define CXX_CONVERSIONS_HXX\n\n# include \n\n# include \n# include \n# include \n\n# include \n# include \n# include \n# include \n# include \n# include \n\nnamespace object\n{\n \/\/ Nothing to do for objects\n template <>\n struct CxxConvert >\n {\n typedef libport::intrusive_ptr target_type;\n\n static rObject\n to(const rObject& o, unsigned)\n {\n return o;\n }\n\n static rObject\n from(rObject o)\n {\n if (!o)\n return void_class;\n return o;\n }\n };\n\n \/\/ Convert between Urbi types\n template \n struct CxxConvert >\n {\n typedef libport::intrusive_ptr target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as();\n }\n\n static rObject\n from(const target_type& v)\n {\n return v;\n }\n };\n\n \/\/ Convert between Urbi types pointers\n template \n struct CxxConvert\n {\n typedef Urbi* target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as().get();\n }\n\n static rObject\n from(target_type v)\n {\n return v;\n }\n };\n\n \/\/ Conversion with int\n template<>\n struct CxxConvert\n {\n typedef int target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->to_int();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with unsigned chars\n template<>\n struct CxxConvert\n {\n typedef unsigned char target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n int res = o->as()->to_int();\n if (res < 0 || res > 255)\n runner::raise_bad_integer_error(res, \"expected a number between 0 and 255, got %s\");\n return res;\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with float\n template<>\n struct CxxConvert\n {\n typedef float target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, Float::proto, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with unsigned int\n template<>\n struct CxxConvert\n {\n typedef unsigned int target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->to_unsigned_int();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with unsigned_type\n template<>\n struct CxxConvert\n {\n typedef Float::unsigned_type target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->to_unsigned_type();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with floating point\n template<>\n struct CxxConvert\n {\n typedef Float::value_type target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with std::strings\n template <>\n struct CxxConvert\n {\n typedef std::string target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(const target_type& v)\n {\n return new String(v);\n }\n };\n\n \/\/ Conversion with libport::Symbols\n template <>\n struct CxxConvert\n {\n typedef libport::Symbol target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return libport::Symbol(o->as()->value_get());\n }\n\n static rObject\n from(target_type v)\n {\n return new String(v.name_get());\n }\n };\n\n \/\/ Conversion with bools\n template <>\n struct CxxConvert\n {\n typedef bool target_type;\n static target_type\n to(const rObject& o, unsigned)\n {\n return is_true(o);\n }\n\n static rObject\n from(target_type v)\n {\n return v ? true_class : false_class;\n }\n };\n\n \/\/ Conversion with libport::path\n template <>\n struct CxxConvert\n {\n typedef libport::path target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n if (rString str = o->as())\n return str->value_get();\n type_check(o, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(const target_type& v)\n {\n return new Path(v);\n }\n };\n\n \/\/ Conversion with containers\n#define CONTAINER(Name, Method, ExtraT, ExtraTDecl) \\\n template \\\n struct CxxConvert > \\\n { \\\n typedef Name target_type; \\\n \\\n static target_type \\\n to(const rObject& o, unsigned idx) \\\n { \\\n type_check(o);\t\t\t\t\t\t\\\n Name res; \\\n foreach (const rObject& elt, o->as()->value_get()) \\\n res.Method(CxxConvert::to(elt, idx)); \\\n return res; \\\n } \\\n \\\n static rObject \\\n from(const target_type& v) \\\n { \\\n objects_type res; \\\n foreach (const T& elt, v) \\\n res.push_back(CxxConvert::from(elt)); \\\n return new List(res); \\\n } \\\n };\n#define comma ,\n CONTAINER(std::set, insert, \/**\/, \/**\/);\n CONTAINER(std::vector, push_back, \/**\/, \/**\/);\n CONTAINER(std::deque, push_back, \/**\/, \/**\/);\n CONTAINER(libport::ReservedVector, push_back, comma R, comma int R);\n#undef comma\n#undef CONTAINER\n\n\n \/\/ Conversion with boost::optional\n template \n struct CxxConvert >\n {\n typedef boost::optional target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n if (o == void_class)\n return target_type();\n return CxxConvert::to(o, idx);\n }\n\n static rObject\n from(const target_type& v)\n {\n if (!v)\n return void_class;\n return CxxConvert::from(v.get());\n }\n };\n\n\n template \n rObject to_urbi(const T& v)\n {\n return CxxConvert::from(v);\n }\n\n template \n T from_urbi(rObject v)\n {\n return CxxConvert::to(v, 0);\n }\n}\n\n#endif\nAdd Urbi\/C++ conversions for std::pair.#ifndef CXX_CONVERSIONS_HXX\n# define CXX_CONVERSIONS_HXX\n\n# include \n\n# include \n# include \n# include \n\n# include \n# include \n# include \n# include \n# include \n# include \n\nnamespace object\n{\n \/\/ Nothing to do for objects\n template <>\n struct CxxConvert >\n {\n typedef libport::intrusive_ptr target_type;\n\n static rObject\n to(const rObject& o, unsigned)\n {\n return o;\n }\n\n static rObject\n from(rObject o)\n {\n if (!o)\n return void_class;\n return o;\n }\n };\n\n \/\/ Convert between Urbi types\n template \n struct CxxConvert >\n {\n typedef libport::intrusive_ptr target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as();\n }\n\n static rObject\n from(const target_type& v)\n {\n return v;\n }\n };\n\n \/\/ Convert between Urbi types pointers\n template \n struct CxxConvert\n {\n typedef Urbi* target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as().get();\n }\n\n static rObject\n from(target_type v)\n {\n return v;\n }\n };\n\n \/\/ Conversion with int\n template<>\n struct CxxConvert\n {\n typedef int target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->to_int();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with unsigned chars\n template<>\n struct CxxConvert\n {\n typedef unsigned char target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n int res = o->as()->to_int();\n if (res < 0 || res > 255)\n runner::raise_bad_integer_error(res, \"expected a number between 0 and 255, got %s\");\n return res;\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with float\n template<>\n struct CxxConvert\n {\n typedef float target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, Float::proto, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with unsigned int\n template<>\n struct CxxConvert\n {\n typedef unsigned int target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->to_unsigned_int();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with unsigned_type\n template<>\n struct CxxConvert\n {\n typedef Float::unsigned_type target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->to_unsigned_type();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with floating point\n template<>\n struct CxxConvert\n {\n typedef Float::value_type target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(target_type v)\n {\n return new Float(v);\n }\n };\n\n \/\/ Conversion with std::strings\n template <>\n struct CxxConvert\n {\n typedef std::string target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(const target_type& v)\n {\n return new String(v);\n }\n };\n\n \/\/ Conversion with libport::Symbols\n template <>\n struct CxxConvert\n {\n typedef libport::Symbol target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n return libport::Symbol(o->as()->value_get());\n }\n\n static rObject\n from(target_type v)\n {\n return new String(v.name_get());\n }\n };\n\n \/\/ Conversion with bools\n template <>\n struct CxxConvert\n {\n typedef bool target_type;\n static target_type\n to(const rObject& o, unsigned)\n {\n return is_true(o);\n }\n\n static rObject\n from(target_type v)\n {\n return v ? true_class : false_class;\n }\n };\n\n \/\/ Conversion with libport::path\n template <>\n struct CxxConvert\n {\n typedef libport::path target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n if (rString str = o->as())\n return str->value_get();\n type_check(o, idx);\n return o->as()->value_get();\n }\n\n static rObject\n from(const target_type& v)\n {\n return new Path(v);\n }\n };\n\n \/\/ Conversion with containers\n#define CONTAINER(Name, Method, ExtraT, ExtraTDecl) \\\n template \\\n struct CxxConvert > \\\n { \\\n typedef Name target_type; \\\n \\\n static target_type \\\n to(const rObject& o, unsigned idx) \\\n { \\\n type_check(o);\t\t\t\t\t\t\\\n Name res; \\\n foreach (const rObject& elt, o->as()->value_get()) \\\n res.Method(CxxConvert::to(elt, idx)); \\\n return res; \\\n } \\\n \\\n static rObject \\\n from(const target_type& v) \\\n { \\\n objects_type res; \\\n foreach (const T& elt, v) \\\n res.push_back(CxxConvert::from(elt)); \\\n return new List(res); \\\n } \\\n };\n#define comma ,\n CONTAINER(std::set, insert, \/**\/, \/**\/);\n CONTAINER(std::vector, push_back, \/**\/, \/**\/);\n CONTAINER(std::deque, push_back, \/**\/, \/**\/);\n CONTAINER(libport::ReservedVector, push_back, comma R, comma int R);\n#undef comma\n#undef CONTAINER\n\n\n \/\/ Conversion with boost::optional\n template \n struct CxxConvert >\n {\n typedef boost::optional target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n if (o == void_class)\n return target_type();\n return CxxConvert::to(o, idx);\n }\n\n static rObject\n from(const target_type& v)\n {\n if (!v)\n return void_class;\n return CxxConvert::from(v.get());\n }\n };\n\n \/\/ Conversion with std::pair\n template \n struct CxxConvert >\n {\n typedef std::pair target_type;\n static target_type\n to(const rObject& o, unsigned idx)\n {\n type_check(o, idx);\n const List::value_type& list = o->as()->value_get();\n if (list.size() != 2)\n runner::raise_primitive_error(\"Expected a list of size 2\");\n return std::make_pair(CxxConvert::to(list[0]),\n CxxConvert::to(list[1]));\n }\n\n static rObject\n from(const target_type& v)\n {\n List::value_type content;\n content.push_back(CxxConvert::from(v.first ));\n content.push_back(CxxConvert::from(v.second));\n return new List(content);\n }\n };\n\n template \n rObject to_urbi(const T& v)\n {\n return CxxConvert::from(v);\n }\n\n template \n T from_urbi(rObject v)\n {\n return CxxConvert::to(v, 0);\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Use of this source code is governed by MIT license that can be found in the\n * LICENSE file in the root of the source tree. All contributing project authors\n * may be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"FFmpegSource.h\"\n#include \"Common\/config.h\"\n#include \"Common\/MediaSource.h\"\n#include \"Util\/File.h\"\n#include \"System.h\"\n#include \"Thread\/WorkThreadPool.h\"\n#include \"Network\/sockutil.h\"\n\nnamespace FFmpeg {\n#define FFmpeg_FIELD \"ffmpeg.\"\nconst string kBin = FFmpeg_FIELD\"bin\";\nconst string kCmd = FFmpeg_FIELD\"cmd\";\nconst string kLog = FFmpeg_FIELD\"log\";\nconst string kSnap = FFmpeg_FIELD\"snap\";\n\nonceToken token([]() {\n#ifdef _WIN32\n string ffmpeg_bin = trim(System::execute(\"where ffmpeg\"));\n#else\n string ffmpeg_bin = trim(System::execute(\"which ffmpeg\"));\n#endif\n \/\/默认ffmpeg命令路径为环境变量中路径\n mINI::Instance()[kBin] = ffmpeg_bin.empty() ? \"ffmpeg\" : ffmpeg_bin;\n \/\/ffmpeg日志保存路径\n mINI::Instance()[kLog] = \".\/ffmpeg\/ffmpeg.log\";\n mINI::Instance()[kCmd] = \"%s -re -i %s -c:a aac -strict -2 -ar 44100 -ab 48k -c:v libx264 -f flv %s\";\n mINI::Instance()[kSnap] = \"%s -i %s -y -f mjpeg -t 0.001 %s\";\n});\n}\n\nFFmpegSource::FFmpegSource() {\n _poller = EventPollerPool::Instance().getPoller();\n}\n\nFFmpegSource::~FFmpegSource() {\n DebugL;\n}\n\nstatic bool is_local_ip(const string &ip){\n if (ip == \"127.0.0.1\" || ip == \"localhost\") {\n return true;\n }\n auto ips = SockUtil::getInterfaceList();\n for (auto &obj : ips) {\n if (ip == obj[\"ip\"]) {\n return true;\n }\n }\n return false;\n}\n\nvoid FFmpegSource::play(const string &src_url,const string &dst_url,int timeout_ms,const onPlay &cb) {\n GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin);\n GET_CONFIG(string,ffmpeg_cmd,FFmpeg::kCmd);\n GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog);\n\n _src_url = src_url;\n _dst_url = dst_url;\n _media_info.parse(dst_url);\n\n char cmd[1024] = {0};\n snprintf(cmd, sizeof(cmd),ffmpeg_cmd.data(),ffmpeg_bin.data(),src_url.data(),dst_url.data());\n _process.run(cmd,ffmpeg_log.empty() ? \"\" : File::absolutePath(\"\",ffmpeg_log));\n InfoL << cmd;\n\n if (is_local_ip(_media_info._host)) {\n \/\/推流给自己的,通过判断流是否注册上来判断是否正常\n if(_media_info._schema != RTSP_SCHEMA && _media_info._schema != RTMP_SCHEMA){\n cb(SockException(Err_other,\"本服务只支持rtmp\/rtsp推流\"));\n return;\n }\n weak_ptr weakSelf = shared_from_this();\n findAsync(timeout_ms,[cb,weakSelf,timeout_ms](const MediaSource::Ptr &src){\n auto strongSelf = weakSelf.lock();\n if(!strongSelf){\n \/\/自己已经销毁\n return;\n }\n if(src){\n \/\/推流给自己成功\n cb(SockException());\n strongSelf->onGetMediaSource(src);\n strongSelf->startTimer(timeout_ms);\n return;\n }\n \/\/推流失败\n if(!strongSelf->_process.wait(false)){\n \/\/ffmpeg进程已经退出\n cb(SockException(Err_other,StrPrinter << \"ffmpeg已经退出,exit code = \" << strongSelf->_process.exit_code()));\n return;\n }\n \/\/ffmpeg进程还在线,但是等待推流超时\n cb(SockException(Err_other,\"等待超时\"));\n });\n } else{\n \/\/推流给其他服务器的,通过判断FFmpeg进程是否在线判断是否成功\n weak_ptr weakSelf = shared_from_this();\n _timer = std::make_shared(timeout_ms \/ 1000,[weakSelf,cb,timeout_ms](){\n auto strongSelf = weakSelf.lock();\n if(!strongSelf){\n \/\/自身已经销毁\n return false;\n }\n \/\/FFmpeg还在线,那么我们认为推流成功\n if(strongSelf->_process.wait(false)){\n cb(SockException());\n strongSelf->startTimer(timeout_ms);\n return false;\n }\n \/\/ffmpeg进程已经退出\n cb(SockException(Err_other,StrPrinter << \"ffmpeg已经退出,exit code = \" << strongSelf->_process.exit_code()));\n return false;\n },_poller);\n }\n}\n\nvoid FFmpegSource::findAsync(int maxWaitMS, const function &cb) {\n auto src = MediaSource::find(_media_info._schema,\n _media_info._vhost,\n _media_info._app,\n _media_info._streamid);\n if(src || !maxWaitMS){\n cb(src);\n return;\n }\n\n void *listener_tag = this;\n \/\/若干秒后执行等待媒体注册超时回调\n auto onRegistTimeout = _poller->doDelayTask(maxWaitMS,[cb,listener_tag](){\n \/\/取消监听该事件\n NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);\n cb(nullptr);\n return 0;\n });\n\n weak_ptr weakSelf = shared_from_this();\n auto onRegist = [listener_tag,weakSelf,cb,onRegistTimeout](BroadcastMediaChangedArgs) {\n auto strongSelf = weakSelf.lock();\n if(!strongSelf) {\n \/\/本身已经销毁,取消延时任务\n onRegistTimeout->cancel();\n NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);\n return;\n }\n\n if (!bRegist ||\n sender.getSchema() != strongSelf->_media_info._schema ||\n sender.getVhost() != strongSelf->_media_info._vhost ||\n sender.getApp() != strongSelf->_media_info._app ||\n sender.getId() != strongSelf->_media_info._streamid) {\n \/\/不是自己感兴趣的事件,忽略之\n return;\n }\n\n \/\/查找的流终于注册上了;取消延时任务,防止多次回调\n onRegistTimeout->cancel();\n \/\/取消事件监听\n NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);\n\n \/\/切换到自己的线程再回复\n strongSelf->_poller->async([listener_tag,weakSelf,cb](){\n auto strongSelf = weakSelf.lock();\n if(!strongSelf) {\n return;\n }\n \/\/再找一遍媒体源,一般能找到\n strongSelf->findAsync(0,cb);\n }, false);\n };\n \/\/监听媒体注册事件\n NoticeCenter::Instance().addListener(listener_tag, Broadcast::kBroadcastMediaChanged, onRegist);\n}\n\n\/**\n * 定时检查媒体是否在线\n *\/\nvoid FFmpegSource::startTimer(int timeout_ms) {\n weak_ptr weakSelf = shared_from_this();\n _timer = std::make_shared(1, [weakSelf, timeout_ms]() {\n auto strongSelf = weakSelf.lock();\n if (!strongSelf) {\n \/\/自身已经销毁\n return false;\n }\n if (is_local_ip(strongSelf->_media_info._host)) {\n \/\/推流给自己的,我们通过检查是否已经注册来判断FFmpeg是否工作正常\n strongSelf->findAsync(0, [&](const MediaSource::Ptr &src) {\n \/\/同步查找流\n if (!src) {\n \/\/流不在线,重新拉流, 这里原先是10秒超时,实际发现10秒不够,改成20秒了\n if(strongSelf->_replay_ticker.elapsedTime() > 20 * 1000){\n \/\/上次重试时间超过10秒,那么再重试FFmpeg拉流\n strongSelf->_replay_ticker.resetTime();\n strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [](const SockException &) {});\n }\n }\n });\n } else {\n \/\/推流给其他服务器的,我们通过判断FFmpeg进程是否在线,如果FFmpeg推流中断,那么它应该会自动退出\n if (!strongSelf->_process.wait(false)) {\n \/\/ffmpeg不在线,重新拉流\n strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [weakSelf](const SockException &ex) {\n if(!ex){\n \/\/没有错误\n return;\n }\n auto strongSelf = weakSelf.lock();\n if (!strongSelf) {\n \/\/自身已经销毁\n return;\n }\n \/\/上次重试时间超过10秒,那么再重试FFmpeg拉流\n strongSelf->startTimer(10 * 1000);\n });\n }\n }\n return true;\n }, _poller);\n}\n\nvoid FFmpegSource::setOnClose(const function &cb){\n _onClose = cb;\n}\n\nbool FFmpegSource::close(MediaSource &sender, bool force) {\n auto listener = _listener.lock();\n if(listener && !listener->close(sender,force)){\n \/\/关闭失败\n return false;\n }\n \/\/该流无人观看,我们停止吧\n if(_onClose){\n _onClose();\n }\n return true;\n}\n\nMediaOriginType FFmpegSource::getOriginType(MediaSource &sender) const{\n return MediaOriginType::ffmpeg_pull;\n}\n\nstring FFmpegSource::getOriginUrl(MediaSource &sender) const{\n return _src_url;\n}\n\nstd::shared_ptr FFmpegSource::getOriginSock(MediaSource &sender) const {\n return nullptr;\n}\n\nvoid FFmpegSource::onGetMediaSource(const MediaSource::Ptr &src) {\n auto listener = src->getListener();\n if (listener.lock().get() != this) {\n \/\/防止多次进入onGetMediaSource函数导致无效递归调用的bug\n _listener = listener;\n src->setListener(shared_from_this());\n } else {\n WarnL << \"多次触发onGetMediaSource事件:\"\n << src->getSchema() << \"\/\"\n << src->getVhost() << \"\/\"\n << src->getApp() << \"\/\"\n << src->getId();\n }\n}\n\nvoid FFmpegSnap::makeSnap(const string &play_url, const string &save_path, float timeout_sec, const function &cb) {\n GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin);\n GET_CONFIG(string,ffmpeg_snap,FFmpeg::kSnap);\n GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog);\n\n std::shared_ptr process = std::make_shared();\n auto delayTask = EventPollerPool::Instance().getPoller()->doDelayTask(timeout_sec * 1000,[process,cb](){\n if(process->wait(false)){\n \/\/FFmpeg进程还在运行,超时就关闭它\n process->kill(2000);\n }\n return 0;\n });\n\n WorkThreadPool::Instance().getPoller()->async([process,play_url,save_path,delayTask,cb](){\n char cmd[1024] = {0};\n snprintf(cmd, sizeof(cmd),ffmpeg_snap.data(),ffmpeg_bin.data(),play_url.data(),save_path.data());\n process->run(cmd,ffmpeg_log.empty() ? \"\" : File::absolutePath(\"\",ffmpeg_log));\n \/\/等待FFmpeg进程退出\n process->wait(true);\n \/\/FFmpeg进程退出了可以取消定时器了\n delayTask->cancel();\n \/\/执行回调函数\n cb(process->exit_code() == 0);\n });\n}\n\n修复FFmpeg截图可能失败的问题\/*\n * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Use of this source code is governed by MIT license that can be found in the\n * LICENSE file in the root of the source tree. All contributing project authors\n * may be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"FFmpegSource.h\"\n#include \"Common\/config.h\"\n#include \"Common\/MediaSource.h\"\n#include \"Util\/File.h\"\n#include \"System.h\"\n#include \"Thread\/WorkThreadPool.h\"\n#include \"Network\/sockutil.h\"\n\nnamespace FFmpeg {\n#define FFmpeg_FIELD \"ffmpeg.\"\nconst string kBin = FFmpeg_FIELD\"bin\";\nconst string kCmd = FFmpeg_FIELD\"cmd\";\nconst string kLog = FFmpeg_FIELD\"log\";\nconst string kSnap = FFmpeg_FIELD\"snap\";\n\nonceToken token([]() {\n#ifdef _WIN32\n string ffmpeg_bin = trim(System::execute(\"where ffmpeg\"));\n#else\n string ffmpeg_bin = trim(System::execute(\"which ffmpeg\"));\n#endif\n \/\/默认ffmpeg命令路径为环境变量中路径\n mINI::Instance()[kBin] = ffmpeg_bin.empty() ? \"ffmpeg\" : ffmpeg_bin;\n \/\/ffmpeg日志保存路径\n mINI::Instance()[kLog] = \".\/ffmpeg\/ffmpeg.log\";\n mINI::Instance()[kCmd] = \"%s -re -i %s -c:a aac -strict -2 -ar 44100 -ab 48k -c:v libx264 -f flv %s\";\n mINI::Instance()[kSnap] = \"%s -i %s -y -f mjpeg -t 0.001 %s\";\n});\n}\n\nFFmpegSource::FFmpegSource() {\n _poller = EventPollerPool::Instance().getPoller();\n}\n\nFFmpegSource::~FFmpegSource() {\n DebugL;\n}\n\nstatic bool is_local_ip(const string &ip){\n if (ip == \"127.0.0.1\" || ip == \"localhost\") {\n return true;\n }\n auto ips = SockUtil::getInterfaceList();\n for (auto &obj : ips) {\n if (ip == obj[\"ip\"]) {\n return true;\n }\n }\n return false;\n}\n\nvoid FFmpegSource::play(const string &src_url,const string &dst_url,int timeout_ms,const onPlay &cb) {\n GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin);\n GET_CONFIG(string,ffmpeg_cmd,FFmpeg::kCmd);\n GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog);\n\n _src_url = src_url;\n _dst_url = dst_url;\n _media_info.parse(dst_url);\n\n char cmd[1024] = {0};\n snprintf(cmd, sizeof(cmd),ffmpeg_cmd.data(),ffmpeg_bin.data(),src_url.data(),dst_url.data());\n _process.run(cmd,ffmpeg_log.empty() ? \"\" : File::absolutePath(\"\",ffmpeg_log));\n InfoL << cmd;\n\n if (is_local_ip(_media_info._host)) {\n \/\/推流给自己的,通过判断流是否注册上来判断是否正常\n if(_media_info._schema != RTSP_SCHEMA && _media_info._schema != RTMP_SCHEMA){\n cb(SockException(Err_other,\"本服务只支持rtmp\/rtsp推流\"));\n return;\n }\n weak_ptr weakSelf = shared_from_this();\n findAsync(timeout_ms,[cb,weakSelf,timeout_ms](const MediaSource::Ptr &src){\n auto strongSelf = weakSelf.lock();\n if(!strongSelf){\n \/\/自己已经销毁\n return;\n }\n if(src){\n \/\/推流给自己成功\n cb(SockException());\n strongSelf->onGetMediaSource(src);\n strongSelf->startTimer(timeout_ms);\n return;\n }\n \/\/推流失败\n if(!strongSelf->_process.wait(false)){\n \/\/ffmpeg进程已经退出\n cb(SockException(Err_other,StrPrinter << \"ffmpeg已经退出,exit code = \" << strongSelf->_process.exit_code()));\n return;\n }\n \/\/ffmpeg进程还在线,但是等待推流超时\n cb(SockException(Err_other,\"等待超时\"));\n });\n } else{\n \/\/推流给其他服务器的,通过判断FFmpeg进程是否在线判断是否成功\n weak_ptr weakSelf = shared_from_this();\n _timer = std::make_shared(timeout_ms \/ 1000,[weakSelf,cb,timeout_ms](){\n auto strongSelf = weakSelf.lock();\n if(!strongSelf){\n \/\/自身已经销毁\n return false;\n }\n \/\/FFmpeg还在线,那么我们认为推流成功\n if(strongSelf->_process.wait(false)){\n cb(SockException());\n strongSelf->startTimer(timeout_ms);\n return false;\n }\n \/\/ffmpeg进程已经退出\n cb(SockException(Err_other,StrPrinter << \"ffmpeg已经退出,exit code = \" << strongSelf->_process.exit_code()));\n return false;\n },_poller);\n }\n}\n\nvoid FFmpegSource::findAsync(int maxWaitMS, const function &cb) {\n auto src = MediaSource::find(_media_info._schema,\n _media_info._vhost,\n _media_info._app,\n _media_info._streamid);\n if(src || !maxWaitMS){\n cb(src);\n return;\n }\n\n void *listener_tag = this;\n \/\/若干秒后执行等待媒体注册超时回调\n auto onRegistTimeout = _poller->doDelayTask(maxWaitMS,[cb,listener_tag](){\n \/\/取消监听该事件\n NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);\n cb(nullptr);\n return 0;\n });\n\n weak_ptr weakSelf = shared_from_this();\n auto onRegist = [listener_tag,weakSelf,cb,onRegistTimeout](BroadcastMediaChangedArgs) {\n auto strongSelf = weakSelf.lock();\n if(!strongSelf) {\n \/\/本身已经销毁,取消延时任务\n onRegistTimeout->cancel();\n NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);\n return;\n }\n\n if (!bRegist ||\n sender.getSchema() != strongSelf->_media_info._schema ||\n sender.getVhost() != strongSelf->_media_info._vhost ||\n sender.getApp() != strongSelf->_media_info._app ||\n sender.getId() != strongSelf->_media_info._streamid) {\n \/\/不是自己感兴趣的事件,忽略之\n return;\n }\n\n \/\/查找的流终于注册上了;取消延时任务,防止多次回调\n onRegistTimeout->cancel();\n \/\/取消事件监听\n NoticeCenter::Instance().delListener(listener_tag,Broadcast::kBroadcastMediaChanged);\n\n \/\/切换到自己的线程再回复\n strongSelf->_poller->async([listener_tag,weakSelf,cb](){\n auto strongSelf = weakSelf.lock();\n if(!strongSelf) {\n return;\n }\n \/\/再找一遍媒体源,一般能找到\n strongSelf->findAsync(0,cb);\n }, false);\n };\n \/\/监听媒体注册事件\n NoticeCenter::Instance().addListener(listener_tag, Broadcast::kBroadcastMediaChanged, onRegist);\n}\n\n\/**\n * 定时检查媒体是否在线\n *\/\nvoid FFmpegSource::startTimer(int timeout_ms) {\n weak_ptr weakSelf = shared_from_this();\n _timer = std::make_shared(1, [weakSelf, timeout_ms]() {\n auto strongSelf = weakSelf.lock();\n if (!strongSelf) {\n \/\/自身已经销毁\n return false;\n }\n if (is_local_ip(strongSelf->_media_info._host)) {\n \/\/推流给自己的,我们通过检查是否已经注册来判断FFmpeg是否工作正常\n strongSelf->findAsync(0, [&](const MediaSource::Ptr &src) {\n \/\/同步查找流\n if (!src) {\n \/\/流不在线,重新拉流, 这里原先是10秒超时,实际发现10秒不够,改成20秒了\n if(strongSelf->_replay_ticker.elapsedTime() > 20 * 1000){\n \/\/上次重试时间超过10秒,那么再重试FFmpeg拉流\n strongSelf->_replay_ticker.resetTime();\n strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [](const SockException &) {});\n }\n }\n });\n } else {\n \/\/推流给其他服务器的,我们通过判断FFmpeg进程是否在线,如果FFmpeg推流中断,那么它应该会自动退出\n if (!strongSelf->_process.wait(false)) {\n \/\/ffmpeg不在线,重新拉流\n strongSelf->play(strongSelf->_src_url, strongSelf->_dst_url, timeout_ms, [weakSelf](const SockException &ex) {\n if(!ex){\n \/\/没有错误\n return;\n }\n auto strongSelf = weakSelf.lock();\n if (!strongSelf) {\n \/\/自身已经销毁\n return;\n }\n \/\/上次重试时间超过10秒,那么再重试FFmpeg拉流\n strongSelf->startTimer(10 * 1000);\n });\n }\n }\n return true;\n }, _poller);\n}\n\nvoid FFmpegSource::setOnClose(const function &cb){\n _onClose = cb;\n}\n\nbool FFmpegSource::close(MediaSource &sender, bool force) {\n auto listener = _listener.lock();\n if(listener && !listener->close(sender,force)){\n \/\/关闭失败\n return false;\n }\n \/\/该流无人观看,我们停止吧\n if(_onClose){\n _onClose();\n }\n return true;\n}\n\nMediaOriginType FFmpegSource::getOriginType(MediaSource &sender) const{\n return MediaOriginType::ffmpeg_pull;\n}\n\nstring FFmpegSource::getOriginUrl(MediaSource &sender) const{\n return _src_url;\n}\n\nstd::shared_ptr FFmpegSource::getOriginSock(MediaSource &sender) const {\n return nullptr;\n}\n\nvoid FFmpegSource::onGetMediaSource(const MediaSource::Ptr &src) {\n auto listener = src->getListener();\n if (listener.lock().get() != this) {\n \/\/防止多次进入onGetMediaSource函数导致无效递归调用的bug\n _listener = listener;\n src->setListener(shared_from_this());\n } else {\n WarnL << \"多次触发onGetMediaSource事件:\"\n << src->getSchema() << \"\/\"\n << src->getVhost() << \"\/\"\n << src->getApp() << \"\/\"\n << src->getId();\n }\n}\n\nvoid FFmpegSnap::makeSnap(const string &play_url, const string &save_path, float timeout_sec, const function &cb) {\n GET_CONFIG(string,ffmpeg_bin,FFmpeg::kBin);\n GET_CONFIG(string,ffmpeg_snap,FFmpeg::kSnap);\n GET_CONFIG(string,ffmpeg_log,FFmpeg::kLog);\n Ticker ticker;\n WorkThreadPool::Instance().getPoller()->async([timeout_sec, play_url,save_path,cb, ticker](){\n auto elapsed_ms = ticker.elapsedTime();\n if (elapsed_ms > timeout_sec * 1000) {\n \/\/超时,后台线程负载太高,当代太久才启动该任务\n cb(false);\n return;\n }\n char cmd[1024] = {0};\n snprintf(cmd, sizeof(cmd),ffmpeg_snap.data(),ffmpeg_bin.data(),play_url.data(),save_path.data());\n std::shared_ptr process = std::make_shared();\n process->run(cmd,ffmpeg_log.empty() ? \"\" : File::absolutePath(\"\",ffmpeg_log));\n \/\/定时器延时应该减去后台任务启动的延时\n auto delayTask = EventPollerPool::Instance().getPoller()->doDelayTask(timeout_sec * 1000 - elapsed_ms,[process,cb](){\n if(process->wait(false)){\n \/\/FFmpeg进程还在运行,超时就关闭它\n process->kill(2000);\n }\n return 0;\n });\n\n \/\/等待FFmpeg进程退出\n process->wait(true);\n \/\/FFmpeg进程退出了可以取消定时器了\n delayTask->cancel();\n \/\/执行回调函数\n cb(process->exit_code() == 0);\n });\n}\n\n<|endoftext|>"} {"text":"p843 - Crypt Kicker<|endoftext|>"} {"text":"#include \n#include \/\/ printf()\n#include \/\/ memcmp()\n#include \n#include \n#include \n#include \n#include \"alphabet.h\"\n\nusing namespace std;\n\n\/\/ clear text password entered by user\nstring pwd;\n\n\/\/ contains the hash of the unknown password\nchar pwdHash[SHA256_DIGEST_LENGTH];\n\n\/\/ contains the hash of a bruteforced string\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\n\/\/ the maximum number of characters bruteforce shall check\nconst unsigned char MaxChars = 20;\n\n\/**\n * @brief prints 32 bytes of memory\n *\n * prints a hex dump of 32 bytes of memory pointed to\n *\n * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash\n *\/\nvoid printSHAHash(const unsigned int *const pbuf)\n{\n \/\/ byteswap the integer pointed to, to display hex dump in correct order\n \/\/ TODO: how to deal with big endian machines\n printf(\"%X%X%X%X%X%X%X%X\\n\",\n bswap_32(*(pbuf)),\n bswap_32(*(pbuf+1)),\n bswap_32(*(pbuf+2)),\n bswap_32(*(pbuf+3)),\n bswap_32(*(pbuf+4)),\n bswap_32(*(pbuf+5)),\n bswap_32(*(pbuf+6)),\n bswap_32(*(pbuf+7))\n );\n}\n\n\/**\n * @brief generates an SHA256 hash\n *\n * generates an SHA256 hash using openSSL\n *\n * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated\n * @param[in] length: the number of bytes the that input points to holds\n * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash\n *\n * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false\n *\/\nbool generateSHA256(const void *const input, const size_t &length, char *const hashStr)\n{\n if(!hashStr || !input || length==0)\n {\n return false;\n }\n\n SHA256_CTX hash;\n if(!SHA256_Init(&hash))\n {\n return false;\n }\n\n if(!SHA256_Update(&hash, input, length))\n {\n return false;\n }\n\n if(!SHA256_Final(reinterpret_cast(hashStr), &hash))\n {\n return false;\n }\n\n return true;\n}\n\n\/**\n * @brief checks equality of two hashes\n *\n * calculates the SHA256 hash of 'password' and compares it\n * with the initial password hash\n *\n * @param[in] password: a const string containing a guessed password\n *\n * @return returns true if hashes match; false if generation of hash failed or hashes not match\n *\/\nbool checkPassword(const string &password)\n{\n#ifdef VERBOSE\n cout << \"checking \" << password << endl;\n#endif \/\/ VERBOSE\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n return false;\n }\n\n if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n {\n cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n printSHAHash((unsigned int*)bruteHash);\n return true;\n }\n\n return false;\n}\n\n\/**\n * @brief recursive implementation of bruteforce\n *\n * recursive implementation of bruteforce attack\n * call it as follows: bruteRecursive(string(\"\"), width);\n *\n * @param[in] baseString: a const string indicates the prefix of a string to be checked\n * @param[in] width: the maximum number of characters you wish to be checked\n *\/\nvolatile bool strFound = false;\nvoid bruteRecursive(const string baseString, const unsigned int width)\n{\n for(int i=0; (i myQueue;\n\n \/\/ myQueue must contain at least one element when entering loop\n \/\/ else: SIGSEGV\n \/\/ hence, start checking with an empty string\n myQueue.push(\"\");\n\n do\n {\n string baseString = myQueue.front();\n myQueue.pop();\n\n for(int i=0; iuse cout instead of printf#include \n#include \/\/ memcmp()\n#include \n#include \n#include \n#include \n#include \"alphabet.h\"\n\nusing namespace std;\n\n\/\/ clear text password entered by user\nstring pwd;\n\n\/\/ contains the hash of the unknown password\nchar pwdHash[SHA256_DIGEST_LENGTH];\n\n\/\/ contains the hash of a bruteforced string\nchar bruteHash[SHA256_DIGEST_LENGTH];\n\n\/\/ the maximum number of characters bruteforce shall check\nconst unsigned char MaxChars = 20;\n\n\/**\n * @brief prints 32 bytes of memory\n *\n * prints a hex dump of 32 bytes of memory pointed to\n *\n * @param[in] pbuf: pointer to some memory, usually containing an SHA256 hash\n *\/\nvoid printSHAHash(const unsigned int *const pbuf)\n{\n \/\/ byteswap the integer pointed to, to display hex dump in correct order\n \/\/ TODO: how to deal with big endian machines\n cout << std::hex << std::uppercase\n << bswap_32(*(pbuf))\n << bswap_32(*(pbuf+1))\n << bswap_32(*(pbuf+2))\n << bswap_32(*(pbuf+3))\n << bswap_32(*(pbuf+4))\n << bswap_32(*(pbuf+5))\n << bswap_32(*(pbuf+6))\n << bswap_32(*(pbuf+7))\n << endl;\n}\n\n\/**\n * @brief generates an SHA256 hash\n *\n * generates an SHA256 hash using openSSL\n *\n * @param[in] input: a const pointer to const block of data, usually a char array of which the hash is being generated\n * @param[in] length: the number of bytes the that input points to holds\n * @param[in,out] hashStr: const pointer to an array of SHA256_DIGEST_LENGTH bytes that will receive the hash\n *\n * @return returns true if the hash has been generated successfully; returns false if input or hashStr is NULL or length==0; else: false\n *\/\nbool generateSHA256(const void *const input, const size_t &length, char *const hashStr)\n{\n if(!hashStr || !input || length==0)\n {\n return false;\n }\n\n SHA256_CTX hash;\n if(!SHA256_Init(&hash))\n {\n return false;\n }\n\n if(!SHA256_Update(&hash, input, length))\n {\n return false;\n }\n\n if(!SHA256_Final(reinterpret_cast(hashStr), &hash))\n {\n return false;\n }\n\n return true;\n}\n\n\/**\n * @brief checks equality of two hashes\n *\n * calculates the SHA256 hash of 'password' and compares it\n * with the initial password hash\n *\n * @param[in] password: a const string containing a guessed password\n *\n * @return returns true if hashes match; false if generation of hash failed or hashes not match\n *\/\nbool checkPassword(const string &password)\n{\n#ifdef VERBOSE\n cout << \"checking \" << password << endl;\n#endif \/\/ VERBOSE\n\n \/\/ generate sha hash from entered string and write it to pwdHash\n if(!generateSHA256(password.c_str(), password.length(), bruteHash))\n {\n cerr << \"Error when generating SHA256 from \\\"\" << password << \"\\\"\" << endl;\n return false;\n }\n\n if (!memcmp(bruteHash, pwdHash, SHA256_DIGEST_LENGTH))\n {\n cout << \"match [\" << password << \"]\" << endl << \"hash: \" << endl;\n printSHAHash((unsigned int*)bruteHash);\n return true;\n }\n\n return false;\n}\n\n\/**\n * @brief recursive implementation of bruteforce\n *\n * recursive implementation of bruteforce attack\n * call it as follows: bruteRecursive(string(\"\"), width);\n *\n * @param[in] baseString: a const string indicates the prefix of a string to be checked\n * @param[in] width: the maximum number of characters you wish to be checked\n *\/\nvolatile bool strFound = false;\nvoid bruteRecursive(const string baseString, const unsigned int width)\n{\n for(int i=0; (i myQueue;\n\n \/\/ myQueue must contain at least one element when entering loop\n \/\/ else: SIGSEGV\n \/\/ hence, start checking with an empty string\n myQueue.push(\"\");\n\n do\n {\n string baseString = myQueue.front();\n myQueue.pop();\n\n for(int i=0; i"} {"text":"#ifndef STAN_MODEL_MODEL_BASE_CRTP_HPP\n#define STAN_MODEL_MODEL_BASE_CRTP_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace model {\n\n\/**\n * Base class employing the curiously recursive template pattern for\n * static inheritance to adapt templated `log_prob` and `write_array`\n * methods to their untemplated virtual counterparts declared in\n * `model_base`.\n *\n * The derived class `M` is required to implement the following two\n * pairs of template functions,\n *\n * ```\n * template \n * T log_prob(std::vector& params_r,\n * std::vector& params_i,\n * std::ostream* msgs = 0) const;\n\n * template \n * T log_prob(Eigen::Matrix& params_r,\n * std::ostream* msgs = 0) const;\n * ```\n *\n * and\n *\n * ```\n * template \n * void write_array(RNG& base_rng,\n * std::vector& params_r,\n * std::vector& params_i,\n * std::vector& vars,\n * bool include_tparams = true,\n * bool include_gqs = true,\n * std::ostream* msgs = 0) const;\n *\n * template \n * void write_array(RNG& base_rng,\n * Eigen::Matrix& params_r,\n * Eigen::Matrix& vars,\n * bool include_tparams = true,\n * bool include_gqs = true,\n * std::ostream* msgs = 0) const\n * ```\n *\n *

The derived class `M` must be declared following the curiously\n * recursive template pattern, for example, if `M` is `foo_model`,\n * then `foo_model` should be declared as\n *\n * ```\n * class foo_model : public stan::model::model_base_crtp { ... };\n * ```\n *\n * The recursion arises when the type of the declared class appears as\n * a template parameter in the class it extends. For example,\n * `foo_model` is declared to extend `model_base_crtp`. In\n * general, the template parameter `M` for this class is called the\n * derived class, and must be declared to extend `foo_model`.\n *\n * @tparam M type of derived model, which must implemented the\n * template methods defined in the class documentation\n *\/\ntemplate \nclass model_base_crtp : public stan::model::model_base {\n public:\n \/**\n * Construct a model with the specified number of real unconstrained\n * parameters.\n *\n * @param[in] num_params_r number of real unconstrained parameters\n *\/\n explicit model_base_crtp(size_t num_params_r) : model_base(num_params_r) {}\n\n \/**\n * Destroy this class. This is required to be virtual to allow\n * subclass references to clean up superclasses, but is otherwise a\n * no-op.\n *\/\n virtual ~model_base_crtp() {}\n\n inline double log_prob(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, msgs);\n }\n inline math::var log_prob(Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n inline double log_prob_jacobian(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n inline math::var log_prob_jacobian(Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n inline double log_prob_propto(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n inline math::var log_prob_propto(Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n inline double log_prob_propto_jacobian(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n inline math::var log_prob_propto_jacobian(\n Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n void write_array(boost::ecuyer1988& rng, Eigen::VectorXd& theta,\n Eigen::VectorXd& vars, bool include_tparams = true,\n bool include_gqs = true,\n std::ostream* msgs = 0) const override {\n return static_cast(this)->template write_array(\n rng, theta, vars, include_tparams, include_gqs, msgs);\n }\n\n \/\/ TODO(carpenter): remove redundant std::vector methods below here =====\n \/\/ ======================================================================\n\n inline double log_prob(std::vector& theta, std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n inline double log_prob_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n inline double log_prob_propto(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob_propto(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n inline double log_prob_propto_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob_propto_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n void write_array(boost::ecuyer1988& rng, std::vector& theta,\n std::vector& theta_i, std::vector& vars,\n bool include_tparams = true, bool include_gqs = true,\n std::ostream* msgs = 0) const override {\n return static_cast(this)->template write_array(\n rng, theta, theta_i, vars, include_tparams, include_gqs, msgs);\n }\n\n void transform_inits(const io::var_context& context,\n Eigen::VectorXd& params_r, std::ostream* msgs) const override {\n return static_cast(this)->template transform_inits(\n context, params_r, msgs);\n }\n};\n\n} \/\/ namespace model\n} \/\/ namespace stan\n#endif\n[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags\/RELEASE_600\/final)#ifndef STAN_MODEL_MODEL_BASE_CRTP_HPP\n#define STAN_MODEL_MODEL_BASE_CRTP_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace model {\n\n\/**\n * Base class employing the curiously recursive template pattern for\n * static inheritance to adapt templated `log_prob` and `write_array`\n * methods to their untemplated virtual counterparts declared in\n * `model_base`.\n *\n * The derived class `M` is required to implement the following two\n * pairs of template functions,\n *\n * ```\n * template \n * T log_prob(std::vector& params_r,\n * std::vector& params_i,\n * std::ostream* msgs = 0) const;\n\n * template \n * T log_prob(Eigen::Matrix& params_r,\n * std::ostream* msgs = 0) const;\n * ```\n *\n * and\n *\n * ```\n * template \n * void write_array(RNG& base_rng,\n * std::vector& params_r,\n * std::vector& params_i,\n * std::vector& vars,\n * bool include_tparams = true,\n * bool include_gqs = true,\n * std::ostream* msgs = 0) const;\n *\n * template \n * void write_array(RNG& base_rng,\n * Eigen::Matrix& params_r,\n * Eigen::Matrix& vars,\n * bool include_tparams = true,\n * bool include_gqs = true,\n * std::ostream* msgs = 0) const\n * ```\n *\n *

The derived class `M` must be declared following the curiously\n * recursive template pattern, for example, if `M` is `foo_model`,\n * then `foo_model` should be declared as\n *\n * ```\n * class foo_model : public stan::model::model_base_crtp { ... };\n * ```\n *\n * The recursion arises when the type of the declared class appears as\n * a template parameter in the class it extends. For example,\n * `foo_model` is declared to extend `model_base_crtp`. In\n * general, the template parameter `M` for this class is called the\n * derived class, and must be declared to extend `foo_model`.\n *\n * @tparam M type of derived model, which must implemented the\n * template methods defined in the class documentation\n *\/\ntemplate \nclass model_base_crtp : public stan::model::model_base {\n public:\n \/**\n * Construct a model with the specified number of real unconstrained\n * parameters.\n *\n * @param[in] num_params_r number of real unconstrained parameters\n *\/\n explicit model_base_crtp(size_t num_params_r) : model_base(num_params_r) {}\n\n \/**\n * Destroy this class. This is required to be virtual to allow\n * subclass references to clean up superclasses, but is otherwise a\n * no-op.\n *\/\n virtual ~model_base_crtp() {}\n\n inline double log_prob(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, msgs);\n }\n inline math::var log_prob(Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n inline double log_prob_jacobian(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n inline math::var log_prob_jacobian(Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n inline double log_prob_propto(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n inline math::var log_prob_propto(Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n inline double log_prob_propto_jacobian(Eigen::VectorXd& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n inline math::var log_prob_propto_jacobian(\n Eigen::Matrix& theta,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(theta,\n msgs);\n }\n\n void write_array(boost::ecuyer1988& rng, Eigen::VectorXd& theta,\n Eigen::VectorXd& vars, bool include_tparams = true,\n bool include_gqs = true,\n std::ostream* msgs = 0) const override {\n return static_cast(this)->template write_array(\n rng, theta, vars, include_tparams, include_gqs, msgs);\n }\n\n \/\/ TODO(carpenter): remove redundant std::vector methods below here =====\n \/\/ ======================================================================\n\n inline double log_prob(std::vector& theta, std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n inline double log_prob_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n inline double log_prob_propto(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob_propto(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n inline double log_prob_propto_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n inline math::var log_prob_propto_jacobian(std::vector& theta,\n std::vector& theta_i,\n std::ostream* msgs) const override {\n return static_cast(this)->template log_prob(\n theta, theta_i, msgs);\n }\n\n void write_array(boost::ecuyer1988& rng, std::vector& theta,\n std::vector& theta_i, std::vector& vars,\n bool include_tparams = true, bool include_gqs = true,\n std::ostream* msgs = 0) const override {\n return static_cast(this)->template write_array(\n rng, theta, theta_i, vars, include_tparams, include_gqs, msgs);\n }\n\n void transform_inits(const io::var_context& context,\n Eigen::VectorXd& params_r,\n std::ostream* msgs) const override {\n return static_cast(this)->template transform_inits(\n context, params_r, msgs);\n }\n};\n\n} \/\/ namespace model\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file Test_StaticStore.cpp\n * @brief Tests: libxaos-core:memory\/store\/impl\/StaticStore.h\n *\n * Several StaticStores are constructed in mememory, populated with data,\n * and tested to see if said data persists.\n *\/\n\n#include \n\n#include \"memory\/store\/impl\/StaticStore.h\"\n\n#include \"catch.hpp\"\n\n\/\/ Define some types.\nconstexpr short Store128_ALIGN = 4;\nconstexpr short Store256_ALIGN = 64;\nconstexpr short Store512_ALIGN = 128;\nconstexpr short Store4096_ALIGN = 4096; \/\/ THIS IS RIDICULOUS\n\nusing Store128 = libxaos::memory::StaticStore<128, Store128_ALIGN, 0>;\nusing Store256 = libxaos::memory::StaticStore<256, Store256_ALIGN, 0>;\nusing Store512 = libxaos::memory::StaticStore<512, Store512_ALIGN, 0>;\nusing Store4096 = libxaos::memory::StaticStore<4096, Store4096_ALIGN, 0>;\n\nTEST_CASE(\"CORE:MEMORY\/STORE\/IMPL\/StaticStore | Stores hold data.\",\n \"[core][memory]\") {\n\n \/\/ create our stores to test\n Store128 storeA {};\n Store256 storeB {};\n Store512 storeC {};\n\n REQUIRE(storeA.getRawStorage());\n REQUIRE(storeB.getRawStorage());\n REQUIRE(storeC.getRawStorage());\n\n \/\/ loop through and populate stores with data\n for (int i = 0; i < 128 + 256 + 512; i++) {\n uint8_t* data = nullptr;\n\n if (i < 128) {\n data = storeA.getRawStorage() + i;\n } else if (i < 256) {\n data = storeB.getRawStorage() + (i - 128);\n } else {\n data = storeC.getRawStorage() + (i - 128 - 256);\n }\n\n *data = i;\n }\n\n \/\/ Verify data is correct.\n uint8_t index = 0;\n for (int i = 0; i < 128 + 256 + 512; i++) {\n if (i < 128) {\n REQUIRE(*(storeA.getRawStorage() + index) == index);\n } else if (i < 256) {\n REQUIRE(*(storeB.getRawStorage() + index - 128) == index);\n } else {\n REQUIRE(*(storeC.getRawStorage() + index - 128 - 256) == index);\n }\n\n index++;\n }\n}\n\nTEST_CASE(\"CORE:MEMORY\/STORE\/IMPL\/StaticStore | Stores are aligned.\",\n \"[core][memory][!mayfail]\") {\n\n \/\/ create our stores\n Store128 storeA {};\n Store256 storeB {};\n Store512 storeC {};\n Store4096 storeD {};\n\n \/\/ Test alignments\n uintptr_t addressA = reinterpret_cast(storeA.getRawStorage());\n uintptr_t addressB = reinterpret_cast(storeB.getRawStorage());\n uintptr_t addressC = reinterpret_cast(storeC.getRawStorage());\n uintptr_t addressD = reinterpret_cast(storeD.getRawStorage());\n\n REQUIRE(addressA % Store128_ALIGN == 0);\n REQUIRE(addressB % Store256_ALIGN == 0);\n REQUIRE(addressC % Store512_ALIGN == 0);\n REQUIRE(addressD % Store4096_ALIGN == 0);\n}\nFixed a StaticStore testing bug.\/**\n * @file Test_StaticStore.cpp\n * @brief Tests: libxaos-core:memory\/store\/impl\/StaticStore.h\n *\n * Several StaticStores are constructed in mememory, populated with data,\n * and tested to see if said data persists.\n *\/\n\n#include \n\n#include \"memory\/store\/impl\/StaticStore.h\"\n\n#include \"catch.hpp\"\n\n\/\/ Define some types.\nconstexpr short Store128_ALIGN = 4;\nconstexpr short Store256_ALIGN = 64;\nconstexpr short Store512_ALIGN = 128;\nconstexpr short Store4096_ALIGN = 4096; \/\/ THIS IS RIDICULOUS\n\nusing Store128 = libxaos::memory::StaticStore<128, Store128_ALIGN, 0>;\nusing Store256 = libxaos::memory::StaticStore<256, Store256_ALIGN, 0>;\nusing Store512 = libxaos::memory::StaticStore<512, Store512_ALIGN, 0>;\nusing Store4096 = libxaos::memory::StaticStore<4096, Store4096_ALIGN, 0>;\n\nTEST_CASE(\"CORE:MEMORY\/STORE\/IMPL\/StaticStore | Stores hold data.\",\n \"[core][memory]\") {\n\n \/\/ create our stores to test\n Store128 storeA {};\n Store256 storeB {};\n Store512 storeC {};\n\n REQUIRE(storeA.getRawStorage());\n REQUIRE(storeB.getRawStorage());\n REQUIRE(storeC.getRawStorage());\n\n \/\/ loop through and populate stores with data\n for (int i = 0; i < 128 + 256 + 512; i++) {\n uint8_t* data = nullptr;\n\n if (i < 128) {\n data = storeA.getRawStorage() + i;\n } else if (i < 256) {\n data = storeB.getRawStorage() + (i - 128);\n } else {\n data = storeC.getRawStorage() + (i - 128 - 256);\n }\n\n *data = i;\n }\n\n \/\/ Verify data is correct.\n uint8_t index = 0;\n for (int i = 0; i < 128 + 256 + 512; i++) {\n INFO(\"Current iteration: \" << i);\n if (i < 128) {\n REQUIRE(*(storeA.getRawStorage() + i) == index);\n } else if (i < 256) {\n REQUIRE(*(storeB.getRawStorage() + i - 128) == index);\n } else {\n REQUIRE(*(storeC.getRawStorage() + i - 128 - 256) == index);\n }\n\n index++;\n }\n}\n\nTEST_CASE(\"CORE:MEMORY\/STORE\/IMPL\/StaticStore | Stores are aligned.\",\n \"[core][memory][!mayfail]\") {\n\n \/\/ create our stores\n Store128 storeA {};\n Store256 storeB {};\n Store512 storeC {};\n Store4096 storeD {};\n\n \/\/ Test alignments\n uintptr_t addressA = reinterpret_cast(storeA.getRawStorage());\n uintptr_t addressB = reinterpret_cast(storeB.getRawStorage());\n uintptr_t addressC = reinterpret_cast(storeC.getRawStorage());\n uintptr_t addressD = reinterpret_cast(storeD.getRawStorage());\n\n REQUIRE(addressA % Store128_ALIGN == 0);\n REQUIRE(addressB % Store256_ALIGN == 0);\n REQUIRE(addressC % Store512_ALIGN == 0);\n REQUIRE(addressD % Store4096_ALIGN == 0);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nmap Dict;\n\/\/debug\n#ifdef LOCAL\n#define fp stdin \n#else\nFILE *fp;\n#endif\nstring getword(){\n\tchar ch;\n\tstring s;\n\twhile((ch=getc(fp))!=EOF){\n\t\tif(ch=='-'){\n\n\t\t\tif(getc(fp)=='\\n'){\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tfseek(fp,ftell(fp)-1,SEEK_CUR);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z')\n\t\t\ts.push_back(ch);\n\t\telse\n\t\t\tbreak;\n\t}\n}\nint main(int argc, char const *argv[])\n{\n\t#ifndef LOCAL\n\tfp=fopen(\"case1.in\",\"r\");\n\t#else\n\tprintf(\"used LOCAL\");\n\t#endif\n\tcout<< getword()<update uoj1109#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nmap Dict;\n\/\/debug\n#ifdef LOCAL\n#define fp stdin \n#else\nFILE *fp;\n#endif\nstring getword(){\n\tchar ch;\n\tstring s;\n\twhile((ch=getc(fp))!=EOF){\n\t\tif(ch=='-'){\n\n\t\t\tif(getc(fp)=='\\n'){\n\t\t\t\tcontinue;\n\t\t\t}else{\n\t\t\t\tfseek(fp,ftell(fp)-1,SEEK_CUR);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z')\n\t\t\ts.push_back(ch);\n\t\telse\n\t\t\tbreak;\n\t}\n}\nint main(int argc, char const *argv[])\n{\n\t#ifndef LOCAL\n\tfp=fopen(\"case1.in\",\"r\");\n\t#else\n\tprintf(\"used LOCAL\");\n\t#endif\n\tcout << getword()<"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<update uoj1138#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\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nqueue lv1;\nqueue lv2;\nqueue lv3;\nqueue lv4;\n\nstring temp;\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime || users>usernum) return 0;\n\n\tdo{\n\t\t\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t\t\tcase 4:\n\t\t\t\t\tlv4.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tusers++;\n\t\tif(users<=usernum){\n\t\t\ttemp.resize(21); \/\/需要预先分配空间\n\t\t\tscanf(\"%d%d%s\",&temptime,&templv,&temp[0]);\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}while(temptime<=now);\n\n\n\n}\nint pop(){\n\nif(lv4.size()>0){\n\t\tprintf(\"%s\\n\",lv4.front().c_str());\n\t\tlv4.pop();\n\t\treturn 4;\n\t}\n\n\tif(lv3.size()>0){\n\t\tprintf(\"%s\\n\",lv3.front().c_str());\n\t\tlv3.pop();\n\t\treturn 3;\n\t}\n\n\tif(lv2.size()>0){\n\t\tprintf(\"%s\\n\",lv2.front().c_str());\n\t\tlv2.pop();\n\t\treturn 2;\n\t}\n\n\tif(lv1.size()>0){\n\t\tprintf(\"%s\\n\",lv1.front().c_str());\n\t\tlv1.pop();\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time && i< usernum *5; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\t\/\/cout<update uoj2254#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nqueue lv1;\nqueue lv2;\nqueue lv3;\nqueue lv4;\n\nstring temp;\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime || users>usernum) return 0;\n\n\tdo{\n\t\t\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t\t\tcase 4:\n\t\t\t\t\tlv4.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tusers++;\n\t\tif(users<=usernum){\n\t\t\ttemp.resize(21); \/\/需要预先分配空间\n\t\t\tscanf(\"%d%d%s\",&temptime,&templv,&temp[0]);\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}while(temptime<=now);\n\n}\nint pop(){\n\nif(lv4.size()>0){\n\t\tprintf(\"%s\\n\",lv4.front().c_str());\n\t\tlv4.pop();\n\t\treturn 4;\n\t}\n\n\tif(lv3.size()>0){\n\t\tprintf(\"%s\\n\",lv3.front().c_str());\n\t\tlv3.pop();\n\t\treturn 3;\n\t}\n\n\tif(lv2.size()>0){\n\t\tprintf(\"%s\\n\",lv2.front().c_str());\n\t\tlv2.pop();\n\t\treturn 2;\n\t}\n\n\tif(lv1.size()>0){\n\t\tprintf(\"%s\\n\",lv1.front().c_str());\n\t\tlv1.pop();\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time && i< usernum *5; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\t\/\/cout<"} {"text":"\/\/ rbOOmit: An implementation of the Certified Reduced Basis method.\n\/\/ Copyright (C) 2009, 2010 David J. Knezevic\n\n\/\/ This file is part of rbOOmit.\n\n\/\/ rbOOmit 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\/\/ rbOOmit 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#include \"transient_rb_param_subdomain_node.h\"\n#include \"transient_rb_param_subdomain_tree.h\"\n#include \"transient_rb_system.h\"\n#include \"libmesh_logging.h\"\n\nnamespace libMesh\n{\n\nTransientRBParamSubdomainNode::TransientRBParamSubdomainNode(TransientRBParamSubdomainTree& tree_in,\n const std::vector& anchor_in)\n : Parent(tree_in, anchor_in)\n{ }\n\nvoid TransientRBParamSubdomainNode::add_child(const std::vector& new_anchor, Child c)\n{\n START_LOG(\"add_child()\", \"TransientRBParamSubdomainNode\");\n\n \/\/ cast the tree reference to a TransientRBParamSubdomainTree\n TransientRBParamSubdomainTree& trans_tree =\n libmesh_cast_ref(_tree);\n\n if(c == LEFT)\n {\n if(left_child != NULL)\n {\n std::cout << \"Error: Child already exists!\"\n << std::endl;\n libmesh_error();\n }\n else\n {\n \/\/ Allocate a new child node\n left_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor);\n }\n }\n\n if(c == RIGHT)\n {\n if(right_child != NULL)\n {\n std::cout << \"Error: Child already exists!\"\n << std::endl;\n libmesh_error();\n }\n else\n {\n \/\/ Allocate a new child node\n right_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor);\n }\n }\n\n STOP_LOG(\"add_child()\", \"TransientRBParamSubdomainNode\");\n}\n\nvoid TransientRBParamSubdomainNode::hp_greedy()\n{\n _rb_system.clear_basis_function_dependent_data();\n\n \/\/ Load the (full or subsampled) training set\n if(_tree.n_subsampled_training_points >= n_global_training_parameters())\n {\n _rb_system.load_training_set( training_set );\n }\n else\n {\n std::vector< std::vector > subsampled_training_set = get_subsampled_training_set();\n _rb_system.load_training_set( subsampled_training_set );\n }\n\n _rb_system.set_current_parameters( this->anchor );\n _rb_system.set_training_tolerance(_tree.h_tol);\n\n Real greedy_bound;\n\n \/\/ These casts have to succeed\n TransientRBParamSubdomainTree& trans_tree =\n libmesh_cast_ref(_tree);\n\n TransientRBSystem& trans_rb = libmesh_cast_ref(_rb_system);\n\n \/\/ Set the maximum number of truth solves to N_bar in the time-dependent case\n trans_rb.set_max_truth_solves(_tree.N_bar);\n\n if (!trans_tree.use_delta_N_in_h_stage)\n {\n trans_rb.set_POD_tol(_tree.h_tol\/trans_tree.conserv_factor);\n }\n else\n {\n trans_rb.set_POD_tol(-1.);\n }\n\n \/\/ delta_N might be changed in basis training in the transient case\n \/\/ (i.e., if we're using POD_tol, or if we hit Nmax)\n \/\/ hence we save and reload delta_N\n unsigned int saved_delta_N = trans_rb.get_delta_N();\n greedy_bound = trans_rb.train_reduced_basis();\n \/\/ Reload delta_N\n trans_rb.set_delta_N(saved_delta_N);\n\n trans_rb.set_current_parameters(this->anchor);\n Real RB_error = trans_rb.RB_solve(trans_rb.get_n_basis_functions());\n if (RB_error > _tree.h_tol\/trans_tree.conserv_factor)\n {\n std::cout << \"Error: The h-tolerance was not satisfied at the \"\n << \"anchor point hence h-type refinement may not converge.\"\n << std::endl;\n libmesh_error();\n }\n\n\n\n\n if ( greedy_bound > _tree.h_tol) \/\/ recursive call to hp_greedy\n {\n std::cout << \"h tolerance not satisfied, splitting subdomain...\" << std::endl;\n split_this_subdomain(true);\n\n left_child->hp_greedy();\n right_child->hp_greedy();\n }\n else \/\/ terminate branch, populate the model with standard p-type,write out subelement data\n {\n std::cout << \"h tolerance satisfied, performing p-refinement...\" << std::endl;\n greedy_bound = perform_p_stage(greedy_bound);\n if (greedy_bound > _tree.p_tol)\n {\n std::cout << \"p tolerance not satisfied, splitting subdomain...\" << std::endl;\n split_this_subdomain(false);\n\n left_child->hp_greedy();\n right_child->hp_greedy();\n }\n else\n {\n std::cout << \"p tolerance satisfied, subdomain \"\n << _tree.leaf_node_index << \" is a leaf node...\"\n << std::endl;\n\n \/\/ Finally, write out the data for this subdomain\n write_subdomain_data_to_files();\n _tree.leaf_node_index++;\n }\n }\n}\n\nReal TransientRBParamSubdomainNode::perform_p_stage(Real greedy_bound)\n{\n START_LOG(\"perform_p_stage()\", \"TransientRBParamSubdomainNode\");\n \n \/\/ Continue the greedy process on this subdomain, i.e.\n \/\/ we do not discard the basis functions generated for\n \/\/ this subdomain in the h-refinement phase\n _rb_system.set_training_tolerance(_tree.p_tol);\n\n TransientRBSystem& trans_rb = libmesh_cast_ref(_rb_system);\n\n \/\/ Ignore max_truth_solves and POD-tol in the p-stage\n trans_rb.set_POD_tol(-1.);\n trans_rb.set_max_truth_solves(-1);\n\n \/\/ Clear the reduced basis and reinitialize the greedy to the anchor point\n trans_rb.clear_basis_function_dependent_data();\n trans_rb.set_current_parameters( this->anchor );\n\n \/\/ Checking if p-tol is already satisfied or Nmax has been reached\n \/\/ if not do another (standard) greedy\n if ( (greedy_bound > _tree.p_tol) || (_rb_system.get_n_basis_functions() < _rb_system.get_Nmax()) )\n {\n greedy_bound = _rb_system.train_reduced_basis();\n }\n\n STOP_LOG(\"perform_p_stage()\", \"TransientRBParamSubdomainNode\");\n\n return greedy_bound;\n}\n\nvoid TransientRBParamSubdomainNode::split_this_subdomain(bool h_stage_split)\n{\n START_LOG(\"split_this_subdomain()\", \"TransientRBParamSubdomainNode\");\n\n \/\/ These first few lines are the same as RBParamSubdomainNode::split_this_subdomain\n this->add_child( _rb_system.get_greedy_parameter(0), RBParamSubdomainNode::LEFT);\n this->add_child( _rb_system.get_greedy_parameter(1), RBParamSubdomainNode::RIGHT);\n\n \/\/ Compute distance between the children anchor points, and pass to children (JLE 2010-09-16)\n Real distance_between_children_anchors = 0.;\n for (unsigned int i = 0; i < left_child->anchor.size(); i++)\n {\n distance_between_children_anchors += std::pow((left_child->anchor[i] - right_child->anchor[i]),2.);\n }\n distance_between_children_anchors = std::sqrt(distance_between_children_anchors);\n left_child->distance_between_anchors = distance_between_children_anchors;\n right_child->distance_between_anchors = distance_between_children_anchors;\n\n\n \/\/ We now need some code specific to the transient case because it\n \/\/ is possible that we have repeated selection of training points\n \/\/ in the transient case (due to the POD-Greedy) and hence we\n \/\/ may have distance_between_children_anchors == 0.\n bool anchors_are_equal = (distance_between_children_anchors == 0.);\n\n if (h_stage_split)\n {\n if (anchors_are_equal)\n {\n std::cout << \"Error: Anchor points for children are equal!\"\n << std::endl;\n libmesh_error();\n }\n }\n else\n {\n if (anchors_are_equal)\n {\n for (unsigned int i=2; i< _rb_system.greedy_param_list.size() ; i++)\n {\n bool parameters_are_equal = true;\n for (unsigned int j = 0; j < left_child->anchor.size(); j++)\n {\n parameters_are_equal = ( parameters_are_equal && (left_child->anchor[j] == _rb_system.get_greedy_parameter(i)[j]));\n }\n if (!parameters_are_equal)\n {\n right_child->anchor = _rb_system.get_greedy_parameter(i);\n anchors_are_equal = false;\n break;\n }\n }\n \n \/\/ anchors_are_equal has been updated, check if we have found different point.\n if(anchors_are_equal) \n {\n std::cout << \"Error: Unable to find distinct anchors in additional splitting step.\" << std::endl;\n libmesh_error();\n }\n }\n }\n\n this->initialize_child_training_sets();\n\n STOP_LOG(\"split_this_subdomain()\", \"TransientRBParamSubdomainNode\");\n}\n\n} \/\/ namespace libMesh\nFixing single precision regression\/\/ rbOOmit: An implementation of the Certified Reduced Basis method.\n\/\/ Copyright (C) 2009, 2010 David J. Knezevic\n\n\/\/ This file is part of rbOOmit.\n\n\/\/ rbOOmit 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\/\/ rbOOmit 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#include \"transient_rb_param_subdomain_node.h\"\n#include \"transient_rb_param_subdomain_tree.h\"\n#include \"transient_rb_system.h\"\n#include \"libmesh_logging.h\"\n\nnamespace libMesh\n{\n\nTransientRBParamSubdomainNode::TransientRBParamSubdomainNode(TransientRBParamSubdomainTree& tree_in,\n const std::vector& anchor_in)\n : Parent(tree_in, anchor_in)\n{ }\n\nvoid TransientRBParamSubdomainNode::add_child(const std::vector& new_anchor, Child c)\n{\n START_LOG(\"add_child()\", \"TransientRBParamSubdomainNode\");\n\n \/\/ cast the tree reference to a TransientRBParamSubdomainTree\n TransientRBParamSubdomainTree& trans_tree =\n libmesh_cast_ref(_tree);\n\n if(c == LEFT)\n {\n if(left_child != NULL)\n {\n std::cout << \"Error: Child already exists!\"\n << std::endl;\n libmesh_error();\n }\n else\n {\n \/\/ Allocate a new child node\n left_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor);\n }\n }\n\n if(c == RIGHT)\n {\n if(right_child != NULL)\n {\n std::cout << \"Error: Child already exists!\"\n << std::endl;\n libmesh_error();\n }\n else\n {\n \/\/ Allocate a new child node\n right_child = new TransientRBParamSubdomainNode(trans_tree, new_anchor);\n }\n }\n\n STOP_LOG(\"add_child()\", \"TransientRBParamSubdomainNode\");\n}\n\nvoid TransientRBParamSubdomainNode::hp_greedy()\n{\n _rb_system.clear_basis_function_dependent_data();\n\n \/\/ Load the (full or subsampled) training set\n if(_tree.n_subsampled_training_points >= n_global_training_parameters())\n {\n _rb_system.load_training_set( training_set );\n }\n else\n {\n std::vector< std::vector > subsampled_training_set = get_subsampled_training_set();\n _rb_system.load_training_set( subsampled_training_set );\n }\n\n _rb_system.set_current_parameters( this->anchor );\n _rb_system.set_training_tolerance(_tree.h_tol);\n\n Real greedy_bound;\n\n \/\/ These casts have to succeed\n TransientRBParamSubdomainTree& trans_tree =\n libmesh_cast_ref(_tree);\n\n TransientRBSystem& trans_rb = libmesh_cast_ref(_rb_system);\n\n \/\/ Set the maximum number of truth solves to N_bar in the time-dependent case\n trans_rb.set_max_truth_solves(_tree.N_bar);\n\n if (!trans_tree.use_delta_N_in_h_stage)\n {\n trans_rb.set_POD_tol(_tree.h_tol\/trans_tree.conserv_factor);\n }\n else\n {\n trans_rb.set_POD_tol(-1.);\n }\n\n \/\/ delta_N might be changed in basis training in the transient case\n \/\/ (i.e., if we're using POD_tol, or if we hit Nmax)\n \/\/ hence we save and reload delta_N\n unsigned int saved_delta_N = trans_rb.get_delta_N();\n greedy_bound = trans_rb.train_reduced_basis();\n \/\/ Reload delta_N\n trans_rb.set_delta_N(saved_delta_N);\n\n trans_rb.set_current_parameters(this->anchor);\n Real RB_error = trans_rb.RB_solve(trans_rb.get_n_basis_functions());\n if (RB_error > _tree.h_tol\/trans_tree.conserv_factor)\n {\n std::cout << \"Error: The h-tolerance was not satisfied at the \"\n << \"anchor point hence h-type refinement may not converge.\"\n << std::endl;\n libmesh_error();\n }\n\n\n\n\n if ( greedy_bound > _tree.h_tol) \/\/ recursive call to hp_greedy\n {\n std::cout << \"h tolerance not satisfied, splitting subdomain...\" << std::endl;\n split_this_subdomain(true);\n\n left_child->hp_greedy();\n right_child->hp_greedy();\n }\n else \/\/ terminate branch, populate the model with standard p-type,write out subelement data\n {\n std::cout << \"h tolerance satisfied, performing p-refinement...\" << std::endl;\n greedy_bound = perform_p_stage(greedy_bound);\n if (greedy_bound > _tree.p_tol)\n {\n std::cout << \"p tolerance not satisfied, splitting subdomain...\" << std::endl;\n split_this_subdomain(false);\n\n left_child->hp_greedy();\n right_child->hp_greedy();\n }\n else\n {\n std::cout << \"p tolerance satisfied, subdomain \"\n << _tree.leaf_node_index << \" is a leaf node...\"\n << std::endl;\n\n \/\/ Finally, write out the data for this subdomain\n write_subdomain_data_to_files();\n _tree.leaf_node_index++;\n }\n }\n}\n\nReal TransientRBParamSubdomainNode::perform_p_stage(Real greedy_bound)\n{\n START_LOG(\"perform_p_stage()\", \"TransientRBParamSubdomainNode\");\n \n \/\/ Continue the greedy process on this subdomain, i.e.\n \/\/ we do not discard the basis functions generated for\n \/\/ this subdomain in the h-refinement phase\n _rb_system.set_training_tolerance(_tree.p_tol);\n\n TransientRBSystem& trans_rb = libmesh_cast_ref(_rb_system);\n\n \/\/ Ignore max_truth_solves and POD-tol in the p-stage\n trans_rb.set_POD_tol(-1.);\n trans_rb.set_max_truth_solves(-1);\n\n \/\/ Clear the reduced basis and reinitialize the greedy to the anchor point\n trans_rb.clear_basis_function_dependent_data();\n trans_rb.set_current_parameters( this->anchor );\n\n \/\/ Checking if p-tol is already satisfied or Nmax has been reached\n \/\/ if not do another (standard) greedy\n if ( (greedy_bound > _tree.p_tol) || (_rb_system.get_n_basis_functions() < _rb_system.get_Nmax()) )\n {\n greedy_bound = _rb_system.train_reduced_basis();\n }\n\n STOP_LOG(\"perform_p_stage()\", \"TransientRBParamSubdomainNode\");\n\n return greedy_bound;\n}\n\nvoid TransientRBParamSubdomainNode::split_this_subdomain(bool h_stage_split)\n{\n START_LOG(\"split_this_subdomain()\", \"TransientRBParamSubdomainNode\");\n\n \/\/ These first few lines are the same as RBParamSubdomainNode::split_this_subdomain\n this->add_child( _rb_system.get_greedy_parameter(0), RBParamSubdomainNode::LEFT);\n this->add_child( _rb_system.get_greedy_parameter(1), RBParamSubdomainNode::RIGHT);\n\n \/\/ Compute distance between the children anchor points, and pass to children (JLE 2010-09-16)\n Real distance_between_children_anchors = 0.;\n for (unsigned int i = 0; i < left_child->anchor.size(); i++)\n {\n distance_between_children_anchors += std::pow((left_child->anchor[i] - right_child->anchor[i]),Real(2.));\n }\n distance_between_children_anchors = std::sqrt(distance_between_children_anchors);\n left_child->distance_between_anchors = distance_between_children_anchors;\n right_child->distance_between_anchors = distance_between_children_anchors;\n\n\n \/\/ We now need some code specific to the transient case because it\n \/\/ is possible that we have repeated selection of training points\n \/\/ in the transient case (due to the POD-Greedy) and hence we\n \/\/ may have distance_between_children_anchors == 0.\n bool anchors_are_equal = (distance_between_children_anchors == 0.);\n\n if (h_stage_split)\n {\n if (anchors_are_equal)\n {\n std::cout << \"Error: Anchor points for children are equal!\"\n << std::endl;\n libmesh_error();\n }\n }\n else\n {\n if (anchors_are_equal)\n {\n for (unsigned int i=2; i< _rb_system.greedy_param_list.size() ; i++)\n {\n bool parameters_are_equal = true;\n for (unsigned int j = 0; j < left_child->anchor.size(); j++)\n {\n parameters_are_equal = ( parameters_are_equal && (left_child->anchor[j] == _rb_system.get_greedy_parameter(i)[j]));\n }\n if (!parameters_are_equal)\n {\n right_child->anchor = _rb_system.get_greedy_parameter(i);\n anchors_are_equal = false;\n break;\n }\n }\n \n \/\/ anchors_are_equal has been updated, check if we have found different point.\n if(anchors_are_equal) \n {\n std::cout << \"Error: Unable to find distinct anchors in additional splitting step.\" << std::endl;\n libmesh_error();\n }\n }\n }\n\n this->initialize_child_training_sets();\n\n STOP_LOG(\"split_this_subdomain()\", \"TransientRBParamSubdomainNode\");\n}\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"\/**\n * Open[Flex] Board View\n *\n * Copyright chloridite 2016\n * Copyright inflex 2016 (Paul Daniels)\n *\n * Git Fork: https:\/\/github.com\/inflex\/OpenBoardView\n *\n *\/\n#include \"BoardView.h\"\n\n#include \"imgui_impl_dx9.h\"\n#include \n#define DIRECTINPUT_VERSION 0x0800\n#include \"platform.h\"\n#include \"confparse.h\"\n#include \"crtdbg.h\"\n#include \"resource.h\"\n#include \n#include \n#include \n#include \n\n\/\/ Data\nstatic LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;\nstatic D3DPRESENT_PARAMETERS g_d3dpp;\n\n\/\/ local functions\n#ifndef S_ISDIR\n#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)\n#endif\nuint32_t byte4swap(uint32_t x) {\n\t\/*\n\t* used to convert RGBA -> ABGR etc\n\t*\/\n\treturn (((x & 0x000000ff) << 24) | ((x & 0x0000ff00) << 8) | ((x & 0x00ff0000) >> 8) | ((x & 0xff000000) >> 24));\n}\n\nextern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);\nLRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n\tif (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam)) return true;\n\n\tswitch (msg) {\n\t\tcase WM_SIZE:\n\t\t\tif (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) {\n\t\t\t\tImGui_ImplDX9_InvalidateDeviceObjects();\n\t\t\t\tg_d3dpp.BackBufferWidth = LOWORD(lParam);\n\t\t\t\tg_d3dpp.BackBufferHeight = HIWORD(lParam);\n\t\t\t\tHRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);\n\t\t\t\tif (hr == D3DERR_INVALIDCALL) IM_ASSERT(0);\n\t\t\t\tImGui_ImplDX9_CreateDeviceObjects();\n\t\t\t}\n\t\t\treturn 0;\n\t\tcase WM_SYSCOMMAND:\n\t\t\tif ((wParam & 0xfff0) == SC_KEYMENU) \/\/ Disable ALT application menu\n\t\t\t\treturn 0;\n\t\t\tbreak;\n\t\tcase WM_DESTROY: PostQuitMessage(0); return 0;\n\t}\n\treturn DefWindowProc(hWnd, msg, wParam, lParam);\n}\n\nint CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n\n\t\/\/ Initialize comctl\n\tCoInitializeEx(NULL, COINIT_MULTITHREADED);\n\n\tchar ss[1025];\n\tchar *homepath;\n\tint err;\n\tsize_t hpsz;\n\t\/\/ Confparse obvconfig;\n\tint sizex, sizey;\n\tbool use_exepath = false;\n\tbool use_homepath = true;\n\tBoardView app{};\n\tCHAR history_file[MAX_PATH];\n\tCHAR conf_file[MAX_PATH];\n\n\tstatic const wchar_t *class_name = L\"Openflex Board View\";\n\n\t\/*\n\t * To make OBV very easy to use and transportable among windows\n\t * users, one method is to just make it do all its business in the\n\t * folder that the EXE is launched from. It's not \"proper\" but\n\t * it is very simple and it works.\n\t *\/\n\tHMODULE hModule = GetModuleHandleA(NULL);\n\tCHAR exepath[MAX_PATH];\n\tGetModuleFileNameA(hModule, exepath, MAX_PATH);\n\n\t\/*\n\t * Trim off the filename at the end of the path\n\t *\/\n\tint l = strlen(exepath);\n\twhile (--l) {\n\t\tif (exepath[l] == '\\\\') {\n\t\t\texepath[l] = '\\0';\n\t\t\tbreak;\n\t\t}\n\t}\n\tsnprintf(history_file, sizeof(history_file), \"%s\\\\obv.history\", exepath);\n\tsnprintf(conf_file, sizeof(conf_file), \"%s\\\\obv.conf\", exepath);\n\n\t\/*\n\t * Next, we check to see if there's an APPDATA folder that's\n\t * already setup with our name on it. This will be the case\n\t * if OBV has been 'installed', even via the simple install.bat\n\t * script.\n\t *\/\n\terr = _dupenv_s(&homepath, &hpsz, \"APPDATA\");\n\tif (homepath) {\n\t\tstruct stat st;\n\t\tint sr;\n\t\tsnprintf(ss, sizeof(ss), \"%s\/openboardview\", homepath);\n\t\tsr = stat(ss, &st);\n\t\tif (sr == -1) {\n\t\t\t\/\/_mkdir(ss);\n\t\t\t\/\/ sr = stat(ss, &st);\n\t\t} else {\n\t\t\tsnprintf(history_file, sizeof(history_file), \"%s\\\\obv.history\", homepath);\n\t\t\tsnprintf(conf_file, sizeof(conf_file), \"%s\\\\obv.conf\", homepath);\n\t\t}\n\t}\n\n\t\/\/ Create application window\n\tHINSTANCE instance = GetModuleHandle(NULL);\n\tHICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1));\n\tWNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, instance, icon, NULL, NULL, NULL, class_name, NULL};\n\tRegisterClassEx(&wc);\n\n\tapp.obvconfig.Load(conf_file);\n\tsizex = app.obvconfig.ParseInt(\"windowX\", 900);\n\tsizey = app.obvconfig.ParseInt(\"windowY\", 600);\n\n\tHWND hwnd = CreateWindow(class_name,\n\t _T(\"Openflex Board Viewer\"),\n\t WS_OVERLAPPEDWINDOW,\n\t CW_USEDEFAULT,\n\t CW_USEDEFAULT,\n\t sizex,\n\t sizey,\n\t NULL,\n\t NULL,\n\t wc.hInstance,\n\t NULL);\n\n\t\/\/ Initialize Direct3D\n\tLPDIRECT3D9 pD3D;\n\tif ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) {\n\t\tUnregisterClass(class_name, wc.hInstance);\n\t\treturn 0;\n\t}\n\tZeroMemory(&g_d3dpp, sizeof(g_d3dpp));\n\tg_d3dpp.Windowed = TRUE;\n\tg_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;\n\tg_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;\n\tg_d3dpp.EnableAutoDepthStencil = TRUE;\n\tg_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;\n\tg_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;\n\n\t\/\/ Create the D3DDevice\n\tif (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) <\n\t 0) {\n\t\tpD3D->Release();\n\t\tUnregisterClass(class_name, wc.hInstance);\n\t\treturn 0;\n\t}\n\n\t\/\/ Setup ImGui binding\n\tImGui_ImplDX9_Init(hwnd, g_pd3dDevice);\n\n\t\/\/ Load Fonts\n\t\/\/ (there is a default font, this is only if you want to change it. see\n\t\/\/ extra_fonts\/README.txt\n\t\/\/ for more details)\n\tImGuiIO &io = ImGui::GetIO();\n\tio.IniFilename = NULL;\n\tint ttf_size;\n\tunsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS);\n\tImFontConfig font_cfg{};\n\tfont_cfg.FontDataOwnedByAtlas = false;\n\tio.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, app.obvconfig.ParseDouble(\"fontSize\", 20.0f), &font_cfg);\n\n\t\/*\n\t * Load the existing file loaded history\n\t *\/\n\tif (history_file[0] != '\\0') {\n\t\tapp.fhistory.Set_filename(history_file);\n\t\tapp.fhistory.Load();\n\t}\n\n\t\/*\n\t * Parse the settings in the configuration file\n\t *\n\t * There are some settings which have been parsed\n\t * earlier but they apply to the startup of the\n\t * main, as opposed to OBV itself. This call\n\t * parses all the things that'll influence OBV\n\t *\/\n\tapp.ConfigParse();\n\n\tbool show_test_window = true;\n\tbool show_another_window = false;\n\tImVec4 clear_col = ImColor(app.m_colors.backgroundColor);\n\n\t\/\/ Main loop\n\tMSG msg;\n\tZeroMemory(&msg, sizeof(msg));\n\tShowWindow(hwnd, SW_SHOWDEFAULT);\n\tUpdateWindow(hwnd);\n\twhile (msg.message != WM_QUIT) {\n\t\tif (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {\n\t\t\tTranslateMessage(&msg);\n\t\t\tDispatchMessage(&msg);\n\t\t\tcontinue;\n\t\t}\n\t\tImGui_ImplDX9_NewFrame();\n\t\tapp.Update();\n\t\tif (app.m_wantsQuit) {\n\t\t\tPostMessage(hwnd, WM_QUIT, 0, 0);\n\t\t}\n\n\t\t\/\/ Rendering\n\t\tg_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);\n\t\tg_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);\n\t\tg_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);\n\t\tD3DCOLOR clear_col_dx = D3DCOLOR_RGBA(\n\t\t (int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f), (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f));\n\t\tg_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);\n\t\tif (g_pd3dDevice->BeginScene() >= 0) {\n\t\t\tImGui::Render();\n\t\t\tg_pd3dDevice->EndScene();\n\t\t}\n\t\tg_pd3dDevice->Present(NULL, NULL, NULL, NULL);\n\t}\n\n\tImGui_ImplDX9_Shutdown();\n\tif (g_pd3dDevice) g_pd3dDevice->Release();\n\tif (pD3D) pD3D->Release();\n\tUnregisterClass(class_name, wc.hInstance);\n\n\treturn 0;\n}\nWindows dpi font setup\/**\n * Open[Flex] Board View\n *\n * Copyright chloridite 2016\n * Copyright inflex 2016 (Paul Daniels)\n *\n * Git Fork: https:\/\/github.com\/inflex\/OpenBoardView\n *\n *\/\n#include \"BoardView.h\"\n\n#include \"imgui_impl_dx9.h\"\n#include \n#define DIRECTINPUT_VERSION 0x0800\n#include \"platform.h\"\n#include \"confparse.h\"\n#include \"crtdbg.h\"\n#include \"resource.h\"\n#include \n#include \n#include \n#include \n\n\/\/ Data\nstatic LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;\nstatic D3DPRESENT_PARAMETERS g_d3dpp;\n\n\/\/ local functions\n#ifndef S_ISDIR\n#define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR)\n#endif\nuint32_t byte4swap(uint32_t x) {\n\t\/*\n\t* used to convert RGBA -> ABGR etc\n\t*\/\n\treturn (((x & 0x000000ff) << 24) | ((x & 0x0000ff00) << 8) | ((x & 0x00ff0000) >> 8) | ((x & 0xff000000) >> 24));\n}\n\nextern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);\nLRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {\n\tif (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam)) return true;\n\n\tswitch (msg) {\n\t\tcase WM_SIZE:\n\t\t\tif (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) {\n\t\t\t\tImGui_ImplDX9_InvalidateDeviceObjects();\n\t\t\t\tg_d3dpp.BackBufferWidth = LOWORD(lParam);\n\t\t\t\tg_d3dpp.BackBufferHeight = HIWORD(lParam);\n\t\t\t\tHRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);\n\t\t\t\tif (hr == D3DERR_INVALIDCALL) IM_ASSERT(0);\n\t\t\t\tImGui_ImplDX9_CreateDeviceObjects();\n\t\t\t}\n\t\t\treturn 0;\n\t\tcase WM_SYSCOMMAND:\n\t\t\tif ((wParam & 0xfff0) == SC_KEYMENU) \/\/ Disable ALT application menu\n\t\t\t\treturn 0;\n\t\t\tbreak;\n\t\tcase WM_DESTROY: PostQuitMessage(0); return 0;\n\t}\n\treturn DefWindowProc(hWnd, msg, wParam, lParam);\n}\n\nint CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {\n\n\t\/\/ Initialize comctl\n\tCoInitializeEx(NULL, COINIT_MULTITHREADED);\n\n\tchar ss[1025];\n\tchar *homepath;\n\tint err;\n\tsize_t hpsz;\n\t\/\/ Confparse obvconfig;\n\tint sizex, sizey;\n\tbool use_exepath = false;\n\tbool use_homepath = true;\n\tBoardView app{};\n\tCHAR history_file[MAX_PATH];\n\tCHAR conf_file[MAX_PATH];\n\n\tstatic const wchar_t *class_name = L\"Openflex Board View\";\n\n\t\/*\n\t * To make OBV very easy to use and transportable among windows\n\t * users, one method is to just make it do all its business in the\n\t * folder that the EXE is launched from. It's not \"proper\" but\n\t * it is very simple and it works.\n\t *\/\n\tHMODULE hModule = GetModuleHandleA(NULL);\n\tCHAR exepath[MAX_PATH];\n\tGetModuleFileNameA(hModule, exepath, MAX_PATH);\n\n\t\/*\n\t * Trim off the filename at the end of the path\n\t *\/\n\tint l = strlen(exepath);\n\twhile (--l) {\n\t\tif (exepath[l] == '\\\\') {\n\t\t\texepath[l] = '\\0';\n\t\t\tbreak;\n\t\t}\n\t}\n\tsnprintf(history_file, sizeof(history_file), \"%s\\\\obv.history\", exepath);\n\tsnprintf(conf_file, sizeof(conf_file), \"%s\\\\obv.conf\", exepath);\n\n\t\/*\n\t * Next, we check to see if there's an APPDATA folder that's\n\t * already setup with our name on it. This will be the case\n\t * if OBV has been 'installed', even via the simple install.bat\n\t * script.\n\t *\/\n\terr = _dupenv_s(&homepath, &hpsz, \"APPDATA\");\n\tif (homepath) {\n\t\tstruct stat st;\n\t\tint sr;\n\t\tsnprintf(ss, sizeof(ss), \"%s\/openboardview\", homepath);\n\t\tsr = stat(ss, &st);\n\t\tif (sr == -1) {\n\t\t\t\/\/_mkdir(ss);\n\t\t\t\/\/ sr = stat(ss, &st);\n\t\t} else {\n\t\t\tsnprintf(history_file, sizeof(history_file), \"%s\\\\obv.history\", homepath);\n\t\t\tsnprintf(conf_file, sizeof(conf_file), \"%s\\\\obv.conf\", homepath);\n\t\t}\n\t}\n\n\t\/\/ Create application window\n\tHINSTANCE instance = GetModuleHandle(NULL);\n\tHICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1));\n\tWNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, instance, icon, NULL, NULL, NULL, class_name, NULL};\n\tRegisterClassEx(&wc);\n\n\tapp.obvconfig.Load(conf_file);\n\tsizex = app.obvconfig.ParseInt(\"windowX\", 900);\n\tsizey = app.obvconfig.ParseInt(\"windowY\", 600);\n\n\tHWND hwnd = CreateWindow(class_name,\n\t _T(\"Openflex Board Viewer\"),\n\t WS_OVERLAPPEDWINDOW,\n\t CW_USEDEFAULT,\n\t CW_USEDEFAULT,\n\t sizex,\n\t sizey,\n\t NULL,\n\t NULL,\n\t wc.hInstance,\n\t NULL);\n\n\t\/\/ Initialize Direct3D\n\tLPDIRECT3D9 pD3D;\n\tif ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) {\n\t\tUnregisterClass(class_name, wc.hInstance);\n\t\treturn 0;\n\t}\n\tZeroMemory(&g_d3dpp, sizeof(g_d3dpp));\n\tg_d3dpp.Windowed = TRUE;\n\tg_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;\n\tg_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;\n\tg_d3dpp.EnableAutoDepthStencil = TRUE;\n\tg_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;\n\tg_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;\n\n\t\/\/ Create the D3DDevice\n\tif (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) <\n\t 0) {\n\t\tpD3D->Release();\n\t\tUnregisterClass(class_name, wc.hInstance);\n\t\treturn 0;\n\t}\n\n\t\/\/ Setup ImGui binding\n\tImGui_ImplDX9_Init(hwnd, g_pd3dDevice);\n\n\t\/\/ Load Fonts\n\t\/\/ (there is a default font, this is only if you want to change it. see\n\t\/\/ extra_fonts\/README.txt\n\t\/\/ for more details)\n\tImGuiIO &io = ImGui::GetIO();\n\tio.IniFilename = NULL;\n\n\t\/*\n\t * Load the existing file loaded history\n\t *\/\n\tif (history_file[0] != '\\0') {\n\t\tapp.fhistory.Set_filename(history_file);\n\t\tapp.fhistory.Load();\n\t}\n\n\t\/*\n\t * Parse the settings in the configuration file\n\t *\n\t * There are some settings which have been parsed\n\t * earlier but they apply to the startup of the\n\t * main, as opposed to OBV itself. This call\n\t * parses all the things that'll influence OBV\n\t *\/\n\tapp.ConfigParse();\n\n\t\/*\n\t * Set the font based on the dpi\n\t *\/\n\tint ttf_size;\n\tunsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS);\n\tImFontConfig font_cfg{};\n\tfont_cfg.FontDataOwnedByAtlas = false;\n\tio.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, app.obvconfig.ParseDouble(\"fontSize\", 20.0f * (app.dpi \/ 100.0)), &font_cfg);\n\n\tbool show_test_window = true;\n\tbool show_another_window = false;\n\tImVec4 clear_col = ImColor(app.m_colors.backgroundColor);\n\n\t\/\/ Main loop\n\tMSG msg;\n\tZeroMemory(&msg, sizeof(msg));\n\tShowWindow(hwnd, SW_SHOWDEFAULT);\n\tUpdateWindow(hwnd);\n\twhile (msg.message != WM_QUIT) {\n\t\tif (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {\n\t\t\tTranslateMessage(&msg);\n\t\t\tDispatchMessage(&msg);\n\t\t\tcontinue;\n\t\t}\n\t\tImGui_ImplDX9_NewFrame();\n\t\tapp.Update();\n\t\tif (app.m_wantsQuit) {\n\t\t\tPostMessage(hwnd, WM_QUIT, 0, 0);\n\t\t}\n\n\t\t\/\/ Rendering\n\t\tg_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);\n\t\tg_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);\n\t\tg_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);\n\t\tD3DCOLOR clear_col_dx = D3DCOLOR_RGBA(\n\t\t (int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f), (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f));\n\t\tg_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);\n\t\tif (g_pd3dDevice->BeginScene() >= 0) {\n\t\t\tImGui::Render();\n\t\t\tg_pd3dDevice->EndScene();\n\t\t}\n\t\tg_pd3dDevice->Present(NULL, NULL, NULL, NULL);\n\t}\n\n\tImGui_ImplDX9_Shutdown();\n\tif (g_pd3dDevice) g_pd3dDevice->Release();\n\tif (pD3D) pD3D->Release();\n\tUnregisterClass(class_name, wc.hInstance);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \"angort.h\"\n\n\n#define FN(f) a->pushFloat(f(a->popFloat()))\n%name stdmath\n\n\n%word cos (x -- cos x)\n{\n FN(cosf);\n}\n%word sin (x -- sin x)\n{\n FN(sinf);\n}\n%word tan (x -- tan x)\n{\n FN(tanf);\n}\n%word ln (x -- ln x)\n{\n FN(logf);\n}\n%word log (x -- ln x)\n{\n FN(log10f);\n}\n%word log2 (x -- log2 x)\n{\n FN(log2f);\n}\n%word sqrt (x -- sqrt x)\n{\n FN(sqrtf);\n}\nadded exp to math#include \n#include \"angort.h\"\n\n\/*\n * Mappings for (some) standard maths library functions\n *\/\n\n\n\/\/ macro for helping generate unary float functions\n#define FN(f) a->pushFloat(f(a->popFloat()))\n\n%name stdmath\n\n\n%word cos (x -- cos x)\n{\n FN(cosf);\n}\n%word sin (x -- sin x)\n{\n FN(sinf);\n}\n%word tan (x -- tan x)\n{\n FN(tanf);\n}\n%word ln (x -- ln x)\n{\n FN(logf);\n}\n%word log (x -- ln x)\n{\n FN(log10f);\n}\n%word log2 (x -- log2 x)\n{\n FN(log2f);\n}\n%word sqrt (x -- sqrt x)\n{\n FN(sqrtf);\n}\n\n%word exp (x -- exp x)\n{\n FN(exp);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include \n#include \n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"BitBar\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"-beta\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \"32a928e\"\n# define GIT_COMMIT_DATE __DATE__\n\/\/# define GIT_COMMIT_DATE \"Apr 15 2016\"\n\n\/\/ when cross compiling for windows, the commit date shows\n\/\/ in the rpcconsole build date as \"$Format:%cD\"\n time_t t=time(NULL);\n struct tm *tm=localtime(&t);\n\/\/ #define GIT_COMMIT_DATE asctime(tm)\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-g\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\nMarked for release\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include \n#include \n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"BitBar\");\n\n\/\/ Client version number\n\/\/#define CLIENT_VERSION_SUFFIX \"-beta\"\n#define CLIENT_VERSION_SUFFIX \"-release\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \"32a928e\"\n# define GIT_COMMIT_DATE __DATE__\n\/\/# define GIT_COMMIT_DATE \"Apr 15 2016\"\n\n\/\/ when cross compiling for windows, the commit date shows\n\/\/ in the rpcconsole build date as \"$Format:%cD\"\n time_t t=time(NULL);\n struct tm *tm=localtime(&t);\n\/\/ #define GIT_COMMIT_DATE asctime(tm)\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-g\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"} {"text":"\/*\n This file is part of Android File Transfer For Linux.\n Copyright (C) 2015-2018 Vladimir Menshakov\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 2.1 of the License,\n or (at your option) any later version.\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 License\n along with this library; if not, write to the Free Software Foundation,\n Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\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\n#include \"linux\/usbdevice_fs.h\"\n\n#define IOCTL(FD, ...) do \\\n{ \\\n\tint r = ioctl(FD, __VA_ARGS__); \\\n\tif (r < 0) \\\n\t{ \\\n\t\tif (errno == EBUSY) \\\n\t\t\tthrow DeviceBusyException(FD); \\\n\t\telse if (errno == ENODEV) \\\n\t\t\tthrow DeviceNotFoundException(); \\\n\t\telse \\\n\t\t\tthrow posix::Exception(\"ioctl(\" #__VA_ARGS__ \")\"); \\\n\t} \\\n} while(false)\n\nnamespace mtp { namespace usb\n{\n\n\tInterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber)\n\t{\n\t\tIOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber);\n\t}\n\n\tInterfaceToken::~InterfaceToken()\n\t{\n\t\tioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber);\n\t}\n\n#define PRINT_CAP(CAP, NAME) \\\n\tif (capabilities & (CAP)) \\\n\t{ \\\n\t\tdebug(NAME \" \"); \\\n\t\tcapabilities &= ~(CAP); \\\n\t}\n\n\n\tDevice::Device(int fd, const EndpointPtr &controlEp): _fd(fd), _capabilities(0), _controlEp(controlEp)\n\t{\n\t\ttry\n\t\t{ IOCTL(_fd.Get(), USBDEVFS_RESET); }\n\t\tcatch(const std::exception &ex)\n\t\t{ error(\"resetting device failed: \", ex.what()); }\n\n\t\ttry { IOCTL(_fd.Get(), USBDEVFS_GET_CAPABILITIES, &_capabilities); }\n\t\tcatch(const std::exception &ex)\n\t\t{ error(\"get usbfs capabilities failed: \", ex.what()); }\n\n\t\tdebug(\"capabilities = 0x\", hex(_capabilities, 8));\n\t\tbool mmap = _capabilities & USBDEVFS_CAP_MMAP;\n\t\t\/\/disable mmap allocation for now, see https:\/\/github.com\/whoozle\/android-file-transfer-linux\/issues\/194\n#if 1\n\t\tmmap = false;\n#endif\n\t\t_bufferAllocator = std::make_shared(mmap? fd: -1);\n\n\t\tif (_capabilities)\n\t\t{\n\t\t\tu32 capabilities = _capabilities;\n\t\t\tPRINT_CAP(USBDEVFS_CAP_ZERO_PACKET, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_BULK_CONTINUATION, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_NO_PACKET_SIZE_LIM, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_BULK_SCATTER_GATHER, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_REAP_AFTER_DISCONNECT, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_MMAP, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_DROP_PRIVILEGES, \"\");\n\t\t\tif (capabilities)\n\t\t\t\tdebug(\"\");\n\t\t}\n\t\telse\n\t\t\tdebug(\"[none]\\n\");\n\t}\n\n\tDevice::~Device()\n\t{ }\n\n\tint Device::GetConfiguration() const\n\t{\n\t\treturn 0;\n\t}\n\n\tvoid Device::SetConfiguration(int idx)\n\t{\n\t\terror(\"SetConfiguration(\", idx, \"): not implemented\");\n\t}\n\n\tstruct Device::Urb : usbdevfs_urb, Noncopyable\n\t{\n\t\tstatic const int \t\tMaxBufferSize = 4096;\n\t\tBufferAllocator &\t\tAllocator;\n\t\tint\t\t\t\t\t\tFd;\n\t\tint\t\t\t\t\t\tPacketSize;\n\t\tBuffer\t\t\t\t\tDataBuffer;\n\n\t\tUrb(BufferAllocator & allocator, int fd, u8 urbType, const EndpointPtr & ep):\n\t\t\tusbdevfs_urb(),\n\t\t\tAllocator(allocator),\n\t\t\tFd(fd),\n\t\t\tPacketSize(ep->GetMaxPacketSize()),\n\t\t\tDataBuffer(Allocator.Allocate(std::max(PacketSize, MaxBufferSize \/ PacketSize * PacketSize)))\n\t\t{\n\t\t\ttype\t\t\t= urbType;\n\t\t\tendpoint\t\t= ep->GetAddress();\n\t\t\tbuffer\t\t\t= DataBuffer.GetData();\n\t\t\tbuffer_length\t= DataBuffer.GetSize();\n\t\t}\n\n\t\tusbdevfs_urb *GetKernelUrb()\n\t\t{ return static_cast(this); }\n\n\t\t~Urb()\n\t\t{ Allocator.Free(DataBuffer); }\n\n\t\tsize_t GetTransferSize() const\n\t\t{ return DataBuffer.GetSize(); }\n\n\t\tvoid Submit()\n\t\t{\n\t\t\tIOCTL(Fd, USBDEVFS_SUBMITURB, GetKernelUrb());\n\t\t}\n\n\t\tvoid Discard()\n\t\t{\n\t\t\tint r = ioctl(Fd, USBDEVFS_DISCARDURB, GetKernelUrb());\n\t\t\tif (r != 0)\n\t\t\t{\n\t\t\t\tperror(\"ioctl(USBDEVFS_DISCARDURB)\");\n\t\t\t}\n\t\t}\n\n\t\tsize_t Send(const IObjectInputStreamPtr &inputStream, size_t size)\n\t\t{\n\t\t\tif (size > DataBuffer.GetSize())\n\t\t\t\tthrow std::logic_error(\"invalid size passed to Send\");\n\t\t\tauto data = DataBuffer.GetData();\n\t\t\tsize_t r = inputStream->Read(data, size);\n\t\t\t\/\/HexDump(\"write\", ByteArray(data, data + r), true);\n\t\t\tbuffer_length = r;\n\t\t\treturn r;\n\t\t}\n\n\t\tsize_t Send(const ByteArray &inputData)\n\t\t{\n\t\t\tsize_t r = std::min(DataBuffer.GetSize(), inputData.size());\n\t\t\tstd::copy(inputData.data(), inputData.data() + r, DataBuffer.GetData());\n\t\t\tbuffer_length = r;\n\t\t\treturn r;\n\t\t}\n\n\t\tsize_t Recv(const IObjectOutputStreamPtr &outputStream)\n\t\t{\n\t\t\tauto data = DataBuffer.GetData();\n\t\t\t\/\/HexDump(\"read\", ByteArray(data, data + actual_length), true);\n\t\t\treturn outputStream->Write(data, actual_length);\n\t\t}\n\n\t\ttemplate\n\t\tvoid SetFlag(bool value)\n\t\t{\n\t\t\tif (value)\n\t\t\t\tflags |= Flag;\n\t\t\telse\n\t\t\t\tflags &= ~Flag;\n\t\t}\n\n\t\tvoid SetContinuationFlag(bool continuation)\n\t\t{ SetFlag(continuation); }\n\n\t\tvoid SetZeroPacketFlag(bool zero)\n\t\t{ SetFlag(zero); }\n\t};\n\n\tvoid * Device::Reap(int timeout)\n\t{\n\t\tauto urb = AsyncReap(); \/\/attempt to pick up old urbs\n\t\tif (urb)\n\t\t\treturn urb;\n\n\t\ttimeval started = {};\n\t\tif (gettimeofday(&started, NULL) == -1)\n\t\t\tthrow posix::Exception(\"gettimeofday\");\n\n\t\tpollfd fd = {};\n\t\tfd.fd\t\t= _fd.Get();\n\t\tfd.events\t= POLLOUT | POLLWRNORM;\n\t\tint r = poll(&fd, 1, timeout);\n\n\t\ttimeval now = {};\n\t\tif (gettimeofday(&now, NULL) == -1)\n\t\t\tthrow posix::Exception(\"gettimeofday\");\n\n\t\tif (r < 0)\n\t\t\tthrow posix::Exception(\"poll\");\n\n\t\tif (r == 0 && timeout > 0)\n\t\t{\n\t\t\tint ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) \/ 1000;\n\t\t\terror(ms, \" ms since the last poll call\");\n\t\t}\n\t\turb = AsyncReap();\n\t\tif (urb)\n\t\t\treturn urb;\n\t\telse\n\t\t\tthrow TimeoutException(\"timeout reaping usb urb\");\n\t}\n\n\tvoid * Device::AsyncReap()\n\t{\n\t\tusbdevfs_urb *urb;\n\t\tint r = ioctl(_fd.Get(), USBDEVFS_REAPURBNDELAY, &urb);\n\t\tif (r == 0)\n\t\t\treturn urb;\n\t\telse if (errno == EAGAIN)\n\t\t\treturn nullptr;\n\t\telse\n\t\t\tthrow posix::Exception(\"ioctl(USBDEVFS_REAPURBNDELAY)\");\n\t}\n\n\tvoid Device::ClearHalt(const EndpointPtr & ep)\n\t{\n\t\ttry\n\t\t{ unsigned index = ep->GetAddress(); IOCTL(_fd.Get(), USBDEVFS_CLEAR_HALT, &index); }\n\t\tcatch(const std::exception &ex)\n\t\t{ error(\"clearing halt status for ep \", hex(ep->GetAddress(), 2), \": \", ex.what()); }\n\t}\n\n\tvoid Device::Submit(Urb *urb, int timeout)\n\t{\n\t\turb->Submit();\n\t\ttry\n\t\t{\n\t\t\twhile(true)\n\t\t\t{\n\t\t\t\tusbdevfs_urb * completedKernelUrb = static_cast(Reap(timeout));\n\t\t\t\tif (urb->GetKernelUrb() != completedKernelUrb)\n\t\t\t\t{\n\t\t\t\t\terror(\"got unknown urb: \", completedKernelUrb);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcatch(const TimeoutException &ex)\n\t\t{\n\t\t\turb->Discard();\n\t\t\tthrow;\n\t\t}\n\t\tcatch(const std::exception &ex)\n\t\t{\n\t\t\terror(\"error while submitting urb: \", ex.what());\n\t\t\turb->Discard();\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tvoid Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)\n\t{\n\t\tUrb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);\n\t\tsize_t transferSize = urb.GetTransferSize();\n\n\t\tsize_t r;\n\t\tbool continuation = false;\n\t\tdo\n\t\t{\n\t\t\tr = urb.Send(inputStream, transferSize);\n\n\t\t\tif (_capabilities & USBDEVFS_CAP_ZERO_PACKET)\n\t\t\t\turb.SetZeroPacketFlag(r != transferSize);\n\n\t\t\tif (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION)\n\t\t\t{\n\t\t\t\turb.SetContinuationFlag(continuation);\n\t\t\t\tcontinuation = true;\n\t\t\t}\n\t\t\tSubmit(&urb, timeout);\n\t\t}\n\t\twhile(r == transferSize);\n\t}\n\n\tvoid Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)\n\t{\n\t\tUrb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);\n\t\tsize_t transferSize = urb.GetTransferSize();\n\n\t\tsize_t r;\n\t\tbool continuation = false;\n\t\tdo\n\t\t{\n\t\t\tif (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION)\n\t\t\t{\n\t\t\t\turb.SetContinuationFlag(continuation);\n\t\t\t\tcontinuation = true;\n\t\t\t}\n\t\t\tSubmit(&urb, timeout);\n\n\t\t\tr = urb.Recv(outputStream);\n\t\t}\n\t\twhile(r == transferSize);\n\t}\n\n\tu8 Device::TransactionType(const EndpointPtr &ep)\n\t{\n\t\tEndpointType type = ep->GetType();\n\t\tswitch(type)\n\t\t{\n\t\tcase EndpointType::Control:\n\t\t\treturn USBDEVFS_URB_TYPE_CONTROL;\n\t\tcase EndpointType::Isochronous:\n\t\t\treturn USBDEVFS_URB_TYPE_ISO;\n\t\tcase EndpointType::Bulk:\n\t\t\treturn USBDEVFS_URB_TYPE_BULK;\n\t\tcase EndpointType::Interrupt:\n\t\t\treturn USBDEVFS_URB_TYPE_INTERRUPT;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"invalid endpoint type\");\n\t\t}\n\t}\n\n\tvoid Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)\n\t{\n\t\tdebug(\"read control \", hex(type, 2), \" \", hex(req, 2), \" \", hex(value, 4), \" \", hex(index, 4));\n\t\tusbdevfs_ctrltransfer ctrl = { };\n\t\tctrl.bRequestType = type;\n\t\tctrl.bRequest = req;\n\t\tctrl.wValue = value;\n\t\tctrl.wIndex = index;\n\t\tctrl.wLength = data.size();\n\t\tctrl.data = const_cast(data.data());\n\t\tctrl.timeout = timeout;\n\n\t\tint fd = _fd.Get();\n\n\t\tint r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);\n\t\tif (r >= 0)\n\t\t\tdata.resize(r);\n\t\telse if (errno == EAGAIN)\n\t\t\tthrow TimeoutException(\"timeout sending control transfer\");\n\t\telse\n\t\t\tthrow posix::Exception(\"ioctl\");\n\t}\n\n\tvoid Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, int timeout)\n\t{\n\t\tdebug(\"write control \", hex(type, 2), \" \", hex(req, 2), \" \", hex(value, 4), \" \", hex(index, 4));\n\t\tusbdevfs_ctrltransfer ctrl = { };\n\t\tctrl.bRequestType = type;\n\t\tctrl.bRequest = req;\n\t\tctrl.wValue = value;\n\t\tctrl.wIndex = index;\n\t\tctrl.wLength = data.size();\n\t\tctrl.data = const_cast(data.data());\n\t\tctrl.timeout = timeout;\n\n\t\tint fd = _fd.Get();\n\n\t\tint r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);\n\t\tif (r >= 0)\n\t\t\treturn;\n\t\telse if (errno == EAGAIN)\n\t\t\tthrow TimeoutException(\"timeout sending control transfer\");\n\t\telse\n\t\t\tthrow posix::Exception(\"ioctl\");\n\t}\n\n}}\ncall gettimeofday after exception being thrown\/*\n This file is part of Android File Transfer For Linux.\n Copyright (C) 2015-2018 Vladimir Menshakov\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 2.1 of the License,\n or (at your option) any later version.\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 License\n along with this library; if not, write to the Free Software Foundation,\n Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\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\n#include \"linux\/usbdevice_fs.h\"\n\n#define IOCTL(FD, ...) do \\\n{ \\\n\tint r = ioctl(FD, __VA_ARGS__); \\\n\tif (r < 0) \\\n\t{ \\\n\t\tif (errno == EBUSY) \\\n\t\t\tthrow DeviceBusyException(FD); \\\n\t\telse if (errno == ENODEV) \\\n\t\t\tthrow DeviceNotFoundException(); \\\n\t\telse \\\n\t\t\tthrow posix::Exception(\"ioctl(\" #__VA_ARGS__ \")\"); \\\n\t} \\\n} while(false)\n\nnamespace mtp { namespace usb\n{\n\n\tInterfaceToken::InterfaceToken(int fd, unsigned interfaceNumber): _fd(fd), _interfaceNumber(interfaceNumber)\n\t{\n\t\tIOCTL(_fd, USBDEVFS_CLAIMINTERFACE, &interfaceNumber);\n\t}\n\n\tInterfaceToken::~InterfaceToken()\n\t{\n\t\tioctl(_fd, USBDEVFS_RELEASEINTERFACE, &_interfaceNumber);\n\t}\n\n#define PRINT_CAP(CAP, NAME) \\\n\tif (capabilities & (CAP)) \\\n\t{ \\\n\t\tdebug(NAME \" \"); \\\n\t\tcapabilities &= ~(CAP); \\\n\t}\n\n\n\tDevice::Device(int fd, const EndpointPtr &controlEp): _fd(fd), _capabilities(0), _controlEp(controlEp)\n\t{\n\t\ttry\n\t\t{ IOCTL(_fd.Get(), USBDEVFS_RESET); }\n\t\tcatch(const std::exception &ex)\n\t\t{ error(\"resetting device failed: \", ex.what()); }\n\n\t\ttry { IOCTL(_fd.Get(), USBDEVFS_GET_CAPABILITIES, &_capabilities); }\n\t\tcatch(const std::exception &ex)\n\t\t{ error(\"get usbfs capabilities failed: \", ex.what()); }\n\n\t\tdebug(\"capabilities = 0x\", hex(_capabilities, 8));\n\t\tbool mmap = _capabilities & USBDEVFS_CAP_MMAP;\n\t\t\/\/disable mmap allocation for now, see https:\/\/github.com\/whoozle\/android-file-transfer-linux\/issues\/194\n#if 1\n\t\tmmap = false;\n#endif\n\t\t_bufferAllocator = std::make_shared(mmap? fd: -1);\n\n\t\tif (_capabilities)\n\t\t{\n\t\t\tu32 capabilities = _capabilities;\n\t\t\tPRINT_CAP(USBDEVFS_CAP_ZERO_PACKET, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_BULK_CONTINUATION, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_NO_PACKET_SIZE_LIM, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_BULK_SCATTER_GATHER, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_REAP_AFTER_DISCONNECT, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_MMAP, \"\");\n\t\t\tPRINT_CAP(USBDEVFS_CAP_DROP_PRIVILEGES, \"\");\n\t\t\tif (capabilities)\n\t\t\t\tdebug(\"\");\n\t\t}\n\t\telse\n\t\t\tdebug(\"[none]\\n\");\n\t}\n\n\tDevice::~Device()\n\t{ }\n\n\tint Device::GetConfiguration() const\n\t{\n\t\treturn 0;\n\t}\n\n\tvoid Device::SetConfiguration(int idx)\n\t{\n\t\terror(\"SetConfiguration(\", idx, \"): not implemented\");\n\t}\n\n\tstruct Device::Urb : usbdevfs_urb, Noncopyable\n\t{\n\t\tstatic const int \t\tMaxBufferSize = 4096;\n\t\tBufferAllocator &\t\tAllocator;\n\t\tint\t\t\t\t\t\tFd;\n\t\tint\t\t\t\t\t\tPacketSize;\n\t\tBuffer\t\t\t\t\tDataBuffer;\n\n\t\tUrb(BufferAllocator & allocator, int fd, u8 urbType, const EndpointPtr & ep):\n\t\t\tusbdevfs_urb(),\n\t\t\tAllocator(allocator),\n\t\t\tFd(fd),\n\t\t\tPacketSize(ep->GetMaxPacketSize()),\n\t\t\tDataBuffer(Allocator.Allocate(std::max(PacketSize, MaxBufferSize \/ PacketSize * PacketSize)))\n\t\t{\n\t\t\ttype\t\t\t= urbType;\n\t\t\tendpoint\t\t= ep->GetAddress();\n\t\t\tbuffer\t\t\t= DataBuffer.GetData();\n\t\t\tbuffer_length\t= DataBuffer.GetSize();\n\t\t}\n\n\t\tusbdevfs_urb *GetKernelUrb()\n\t\t{ return static_cast(this); }\n\n\t\t~Urb()\n\t\t{ Allocator.Free(DataBuffer); }\n\n\t\tsize_t GetTransferSize() const\n\t\t{ return DataBuffer.GetSize(); }\n\n\t\tvoid Submit()\n\t\t{\n\t\t\tIOCTL(Fd, USBDEVFS_SUBMITURB, GetKernelUrb());\n\t\t}\n\n\t\tvoid Discard()\n\t\t{\n\t\t\tint r = ioctl(Fd, USBDEVFS_DISCARDURB, GetKernelUrb());\n\t\t\tif (r != 0)\n\t\t\t{\n\t\t\t\tperror(\"ioctl(USBDEVFS_DISCARDURB)\");\n\t\t\t}\n\t\t}\n\n\t\tsize_t Send(const IObjectInputStreamPtr &inputStream, size_t size)\n\t\t{\n\t\t\tif (size > DataBuffer.GetSize())\n\t\t\t\tthrow std::logic_error(\"invalid size passed to Send\");\n\t\t\tauto data = DataBuffer.GetData();\n\t\t\tsize_t r = inputStream->Read(data, size);\n\t\t\t\/\/HexDump(\"write\", ByteArray(data, data + r), true);\n\t\t\tbuffer_length = r;\n\t\t\treturn r;\n\t\t}\n\n\t\tsize_t Send(const ByteArray &inputData)\n\t\t{\n\t\t\tsize_t r = std::min(DataBuffer.GetSize(), inputData.size());\n\t\t\tstd::copy(inputData.data(), inputData.data() + r, DataBuffer.GetData());\n\t\t\tbuffer_length = r;\n\t\t\treturn r;\n\t\t}\n\n\t\tsize_t Recv(const IObjectOutputStreamPtr &outputStream)\n\t\t{\n\t\t\tauto data = DataBuffer.GetData();\n\t\t\t\/\/HexDump(\"read\", ByteArray(data, data + actual_length), true);\n\t\t\treturn outputStream->Write(data, actual_length);\n\t\t}\n\n\t\ttemplate\n\t\tvoid SetFlag(bool value)\n\t\t{\n\t\t\tif (value)\n\t\t\t\tflags |= Flag;\n\t\t\telse\n\t\t\t\tflags &= ~Flag;\n\t\t}\n\n\t\tvoid SetContinuationFlag(bool continuation)\n\t\t{ SetFlag(continuation); }\n\n\t\tvoid SetZeroPacketFlag(bool zero)\n\t\t{ SetFlag(zero); }\n\t};\n\n\tvoid * Device::Reap(int timeout)\n\t{\n\t\tauto urb = AsyncReap(); \/\/attempt to pick up old urbs\n\t\tif (urb)\n\t\t\treturn urb;\n\n\t\ttimeval started = {};\n\t\tif (gettimeofday(&started, NULL) == -1)\n\t\t\tthrow posix::Exception(\"gettimeofday\");\n\n\t\tpollfd fd = {};\n\t\tfd.fd\t\t= _fd.Get();\n\t\tfd.events\t= POLLOUT | POLLWRNORM;\n\t\tint r = poll(&fd, 1, timeout);\n\n\t\tif (r < 0)\n\t\t\tthrow posix::Exception(\"poll\");\n\n\t\ttimeval now = {};\n\t\tif (gettimeofday(&now, NULL) == -1)\n\t\t\tthrow posix::Exception(\"gettimeofday\");\n\n\t\tif (r == 0 && timeout > 0)\n\t\t{\n\t\t\tint ms = (now.tv_sec - started.tv_sec) * 1000 + (now.tv_usec - started.tv_usec) \/ 1000;\n\t\t\terror(ms, \" ms since the last poll call\");\n\t\t}\n\t\turb = AsyncReap();\n\t\tif (urb)\n\t\t\treturn urb;\n\t\telse\n\t\t\tthrow TimeoutException(\"timeout reaping usb urb\");\n\t}\n\n\tvoid * Device::AsyncReap()\n\t{\n\t\tusbdevfs_urb *urb;\n\t\tint r = ioctl(_fd.Get(), USBDEVFS_REAPURBNDELAY, &urb);\n\t\tif (r == 0)\n\t\t\treturn urb;\n\t\telse if (errno == EAGAIN)\n\t\t\treturn nullptr;\n\t\telse\n\t\t\tthrow posix::Exception(\"ioctl(USBDEVFS_REAPURBNDELAY)\");\n\t}\n\n\tvoid Device::ClearHalt(const EndpointPtr & ep)\n\t{\n\t\ttry\n\t\t{ unsigned index = ep->GetAddress(); IOCTL(_fd.Get(), USBDEVFS_CLEAR_HALT, &index); }\n\t\tcatch(const std::exception &ex)\n\t\t{ error(\"clearing halt status for ep \", hex(ep->GetAddress(), 2), \": \", ex.what()); }\n\t}\n\n\tvoid Device::Submit(Urb *urb, int timeout)\n\t{\n\t\turb->Submit();\n\t\ttry\n\t\t{\n\t\t\twhile(true)\n\t\t\t{\n\t\t\t\tusbdevfs_urb * completedKernelUrb = static_cast(Reap(timeout));\n\t\t\t\tif (urb->GetKernelUrb() != completedKernelUrb)\n\t\t\t\t{\n\t\t\t\t\terror(\"got unknown urb: \", completedKernelUrb);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcatch(const TimeoutException &ex)\n\t\t{\n\t\t\turb->Discard();\n\t\t\tthrow;\n\t\t}\n\t\tcatch(const std::exception &ex)\n\t\t{\n\t\t\terror(\"error while submitting urb: \", ex.what());\n\t\t\turb->Discard();\n\t\t\tthrow;\n\t\t}\n\t}\n\n\tvoid Device::WriteBulk(const EndpointPtr & ep, const IObjectInputStreamPtr &inputStream, int timeout)\n\t{\n\t\tUrb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);\n\t\tsize_t transferSize = urb.GetTransferSize();\n\n\t\tsize_t r;\n\t\tbool continuation = false;\n\t\tdo\n\t\t{\n\t\t\tr = urb.Send(inputStream, transferSize);\n\n\t\t\tif (_capabilities & USBDEVFS_CAP_ZERO_PACKET)\n\t\t\t\turb.SetZeroPacketFlag(r != transferSize);\n\n\t\t\tif (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION)\n\t\t\t{\n\t\t\t\turb.SetContinuationFlag(continuation);\n\t\t\t\tcontinuation = true;\n\t\t\t}\n\t\t\tSubmit(&urb, timeout);\n\t\t}\n\t\twhile(r == transferSize);\n\t}\n\n\tvoid Device::ReadBulk(const EndpointPtr & ep, const IObjectOutputStreamPtr &outputStream, int timeout)\n\t{\n\t\tUrb urb(*_bufferAllocator, _fd.Get(), USBDEVFS_URB_TYPE_BULK, ep);\n\t\tsize_t transferSize = urb.GetTransferSize();\n\n\t\tsize_t r;\n\t\tbool continuation = false;\n\t\tdo\n\t\t{\n\t\t\tif (_capabilities & USBDEVFS_CAP_BULK_CONTINUATION)\n\t\t\t{\n\t\t\t\turb.SetContinuationFlag(continuation);\n\t\t\t\tcontinuation = true;\n\t\t\t}\n\t\t\tSubmit(&urb, timeout);\n\n\t\t\tr = urb.Recv(outputStream);\n\t\t}\n\t\twhile(r == transferSize);\n\t}\n\n\tu8 Device::TransactionType(const EndpointPtr &ep)\n\t{\n\t\tEndpointType type = ep->GetType();\n\t\tswitch(type)\n\t\t{\n\t\tcase EndpointType::Control:\n\t\t\treturn USBDEVFS_URB_TYPE_CONTROL;\n\t\tcase EndpointType::Isochronous:\n\t\t\treturn USBDEVFS_URB_TYPE_ISO;\n\t\tcase EndpointType::Bulk:\n\t\t\treturn USBDEVFS_URB_TYPE_BULK;\n\t\tcase EndpointType::Interrupt:\n\t\t\treturn USBDEVFS_URB_TYPE_INTERRUPT;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"invalid endpoint type\");\n\t\t}\n\t}\n\n\tvoid Device::ReadControl(u8 type, u8 req, u16 value, u16 index, ByteArray &data, int timeout)\n\t{\n\t\tdebug(\"read control \", hex(type, 2), \" \", hex(req, 2), \" \", hex(value, 4), \" \", hex(index, 4));\n\t\tusbdevfs_ctrltransfer ctrl = { };\n\t\tctrl.bRequestType = type;\n\t\tctrl.bRequest = req;\n\t\tctrl.wValue = value;\n\t\tctrl.wIndex = index;\n\t\tctrl.wLength = data.size();\n\t\tctrl.data = const_cast(data.data());\n\t\tctrl.timeout = timeout;\n\n\t\tint fd = _fd.Get();\n\n\t\tint r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);\n\t\tif (r >= 0)\n\t\t\tdata.resize(r);\n\t\telse if (errno == EAGAIN)\n\t\t\tthrow TimeoutException(\"timeout sending control transfer\");\n\t\telse\n\t\t\tthrow posix::Exception(\"ioctl\");\n\t}\n\n\tvoid Device::WriteControl(u8 type, u8 req, u16 value, u16 index, const ByteArray &data, int timeout)\n\t{\n\t\tdebug(\"write control \", hex(type, 2), \" \", hex(req, 2), \" \", hex(value, 4), \" \", hex(index, 4));\n\t\tusbdevfs_ctrltransfer ctrl = { };\n\t\tctrl.bRequestType = type;\n\t\tctrl.bRequest = req;\n\t\tctrl.wValue = value;\n\t\tctrl.wIndex = index;\n\t\tctrl.wLength = data.size();\n\t\tctrl.data = const_cast(data.data());\n\t\tctrl.timeout = timeout;\n\n\t\tint fd = _fd.Get();\n\n\t\tint r = ioctl(fd, USBDEVFS_CONTROL, &ctrl);\n\t\tif (r >= 0)\n\t\t\treturn;\n\t\telse if (errno == EAGAIN)\n\t\t\tthrow TimeoutException(\"timeout sending control transfer\");\n\t\telse\n\t\t\tthrow posix::Exception(\"ioctl\");\n\t}\n\n}}\n<|endoftext|>"} {"text":"\/*\n\nCopyright 2015 Virtium Technology\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<\/License>\n*\/\n\n#include \n\n#include \"AtaProtocolEssense1.h\"\n\n#include \"ProtocolAtaPassThrough.h\"\n\nnamespace vtStor\n{\nnamespace Protocol\n{\n\n const vtStor::U8 FEATURE_REGISTER_OFFSET = 0;\n const vtStor::U8 ERROR_REGISTER_OFFSET = 0;\n const vtStor::U8 COUNT_REGISTER_OFFSET = 1;\n const vtStor::U8 LBA_LOW_REGISTER_OFFSET = 2;\n const vtStor::U8 LBA_MID_REGISTER_OFFSET = 3;\n const vtStor::U8 LBA_HIGH_REGISTER_OFFSET = 4;\n const vtStor::U8 DEVICE_REGISTER_OFFSET = 5;\n const vtStor::U8 COMMAND_REGISTER_OFFSET = 6;\n const vtStor::U8 STATUS_REGISTER_OFFSET = 6;\n const vtStor::U8 RESERVED_REGISTER_OFFSET = 7;\n \n eErrorCode cAtaPassThrough::IssueCommand( std::shared_ptr Essense, std::shared_ptr DataBuffer )\n {\n eErrorCode errorCode = eErrorCode::None;\n\n cEssenseAta1 essense = cEssenseAta1::Reader( Essense ); \n \n switch (essense.GetHeader().Format)\n {\n case 1:\n {\n m_DeviceHandle = essense.GetDeviceHandle();\n\n InitializePassThroughDirect(\n essense.GetCommandCharacteristics(),\n essense.GetTaskFileExt(),\n essense.GetTaskFile(),\n DataBuffer,\n 60 \/\/TODO: allow configurable timeout\n );\n\n \n U32 bytesReturned = 0;\n errorCode = IssuePassThroughDirectCommand(bytesReturned);\n } break;\n\n default:\n errorCode = eErrorCode::FormatNotSupported;\n break; \n } \n\n return(errorCode);\n }\n\n void cAtaPassThrough::InitializePassThroughDirect( const StorageUtility::Ata::sCommandCharacteristic& CommandCharacteristics, const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile, std::shared_ptr DataBuffer, U32 TimeoutValueInSeconds )\n {\n m_AtaPassThrough.Length = sizeof( ATA_PASS_THROUGH_DIRECT );\n m_AtaPassThrough.DataTransferLength = CommandCharacteristics.DataTransferLengthInBytes;\n m_AtaPassThrough.TimeOutValue = TimeoutValueInSeconds;\n if (nullptr != DataBuffer)\n {\n m_AtaPassThrough.DataBuffer = DataBuffer->ToDataBuffer();\n }\n m_AtaPassThrough.ReservedAsUchar = 0;\n m_AtaPassThrough.ReservedAsUlong = 0;\n\n InitializeFlags( CommandCharacteristics );\n InitializeTaskFileInputRegisters( PreviousTaskFile, CurrentTaskFile );\n }\n\n void cAtaPassThrough::InitializeFlags( const StorageUtility::Ata::sCommandCharacteristic& AtaCommandCharacteristic )\n {\n \/\/ Clear all flags\n m_AtaPassThrough.AtaFlags = 0;\n\n if (StorageUtility::Ata::eDeviceReadyFlag::DEVICE_READY_REQUIRED == AtaCommandCharacteristic.DeviceReadyFlag)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DRDY_REQUIRED;\n }\n\n switch (AtaCommandCharacteristic.DataAccess)\n {\n case StorageUtility::Ata::eDataAccess::READ_FROM_DEVICE:\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_IN;\n } break;\n case StorageUtility::Ata::eDataAccess::WRITE_TO_DEVICE:\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_OUT;\n } break;\n }\n\n if (StorageUtility::Ata::eFieldFormatting::COMMAND_48_BIT == AtaCommandCharacteristic.FieldFormatting)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_48BIT_COMMAND;\n }\n\n if (StorageUtility::Ata::eTransferMode::DMA_PROTOCOL == AtaCommandCharacteristic.TransferMode)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_USE_DMA;\n }\n\n if (StorageUtility::Ata::eMultipleMode::NOT_MULTIPLE_COMMAND == AtaCommandCharacteristic.MultipleMode)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_NO_MULTIPLE;\n }\n }\n\n void cAtaPassThrough::InitializeTaskFileInputRegisters( const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile )\n {\n m_AtaPassThrough.PreviousTaskFile[FEATURE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Feature;\n m_AtaPassThrough.PreviousTaskFile[COUNT_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Count;\n m_AtaPassThrough.PreviousTaskFile[LBA_LOW_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaLow;\n m_AtaPassThrough.PreviousTaskFile[LBA_MID_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaMid;\n m_AtaPassThrough.PreviousTaskFile[LBA_HIGH_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaHigh;\n m_AtaPassThrough.PreviousTaskFile[DEVICE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Device;\n m_AtaPassThrough.PreviousTaskFile[COMMAND_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Command;\n m_AtaPassThrough.PreviousTaskFile[RESERVED_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Reserved;\n\n m_AtaPassThrough.CurrentTaskFile[FEATURE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Feature;\n m_AtaPassThrough.CurrentTaskFile[COUNT_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Count;\n m_AtaPassThrough.CurrentTaskFile[LBA_LOW_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaLow;\n m_AtaPassThrough.CurrentTaskFile[LBA_MID_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaMid;\n m_AtaPassThrough.CurrentTaskFile[LBA_HIGH_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaHigh;\n m_AtaPassThrough.CurrentTaskFile[DEVICE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Device;\n m_AtaPassThrough.CurrentTaskFile[COMMAND_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Command;\n m_AtaPassThrough.CurrentTaskFile[RESERVED_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Reserved;\n }\n\n eErrorCode cAtaPassThrough::IssuePassThroughDirectCommand( U32& BytesReturned )\n {\n \n assert( INVALID_HANDLE_VALUE != m_DeviceHandle );\n\n eErrorCode error;\n error = eErrorCode::None;\n \n BOOL commandSuccessfulFlag;\n DWORD bytesReturned;\n commandSuccessfulFlag = DeviceIoControl\n (\n m_DeviceHandle,\n IOCTL_ATA_PASS_THROUGH_DIRECT,\n &m_AtaPassThrough,\n m_AtaPassThrough.Length,\n &m_AtaPassThrough,\n m_AtaPassThrough.Length,\n &bytesReturned,\n NULL\n );\n\n \/\/ If the operation was not successful:\n if (FALSE == commandSuccessfulFlag)\n {\n error = eErrorCode::Io;\n \n \/\/TODO: report extended error\n \/\/fprintf( stderr, \"\\nDeviceIoControl was not successful. Error Code: %d\", GetLastError() );\n }\n\n BytesReturned = bytesReturned;\n\n return(error);\n }\n\n}\n}\n\nVT_STOR_ATA_PROTOCOL_API void vtStorProtocolAtaPassThroughInit(std::shared_ptr& Protocol)\n{\n Protocol = std::make_shared();\n}Check header of Essense before create Essense object\/*\n\nCopyright 2015 Virtium Technology\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<\/License>\n*\/\n\n#include \n\n#include \"AtaProtocolEssense1.h\"\n\n#include \"ProtocolAtaPassThrough.h\"\n\nnamespace vtStor\n{\nnamespace Protocol\n{\n\n const vtStor::U8 FEATURE_REGISTER_OFFSET = 0;\n const vtStor::U8 ERROR_REGISTER_OFFSET = 0;\n const vtStor::U8 COUNT_REGISTER_OFFSET = 1;\n const vtStor::U8 LBA_LOW_REGISTER_OFFSET = 2;\n const vtStor::U8 LBA_MID_REGISTER_OFFSET = 3;\n const vtStor::U8 LBA_HIGH_REGISTER_OFFSET = 4;\n const vtStor::U8 DEVICE_REGISTER_OFFSET = 5;\n const vtStor::U8 COMMAND_REGISTER_OFFSET = 6;\n const vtStor::U8 STATUS_REGISTER_OFFSET = 6;\n const vtStor::U8 RESERVED_REGISTER_OFFSET = 7;\n \n eErrorCode cAtaPassThrough::IssueCommand( std::shared_ptr Essense, std::shared_ptr DataBuffer )\n {\n eErrorCode errorCode = eErrorCode::None;\n\n cBufferFormatter bufferFormatter = cBufferFormatter::Reader(Essense); \n \n switch (bufferFormatter.GetHeader().Format)\n {\n case 1:\n {\n cEssenseAta1 essense = cEssenseAta1::Reader(Essense);\n m_DeviceHandle = essense.GetDeviceHandle();\n\n InitializePassThroughDirect(\n essense.GetCommandCharacteristics(),\n essense.GetTaskFileExt(),\n essense.GetTaskFile(),\n DataBuffer,\n 60 \/\/TODO: allow configurable timeout\n );\n\n \n U32 bytesReturned = 0;\n errorCode = IssuePassThroughDirectCommand(bytesReturned);\n } break;\n\n default:\n errorCode = eErrorCode::FormatNotSupported;\n break; \n } \n\n return(errorCode);\n }\n\n void cAtaPassThrough::InitializePassThroughDirect( const StorageUtility::Ata::sCommandCharacteristic& CommandCharacteristics, const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile, std::shared_ptr DataBuffer, U32 TimeoutValueInSeconds )\n {\n m_AtaPassThrough.Length = sizeof( ATA_PASS_THROUGH_DIRECT );\n m_AtaPassThrough.DataTransferLength = CommandCharacteristics.DataTransferLengthInBytes;\n m_AtaPassThrough.TimeOutValue = TimeoutValueInSeconds;\n if (nullptr != DataBuffer)\n {\n m_AtaPassThrough.DataBuffer = DataBuffer->ToDataBuffer();\n }\n m_AtaPassThrough.ReservedAsUchar = 0;\n m_AtaPassThrough.ReservedAsUlong = 0;\n\n InitializeFlags( CommandCharacteristics );\n InitializeTaskFileInputRegisters( PreviousTaskFile, CurrentTaskFile );\n }\n\n void cAtaPassThrough::InitializeFlags( const StorageUtility::Ata::sCommandCharacteristic& AtaCommandCharacteristic )\n {\n \/\/ Clear all flags\n m_AtaPassThrough.AtaFlags = 0;\n\n if (StorageUtility::Ata::eDeviceReadyFlag::DEVICE_READY_REQUIRED == AtaCommandCharacteristic.DeviceReadyFlag)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DRDY_REQUIRED;\n }\n\n switch (AtaCommandCharacteristic.DataAccess)\n {\n case StorageUtility::Ata::eDataAccess::READ_FROM_DEVICE:\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_IN;\n } break;\n case StorageUtility::Ata::eDataAccess::WRITE_TO_DEVICE:\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_DATA_OUT;\n } break;\n }\n\n if (StorageUtility::Ata::eFieldFormatting::COMMAND_48_BIT == AtaCommandCharacteristic.FieldFormatting)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_48BIT_COMMAND;\n }\n\n if (StorageUtility::Ata::eTransferMode::DMA_PROTOCOL == AtaCommandCharacteristic.TransferMode)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_USE_DMA;\n }\n\n if (StorageUtility::Ata::eMultipleMode::NOT_MULTIPLE_COMMAND == AtaCommandCharacteristic.MultipleMode)\n {\n m_AtaPassThrough.AtaFlags |= ATA_FLAGS_NO_MULTIPLE;\n }\n }\n\n void cAtaPassThrough::InitializeTaskFileInputRegisters( const StorageUtility::Ata::uTaskFileRegister& PreviousTaskFile, const StorageUtility::Ata::uTaskFileRegister& CurrentTaskFile )\n {\n m_AtaPassThrough.PreviousTaskFile[FEATURE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Feature;\n m_AtaPassThrough.PreviousTaskFile[COUNT_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Count;\n m_AtaPassThrough.PreviousTaskFile[LBA_LOW_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaLow;\n m_AtaPassThrough.PreviousTaskFile[LBA_MID_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaMid;\n m_AtaPassThrough.PreviousTaskFile[LBA_HIGH_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.LbaHigh;\n m_AtaPassThrough.PreviousTaskFile[DEVICE_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Device;\n m_AtaPassThrough.PreviousTaskFile[COMMAND_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Command;\n m_AtaPassThrough.PreviousTaskFile[RESERVED_REGISTER_OFFSET] = PreviousTaskFile.InputRegister.Reserved;\n\n m_AtaPassThrough.CurrentTaskFile[FEATURE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Feature;\n m_AtaPassThrough.CurrentTaskFile[COUNT_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Count;\n m_AtaPassThrough.CurrentTaskFile[LBA_LOW_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaLow;\n m_AtaPassThrough.CurrentTaskFile[LBA_MID_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaMid;\n m_AtaPassThrough.CurrentTaskFile[LBA_HIGH_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.LbaHigh;\n m_AtaPassThrough.CurrentTaskFile[DEVICE_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Device;\n m_AtaPassThrough.CurrentTaskFile[COMMAND_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Command;\n m_AtaPassThrough.CurrentTaskFile[RESERVED_REGISTER_OFFSET] = CurrentTaskFile.InputRegister.Reserved;\n }\n\n eErrorCode cAtaPassThrough::IssuePassThroughDirectCommand( U32& BytesReturned )\n {\n \n assert( INVALID_HANDLE_VALUE != m_DeviceHandle );\n\n eErrorCode error;\n error = eErrorCode::None;\n \n BOOL commandSuccessfulFlag;\n DWORD bytesReturned;\n commandSuccessfulFlag = DeviceIoControl\n (\n m_DeviceHandle,\n IOCTL_ATA_PASS_THROUGH_DIRECT,\n &m_AtaPassThrough,\n m_AtaPassThrough.Length,\n &m_AtaPassThrough,\n m_AtaPassThrough.Length,\n &bytesReturned,\n NULL\n );\n\n \/\/ If the operation was not successful:\n if (FALSE == commandSuccessfulFlag)\n {\n error = eErrorCode::Io;\n \n \/\/TODO: report extended error\n \/\/fprintf( stderr, \"\\nDeviceIoControl was not successful. Error Code: %d\", GetLastError() );\n }\n\n BytesReturned = bytesReturned;\n\n return(error);\n }\n\n}\n}\n\nVT_STOR_ATA_PROTOCOL_API void vtStorProtocolAtaPassThroughInit(std::shared_ptr& Protocol)\n{\n Protocol = std::make_shared();\n}<|endoftext|>"} {"text":"#include \"Core\\Context.h\"\n#include \"Core\\Engine.h\"\n\nusing namespace Mile;\n\nint main( )\n{\n auto context = std::make_unique( );\n auto engine = new Engine( context.get( ) );\n\n if ( !engine->Init( ) )\n {\n return 1;\n }\n\n int execute = engine->Execute( );\n context.reset( );\n return execute;\n}Fxied Component Register#include \"Core\\Context.h\"\n#include \"Core\\Engine.h\"\n#include \"Core\\World.h\"\n#include \"Core\\Entity.h\"\n#include \"Component\\CameraComponent.h\"\n#include \"Component\\MeshRenderComponent.h\"\n#include \"Component\\LightComponent.h\"\n#include \"Resource\\ResourceManager.h\"\n#include \"Resource\\Model.h\"\n#include \"Resource\\ModelLoader.h\"\n#include \"Resource\\Material.h\"\n#include \"Resource\\Texture2D.h\"\n\nusing namespace Mile;\n\nint main( )\n{\n auto context = std::make_unique( );\n auto engine = new Engine( context.get( ) );\n\n if ( !engine->Init( ) )\n {\n return 1;\n }\n\n auto world = context->GetSubSystem( );\n auto resMng = context->GetSubSystem( );\n\n auto camera = world->CreateEntity( TEXT( \"Camera\" ) );\n auto camComp = camera->AddComponent( );\n auto camTransform = camera->GetTransform( );\n camTransform->SetPosition( Vector3( 0.0f, 0.0f, -100.0f ) );\n\n \/\/ Camera setup\n\n auto light = world->CreateEntity( TEXT( \"DirectionalLight\" ) );\n auto lightComp = camera->AddComponent( );\n\n \/\/ Light setup\n\n auto model = resMng->Load( TEXT( \"Contents\/Models\/dragon.obj\" ) );\n auto modelEntity = Model::Instantiate( model, world );\n auto modelMeshRenderer = modelEntity->GetComponent( );\n auto mat = modelMeshRenderer->GetMaterial( );\n\n auto texture = resMng->Load( TEXT( \"Contents\/Textures\/test.png\" ) );\n mat->SetDiffuseMap( texture );\n\n \/\/ Model setup\n\n int execute = engine->Execute( );\n SafeDelete( engine );\n return execute;\n}<|endoftext|>"} {"text":"\/*************************************************************************\r\n* UrBackup - Client\/Server backup system\r\n* Copyright (C) 2011-2016 Martin Raiber\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see .\r\n**************************************************************************\/\r\n\r\n#include \"Interface\/Thread.h\"\r\n\r\n#include \"ThreadPool.h\"\r\n#include \"Server.h\"\r\n#include \"stringtools.h\"\r\n\r\nconst unsigned int max_waiting_threads=2;\r\n\r\nCPoolThread::CPoolThread(CThreadPool *pMgr)\r\n{\r\n\tmgr=pMgr;\r\n\tdexit=false;\r\n}\r\n\r\nvoid CPoolThread::operator()(void)\r\n{\r\n\tTHREAD_ID tid = Server->getThreadID();\r\n\tTHREADPOOL_TICKET ticket;\r\n\tbool stop=false;\r\n\tstd::string name;\r\n\tIThread *tr=mgr->getRunnable(&ticket, false, stop, name);\r\n\tif(tr!=NULL)\r\n\t{\r\n\t\tif (!name.empty())\r\n\t\t{\r\n\t\t\tServer->setCurrentThreadName(name);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tServer->setCurrentThreadName(\"unnamed\");\r\n\t\t}\r\n\t\t(*tr)();\r\n\t\tServer->clearDatabases(tid);\r\n\t}\r\n\r\n\tif(!stop)\r\n\t{\r\n\t\twhile(dexit==false)\r\n\t\t{\r\n\t\t\tstop=false;\r\n\t\t\tstd::string name;\r\n\t\t\tIThread *tr=mgr->getRunnable(&ticket, true, stop, name);\r\n\t\t\tif(tr!=NULL)\r\n\t\t\t{\r\n\t\t\t\tif (!name.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tServer->setCurrentThreadName(name);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tServer->setCurrentThreadName(\"unnamed\");\r\n\t\t\t\t}\r\n\t\t\t\t(*tr)();\r\n\t\t\t\tServer->clearDatabases(tid);\r\n\t\t\t}\r\n\t\t\telse if(stop)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tServer->destroyDatabases(tid);\r\n\tmgr->Remove(this);\r\n\tdelete this;\r\n}\r\n\r\nvoid CPoolThread::shutdown(void)\r\n{\r\n\tdexit=true;\r\n}\r\n\r\nIThread * CThreadPool::getRunnable(THREADPOOL_TICKET *todel, bool del, bool& stop, std::string& name)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\r\n\tif( del==true )\r\n\t{\r\n\t\t--nRunning;\r\n\t\tstd::map::iterator it=running.find(*todel);\r\n\t\tif( it!=running.end() )\r\n\t\t{\r\n\t\t\tif( it->second!=NULL )\r\n\t\t\t\tit->second->notify_all();\r\n\r\n\t\t\trunning.erase(it);\r\n\t\t}\r\n\t}\r\n\r\n\tIThread *ret=NULL;\r\n\twhile(ret==NULL && dexit==false)\r\n\t{\r\n\t\tif( toexecute.size()==0)\r\n\t\t{\r\n\t\t\tif(nThreads-nRunning>max_waiting_threads)\r\n\t\t\t{\r\n\t\t\t\tstop=true;\r\n\t\t\t\treturn NULL;\r\n\t\t\t}\r\n\t\t\tServer->setCurrentThreadName(\"idle pool thread\");\r\n\t\t\tcond->wait(&lock);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tret=toexecute[0].runnable;\r\n\t\t\t*todel=toexecute[0].ticket;\r\n\t\t\tname = toexecute[0].name;\r\n\t\t\ttoexecute.erase( toexecute.begin() );\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nvoid CThreadPool::Remove(CPoolThread *pt)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tfor(size_t i=0;icreateMutex();\r\n\tcond=Server->createCondition();\r\n}\r\n\r\nCThreadPool::~CThreadPool()\r\n{\t\r\n\tdelete mutex;\r\n\tdelete cond;\r\n}\r\n\r\nvoid CThreadPool::Shutdown(void)\r\n{\r\n\tbool do_leak_check=(Server->getServerParameter(\"leak_check\")==\"true\");\r\n\tIScopedLock lock(mutex);\r\n\tfor(size_t i=0;ishutdown();\r\n\t}\r\n\tdexit=true;\r\n\r\n\tunsigned int max=0;\r\n\twhile(threads.size()>0 )\r\n\t{\r\n\t\tlock.relock(NULL);\r\n\t\tcond->notify_all();\r\n\t\tServer->wait(100);\r\n\t\tlock.relock(mutex);\r\n\r\n\t\t\/\/wait for max 300 msec\r\n\t\tif( (!do_leak_check && max>=3) || (do_leak_check && max>=30) )\r\n\t\t{\r\n\t\t\tServer->Log(\"Maximum wait time for thread pool exceeded. Shutting down the hard way\", LL_ERROR);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t++max;\r\n\t}\r\n}\r\n\r\nbool CThreadPool::isRunningInt(THREADPOOL_TICKET ticket)\r\n{\r\n\tstd::map::iterator it=running.find(ticket);\r\n\tif( it!=running.end() )\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n}\r\n\r\nbool CThreadPool::isRunning(THREADPOOL_TICKET ticket)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\treturn isRunningInt(ticket);\r\n}\r\n\r\nbool CThreadPool::waitFor(std::vector tickets, int timems)\r\n{\r\n\tint64 starttime;\r\n\tif(timems>=0)\r\n\t{\r\n\t\tstarttime = Server->getTimeMS();\r\n\t}\r\n\r\n\tIScopedLock lock(mutex);\r\n\tICondition *cond=Server->createCondition();\r\n\r\n\tfor( size_t i=0;i::iterator it=running.find(tickets[i]);\r\n\t\tif( it!=running.end() )\r\n\t\t{\r\n\t\t\tit->second=cond;\r\n\t\t}\r\n\t}\r\n\r\n\tbool ret=false;\r\n\r\n\twhile(true)\r\n\t{\r\n\t\tbool r=false;\r\n\t\tfor(size_t i=0;iwait(&lock, timems);\r\n\r\n\t\tif(timems>=0)\r\n\t\t{\r\n\t\t\tint64 ctime = Server->getTimeMS();\r\n\t\t\tif(ctime-starttime>timems)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tfor( size_t i=0;i::iterator it=running.find(tickets[i]);\r\n\t\tif( it!=running.end() )\r\n\t\t{\r\n\t\t\tif(it->second==cond)\r\n\t\t\t{\r\n\t\t\t\tit->second=NULL;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tServer->destroy(cond);\r\n\r\n\treturn ret;\r\n}\r\n\r\nTHREADPOOL_TICKET CThreadPool::execute(IThread *runnable, const std::string& name)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tif( nThreads-nRunning==0 )\r\n\t{\r\n\t\tCPoolThread *nt=new CPoolThread(this);\r\n\t\tServer->createThread(nt);\r\n\t\t++nThreads;\r\n\t\tthreads.push_back(nt);\r\n\t}\r\n\r\n\ttoexecute.push_back(SNewTask(runnable, ++currticket, name));\r\n\trunning.insert(std::pair(currticket, (ICondition*)NULL) );\r\n\t++nRunning;\r\n\tcond->notify_one();\r\n\treturn currticket;\r\n}\r\n\r\nvoid CThreadPool::executeWait(IThread *runnable, const std::string& name)\r\n{\r\n\tTHREADPOOL_TICKET ticket=execute(runnable, name);\r\n\twaitFor(ticket);\r\n}\r\n\r\nbool CThreadPool::waitFor(THREADPOOL_TICKET ticket, int timems)\r\n{\r\n\tstd::vector t;\r\n\tt.push_back(ticket);\r\n\treturn waitFor(t, timems);\r\n}\r\n\r\nCheck waitFor timeout before condition wait\/*************************************************************************\r\n* UrBackup - Client\/Server backup system\r\n* Copyright (C) 2011-2016 Martin Raiber\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see .\r\n**************************************************************************\/\r\n\r\n#include \"Interface\/Thread.h\"\r\n\r\n#include \"ThreadPool.h\"\r\n#include \"Server.h\"\r\n#include \"stringtools.h\"\r\n\r\nconst unsigned int max_waiting_threads=2;\r\n\r\nCPoolThread::CPoolThread(CThreadPool *pMgr)\r\n{\r\n\tmgr=pMgr;\r\n\tdexit=false;\r\n}\r\n\r\nvoid CPoolThread::operator()(void)\r\n{\r\n\tTHREAD_ID tid = Server->getThreadID();\r\n\tTHREADPOOL_TICKET ticket;\r\n\tbool stop=false;\r\n\tstd::string name;\r\n\tIThread *tr=mgr->getRunnable(&ticket, false, stop, name);\r\n\tif(tr!=NULL)\r\n\t{\r\n\t\tif (!name.empty())\r\n\t\t{\r\n\t\t\tServer->setCurrentThreadName(name);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tServer->setCurrentThreadName(\"unnamed\");\r\n\t\t}\r\n\t\t(*tr)();\r\n\t\tServer->clearDatabases(tid);\r\n\t}\r\n\r\n\tif(!stop)\r\n\t{\r\n\t\twhile(dexit==false)\r\n\t\t{\r\n\t\t\tstop=false;\r\n\t\t\tstd::string name;\r\n\t\t\tIThread *tr=mgr->getRunnable(&ticket, true, stop, name);\r\n\t\t\tif(tr!=NULL)\r\n\t\t\t{\r\n\t\t\t\tif (!name.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\tServer->setCurrentThreadName(name);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tServer->setCurrentThreadName(\"unnamed\");\r\n\t\t\t\t}\r\n\t\t\t\t(*tr)();\r\n\t\t\t\tServer->clearDatabases(tid);\r\n\t\t\t}\r\n\t\t\telse if(stop)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tServer->destroyDatabases(tid);\r\n\tmgr->Remove(this);\r\n\tdelete this;\r\n}\r\n\r\nvoid CPoolThread::shutdown(void)\r\n{\r\n\tdexit=true;\r\n}\r\n\r\nIThread * CThreadPool::getRunnable(THREADPOOL_TICKET *todel, bool del, bool& stop, std::string& name)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\r\n\tif( del==true )\r\n\t{\r\n\t\t--nRunning;\r\n\t\tstd::map::iterator it=running.find(*todel);\r\n\t\tif( it!=running.end() )\r\n\t\t{\r\n\t\t\tif( it->second!=NULL )\r\n\t\t\t\tit->second->notify_all();\r\n\r\n\t\t\trunning.erase(it);\r\n\t\t}\r\n\t}\r\n\r\n\tIThread *ret=NULL;\r\n\twhile(ret==NULL && dexit==false)\r\n\t{\r\n\t\tif( toexecute.size()==0)\r\n\t\t{\r\n\t\t\tif(nThreads-nRunning>max_waiting_threads)\r\n\t\t\t{\r\n\t\t\t\tstop=true;\r\n\t\t\t\treturn NULL;\r\n\t\t\t}\r\n\t\t\tServer->setCurrentThreadName(\"idle pool thread\");\r\n\t\t\tcond->wait(&lock);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tret=toexecute[0].runnable;\r\n\t\t\t*todel=toexecute[0].ticket;\r\n\t\t\tname = toexecute[0].name;\r\n\t\t\ttoexecute.erase( toexecute.begin() );\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nvoid CThreadPool::Remove(CPoolThread *pt)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tfor(size_t i=0;icreateMutex();\r\n\tcond=Server->createCondition();\r\n}\r\n\r\nCThreadPool::~CThreadPool()\r\n{\t\r\n\tdelete mutex;\r\n\tdelete cond;\r\n}\r\n\r\nvoid CThreadPool::Shutdown(void)\r\n{\r\n\tbool do_leak_check=(Server->getServerParameter(\"leak_check\")==\"true\");\r\n\tIScopedLock lock(mutex);\r\n\tfor(size_t i=0;ishutdown();\r\n\t}\r\n\tdexit=true;\r\n\r\n\tunsigned int max=0;\r\n\twhile(threads.size()>0 )\r\n\t{\r\n\t\tlock.relock(NULL);\r\n\t\tcond->notify_all();\r\n\t\tServer->wait(100);\r\n\t\tlock.relock(mutex);\r\n\r\n\t\t\/\/wait for max 300 msec\r\n\t\tif( (!do_leak_check && max>=3) || (do_leak_check && max>=30) )\r\n\t\t{\r\n\t\t\tServer->Log(\"Maximum wait time for thread pool exceeded. Shutting down the hard way\", LL_ERROR);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t++max;\r\n\t}\r\n}\r\n\r\nbool CThreadPool::isRunningInt(THREADPOOL_TICKET ticket)\r\n{\r\n\tstd::map::iterator it=running.find(ticket);\r\n\tif( it!=running.end() )\r\n\t\treturn true;\r\n\telse\r\n\t\treturn false;\r\n}\r\n\r\nbool CThreadPool::isRunning(THREADPOOL_TICKET ticket)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\treturn isRunningInt(ticket);\r\n}\r\n\r\nbool CThreadPool::waitFor(std::vector tickets, int timems)\r\n{\r\n\tint64 starttime;\r\n\tif(timems>=0)\r\n\t{\r\n\t\tstarttime = Server->getTimeMS();\r\n\t}\r\n\r\n\tIScopedLock lock(mutex);\r\n\tICondition *cond=Server->createCondition();\r\n\r\n\tfor( size_t i=0;i::iterator it=running.find(tickets[i]);\r\n\t\tif( it!=running.end() )\r\n\t\t{\r\n\t\t\tit->second=cond;\r\n\t\t}\r\n\t}\r\n\r\n\tbool ret=false;\r\n\r\n\twhile(true)\r\n\t{\r\n\t\tbool r=false;\r\n\t\tfor(size_t i=0;i= 0)\r\n\t\t{\r\n\t\t\tint64 ctime = Server->getTimeMS();\r\n\t\t\tif (ctime - starttime>=timems)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tcond->wait(&lock, timems);\r\n\t}\r\n\r\n\tfor( size_t i=0;i::iterator it=running.find(tickets[i]);\r\n\t\tif( it!=running.end() )\r\n\t\t{\r\n\t\t\tif(it->second==cond)\r\n\t\t\t{\r\n\t\t\t\tit->second=NULL;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tServer->destroy(cond);\r\n\r\n\treturn ret;\r\n}\r\n\r\nTHREADPOOL_TICKET CThreadPool::execute(IThread *runnable, const std::string& name)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tif( nThreads-nRunning==0 )\r\n\t{\r\n\t\tCPoolThread *nt=new CPoolThread(this);\r\n\t\tServer->createThread(nt);\r\n\t\t++nThreads;\r\n\t\tthreads.push_back(nt);\r\n\t}\r\n\r\n\ttoexecute.push_back(SNewTask(runnable, ++currticket, name));\r\n\trunning.insert(std::pair(currticket, (ICondition*)NULL) );\r\n\t++nRunning;\r\n\tcond->notify_one();\r\n\treturn currticket;\r\n}\r\n\r\nvoid CThreadPool::executeWait(IThread *runnable, const std::string& name)\r\n{\r\n\tTHREADPOOL_TICKET ticket=execute(runnable, name);\r\n\twaitFor(ticket);\r\n}\r\n\r\nbool CThreadPool::waitFor(THREADPOOL_TICKET ticket, int timems)\r\n{\r\n\tstd::vector t;\r\n\tt.push_back(ticket);\r\n\treturn waitFor(t, timems);\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/**\n * Appcelerator Titanium Mobile\n * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.\n * Licensed under the terms of the Apache Public License\n * Please see the LICENSE included with this distribution for details.\n *\/\n\n#include \"TiUIPicker.h\"\n#include \"TiGenericFunctionObject.h\"\n\nTiUIPicker::TiUIPicker(NativeObjectFactory* nativeObjectFactory)\n : TiUIBase(nativeObjectFactory, \"\")\n{\n}\n\nTiUIPicker::~TiUIPicker()\n{\n}\n\nTiUIPicker* TiUIPicker::createPicker(NativeObjectFactory* nativeObjectFactory)\n{\n TiUIPicker* obj = new TiUIPicker(nativeObjectFactory);\n obj->initializeTiObject(NULL);\n return obj;\n}\n\nvoid TiUIPicker::initializeTiObject(TiObject* parentContext)\n{\n if (!isInitialized())\n {\n TiUIBase::initializeTiObject(parentContext);\n \/\/currently cascades only supports date\/time picker that is why we should create native DateTimePicker object here\n NativeObject* obj = getNativeObjectFactory()->createNativeObject(N_TYPE_DATE_TIME_PICKER);\n setNativeObject(obj);\n obj->release();\n }\n}\n\nvoid TiUIPicker::onCreateStaticMembers()\n{\n TiUIBase::onCreateStaticMembers();\n}\nTIMOB-9876: BlackBerry: Fix build failure Reviewers: JP, David L\/**\n * Appcelerator Titanium Mobile\n * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved.\n * Licensed under the terms of the Apache Public License\n * Please see the LICENSE included with this distribution for details.\n *\/\n\n#include \"TiUIPicker.h\"\n#include \"TiGenericFunctionObject.h\"\n\nTiUIPicker::TiUIPicker(NativeObjectFactory* nativeObjectFactory)\n : TiUIBase(\"\")\n{\n}\n\nTiUIPicker::~TiUIPicker()\n{\n}\n\nTiUIPicker* TiUIPicker::createPicker(NativeObjectFactory* nativeObjectFactory)\n{\n TiUIPicker* obj = new TiUIPicker(nativeObjectFactory);\n obj->initializeTiObject(NULL);\n return obj;\n}\n\nvoid TiUIPicker::initializeTiObject(TiObject* parentContext)\n{\n if (!isInitialized())\n {\n TiUIBase::initializeTiObject(parentContext);\n \/\/currently cascades only supports date\/time picker that is why we should create native DateTimePicker object here\n NativeObject* obj = getNativeObjectFactory()->createNativeObject(N_TYPE_DATE_TIME_PICKER);\n setNativeObject(obj);\n obj->release();\n }\n}\n\nvoid TiUIPicker::onCreateStaticMembers()\n{\n TiUIBase::onCreateStaticMembers();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"camera.hpp\"\n\n#pragma comment(lib,\"opencv_world320.lib\")\n\nstatic const int N = 256;\/\/文字列の長さ\nstatic const int AOV = 62.2;\/\/ANGLE OF VIEW\n\/\/明度について\nstatic const int MAX_VALUE = 255;\/\/明るさ最大\nstatic const int NO_VALUE = 0;\/\/明るさ最小\n\n\n\/\/時間を元にStringを作る\nchar* makeTimeString(void)\n{\n\tstatic char timeString[N];\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(timeString, N, \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\treturn timeString;\n}\n\nchar* makeBinaryString(char *timeString)\n{\n\tstatic char binaryString[N];\n\tsprintf(binaryString, \"%s%s\",timeString,\"Binary\");\n\treturn binaryString;\n}\n\n\/\/full_pathを作る\nchar* makePath(char* name)\n{\n\tstatic char full_path[N];\/\/NOTE 自動変数をreturn するために使った. smartなやり方か?\n\tchar directry_path[] = \"\/home\/pi\/Pictures\/\";\/\/pathの先頭\n\tchar file_extention[] = \".jpg\";\/\/拡張子\n\tsprintf(full_path, \"%s%s%s\",directry_path,name,file_extention);\n\treturn full_path;\n}\n\/\/写真をとる\nint takePhoto(char* name)\n{\n\tchar full_command[N];\n\tchar front_command[] = \"raspistill -o \";\/\/command\n\tsprintf(full_command, \"%s%s\", front_command,name);\/\/コマンドの文字列をつなげる。\n\tsystem(full_command);\/\/raspistillで静止画を撮って日時を含むファイル名で保存。\n\tprintf(\"%s\\n\",full_command);\n\t\/\/NOTE system関数以外を使うべきか?\n\treturn 0;\n}\n\n\/\/二値化画像を作成\ncv::Mat binarize(cv::Mat src)\n{\n\tcv::Mat hsv;\n\tcv::Mat hsv_filtered15 ;\/\/画像の初期化\n\tcv::Mat hsv_filtered180;\/\/画像の初期化\n\tcv::cvtColor(src, hsv, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(dst)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);\n\tcv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);\n\tcv::add(hsv_filtered15,hsv_filtered180,hsv);\n\treturn hsv;\n}\n\/\/ノイズ除去\ncv::Mat rmNoize(cv::Mat src)\n{\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);\/\/縮小処理\n\tcv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);\/\/膨張処理\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);\/\/縮小処理\n\treturn src;\n}\n\nint saveBinary(cv::Mat src,char* path)\n{\n\tcv::Mat binary_img;\n\tcv::resize(src,binary_img,cv::Size(),0.25,0.25);\n\treturn 0;\n}\n\n\/\/写真を撮り画像処理する\ncv::Mat Mred(void)\n{\n\tchar* stime = makeTimeString();\n\tprintf(\"%s\\n\",stime);\n\tchar* sbtime = makeBinaryString(stime);\n\tprintf(\"%s\\n\",sbtime);\n\tchar* path = makePath(stime);\n\tprintf(\"%s\\n\",path);\n\ttakePhoto(path);\n\tchar* bpath = makePath(sbtime);\n\tprintf(\"%s\\n\",path);\n \tcv::Mat src = cv::imread(path);\/\/画像の読み込み\n\tcv::Mat hsv;\n\thsv = rmNoize(binarize(src));\n\tsaveBinary(hsv,bpath);\n\treturn hsv;\n}\n\n\n\/\/二値化した画像から1の面積を抽出\ndouble countArea(cv::Mat src)\n{\n\n\tdouble Area = src.rows*src.cols;\/\/全ピクセル数\n\tdouble redCount = 0; \/\/赤色を認識したピクセルの数\n\tredCount = cv::countNonZero(src);\/\/赤色部分の面積を計算\n\tdouble percentage = 0; \/\/割合\n\tpercentage = (redCount \/ Area)*100;\/\/割合を計算\n\tprintf(\"面積のPercentageは%f\\n\", percentage);\n\treturn percentage;\n}\n\n\/\/二値化画像のcenterを角度で返す\ndouble getCenter(cv::Mat src)\n{\n\tcv::Moments mu = cv::moments(src, false);\/\/重心の計算結果をmuに代入\n\tdouble mc = mu.m10 \/ mu.m00;\/\/重心のx座標\n\tdouble center = (mc - src.cols \/ 2) * AOV \/ src.cols;\/\/正規化\n\tprintf(\"重心の位置は%f\\n\",center);\n\treturn center;\n}\ndbeug#include \n#include \n#include \n#include \n#include \n#include \"camera.hpp\"\n\n#pragma comment(lib,\"opencv_world320.lib\")\n\nstatic const int N = 256;\/\/文字列の長さ\nstatic const int AOV = 62.2;\/\/ANGLE OF VIEW\n\/\/明度について\nstatic const int MAX_VALUE = 255;\/\/明るさ最大\nstatic const int NO_VALUE = 0;\/\/明るさ最小\n\n\n\/\/時間を元にStringを作る\nchar* makeTimeString(void)\n{\n\tstatic char timeString[N];\n\ttime_t timer;\/\/時刻を受け取る変数\n\tstruct tm *timeptr;\/\/日時を集めた構造体ポインタ\n\ttime(&timer);\/\/現在時刻の取得\n\ttimeptr = localtime(&timer);\/\/ポインタ\n\tstrftime(timeString, N, \"%Y%m%d-%H%M%S\", timeptr);\/\/日時を文字列に変換してsに代入\n\treturn timeString;\n}\n\nchar* makeBinaryString(char *timeString)\n{\n\tstatic char binaryString[N];\n\tsprintf(binaryString, \"%s%s\",timeString,\"Binary\");\n\treturn binaryString;\n}\n\n\/\/full_pathを作る\nchar* makePath(char* name)\n{\n\tstatic char full_path[N];\/\/NOTE 自動変数をreturn するために使った. smartなやり方か?\n\tchar directry_path[] = \"\/home\/pi\/Pictures\/\";\/\/pathの先頭\n\tchar file_extention[] = \".jpg\";\/\/拡張子\n\tsprintf(full_path, \"%s%s%s\",directry_path,name,file_extention);\n\treturn full_path;\n}\n\/\/写真をとる\nint takePhoto(char* name)\n{\n\tchar full_command[N];\n\tchar front_command[] = \"raspistill -o \";\/\/command\n\tsprintf(full_command, \"%s%s\", front_command,name);\/\/コマンドの文字列をつなげる。\n\tsystem(full_command);\/\/raspistillで静止画を撮って日時を含むファイル名で保存。\n\tprintf(\"%s\\n\",full_command);\n\t\/\/NOTE system関数以外を使うべきか?\n\treturn 0;\n}\n\n\/\/二値化画像を作成\ncv::Mat binarize(cv::Mat src)\n{\n\tcv::Mat hsv;\n\tcv::Mat hsv_filtered15 ;\/\/画像の初期化\n\tcv::Mat hsv_filtered180;\/\/画像の初期化\n\tcv::cvtColor(src, hsv, CV_BGR2HSV);\/\/入力画像(src)をhsv色空間(dst)に変換\n\t\/\/inRange(入力画像,下界画像,上界画像,出力画像)\n\t\/\/「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)\n\tcv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);\n\tcv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);\n\tcv::add(hsv_filtered15,hsv_filtered180,hsv);\n\treturn hsv;\n}\n\/\/ノイズ除去\ncv::Mat rmNoize(cv::Mat src)\n{\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);\/\/縮小処理\n\tcv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);\/\/膨張処理\n\tcv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);\/\/縮小処理\n\treturn src;\n}\n\nint saveBinary(cv::Mat src,char* path)\n{\n\tcv::Mat binary_img;\n\tcv::resize(src,binary_img,cv::Size(),0.25,0.25);\n\treturn 0;\n}\n\n\/\/写真を撮り画像処理する\ncv::Mat Mred(void)\n{\n\tchar* stime = makeTimeString();\n\tprintf(\"%s\\n\",stime);\n\tchar* sbtime = makeBinaryString(stime);\n\tprintf(\"%s\\n\",sbtime);\n\tconst char* path = makePath(stime);\n\tprintf(\"%s\\n\",path);\n\ttakePhoto(path);\n\tchar* bpath = makePath(sbtime);\n\tprintf(\"%s\\n\",path);\n \tcv::Mat src = cv::imread(path);\/\/画像の読み込み\n\tcv::Mat hsv;\n\thsv = rmNoize(binarize(src));\n\tsaveBinary(hsv,bpath);\n\treturn hsv;\n}\n\n\n\/\/二値化した画像から1の面積を抽出\ndouble countArea(cv::Mat src)\n{\n\n\tdouble Area = src.rows*src.cols;\/\/全ピクセル数\n\tdouble redCount = 0; \/\/赤色を認識したピクセルの数\n\tredCount = cv::countNonZero(src);\/\/赤色部分の面積を計算\n\tdouble percentage = 0; \/\/割合\n\tpercentage = (redCount \/ Area)*100;\/\/割合を計算\n\tprintf(\"面積のPercentageは%f\\n\", percentage);\n\treturn percentage;\n}\n\n\/\/二値化画像のcenterを角度で返す\ndouble getCenter(cv::Mat src)\n{\n\tcv::Moments mu = cv::moments(src, false);\/\/重心の計算結果をmuに代入\n\tdouble mc = mu.m10 \/ mu.m00;\/\/重心のx座標\n\tdouble center = (mc - src.cols \/ 2) * AOV \/ src.cols;\/\/正規化\n\tprintf(\"重心の位置は%f\\n\",center);\n\treturn center;\n}\n<|endoftext|>"} {"text":"#ifndef TSA_VU8_DETAIL_FROM_V8_HPP\n#define TSA_VU8_DETAIL_FROM_V8_HPP\n\n#include \n\n#include \n\n#include \n#include \n#include \n\nnamespace vu8 { namespace detail {\n\ntypedef v8::Handle ValueHandle;\n\ntemplate \nstruct FromV8;\n\ntemplate <>\nstruct FromV8 {\n static inline std::string exec(ValueHandle value) {\n if (! value->IsString())\n throw std::runtime_error(\"cannot make string from non-string type\");\n\n v8::String::Utf8Value str(value);\n return *str;\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline ConvertibleString exec(ValueHandle value) {\n if (! value->IsString())\n throw std::runtime_error(\"cannot make string from non-string type\");\n\n v8::String::Utf8Value str(value);\n return *str;\n }\n};\n\ntemplate <>\nstruct FromV8< v8::Handle > {\n static inline v8::Handle exec(ValueHandle value) {\n if (! value->IsFunction())\n throw std::runtime_error(\"expected javascript function\");\n\n return value.As();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline int32_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToInt32()->Value();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline uint32_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToUint32()->Value();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline int64_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToNumber()->Value();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline uint64_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToNumber()->Value();\n }\n};\n\n\ntemplate \nstruct FromV8< std::vector > {\n static inline std::vector exec(ValueHandle value) {\n if (! value->IsArray())\n throw std::runtime_error(\"expected javascript array\");\n\n v8::Array *array = v8::Array::Cast(*value);\n std::vector result;\n for (uint32_t i = 0; i < array->Length(); ++i) {\n v8::Local obj = array->Get(i);\n result.push_back(FromV8::exec(obj));\n }\n return result;\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline ValueHandle exec(ValueHandle value) {\n return value;\n }\n};\n\n} }\n#endif\ncan extract object pointers from v8 handles now#ifndef TSA_VU8_DETAIL_FROM_V8_HPP\n#define TSA_VU8_DETAIL_FROM_V8_HPP\n\n#include \n\n#include \n\n#include \n#include \n#include \n\nnamespace vu8 { namespace detail {\n\ntypedef v8::Handle ValueHandle;\n\ntemplate \nstruct FromV8;\n\ntemplate <>\nstruct FromV8 {\n static inline std::string exec(ValueHandle value) {\n if (! value->IsString())\n throw std::runtime_error(\"cannot make string from non-string type\");\n\n v8::String::Utf8Value str(value);\n return *str;\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline ConvertibleString exec(ValueHandle value) {\n if (! value->IsString())\n throw std::runtime_error(\"cannot make string from non-string type\");\n\n v8::String::Utf8Value str(value);\n return *str;\n }\n};\n\ntemplate <>\nstruct FromV8< v8::Handle > {\n static inline v8::Handle exec(ValueHandle value) {\n if (! value->IsFunction())\n throw std::runtime_error(\"expected javascript function\");\n\n return value.As();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline int32_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToInt32()->Value();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline uint32_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToUint32()->Value();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline int64_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToNumber()->Value();\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline uint64_t exec(ValueHandle value) {\n if (! value->IsNumber())\n throw std::runtime_error(\"expected javascript number\");\n\n return value->ToNumber()->Value();\n }\n};\n\n\ntemplate \nstruct FromV8< std::vector > {\n static inline std::vector exec(ValueHandle value) {\n if (! value->IsArray())\n throw std::runtime_error(\"expected javascript array\");\n\n v8::Array *array = v8::Array::Cast(*value);\n std::vector result;\n for (uint32_t i = 0; i < array->Length(); ++i) {\n v8::Local obj = array->Get(i);\n result.push_back(FromV8::exec(obj));\n }\n return result;\n }\n};\n\ntemplate <>\nstruct FromV8 {\n static inline ValueHandle exec(ValueHandle value) {\n return value;\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ extracting classes\ntemplate \nstruct FromV8Ptr {\n static inline T exec(ValueHandle value) {\n if (! value->IsObject())\n throw std::runtime_error(\"expected object\");\n\n v8::Local obj = value->ToObject();\n\n if (! obj->InternalFieldCount())\n throw std::runtime_error(\"expected c++ wrapped object\");\n\n return static_cast(obj->GetPointerFromInternalField(0));\n }\n};\n\ntemplate \nstruct FromV8 : FromV8Ptr {};\n\ntemplate \nstruct FromV8 : FromV8Ptr {};\n\n\n} }\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nany\/nany.h\"\n#include \n#include \n#include \n#include \n\nusing namespace Yuni;\n\n\nnamespace {\n\n\nstruct {\n\t\/\/! List of filenames to verify\n\tstd::vector filenames;\n\t\/\/ no colors\n\tbool noColors = false;\n\t\/\/ Result expected from filename convention\n\tbool useFilenameConvention = false;\n}\nsettings;\n\n\ntemplate\nstruct ParseVerbosity : public LeftType {\n\ttemplate\n\tvoid internalDecoratorAddPrefix(O& out, const AnyString& s) const {\n\t\t\/\/ Write the verbosity to the output\n\t\tif (VerbosityType::hasName) {\n\t\t\tAnyString name{VerbosityType::Name()};\n\t\t\tif (s.empty()) {\n\t\t\t}\n\t\t\telse if (name == \"info\") {\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\t#ifndef YUNI_OS_WINDOWS\n\t\t\t\tout << \" \\u2713 \";\n\t\t\t\t#else\n\t\t\t\tout << \" > \";\n\t\t\t\t#endif\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \"parsing\";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t\telse if (name == \"error\") {\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \" FAILED \";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \"parsing\";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t\telse if (name == \"warning\") {\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \" {warn} \";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \"parsing\";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ Set Color\n\t\t\t\tif (Handler::colorsAllowed && VerbosityType::color != System::Console::none)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\t\/\/ The verbosity\n\t\t\t\tVerbosityType::AppendName(out);\n\t\t\t\t\/\/ Reset Color\n\t\t\t\tif (Handler::colorsAllowed && VerbosityType::color != System::Console::none)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t}\n\t\t\/\/ Transmit the message to the next decorator\n\t\tLeftType::template internalDecoratorAddPrefix(out, s);\n\t}\n}; \/\/ struct VerbosityLevel\n\n\nusing Logging = Logs::Logger, ParseVerbosity>>;\nstatic Logging logs;\n\n\nuint32_t fincCommonFolderLength(const std::vector& filenames) {\n\tif (filenames.empty())\n\t\treturn 0;\n\tauto& firstElement = filenames[0];\n\tconst char sep = IO::Separator;\n\tuint32_t pos = 0;\n\tfor (; ; ++pos) {\n\t\tfor (size_t i = 0; i < filenames.size(); ++i) {\n\t\t\tauto& str = filenames[i];\n\t\t\tif (pos == firstElement.size())\n\t\t\t\treturn pos;\n\t\t\tif (pos < str.size() and str[pos] != '\\0' and str[pos] == firstElement[pos])\n\t\t\t\tcontinue;\n\t\t\t\/\/ back to the last sep\n\t\t\twhile (pos > 0 && firstElement[--pos] != sep) {\n\t\t\t}\n\t\t\treturn pos;\n\t\t}\n\t}\n\treturn pos;\n}\n\nbool expandFilelist(std::vector& list) {\n\tstd::vector filelist;\n\tfilelist.reserve(512);\n\tString currentfile;\n\tcurrentfile.reserve(4096);\n\tfor (auto& element: list) {\n\t\tIO::Canonicalize(currentfile, element);\n\t\tswitch (IO::TypeOf(currentfile)) {\n\t\t\tcase IO::typeFile: {\n\t\t\t\tfilelist.emplace_back(currentfile);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase IO::typeFolder: {\n\t\t\t\tShortString16 ext;\n\t\t\t\tIO::Directory::Info info(currentfile);\n\t\t\t\tauto end = info.recursive_file_end();\n\t\t\t\tfor (auto i = info.recursive_file_begin(); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tIO::ExtractExtension(ext, *i);\n\t\t\t\t\tif (ext == \".ny\")\n\t\t\t\t\t\tfilelist.emplace_back(i.filename());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tlogs.error() << \"impossible to find '\" << currentfile << \"'\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ for beauty in singled-threaded (and to always produce the same output)\n\tstd::sort(filelist.begin(), filelist.end());\n\tlist.swap(filelist);\n\treturn true;\n}\n\ntemplate\nbool IterateThroughAllFiles(const std::vector& filenames, const F& callback) {\n\tString currentfile;\n\tuint32_t testOK = 0;\n\tuint32_t testFAILED = 0;\n\tint64_t maxCheckDuration = 0;\n\tint64_t startTime = DateTime::NowMilliSeconds();\n\tfor (auto& filename: filenames) {\n\t\tint64_t duration = 0;\n\t\tif (callback(filename, duration))\n\t\t\t++testOK;\n\t\telse\n\t\t\t++testFAILED;\n\t\tif (duration > maxCheckDuration)\n\t\t\tmaxCheckDuration = duration;\n\t}\n\tint64_t endTime = DateTime::NowMilliSeconds();\n\tuint32_t total = testOK + testFAILED;\n\tif (total > 0) {\n\t\tint64_t duration = (endTime - startTime);\n\t\tString durationStr;\n\t\tdurationStr << \" (in \" << duration << \"ms, max: \" << maxCheckDuration << \"ms)\";\n\t\tif (total > 1) {\n\t\t\tif (0 != testFAILED) {\n\t\t\t\tswitch (total) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tlogs.warning() << \"-- FAILED -- 1 file, +\" << testOK << \", -\" << testFAILED << durationStr;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlogs.warning() << \"-- FAILED -- \" << total << \" files, +\" << testOK << \", -\" << testFAILED << durationStr;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tswitch (total) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tlogs.info() << \"success: 1 file, +\" << testOK << \", -0\" << durationStr;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlogs.info() << \"success: \" << total << \" files, +\" << testOK << \", -0\" << durationStr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tlogs.warning() << \"no input file\";\n\treturn (0 == testFAILED);\n}\n\nbool batchCheckIfFilenamesConformToGrammar(std::vector& filenames) {\n\tif (not expandFilelist(filenames))\n\t\treturn false;\n\tauto commonFolder = (filenames.size() > 1 ? fincCommonFolderLength(filenames) : 0);\n\tif (0 != commonFolder)\n\t\t++commonFolder;\n\treturn IterateThroughAllFiles(filenames, [&](const AnyString& file, int64_t& duration) -> bool {\n\t\tString barefile;\n\t\tIO::ExtractFileName(barefile, file);\n\t\tbool expected = true;\n\t\tbool canfail = false;\n\t\tif (settings.useFilenameConvention)\n\t\t{\n\t\t\tif (barefile.startsWith(\"ko-\"))\n\t\t\t\texpected = false;\n\t\t\tif (barefile.find(\"-canfail-\") < barefile.size())\n\t\t\t\tcanfail = true;\n\t\t}\n\t\t\/\/ PARSE\n\t\tint64_t start = DateTime::NowMilliSeconds();\n\t\tbool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size()));\n\t\tduration = DateTime::NowMilliSeconds() - start;\n\t\tsuccess = (success == expected);\n\t\tif (success and duration < 300) {\n\t\t\tlogs.info() << AnyString{file, commonFolder} << \" [\" << duration << \"ms]\";\n\t\t}\n\t\telse {\n\t\t\tif (not success) {\n\t\t\t\tif (not canfail)\n\t\t\t\t\tlogs.error() << AnyString{file, commonFolder} << \" [\" << duration << \"ms]\";\n\t\t\t\telse\n\t\t\t\t\tlogs.warning() << AnyString{file, commonFolder} << \" [\" << duration << \"ms, can fail]\";\n\t\t\t}\n\t\t\telse\n\t\t\t\tlogs.error() << AnyString{file, commonFolder} << \" [\" << duration << \"ms - time limit reached]\";\n\t\t\tsuccess = canfail;\n\t\t}\n\t\treturn success;\n\t});\n}\n\n\n} \/\/ namespace\n\n\nint main(int argc, char** argv)\n{\n\t\/\/ parse the command\n\t{\n\t\t\/\/ The command line options parser\n\t\tGetOpt::Parser options;\n\t\t\/\/ Input files\n\t\toptions.add(settings.filenames, 'i', \"input\", \"Input files (or folders)\");\n\t\toptions.remainingArguments(settings.filenames);\n\t\t\/\/ --no-color\n\t\toptions.addFlag(settings.noColors, ' ', \"no-color\", \"Disable color output\");\n\t\t\/\/ use filename convention\n\t\toptions.addFlag(settings.useFilenameConvention, ' ', \"use-filename-convention\",\n\t\t\t\"Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'\");\n\t\t\/\/ version\n\t\tbool optVersion = false;\n\t\toptions.addFlag(optVersion, ' ', \"version\", \"Display the version of the compiler and exit\");\n\t\t\/\/ Ask to the parser to parse the command line\n\t\tif (not options(argc, argv)) {\n\t\t\t\/\/ The program should not continue here\n\t\t\t\/\/ The user may have requested the help or an error has happened\n\t\t\t\/\/ If an error has happened, the exit status should be different from 0\n\t\t\tif (options.errors()) {\n\t\t\t\tstd::cerr << \"Abort due to error\\n\";\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\n\t\tif (optVersion) {\n\t\t\tstd::cout << \"0.0\\n\";\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\t\tif (settings.filenames.empty()) {\n\t\t\tstd::cerr << argv[0] << \": no input file\\n\";\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\t\/\/ Print AST or check for Nany Grammar\n\tbool success = batchCheckIfFilenamesConformToGrammar(settings.filenames);\n\treturn success ? EXIT_SUCCESS : EXIT_FAILURE;\n}\ncheck-syntax: remove global variable 'settings'#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"nany\/nany.h\"\n#include \n#include \n#include \n#include \n\nusing namespace Yuni;\n\n\nnamespace {\n\n\nstruct Settings {\n\t\/\/! List of filenames to verify\n\tstd::vector filenames;\n\t\/\/ no colors\n\tbool noColors = false;\n\t\/\/ Result expected from filename convention\n\tbool useFilenameConvention = false;\n};\n\n\ntemplate\nstruct ParseVerbosity : public LeftType {\n\ttemplate\n\tvoid internalDecoratorAddPrefix(O& out, const AnyString& s) const {\n\t\t\/\/ Write the verbosity to the output\n\t\tif (VerbosityType::hasName) {\n\t\t\tAnyString name{VerbosityType::Name()};\n\t\t\tif (s.empty()) {\n\t\t\t}\n\t\t\telse if (name == \"info\") {\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\t#ifndef YUNI_OS_WINDOWS\n\t\t\t\tout << \" \\u2713 \";\n\t\t\t\t#else\n\t\t\t\tout << \" > \";\n\t\t\t\t#endif\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \"parsing\";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t\telse if (name == \"error\") {\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \" FAILED \";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \"parsing\";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t\telse if (name == \"warning\") {\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \" {warn} \";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\tout << \"parsing\";\n\t\t\t\tif (Handler::colorsAllowed)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ Set Color\n\t\t\t\tif (Handler::colorsAllowed && VerbosityType::color != System::Console::none)\n\t\t\t\t\tSystem::Console::TextColor::Set(out);\n\t\t\t\t\/\/ The verbosity\n\t\t\t\tVerbosityType::AppendName(out);\n\t\t\t\t\/\/ Reset Color\n\t\t\t\tif (Handler::colorsAllowed && VerbosityType::color != System::Console::none)\n\t\t\t\t\tSystem::Console::ResetTextColor(out);\n\t\t\t}\n\t\t}\n\t\t\/\/ Transmit the message to the next decorator\n\t\tLeftType::template internalDecoratorAddPrefix(out, s);\n\t}\n}; \/\/ struct VerbosityLevel\n\n\nusing Logging = Logs::Logger, ParseVerbosity>>;\nstatic Logging logs;\n\n\nuint32_t fincCommonFolderLength(const std::vector& filenames) {\n\tif (filenames.empty())\n\t\treturn 0;\n\tauto& firstElement = filenames[0];\n\tconst char sep = IO::Separator;\n\tuint32_t pos = 0;\n\tfor (; ; ++pos) {\n\t\tfor (size_t i = 0; i < filenames.size(); ++i) {\n\t\t\tauto& str = filenames[i];\n\t\t\tif (pos == firstElement.size())\n\t\t\t\treturn pos;\n\t\t\tif (pos < str.size() and str[pos] != '\\0' and str[pos] == firstElement[pos])\n\t\t\t\tcontinue;\n\t\t\t\/\/ back to the last sep\n\t\t\twhile (pos > 0 && firstElement[--pos] != sep) {\n\t\t\t}\n\t\t\treturn pos;\n\t\t}\n\t}\n\treturn pos;\n}\n\nbool expandFilelist(std::vector& list) {\n\tstd::vector filelist;\n\tfilelist.reserve(512);\n\tString currentfile;\n\tcurrentfile.reserve(4096);\n\tfor (auto& element: list) {\n\t\tIO::Canonicalize(currentfile, element);\n\t\tswitch (IO::TypeOf(currentfile)) {\n\t\t\tcase IO::typeFile: {\n\t\t\t\tfilelist.emplace_back(currentfile);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase IO::typeFolder: {\n\t\t\t\tShortString16 ext;\n\t\t\t\tIO::Directory::Info info(currentfile);\n\t\t\t\tauto end = info.recursive_file_end();\n\t\t\t\tfor (auto i = info.recursive_file_begin(); i != end; ++i)\n\t\t\t\t{\n\t\t\t\t\tIO::ExtractExtension(ext, *i);\n\t\t\t\t\tif (ext == \".ny\")\n\t\t\t\t\t\tfilelist.emplace_back(i.filename());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tlogs.error() << \"impossible to find '\" << currentfile << \"'\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ for beauty in singled-threaded (and to always produce the same output)\n\tstd::sort(filelist.begin(), filelist.end());\n\tlist.swap(filelist);\n\treturn true;\n}\n\ntemplate\nbool IterateThroughAllFiles(const std::vector& filenames, const F& callback) {\n\tString currentfile;\n\tuint32_t testOK = 0;\n\tuint32_t testFAILED = 0;\n\tint64_t maxCheckDuration = 0;\n\tint64_t startTime = DateTime::NowMilliSeconds();\n\tfor (auto& filename: filenames) {\n\t\tint64_t duration = 0;\n\t\tif (callback(filename, duration))\n\t\t\t++testOK;\n\t\telse\n\t\t\t++testFAILED;\n\t\tif (duration > maxCheckDuration)\n\t\t\tmaxCheckDuration = duration;\n\t}\n\tint64_t endTime = DateTime::NowMilliSeconds();\n\tuint32_t total = testOK + testFAILED;\n\tif (total > 0) {\n\t\tint64_t duration = (endTime - startTime);\n\t\tString durationStr;\n\t\tdurationStr << \" (in \" << duration << \"ms, max: \" << maxCheckDuration << \"ms)\";\n\t\tif (total > 1) {\n\t\t\tif (0 != testFAILED) {\n\t\t\t\tswitch (total) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tlogs.warning() << \"-- FAILED -- 1 file, +\" << testOK << \", -\" << testFAILED << durationStr;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlogs.warning() << \"-- FAILED -- \" << total << \" files, +\" << testOK << \", -\" << testFAILED << durationStr;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tswitch (total) {\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tlogs.info() << \"success: 1 file, +\" << testOK << \", -0\" << durationStr;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlogs.info() << \"success: \" << total << \" files, +\" << testOK << \", -0\" << durationStr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tlogs.warning() << \"no input file\";\n\treturn (0 == testFAILED);\n}\n\nbool batchCheckIfFilenamesConformToGrammar(Settings& settings) {\n\tif (not expandFilelist(settings.filenames))\n\t\treturn false;\n\tauto commonFolder = (settings.filenames.size() > 1 ? fincCommonFolderLength(settings.filenames) : 0);\n\tif (0 != commonFolder)\n\t\t++commonFolder;\n\treturn IterateThroughAllFiles(settings.filenames, [&](const AnyString& file, int64_t& duration) -> bool {\n\t\tString barefile;\n\t\tIO::ExtractFileName(barefile, file);\n\t\tbool expected = true;\n\t\tbool canfail = false;\n\t\tif (settings.useFilenameConvention)\n\t\t{\n\t\t\tif (barefile.startsWith(\"ko-\"))\n\t\t\t\texpected = false;\n\t\t\tif (barefile.find(\"-canfail-\") < barefile.size())\n\t\t\t\tcanfail = true;\n\t\t}\n\t\t\/\/ PARSE\n\t\tint64_t start = DateTime::NowMilliSeconds();\n\t\tbool success = (nytrue == nytry_parse_file_n(file.c_str(), file.size()));\n\t\tduration = DateTime::NowMilliSeconds() - start;\n\t\tsuccess = (success == expected);\n\t\tif (success and duration < 300) {\n\t\t\tlogs.info() << AnyString{file, commonFolder} << \" [\" << duration << \"ms]\";\n\t\t}\n\t\telse {\n\t\t\tif (not success) {\n\t\t\t\tif (not canfail)\n\t\t\t\t\tlogs.error() << AnyString{file, commonFolder} << \" [\" << duration << \"ms]\";\n\t\t\t\telse\n\t\t\t\t\tlogs.warning() << AnyString{file, commonFolder} << \" [\" << duration << \"ms, can fail]\";\n\t\t\t}\n\t\t\telse\n\t\t\t\tlogs.error() << AnyString{file, commonFolder} << \" [\" << duration << \"ms - time limit reached]\";\n\t\t\tsuccess = canfail;\n\t\t}\n\t\treturn success;\n\t});\n}\n\n\n} \/\/ namespace\n\n\nint main(int argc, char** argv)\n{\n\tSettings settings;\n\t\/\/ parse the command\n\t{\n\t\t\/\/ The command line options parser\n\t\tGetOpt::Parser options;\n\t\t\/\/ Input files\n\t\toptions.add(settings.filenames, 'i', \"input\", \"Input files (or folders)\");\n\t\toptions.remainingArguments(settings.filenames);\n\t\t\/\/ --no-color\n\t\toptions.addFlag(settings.noColors, ' ', \"no-color\", \"Disable color output\");\n\t\t\/\/ use filename convention\n\t\toptions.addFlag(settings.useFilenameConvention, ' ', \"use-filename-convention\",\n\t\t\t\"Use the filename to determine if the test should succeed or not (should succeed if starting with 'ok-'\");\n\t\t\/\/ version\n\t\tbool optVersion = false;\n\t\toptions.addFlag(optVersion, ' ', \"version\", \"Display the version of the compiler and exit\");\n\t\t\/\/ Ask to the parser to parse the command line\n\t\tif (not options(argc, argv)) {\n\t\t\t\/\/ The program should not continue here\n\t\t\t\/\/ The user may have requested the help or an error has happened\n\t\t\t\/\/ If an error has happened, the exit status should be different from 0\n\t\t\tif (options.errors()) {\n\t\t\t\tstd::cerr << \"Abort due to error\\n\";\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\n\t\tif (optVersion) {\n\t\t\tstd::cout << \"0.0\\n\";\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\t\tif (settings.filenames.empty()) {\n\t\t\tstd::cerr << argv[0] << \": no input file\\n\";\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\t\/\/ Print AST or check for Nany Grammar\n\tbool success = batchCheckIfFilenamesConformToGrammar(settings);\n\treturn success ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 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\/file_system_provider\/request_manager.h\"\n\n#include \"base\/files\/file.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/trace_event\/trace_event.h\"\n#include \"chrome\/browser\/extensions\/window_controller_list.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"extensions\/browser\/app_window\/app_window_registry.h\"\n#include \"extensions\/common\/constants.h\"\n\nnamespace chromeos {\nnamespace file_system_provider {\nnamespace {\n\n\/\/ Timeout in seconds, before a request is considered as stale and hence\n\/\/ aborted.\nconst int kDefaultTimeout = 10;\n\n} \/\/ namespace\n\nRequestManager::RequestManager(\n Profile* profile,\n const std::string& extension_id,\n NotificationManagerInterface* notification_manager)\n : profile_(profile),\n extension_id_(extension_id),\n notification_manager_(notification_manager),\n next_id_(1),\n timeout_(base::TimeDelta::FromSeconds(kDefaultTimeout)),\n weak_ptr_factory_(this) {\n}\n\nRequestManager::~RequestManager() {\n \/\/ Abort all of the active requests.\n RequestMap::iterator it = requests_.begin();\n while (it != requests_.end()) {\n const int request_id = it->first;\n ++it;\n RejectRequest(request_id,\n scoped_ptr(new RequestValue()),\n base::File::FILE_ERROR_ABORT);\n }\n\n DCHECK_EQ(0u, requests_.size());\n STLDeleteValues(&requests_);\n}\n\nint RequestManager::CreateRequest(RequestType type,\n scoped_ptr handler) {\n \/\/ The request id is unique per request manager, so per service, thereof\n \/\/ per profile.\n int request_id = next_id_++;\n\n \/\/ If cycled the int, then signal an error.\n if (requests_.find(request_id) != requests_.end())\n return 0;\n\n TRACE_EVENT_ASYNC_BEGIN1(\"file_system_provider\",\n \"RequestManager::Request\",\n request_id,\n \"type\",\n type);\n\n Request* request = new Request;\n request->handler = handler.Pass();\n requests_[request_id] = request;\n ResetTimer(request_id);\n\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestCreated(request_id, type));\n\n \/\/ Execute the request implementation. In case of an execution failure,\n \/\/ unregister and return 0. This may often happen, eg. if the providing\n \/\/ extension is not listening for the request event being sent.\n \/\/ In such case, we should abort as soon as possible.\n if (!request->handler->Execute(request_id)) {\n DestroyRequest(request_id);\n return 0;\n }\n\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestExecuted(request_id));\n\n return request_id;\n}\n\nbase::File::Error RequestManager::FulfillRequest(\n int request_id,\n scoped_ptr response,\n bool has_more) {\n CHECK(response.get());\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return base::File::FILE_ERROR_NOT_FOUND;\n\n FOR_EACH_OBSERVER(Observer,\n observers_,\n OnRequestFulfilled(request_id, *response.get(), has_more));\n\n request_it->second->handler->OnSuccess(request_id, response.Pass(), has_more);\n\n if (!has_more) {\n DestroyRequest(request_id);\n } else {\n if (notification_manager_)\n notification_manager_->HideUnresponsiveNotification(request_id);\n ResetTimer(request_id);\n }\n\n return base::File::FILE_OK;\n}\n\nbase::File::Error RequestManager::RejectRequest(\n int request_id,\n scoped_ptr response,\n base::File::Error error) {\n CHECK(response.get());\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return base::File::FILE_ERROR_NOT_FOUND;\n\n FOR_EACH_OBSERVER(Observer,\n observers_,\n OnRequestRejected(request_id, *response.get(), error));\n request_it->second->handler->OnError(request_id, response.Pass(), error);\n DestroyRequest(request_id);\n\n return base::File::FILE_OK;\n}\n\nvoid RequestManager::SetTimeoutForTesting(const base::TimeDelta& timeout) {\n timeout_ = timeout;\n}\n\nstd::vector RequestManager::GetActiveRequestIds() const {\n std::vector result;\n\n for (RequestMap::const_iterator request_it = requests_.begin();\n request_it != requests_.end();\n ++request_it) {\n result.push_back(request_it->first);\n }\n\n return result;\n}\n\nvoid RequestManager::AddObserver(Observer* observer) {\n DCHECK(observer);\n observers_.AddObserver(observer);\n}\n\nvoid RequestManager::RemoveObserver(Observer* observer) {\n DCHECK(observer);\n observers_.RemoveObserver(observer);\n}\n\nRequestManager::Request::Request() {}\n\nRequestManager::Request::~Request() {}\n\nvoid RequestManager::OnRequestTimeout(int request_id) {\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestTimeouted(request_id));\n\n if (!notification_manager_) {\n RejectRequest(request_id,\n scoped_ptr(new RequestValue()),\n base::File::FILE_ERROR_ABORT);\n return;\n }\n\n if (!IsInteractingWithUser()) {\n notification_manager_->ShowUnresponsiveNotification(\n request_id,\n base::Bind(&RequestManager::OnUnresponsiveNotificationResult,\n weak_ptr_factory_.GetWeakPtr(), request_id));\n } else {\n ResetTimer(request_id);\n }\n}\n\nvoid RequestManager::OnUnresponsiveNotificationResult(\n int request_id,\n NotificationManagerInterface::NotificationResult result) {\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return;\n\n if (result == NotificationManagerInterface::CONTINUE) {\n ResetTimer(request_id);\n return;\n }\n\n RejectRequest(request_id,\n scoped_ptr(new RequestValue()),\n base::File::FILE_ERROR_ABORT);\n}\n\nvoid RequestManager::ResetTimer(int request_id) {\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return;\n\n request_it->second->timeout_timer.Start(\n FROM_HERE,\n timeout_,\n base::Bind(&RequestManager::OnRequestTimeout,\n weak_ptr_factory_.GetWeakPtr(),\n request_id));\n}\n\nbool RequestManager::IsInteractingWithUser() const {\n \/\/ First try for app windows. If not found, then fall back to browser windows\n \/\/ and tabs.\n\n const extensions::AppWindowRegistry* const registry =\n extensions::AppWindowRegistry::Get(profile_);\n DCHECK(registry);\n if (registry->GetCurrentAppWindowForApp(extension_id_))\n return true;\n\n \/\/ This loop is heavy, but it's not called often. Only when a request timeouts\n \/\/ which is at most once every 10 seconds per request (except tests).\n const extensions::WindowControllerList::ControllerList& windows =\n extensions::WindowControllerList::GetInstance()->windows();\n for (const auto& window : windows) {\n const TabStripModel* const tabs = window->GetBrowser()->tab_strip_model();\n for (int i = 0; i < tabs->count(); ++i) {\n const content::WebContents* const web_contents =\n tabs->GetWebContentsAt(i);\n const GURL& url = web_contents->GetURL();\n if (url.scheme() == extensions::kExtensionScheme &&\n url.host() == extension_id_) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nvoid RequestManager::DestroyRequest(int request_id) {\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return;\n\n delete request_it->second;\n requests_.erase(request_it);\n\n if (notification_manager_)\n notification_manager_->HideUnresponsiveNotification(request_id);\n\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestDestroyed(request_id));\n\n TRACE_EVENT_ASYNC_END0(\n \"file_system_provider\", \"RequestManager::Request\", request_id);\n}\n\n} \/\/ namespace file_system_provider\n} \/\/ namespace chromeos\nFix crash when accessing an archive of a deleted file.\/\/ Copyright 2014 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\/file_system_provider\/request_manager.h\"\n\n#include \"base\/files\/file.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/trace_event\/trace_event.h\"\n#include \"chrome\/browser\/extensions\/window_controller_list.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"extensions\/browser\/app_window\/app_window_registry.h\"\n#include \"extensions\/common\/constants.h\"\n\nnamespace chromeos {\nnamespace file_system_provider {\nnamespace {\n\n\/\/ Timeout in seconds, before a request is considered as stale and hence\n\/\/ aborted.\nconst int kDefaultTimeout = 10;\n\n} \/\/ namespace\n\nRequestManager::RequestManager(\n Profile* profile,\n const std::string& extension_id,\n NotificationManagerInterface* notification_manager)\n : profile_(profile),\n extension_id_(extension_id),\n notification_manager_(notification_manager),\n next_id_(1),\n timeout_(base::TimeDelta::FromSeconds(kDefaultTimeout)),\n weak_ptr_factory_(this) {\n}\n\nRequestManager::~RequestManager() {\n \/\/ Abort all of the active requests.\n RequestMap::iterator it = requests_.begin();\n while (it != requests_.end()) {\n const int request_id = it->first;\n ++it;\n RejectRequest(request_id,\n scoped_ptr(new RequestValue()),\n base::File::FILE_ERROR_ABORT);\n }\n\n DCHECK_EQ(0u, requests_.size());\n STLDeleteValues(&requests_);\n}\n\nint RequestManager::CreateRequest(RequestType type,\n scoped_ptr handler) {\n \/\/ The request id is unique per request manager, so per service, thereof\n \/\/ per profile.\n int request_id = next_id_++;\n\n \/\/ If cycled the int, then signal an error.\n if (requests_.find(request_id) != requests_.end())\n return 0;\n\n TRACE_EVENT_ASYNC_BEGIN1(\"file_system_provider\",\n \"RequestManager::Request\",\n request_id,\n \"type\",\n type);\n\n Request* request = new Request;\n request->handler = handler.Pass();\n requests_[request_id] = request;\n ResetTimer(request_id);\n\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestCreated(request_id, type));\n\n \/\/ Execute the request implementation. In case of an execution failure,\n \/\/ unregister and return 0. This may often happen, eg. if the providing\n \/\/ extension is not listening for the request event being sent.\n \/\/ In such case, we should abort as soon as possible.\n if (!request->handler->Execute(request_id)) {\n DestroyRequest(request_id);\n return 0;\n }\n\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestExecuted(request_id));\n\n return request_id;\n}\n\nbase::File::Error RequestManager::FulfillRequest(\n int request_id,\n scoped_ptr response,\n bool has_more) {\n CHECK(response.get());\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return base::File::FILE_ERROR_NOT_FOUND;\n\n FOR_EACH_OBSERVER(Observer,\n observers_,\n OnRequestFulfilled(request_id, *response.get(), has_more));\n\n request_it->second->handler->OnSuccess(request_id, response.Pass(), has_more);\n\n if (!has_more) {\n DestroyRequest(request_id);\n } else {\n if (notification_manager_)\n notification_manager_->HideUnresponsiveNotification(request_id);\n ResetTimer(request_id);\n }\n\n return base::File::FILE_OK;\n}\n\nbase::File::Error RequestManager::RejectRequest(\n int request_id,\n scoped_ptr response,\n base::File::Error error) {\n CHECK(response.get());\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return base::File::FILE_ERROR_NOT_FOUND;\n\n FOR_EACH_OBSERVER(Observer,\n observers_,\n OnRequestRejected(request_id, *response.get(), error));\n request_it->second->handler->OnError(request_id, response.Pass(), error);\n DestroyRequest(request_id);\n\n return base::File::FILE_OK;\n}\n\nvoid RequestManager::SetTimeoutForTesting(const base::TimeDelta& timeout) {\n timeout_ = timeout;\n}\n\nstd::vector RequestManager::GetActiveRequestIds() const {\n std::vector result;\n\n for (RequestMap::const_iterator request_it = requests_.begin();\n request_it != requests_.end();\n ++request_it) {\n result.push_back(request_it->first);\n }\n\n return result;\n}\n\nvoid RequestManager::AddObserver(Observer* observer) {\n DCHECK(observer);\n observers_.AddObserver(observer);\n}\n\nvoid RequestManager::RemoveObserver(Observer* observer) {\n DCHECK(observer);\n observers_.RemoveObserver(observer);\n}\n\nRequestManager::Request::Request() {}\n\nRequestManager::Request::~Request() {}\n\nvoid RequestManager::OnRequestTimeout(int request_id) {\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestTimeouted(request_id));\n\n if (!notification_manager_) {\n RejectRequest(request_id,\n scoped_ptr(new RequestValue()),\n base::File::FILE_ERROR_ABORT);\n return;\n }\n\n if (!IsInteractingWithUser()) {\n notification_manager_->ShowUnresponsiveNotification(\n request_id,\n base::Bind(&RequestManager::OnUnresponsiveNotificationResult,\n weak_ptr_factory_.GetWeakPtr(), request_id));\n } else {\n ResetTimer(request_id);\n }\n}\n\nvoid RequestManager::OnUnresponsiveNotificationResult(\n int request_id,\n NotificationManagerInterface::NotificationResult result) {\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return;\n\n if (result == NotificationManagerInterface::CONTINUE) {\n ResetTimer(request_id);\n return;\n }\n\n RejectRequest(request_id,\n scoped_ptr(new RequestValue()),\n base::File::FILE_ERROR_ABORT);\n}\n\nvoid RequestManager::ResetTimer(int request_id) {\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return;\n\n request_it->second->timeout_timer.Start(\n FROM_HERE,\n timeout_,\n base::Bind(&RequestManager::OnRequestTimeout,\n weak_ptr_factory_.GetWeakPtr(),\n request_id));\n}\n\nbool RequestManager::IsInteractingWithUser() const {\n \/\/ First try for app windows. If not found, then fall back to browser windows\n \/\/ and tabs.\n\n const extensions::AppWindowRegistry* const registry =\n extensions::AppWindowRegistry::Get(profile_);\n DCHECK(registry);\n if (registry->GetCurrentAppWindowForApp(extension_id_))\n return true;\n\n \/\/ This loop is heavy, but it's not called often. Only when a request timeouts\n \/\/ which is at most once every 10 seconds per request (except tests).\n const extensions::WindowControllerList::ControllerList& windows =\n extensions::WindowControllerList::GetInstance()->windows();\n for (const auto& window : windows) {\n const Browser* const browser = window->GetBrowser();\n if (!browser)\n continue;\n const TabStripModel* const tabs = browser->tab_strip_model();\n DCHECK(tabs);\n for (int i = 0; i < tabs->count(); ++i) {\n const content::WebContents* const web_contents =\n tabs->GetWebContentsAt(i);\n const GURL& url = web_contents->GetURL();\n if (url.scheme() == extensions::kExtensionScheme &&\n url.host() == extension_id_) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nvoid RequestManager::DestroyRequest(int request_id) {\n RequestMap::iterator request_it = requests_.find(request_id);\n if (request_it == requests_.end())\n return;\n\n delete request_it->second;\n requests_.erase(request_it);\n\n if (notification_manager_)\n notification_manager_->HideUnresponsiveNotification(request_id);\n\n FOR_EACH_OBSERVER(Observer, observers_, OnRequestDestroyed(request_id));\n\n TRACE_EVENT_ASYNC_END0(\n \"file_system_provider\", \"RequestManager::Request\", request_id);\n}\n\n} \/\/ namespace file_system_provider\n} \/\/ namespace chromeos\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 \"chrome\/browser\/tab_contents\/render_view_host_delegate_helper.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/background_contents_service.h\"\n#include \"chrome\/browser\/character_encoding.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/prefs\/pref_service.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_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_fullscreen_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/background_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/browser\/user_style_sheet_watcher.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nRenderViewHostDelegateViewHelper::RenderViewHostDelegateViewHelper() {}\n\nRenderViewHostDelegateViewHelper::~RenderViewHostDelegateViewHelper() {}\n\nBackgroundContents*\nRenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n const GURL& opener_url,\n const string16& frame_name) {\n ExtensionService* extensions_service = profile->GetExtensionService();\n\n if (!opener_url.is_valid() ||\n frame_name.empty() ||\n !extensions_service ||\n !extensions_service->is_ready())\n return NULL;\n\n \/\/ Only hosted apps have web extents, so this ensures that only hosted apps\n \/\/ can create BackgroundContents. We don't have to check for background\n \/\/ permission as that is checked in RenderMessageFilter when the CreateWindow\n \/\/ message is processed.\n const Extension* extension =\n extensions_service->GetExtensionByWebExtent(opener_url);\n if (!extension)\n return NULL;\n\n \/\/ Only allow a single background contents per app.\n if (!profile->GetBackgroundContentsService() ||\n profile->GetBackgroundContentsService()->GetAppBackgroundContents(\n ASCIIToUTF16(extension->id())))\n return NULL;\n\n \/\/ Ensure that we're trying to open this from the extension's process.\n ExtensionProcessManager* process_manager =\n profile->GetExtensionProcessManager();\n if (!site->GetProcess() || !process_manager ||\n site->GetProcess() != process_manager->GetExtensionProcess(opener_url))\n return NULL;\n\n \/\/ Passed all the checks, so this should be created as a BackgroundContents.\n return profile->GetBackgroundContentsService()->CreateBackgroundContents(\n site, route_id, profile, frame_name, ASCIIToUTF16(extension->id()));\n}\n\nTabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n WebUITypeID webui_type,\n RenderViewHostDelegate* opener,\n WindowContainerType window_container_type,\n const string16& frame_name) {\n if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {\n BackgroundContents* contents = MaybeCreateBackgroundContents(\n route_id,\n profile,\n site,\n opener->GetURL(),\n frame_name);\n if (contents) {\n pending_contents_[route_id] = contents->render_view_host();\n return NULL;\n }\n }\n\n \/\/ Create the new web contents. This will automatically create the new\n \/\/ TabContentsView. In the future, we may want to create the view separately.\n TabContents* new_contents =\n new TabContents(profile,\n site,\n route_id,\n opener->GetAsTabContents(),\n NULL);\n new_contents->set_opener_web_ui_type(webui_type);\n TabContentsView* new_view = new_contents->view();\n\n \/\/ TODO(brettw) it seems bogus that we have to call this function on the\n \/\/ newly created object and give it one of its own member variables.\n new_view->CreateViewForWidget(new_contents->render_view_host());\n\n \/\/ Save the created window associated with the route so we can show it later.\n pending_contents_[route_id] = new_contents->render_view_host();\n return new_contents;\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(\n int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {\n RenderWidgetHost* widget_host =\n new RenderWidgetHost(process, route_id);\n RenderWidgetHostView* widget_view =\n RenderWidgetHostView::CreateViewForWidget(widget_host);\n \/\/ Popups should not get activated.\n widget_view->set_popup_type(popup_type);\n \/\/ Save the created widget associated with the route so we can show it later.\n pending_widget_views_[route_id] = widget_view;\n return widget_view;\n}\n\nRenderWidgetHostView*\nRenderViewHostDelegateViewHelper::CreateNewFullscreenWidget(\n int route_id, RenderProcessHost* process) {\n RenderWidgetFullscreenHost* fullscreen_widget_host =\n new RenderWidgetFullscreenHost(process, route_id);\n RenderWidgetHostView* widget_view =\n RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host);\n pending_widget_views_[route_id] = widget_view;\n return widget_view;\n}\n\nTabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {\n PendingContents::iterator iter = pending_contents_.find(route_id);\n if (iter == pending_contents_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderViewHost* new_rvh = iter->second;\n pending_contents_.erase(route_id);\n\n \/\/ The renderer crashed or it is a TabContents and has no view.\n if (!new_rvh->process()->HasConnection() ||\n (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))\n return NULL;\n\n \/\/ TODO(brettw) this seems bogus to reach into here and initialize the host.\n new_rvh->Init();\n return new_rvh->delegate()->GetAsTabContents();\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(\n int route_id) {\n PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);\n if (iter == pending_widget_views_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderWidgetHostView* widget_host_view = iter->second;\n pending_widget_views_.erase(route_id);\n\n RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();\n if (!widget_host->process()->HasConnection()) {\n \/\/ The view has gone away or the renderer crashed. Nothing to do.\n return NULL;\n }\n\n return widget_host_view;\n}\n\nvoid RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(\n RenderWidgetHost* host) {\n for (PendingWidgetViews::iterator i = pending_widget_views_.begin();\n i != pending_widget_views_.end(); ++i) {\n if (host->view() == i->second) {\n pending_widget_views_.erase(i);\n return;\n }\n }\n}\n\nbool RenderViewHostDelegateHelper::gpu_enabled_ = true;\n\n\/\/ static\nWebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(\n Profile* profile, bool is_web_ui) {\n PrefService* prefs = profile->GetPrefs();\n WebPreferences web_prefs;\n\n web_prefs.fixed_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitFixedFontFamily));\n web_prefs.serif_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitSerifFontFamily));\n web_prefs.sans_serif_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitSansSerifFontFamily));\n if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif))\n web_prefs.standard_font_family = web_prefs.serif_font_family;\n else\n web_prefs.standard_font_family = web_prefs.sans_serif_font_family;\n web_prefs.cursive_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitCursiveFontFamily));\n web_prefs.fantasy_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitFantasyFontFamily));\n\n web_prefs.default_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFontSize);\n web_prefs.default_fixed_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);\n web_prefs.minimum_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumFontSize);\n web_prefs.minimum_logical_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);\n\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n\n web_prefs.javascript_can_open_windows_automatically =\n prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);\n web_prefs.dom_paste_enabled =\n prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);\n web_prefs.shrinks_standalone_images_to_fit =\n prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);\n const DictionaryValue* inspector_settings =\n prefs->GetDictionary(prefs::kWebKitInspectorSettings);\n if (inspector_settings) {\n for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());\n iter != inspector_settings->end_keys(); ++iter) {\n std::string value;\n if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))\n web_prefs.inspector_settings.push_back(\n std::make_pair(*iter, value));\n }\n }\n web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);\n\n { \/\/ Command line switches are used for preferences with no user interface.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n web_prefs.developer_extras_enabled =\n !command_line.HasSwitch(switches::kDisableDevTools);\n web_prefs.javascript_enabled =\n !command_line.HasSwitch(switches::kDisableJavaScript) &&\n prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);\n web_prefs.web_security_enabled =\n !command_line.HasSwitch(switches::kDisableWebSecurity) &&\n prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);\n web_prefs.plugins_enabled =\n !command_line.HasSwitch(switches::kDisablePlugins) &&\n prefs->GetBoolean(prefs::kWebKitPluginsEnabled);\n web_prefs.java_enabled =\n !command_line.HasSwitch(switches::kDisableJava) &&\n prefs->GetBoolean(prefs::kWebKitJavaEnabled);\n web_prefs.loads_images_automatically =\n prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);\n web_prefs.uses_page_cache =\n command_line.HasSwitch(switches::kEnableFastback);\n web_prefs.remote_fonts_enabled =\n !command_line.HasSwitch(switches::kDisableRemoteFonts);\n web_prefs.xss_auditor_enabled =\n !command_line.HasSwitch(switches::kDisableXSSAuditor);\n web_prefs.application_cache_enabled =\n !command_line.HasSwitch(switches::kDisableApplicationCache);\n\n web_prefs.local_storage_enabled =\n !command_line.HasSwitch(switches::kDisableLocalStorage);\n web_prefs.databases_enabled =\n !command_line.HasSwitch(switches::kDisableDatabases);\n web_prefs.webaudio_enabled =\n command_line.HasSwitch(switches::kEnableWebAudio);\n web_prefs.experimental_webgl_enabled =\n gpu_enabled() &&\n !command_line.HasSwitch(switches::kDisable3DAPIs) &&\n !command_line.HasSwitch(switches::kDisableExperimentalWebGL);\n web_prefs.gl_multisampling_enabled =\n !command_line.HasSwitch(switches::kDisableGLMultisampling);\n web_prefs.site_specific_quirks_enabled =\n !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);\n web_prefs.allow_file_access_from_file_urls =\n command_line.HasSwitch(switches::kAllowFileAccessFromFiles);\n web_prefs.show_composited_layer_borders =\n command_line.HasSwitch(switches::kShowCompositedLayerBorders);\n web_prefs.accelerated_compositing_enabled =\n gpu_enabled() &&\n !command_line.HasSwitch(switches::kDisableAcceleratedCompositing);\n web_prefs.accelerated_2d_canvas_enabled =\n gpu_enabled() &&\n command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);\n web_prefs.accelerated_layers_enabled =\n !command_line.HasSwitch(switches::kDisableAcceleratedLayers);\n web_prefs.composite_to_texture_enabled =\n command_line.HasSwitch(switches::kEnableCompositeToTexture);\n web_prefs.accelerated_plugins_enabled =\n command_line.HasSwitch(switches::kEnableAcceleratedPlugins);\n web_prefs.accelerated_video_enabled =\n !command_line.HasSwitch(switches::kDisableAcceleratedVideo);\n web_prefs.memory_info_enabled =\n command_line.HasSwitch(switches::kEnableMemoryInfo);\n web_prefs.hyperlink_auditing_enabled =\n !command_line.HasSwitch(switches::kNoPings);\n web_prefs.interactive_form_validation_enabled =\n !command_line.HasSwitch(switches::kDisableInteractiveFormValidation);\n \/\/ The user stylesheet watcher may not exist in a testing profile.\n if (profile->GetUserStyleSheetWatcher()) {\n web_prefs.user_style_sheet_enabled = true;\n web_prefs.user_style_sheet_location =\n profile->GetUserStyleSheetWatcher()->user_style_sheet();\n } else {\n web_prefs.user_style_sheet_enabled = false;\n }\n }\n\n web_prefs.uses_universal_detector =\n prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);\n web_prefs.text_areas_are_resizable =\n prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);\n\n \/\/ Make sure we will set the default_encoding with canonical encoding name.\n web_prefs.default_encoding =\n CharacterEncoding::GetCanonicalEncodingNameByAliasName(\n web_prefs.default_encoding);\n if (web_prefs.default_encoding.empty()) {\n prefs->ClearPref(prefs::kDefaultCharset);\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n }\n DCHECK(!web_prefs.default_encoding.empty());\n\n if (is_web_ui) {\n web_prefs.loads_images_automatically = true;\n web_prefs.javascript_enabled = true;\n }\n\n return web_prefs;\n}\n\nvoid RenderViewHostDelegateHelper::UpdateInspectorSetting(\n Profile* profile, const std::string& key, const std::string& value) {\n DictionaryValue* inspector_settings =\n profile->GetPrefs()->GetMutableDictionary(\n prefs::kWebKitInspectorSettings);\n inspector_settings->SetWithoutPathExpansion(key,\n Value::CreateStringValue(value));\n}\n\nvoid RenderViewHostDelegateHelper::ClearInspectorSettings(Profile* profile) {\n DictionaryValue* inspector_settings =\n profile->GetPrefs()->GetMutableDictionary(\n prefs::kWebKitInspectorSettings);\n inspector_settings->Clear();\n}\nSet the standard font from 'serif' family font.\/\/ 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 \"chrome\/browser\/tab_contents\/render_view_host_delegate_helper.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/background_contents_service.h\"\n#include \"chrome\/browser\/character_encoding.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/prefs\/pref_service.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_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_fullscreen_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/background_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"chrome\/browser\/user_style_sheet_watcher.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n\nRenderViewHostDelegateViewHelper::RenderViewHostDelegateViewHelper() {}\n\nRenderViewHostDelegateViewHelper::~RenderViewHostDelegateViewHelper() {}\n\nBackgroundContents*\nRenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n const GURL& opener_url,\n const string16& frame_name) {\n ExtensionService* extensions_service = profile->GetExtensionService();\n\n if (!opener_url.is_valid() ||\n frame_name.empty() ||\n !extensions_service ||\n !extensions_service->is_ready())\n return NULL;\n\n \/\/ Only hosted apps have web extents, so this ensures that only hosted apps\n \/\/ can create BackgroundContents. We don't have to check for background\n \/\/ permission as that is checked in RenderMessageFilter when the CreateWindow\n \/\/ message is processed.\n const Extension* extension =\n extensions_service->GetExtensionByWebExtent(opener_url);\n if (!extension)\n return NULL;\n\n \/\/ Only allow a single background contents per app.\n if (!profile->GetBackgroundContentsService() ||\n profile->GetBackgroundContentsService()->GetAppBackgroundContents(\n ASCIIToUTF16(extension->id())))\n return NULL;\n\n \/\/ Ensure that we're trying to open this from the extension's process.\n ExtensionProcessManager* process_manager =\n profile->GetExtensionProcessManager();\n if (!site->GetProcess() || !process_manager ||\n site->GetProcess() != process_manager->GetExtensionProcess(opener_url))\n return NULL;\n\n \/\/ Passed all the checks, so this should be created as a BackgroundContents.\n return profile->GetBackgroundContentsService()->CreateBackgroundContents(\n site, route_id, profile, frame_name, ASCIIToUTF16(extension->id()));\n}\n\nTabContents* RenderViewHostDelegateViewHelper::CreateNewWindow(\n int route_id,\n Profile* profile,\n SiteInstance* site,\n WebUITypeID webui_type,\n RenderViewHostDelegate* opener,\n WindowContainerType window_container_type,\n const string16& frame_name) {\n if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {\n BackgroundContents* contents = MaybeCreateBackgroundContents(\n route_id,\n profile,\n site,\n opener->GetURL(),\n frame_name);\n if (contents) {\n pending_contents_[route_id] = contents->render_view_host();\n return NULL;\n }\n }\n\n \/\/ Create the new web contents. This will automatically create the new\n \/\/ TabContentsView. In the future, we may want to create the view separately.\n TabContents* new_contents =\n new TabContents(profile,\n site,\n route_id,\n opener->GetAsTabContents(),\n NULL);\n new_contents->set_opener_web_ui_type(webui_type);\n TabContentsView* new_view = new_contents->view();\n\n \/\/ TODO(brettw) it seems bogus that we have to call this function on the\n \/\/ newly created object and give it one of its own member variables.\n new_view->CreateViewForWidget(new_contents->render_view_host());\n\n \/\/ Save the created window associated with the route so we can show it later.\n pending_contents_[route_id] = new_contents->render_view_host();\n return new_contents;\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget(\n int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) {\n RenderWidgetHost* widget_host =\n new RenderWidgetHost(process, route_id);\n RenderWidgetHostView* widget_view =\n RenderWidgetHostView::CreateViewForWidget(widget_host);\n \/\/ Popups should not get activated.\n widget_view->set_popup_type(popup_type);\n \/\/ Save the created widget associated with the route so we can show it later.\n pending_widget_views_[route_id] = widget_view;\n return widget_view;\n}\n\nRenderWidgetHostView*\nRenderViewHostDelegateViewHelper::CreateNewFullscreenWidget(\n int route_id, RenderProcessHost* process) {\n RenderWidgetFullscreenHost* fullscreen_widget_host =\n new RenderWidgetFullscreenHost(process, route_id);\n RenderWidgetHostView* widget_view =\n RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host);\n pending_widget_views_[route_id] = widget_view;\n return widget_view;\n}\n\nTabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) {\n PendingContents::iterator iter = pending_contents_.find(route_id);\n if (iter == pending_contents_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderViewHost* new_rvh = iter->second;\n pending_contents_.erase(route_id);\n\n \/\/ The renderer crashed or it is a TabContents and has no view.\n if (!new_rvh->process()->HasConnection() ||\n (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view()))\n return NULL;\n\n \/\/ TODO(brettw) this seems bogus to reach into here and initialize the host.\n new_rvh->Init();\n return new_rvh->delegate()->GetAsTabContents();\n}\n\nRenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget(\n int route_id) {\n PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id);\n if (iter == pending_widget_views_.end()) {\n DCHECK(false);\n return NULL;\n }\n\n RenderWidgetHostView* widget_host_view = iter->second;\n pending_widget_views_.erase(route_id);\n\n RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();\n if (!widget_host->process()->HasConnection()) {\n \/\/ The view has gone away or the renderer crashed. Nothing to do.\n return NULL;\n }\n\n return widget_host_view;\n}\n\nvoid RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed(\n RenderWidgetHost* host) {\n for (PendingWidgetViews::iterator i = pending_widget_views_.begin();\n i != pending_widget_views_.end(); ++i) {\n if (host->view() == i->second) {\n pending_widget_views_.erase(i);\n return;\n }\n }\n}\n\nbool RenderViewHostDelegateHelper::gpu_enabled_ = true;\n\n\/\/ static\nWebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs(\n Profile* profile, bool is_web_ui) {\n PrefService* prefs = profile->GetPrefs();\n WebPreferences web_prefs;\n\n web_prefs.fixed_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitFixedFontFamily));\n web_prefs.serif_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitSerifFontFamily));\n web_prefs.sans_serif_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitSansSerifFontFamily));\n \/\/ TODO(kochi): As we don't have setting UI for kWebKitStandardFontIsSerif,\n \/\/ we always use web_prefs.serif_font_family as a standard font\n \/\/ temporarily for now. Ideally we should have a pref UI for serif\/sans\n \/\/ selection as for CJK font sans-serif family font is the default.\n \/\/ See discussion in http:\/\/crosbug.com\/12311.\n web_prefs.standard_font_family = web_prefs.serif_font_family;\n web_prefs.cursive_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitCursiveFontFamily));\n web_prefs.fantasy_font_family =\n UTF8ToUTF16(prefs->GetString(prefs::kWebKitFantasyFontFamily));\n\n web_prefs.default_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFontSize);\n web_prefs.default_fixed_font_size =\n prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);\n web_prefs.minimum_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumFontSize);\n web_prefs.minimum_logical_font_size =\n prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);\n\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n\n web_prefs.javascript_can_open_windows_automatically =\n prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);\n web_prefs.dom_paste_enabled =\n prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);\n web_prefs.shrinks_standalone_images_to_fit =\n prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);\n const DictionaryValue* inspector_settings =\n prefs->GetDictionary(prefs::kWebKitInspectorSettings);\n if (inspector_settings) {\n for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys());\n iter != inspector_settings->end_keys(); ++iter) {\n std::string value;\n if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value))\n web_prefs.inspector_settings.push_back(\n std::make_pair(*iter, value));\n }\n }\n web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);\n\n { \/\/ Command line switches are used for preferences with no user interface.\n const CommandLine& command_line = *CommandLine::ForCurrentProcess();\n web_prefs.developer_extras_enabled =\n !command_line.HasSwitch(switches::kDisableDevTools);\n web_prefs.javascript_enabled =\n !command_line.HasSwitch(switches::kDisableJavaScript) &&\n prefs->GetBoolean(prefs::kWebKitJavascriptEnabled);\n web_prefs.web_security_enabled =\n !command_line.HasSwitch(switches::kDisableWebSecurity) &&\n prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled);\n web_prefs.plugins_enabled =\n !command_line.HasSwitch(switches::kDisablePlugins) &&\n prefs->GetBoolean(prefs::kWebKitPluginsEnabled);\n web_prefs.java_enabled =\n !command_line.HasSwitch(switches::kDisableJava) &&\n prefs->GetBoolean(prefs::kWebKitJavaEnabled);\n web_prefs.loads_images_automatically =\n prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);\n web_prefs.uses_page_cache =\n command_line.HasSwitch(switches::kEnableFastback);\n web_prefs.remote_fonts_enabled =\n !command_line.HasSwitch(switches::kDisableRemoteFonts);\n web_prefs.xss_auditor_enabled =\n !command_line.HasSwitch(switches::kDisableXSSAuditor);\n web_prefs.application_cache_enabled =\n !command_line.HasSwitch(switches::kDisableApplicationCache);\n\n web_prefs.local_storage_enabled =\n !command_line.HasSwitch(switches::kDisableLocalStorage);\n web_prefs.databases_enabled =\n !command_line.HasSwitch(switches::kDisableDatabases);\n web_prefs.webaudio_enabled =\n command_line.HasSwitch(switches::kEnableWebAudio);\n web_prefs.experimental_webgl_enabled =\n gpu_enabled() &&\n !command_line.HasSwitch(switches::kDisable3DAPIs) &&\n !command_line.HasSwitch(switches::kDisableExperimentalWebGL);\n web_prefs.gl_multisampling_enabled =\n !command_line.HasSwitch(switches::kDisableGLMultisampling);\n web_prefs.site_specific_quirks_enabled =\n !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);\n web_prefs.allow_file_access_from_file_urls =\n command_line.HasSwitch(switches::kAllowFileAccessFromFiles);\n web_prefs.show_composited_layer_borders =\n command_line.HasSwitch(switches::kShowCompositedLayerBorders);\n web_prefs.accelerated_compositing_enabled =\n gpu_enabled() &&\n !command_line.HasSwitch(switches::kDisableAcceleratedCompositing);\n web_prefs.accelerated_2d_canvas_enabled =\n gpu_enabled() &&\n command_line.HasSwitch(switches::kEnableAccelerated2dCanvas);\n web_prefs.accelerated_layers_enabled =\n !command_line.HasSwitch(switches::kDisableAcceleratedLayers);\n web_prefs.composite_to_texture_enabled =\n command_line.HasSwitch(switches::kEnableCompositeToTexture);\n web_prefs.accelerated_plugins_enabled =\n command_line.HasSwitch(switches::kEnableAcceleratedPlugins);\n web_prefs.accelerated_video_enabled =\n !command_line.HasSwitch(switches::kDisableAcceleratedVideo);\n web_prefs.memory_info_enabled =\n command_line.HasSwitch(switches::kEnableMemoryInfo);\n web_prefs.hyperlink_auditing_enabled =\n !command_line.HasSwitch(switches::kNoPings);\n web_prefs.interactive_form_validation_enabled =\n !command_line.HasSwitch(switches::kDisableInteractiveFormValidation);\n \/\/ The user stylesheet watcher may not exist in a testing profile.\n if (profile->GetUserStyleSheetWatcher()) {\n web_prefs.user_style_sheet_enabled = true;\n web_prefs.user_style_sheet_location =\n profile->GetUserStyleSheetWatcher()->user_style_sheet();\n } else {\n web_prefs.user_style_sheet_enabled = false;\n }\n }\n\n web_prefs.uses_universal_detector =\n prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);\n web_prefs.text_areas_are_resizable =\n prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);\n\n \/\/ Make sure we will set the default_encoding with canonical encoding name.\n web_prefs.default_encoding =\n CharacterEncoding::GetCanonicalEncodingNameByAliasName(\n web_prefs.default_encoding);\n if (web_prefs.default_encoding.empty()) {\n prefs->ClearPref(prefs::kDefaultCharset);\n web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset);\n }\n DCHECK(!web_prefs.default_encoding.empty());\n\n if (is_web_ui) {\n web_prefs.loads_images_automatically = true;\n web_prefs.javascript_enabled = true;\n }\n\n return web_prefs;\n}\n\nvoid RenderViewHostDelegateHelper::UpdateInspectorSetting(\n Profile* profile, const std::string& key, const std::string& value) {\n DictionaryValue* inspector_settings =\n profile->GetPrefs()->GetMutableDictionary(\n prefs::kWebKitInspectorSettings);\n inspector_settings->SetWithoutPathExpansion(key,\n Value::CreateStringValue(value));\n}\n\nvoid RenderViewHostDelegateHelper::ClearInspectorSettings(Profile* profile) {\n DictionaryValue* inspector_settings =\n profile->GetPrefs()->GetMutableDictionary(\n prefs::kWebKitInspectorSettings);\n inspector_settings->Clear();\n}\n<|endoftext|>"} {"text":"#ifndef _PITO_INTERCEPTOR_LIB_C_\n#define _PITO_INTERCEPTOR_LIB_C_\n\n#include \n#include \n\n#include \n#include \n#include \n\n#ifndef PITO_SYSTEM_CALL_BASE\n#define PITO_SYSTEM_CALL_BASE SystemCallBase\n#endif\n\n#ifndef PITO_JAIL_BASE\n#define PITO_JAIL_BASE PITO_SYSTEM_CALL_BASE\n#endif\n\nnamespace pito { namespace interceptor {\n\nusing namespace system_call;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ security intercepts\nPITO_SYSTEM_CALL(chmod)\nPITO_SYSTEM_CALL(fchmod)\nPITO_SYSTEM_CALL(fchmodat)\nPITO_SYSTEM_CALL(chown)\nPITO_SYSTEM_CALL(fchown)\nPITO_SYSTEM_CALL(fchownat)\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int open(const char *pathname, int flags, ...) {\n if (flags & O_CREAT) {\n va_list ap;\n va_start(ap, flags);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(open)(pathname, flags, mode);\n }\n else return PITO_SUPER(open)(pathname, flags);\n }\n}\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int openat(int dirfd, const char *pathname, int flags, ...) {\n if (flags & O_CREAT) {\n va_list ap;\n va_start(ap, flags);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(openat)(dirfd, pathname, flags, mode);\n }\n else return PITO_SUPER(openat)(dirfd, pathname, flags);\n }\n}\n\nPITO_SYSTEM_CALL(creat)\nPITO_SYSTEM_CALL(fopen)\nPITO_SYSTEM_CALL(lchown)\nPITO_SYSTEM_CALL(link)\nPITO_SYSTEM_CALL(linkat)\nPITO_SYSTEM_CALL(mkdir)\nPITO_SYSTEM_CALL(mkdirat)\nPITO_SYSTEM_CALL(opendir)\nPITO_SYSTEM_CALL(mknod)\nPITO_SYSTEM_CALL(mknodat)\n\/\/ function todo: __xmknod\nPITO_SYSTEM_CALL(mkfifo)\nPITO_SYSTEM_CALL(mkfifoat)\nPITO_SYSTEM_CALL(access)\nPITO_SYSTEM_CALL(faccessat)\nPITO_SYSTEM_CALL(rename)\nPITO_SYSTEM_CALL(renameat)\nPITO_SYSTEM_CALL(rmdir)\nPITO_SYSTEM_CALL(symlink)\nPITO_SYSTEM_CALL(symlinkat)\nPITO_SYSTEM_CALL(truncate)\nPITO_SYSTEM_CALL(unlink)\nPITO_SYSTEM_CALL(unlinkat)\nPITO_SYSTEM_CALL(getcwd)\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int open64(const char *pathname, int flags, ...) {\n if (flags & O_CREAT) {\n va_list ap;\n va_start(ap, flags);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(open64)(pathname, flags, mode);\n }\n else return PITO_SUPER(open64)(pathname, flags);\n }\n}\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int openat64(RBUTIL_ARGS_3(SystemCall::arg_types), ...) {\n if (arg2 & O_CREAT) {\n va_list ap;\n va_start(ap, arg2);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(openat64)(arg0, arg1, arg2, mode);\n }\n else return PITO_SUPER(openat64)(arg0, arg1, arg2);\n }\n}\n\nPITO_SYSTEM_CALL(creat64)\nPITO_SYSTEM_CALL(fopen64)\nPITO_SYSTEM_CALL(truncate64)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ jail\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPITO_SYSTEM_CALL_WITH_BASE(execve, PITO_JAIL_BASE)\nPITO_SYSTEM_CALL_WITH_BASE(execv, PITO_JAIL_BASE)\nPITO_SYSTEM_CALL_WITH_BASE(execvp, PITO_JAIL_BASE)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ end jail\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPITO_SYSTEM_CALL(utime)\nPITO_SYSTEM_CALL(utimes)\nPITO_SYSTEM_CALL(utimensat)\nPITO_SYSTEM_CALL(futimesat)\nPITO_SYSTEM_CALL(lutimes)\nPITO_SYSTEM_CALL(getuid)\n\n} }\n\n#endif\nremove some code innit#ifndef _PITO_INTERCEPTOR_LIB_C_\n#define _PITO_INTERCEPTOR_LIB_C_\n\n#include \n#include \n\n#include \n#include \n#include \n\n#ifndef PITO_SYSTEM_CALL_BASE\n#define PITO_SYSTEM_CALL_BASE SystemCallBase\n#endif\n\n#ifndef PITO_JAIL_BASE\n#define PITO_JAIL_BASE PITO_SYSTEM_CALL_BASE\n#endif\n\nnamespace pito { namespace interceptor {\n\nusing namespace system_call;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ security intercepts\nPITO_SYSTEM_CALL(chmod)\nPITO_SYSTEM_CALL(fchmod)\nPITO_SYSTEM_CALL(fchmodat)\nPITO_SYSTEM_CALL(chown)\nPITO_SYSTEM_CALL(fchown)\nPITO_SYSTEM_CALL(fchownat)\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int open(PITO_ARGS(open), ...) {\n if (arg1 & O_CREAT) {\n va_list ap;\n va_start(ap, arg1);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(open)(arg0, arg1, mode);\n }\n else return PITO_SUPER(open)(arg0, arg1);\n }\n}\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int openat(PITO_ARGS(openat), ...) {\n if (arg2 & O_CREAT) {\n va_list ap;\n va_start(ap, arg2);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(openat)(arg0, arg1, arg2, mode);\n }\n else return PITO_SUPER(openat)(arg0, arg1, arg2);\n }\n}\n\nPITO_SYSTEM_CALL(creat)\nPITO_SYSTEM_CALL(fopen)\nPITO_SYSTEM_CALL(lchown)\nPITO_SYSTEM_CALL(link)\nPITO_SYSTEM_CALL(linkat)\nPITO_SYSTEM_CALL(mkdir)\nPITO_SYSTEM_CALL(mkdirat)\nPITO_SYSTEM_CALL(opendir)\nPITO_SYSTEM_CALL(mknod)\nPITO_SYSTEM_CALL(mknodat)\n\/\/ function todo: __xmknod\nPITO_SYSTEM_CALL(mkfifo)\nPITO_SYSTEM_CALL(mkfifoat)\nPITO_SYSTEM_CALL(access)\nPITO_SYSTEM_CALL(faccessat)\nPITO_SYSTEM_CALL(rename)\nPITO_SYSTEM_CALL(renameat)\nPITO_SYSTEM_CALL(rmdir)\nPITO_SYSTEM_CALL(symlink)\nPITO_SYSTEM_CALL(symlinkat)\nPITO_SYSTEM_CALL(truncate)\nPITO_SYSTEM_CALL(unlink)\nPITO_SYSTEM_CALL(unlinkat)\nPITO_SYSTEM_CALL(getcwd)\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int open64(PITO_ARGS(open64), ...) {\n if (arg1 & O_CREAT) {\n va_list ap;\n va_start(ap, arg1);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(open64)(arg0, arg1, mode);\n }\n else return PITO_SUPER(open64)(arg0, arg1);\n }\n}\n\ntemplate <>\nstruct SystemCall\n : PITO_SYSTEM_CALL_BASE {};\n\nextern \"C\" {\n int openat64(PITO_ARGS(openat64), ...) {\n if (arg2 & O_CREAT) {\n va_list ap;\n va_start(ap, arg2);\n mode_t mode = va_arg(ap, int);\n va_end(ap);\n return PITO_SUPER(openat64)(arg0, arg1, arg2, mode);\n }\n else return PITO_SUPER(openat64)(arg0, arg1, arg2);\n }\n}\n\nPITO_SYSTEM_CALL(creat64)\nPITO_SYSTEM_CALL(fopen64)\nPITO_SYSTEM_CALL(truncate64)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ jail\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPITO_SYSTEM_CALL_WITH_BASE(execve, PITO_JAIL_BASE)\nPITO_SYSTEM_CALL_WITH_BASE(execv, PITO_JAIL_BASE)\nPITO_SYSTEM_CALL_WITH_BASE(execvp, PITO_JAIL_BASE)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ end jail\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nPITO_SYSTEM_CALL(utime)\nPITO_SYSTEM_CALL(utimes)\nPITO_SYSTEM_CALL(utimensat)\nPITO_SYSTEM_CALL(futimesat)\nPITO_SYSTEM_CALL(lutimes)\nPITO_SYSTEM_CALL(getuid)\n\n} }\n\n#endif\n<|endoftext|>"} {"text":"\/* Copyright (C) 2003 MySQL AB\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\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct Parameter {\n char * name;\n unsigned value;\n unsigned min;\n unsigned max; \n};\n\n#define P_BATCH 0\n#define P_PARRA 1\n#define P_LOCK 2\n#define P_FILT 3\n#define P_BOUND 4\n#define P_ACCESS 5\n#define P_FETCH 6\n#define P_ROWS 7\n#define P_LOOPS 8\n#define P_CREATE 9\n#define P_LOAD 10\n#define P_RESET 11\n\n#define P_MAX 12\n\nstatic \nParameter \ng_paramters[] = {\n { \"batch\", 0, 0, 1 }, \/\/ 0, 15\n { \"parallelism\", 0, 0, 1 }, \/\/ 0, 1\n { \"lock\", 0, 0, 2 }, \/\/ read, exclusive, dirty\n { \"filter\", 0, 0, 3 }, \/\/ all, none, 1, 100\n { \"range\", 0, 0, 3 }, \/\/ all, none, 1, 100\n { \"access\", 0, 0, 2 }, \/\/ scan, idx, idx sorted\n { \"fetch\", 0, 0, 1 }, \/\/ No, yes\n { \"size\", 1000000, 1, ~0 },\n { \"iterations\", 3, 1, ~0 },\n { \"create_drop\", 1, 0, 1 },\n { \"data\", 1, 0, 1 },\n { \"q-reset bounds\", 0, 1, 0 }\n};\n\nstatic Ndb* g_ndb = 0;\nstatic const NdbDictionary::Table * g_table;\nstatic const NdbDictionary::Index * g_index;\nstatic char g_tablename[256];\nstatic char g_indexname[256];\n\nint create_table();\nint load_table();\nint run_scan();\nint clear_table();\nint drop_table();\n\nint\nmain(int argc, const char** argv){\n ndb_init();\n int verbose = 1;\n int optind = 0;\n\n struct getargs args[1+P_MAX] = {\n { \"verbose\", 'v', arg_flag, &verbose, \"Print verbose status\", \"verbose\" }\n };\n const int num_args = 1 + P_MAX;\n int i;\n for(i = 0; iinit() != 0){\n g_err << \"init() failed\" << endl;\n goto error;\n }\n if(g_ndb->waitUntilReady() != 0){\n g_err << \"Wait until ready failed\" << endl;\n goto error;\n }\n for(i = optind; igetDictionary();\n assert(dict);\n if(g_paramters[P_CREATE].value){\n const NdbDictionary::Table * pTab = NDBT_Tables::getTable(g_tablename);\n assert(pTab);\n NdbDictionary::Table copy = * pTab;\n copy.setLogging(false);\n if(dict->createTable(copy) != 0){\n g_err << \"Failed to create table: \" << g_tablename << endl;\n return -1;\n }\n\n NdbDictionary::Index x(g_indexname);\n x.setTable(g_tablename);\n x.setType(NdbDictionary::Index::OrderedIndex);\n x.setLogging(false);\n for (unsigned k = 0; k < copy.getNoOfColumns(); k++){\n if(copy.getColumn(k)->getPrimaryKey()){\n\tx.addColumnName(copy.getColumn(k)->getName());\n }\n }\n\n if(dict->createIndex(x) != 0){\n g_err << \"Failed to create index: \" << endl;\n return -1;\n }\n }\n g_table = dict->getTable(g_tablename);\n g_index = dict->getIndex(g_indexname, g_tablename);\n assert(g_table);\n assert(g_index);\n return 0;\n}\n\nint\ndrop_table(){\n if(!g_paramters[P_CREATE].value)\n return 0;\n if(g_ndb->getDictionary()->dropTable(g_table->getName()) != 0){\n g_err << \"Failed to drop table: \" << g_table->getName() << endl;\n return -1;\n }\n g_table = 0;\n return 0;\n}\n\nint\nload_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n \n int rows = g_paramters[P_ROWS].value;\n HugoTransactions hugoTrans(* g_table);\n if (hugoTrans.loadTable(g_ndb, rows)){\n g_err.println(\"Failed to load %s with %d rows\", g_table->getName(), rows);\n return -1;\n }\n return 0;\n}\n\nint\nclear_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n int rows = g_paramters[P_ROWS].value;\n \n UtilTransactions utilTrans(* g_table);\n if (utilTrans.clearTable(g_ndb, rows) != 0){\n g_err.println(\"Failed to clear table %s\", g_table->getName());\n return -1;\n }\n return 0;\n}\n\ninline \nvoid err(NdbError e){\n ndbout << e << endl;\n}\n\nint\nrun_scan(){\n int iter = g_paramters[P_LOOPS].value;\n NDB_TICKS start1, stop;\n int sum_time= 0;\n\n int sample_rows = 0;\n NDB_TICKS sample_start = NdbTick_CurrentMillisecond();\n\n Uint32 tot = g_paramters[P_ROWS].value;\n\n if(g_paramters[P_BOUND].value == 2 || g_paramters[P_FILT].value == 2)\n iter *= g_paramters[P_ROWS].value;\n\n NdbScanOperation * pOp = 0;\n NdbIndexScanOperation * pIOp = 0;\n NdbConnection * pTrans = 0;\n NdbResultSet * rs = 0;\n int check = 0;\n\n for(int i = 0; istartTransaction();\n if(!pTrans){\n g_err << \"Failed to start transaction\" << endl;\n err(g_ndb->getNdbError());\n return -1;\n }\n \n int par = g_paramters[P_PARRA].value;\n int bat = g_paramters[P_BATCH].value;\n NdbScanOperation::LockMode lm;\n switch(g_paramters[P_LOCK].value){\n case 0:\n lm = NdbScanOperation::LM_CommittedRead;\n break;\n case 1:\n lm = NdbScanOperation::LM_Read;\n break;\n case 2:\n lm = NdbScanOperation::LM_Exclusive;\n break;\n default:\n abort();\n }\n\n if(g_paramters[P_ACCESS].value == 0){\n pOp = pTrans->getNdbScanOperation(g_tablename);\n assert(pOp);\n rs = pOp->readTuples(lm, bat, par);\n } else {\n if(g_paramters[P_RESET].value == 0 || pIOp == 0)\n {\n\tpOp= pIOp= pTrans->getNdbIndexScanOperation(g_indexname, g_tablename);\n\tbool ord = g_paramters[P_ACCESS].value == 2;\n\trs = pIOp->readTuples(lm, bat, par, ord);\n }\n else\n {\n\tpIOp->reset_bounds();\n }\n\n switch(g_paramters[P_BOUND].value){\n case 0: \/\/ All\n\tbreak;\n case 1: \/\/ None\n\tpIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, 0);\n\tbreak;\n case 2: { \/\/ 1 row\n default: \n\tassert(g_table->getNoOfPrimaryKeys() == 1); \/\/ only impl. so far\n\tint tot = g_paramters[P_ROWS].value;\n\tint row = rand() % tot;\n#if 0\n\tfix_eq_bound(pIOp, row);\n#else\n\tpIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, &row);\n#endif\n\tbreak;\n }\n }\n if(g_paramters[P_RESET].value == 1)\n\tgoto execute;\n }\n assert(pOp);\n assert(rs);\n \n switch(g_paramters[P_FILT].value){\n case 0: \/\/ All\n check = pOp->interpret_exit_ok();\n break;\n case 1: \/\/ None\n check = pOp->interpret_exit_nok();\n break;\n case 2: { \/\/ 1 row\n default: \n assert(g_table->getNoOfPrimaryKeys() == 1); \/\/ only impl. so far\n abort();\n#if 0\n int tot = g_paramters[P_ROWS].value;\n int row = rand() % tot;\n NdbScanFilter filter(pOp) ; \n filter.begin(NdbScanFilter::AND);\n fix_eq(filter, pOp, row);\n filter.end();\n break;\n#endif\n }\n }\n if(check != 0){\n err(pOp->getNdbError());\n return -1;\n }\n assert(check == 0);\n\n for(int i = 0; igetNoOfColumns(); i++){\n pOp->getValue(i);\n }\nexecute:\n int rows = 0;\n check = pTrans->execute(NoCommit);\n assert(check == 0);\n int fetch = g_paramters[P_FETCH].value;\n while((check = rs->nextResult(true)) == 0){\n do {\n\trows++;\n } while(!fetch && ((check = rs->nextResult(false)) == 0));\n if(check == -1){\n err(pTrans->getNdbError());\n return -1;\n }\n assert(check == 2);\n }\n\n if(check == -1){\n err(pTrans->getNdbError());\n return -1;\n }\n assert(check == 1);\n if(g_paramters[P_RESET].value == 0)\n {\n pTrans->close();\n pTrans = 0;\n }\n stop = NdbTick_CurrentMillisecond();\n \n int time_passed= (int)(stop - start1);\n sample_rows += rows;\n sum_time+= time_passed;\n \n if(sample_rows >= tot)\n {\n int sample_time = (int)(stop - sample_start);\n g_info << \"Found \" << sample_rows << \" rows\" << endl;\n g_err.println(\"Time: %d ms = %u rows\/sec\", sample_time,\n\t\t (1000*sample_rows)\/sample_time);\n sample_rows = 0;\n sample_start = stop;\n }\n }\n\n g_err.println(\"Avg time: %d ms = %u rows\/sec\", sum_time\/iter,\n (1000*tot*iter)\/sum_time);\n return 0;\n}\nndb - bugfix testScanPerf\/* Copyright (C) 2003 MySQL AB\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\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct Parameter {\n char * name;\n unsigned value;\n unsigned min;\n unsigned max; \n};\n\n#define P_BATCH 0\n#define P_PARRA 1\n#define P_LOCK 2\n#define P_FILT 3\n#define P_BOUND 4\n#define P_ACCESS 5\n#define P_FETCH 6\n#define P_ROWS 7\n#define P_LOOPS 8\n#define P_CREATE 9\n#define P_LOAD 10\n#define P_RESET 11\n\n#define P_MAX 12\n\nstatic \nParameter \ng_paramters[] = {\n { \"batch\", 0, 0, 1 }, \/\/ 0, 15\n { \"parallelism\", 0, 0, 1 }, \/\/ 0, 1\n { \"lock\", 0, 0, 2 }, \/\/ read, exclusive, dirty\n { \"filter\", 0, 0, 3 }, \/\/ all, none, 1, 100\n { \"range\", 0, 0, 3 }, \/\/ all, none, 1, 100\n { \"access\", 0, 0, 2 }, \/\/ scan, idx, idx sorted\n { \"fetch\", 0, 0, 1 }, \/\/ No, yes\n { \"size\", 1000000, 1, ~0 },\n { \"iterations\", 3, 1, ~0 },\n { \"create_drop\", 1, 0, 1 },\n { \"data\", 1, 0, 1 },\n { \"q-reset bounds\", 0, 1, 0 }\n};\n\nstatic Ndb* g_ndb = 0;\nstatic const NdbDictionary::Table * g_table;\nstatic const NdbDictionary::Index * g_index;\nstatic char g_tablename[256];\nstatic char g_indexname[256];\n\nint create_table();\nint load_table();\nint run_scan();\nint clear_table();\nint drop_table();\n\nint\nmain(int argc, const char** argv){\n ndb_init();\n int verbose = 1;\n int optind = 0;\n\n struct getargs args[1+P_MAX] = {\n { \"verbose\", 'v', arg_flag, &verbose, \"Print verbose status\", \"verbose\" }\n };\n const int num_args = 1 + P_MAX;\n int i;\n for(i = 0; iinit() != 0){\n g_err << \"init() failed\" << endl;\n goto error;\n }\n if(g_ndb->waitUntilReady() != 0){\n g_err << \"Wait until ready failed\" << endl;\n goto error;\n }\n for(i = optind; igetDictionary();\n assert(dict);\n if(g_paramters[P_CREATE].value){\n const NdbDictionary::Table * pTab = NDBT_Tables::getTable(g_tablename);\n assert(pTab);\n NdbDictionary::Table copy = * pTab;\n copy.setLogging(false);\n if(dict->createTable(copy) != 0){\n g_err << \"Failed to create table: \" << g_tablename << endl;\n return -1;\n }\n\n NdbDictionary::Index x(g_indexname);\n x.setTable(g_tablename);\n x.setType(NdbDictionary::Index::OrderedIndex);\n x.setLogging(false);\n for (unsigned k = 0; k < copy.getNoOfColumns(); k++){\n if(copy.getColumn(k)->getPrimaryKey()){\n\tx.addColumnName(copy.getColumn(k)->getName());\n }\n }\n\n if(dict->createIndex(x) != 0){\n g_err << \"Failed to create index: \" << endl;\n return -1;\n }\n }\n g_table = dict->getTable(g_tablename);\n g_index = dict->getIndex(g_indexname, g_tablename);\n assert(g_table);\n assert(g_index);\n return 0;\n}\n\nint\ndrop_table(){\n if(!g_paramters[P_CREATE].value)\n return 0;\n if(g_ndb->getDictionary()->dropTable(g_table->getName()) != 0){\n g_err << \"Failed to drop table: \" << g_table->getName() << endl;\n return -1;\n }\n g_table = 0;\n return 0;\n}\n\nint\nload_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n \n int rows = g_paramters[P_ROWS].value;\n HugoTransactions hugoTrans(* g_table);\n if (hugoTrans.loadTable(g_ndb, rows)){\n g_err.println(\"Failed to load %s with %d rows\", g_table->getName(), rows);\n return -1;\n }\n return 0;\n}\n\nint\nclear_table(){\n if(!g_paramters[P_LOAD].value)\n return 0;\n int rows = g_paramters[P_ROWS].value;\n \n UtilTransactions utilTrans(* g_table);\n if (utilTrans.clearTable(g_ndb, rows) != 0){\n g_err.println(\"Failed to clear table %s\", g_table->getName());\n return -1;\n }\n return 0;\n}\n\ninline \nvoid err(NdbError e){\n ndbout << e << endl;\n}\n\nint\nrun_scan(){\n int iter = g_paramters[P_LOOPS].value;\n NDB_TICKS start1, stop;\n int sum_time= 0;\n\n int sample_rows = 0;\n int tot_rows = 0;\n NDB_TICKS sample_start = NdbTick_CurrentMillisecond();\n\n Uint32 tot = g_paramters[P_ROWS].value;\n\n if(g_paramters[P_BOUND].value == 2 || g_paramters[P_FILT].value == 2)\n iter *= g_paramters[P_ROWS].value;\n\n NdbScanOperation * pOp = 0;\n NdbIndexScanOperation * pIOp = 0;\n NdbConnection * pTrans = 0;\n NdbResultSet * rs = 0;\n int check = 0;\n\n for(int i = 0; istartTransaction();\n if(!pTrans){\n g_err << \"Failed to start transaction\" << endl;\n err(g_ndb->getNdbError());\n return -1;\n }\n \n int par = g_paramters[P_PARRA].value;\n int bat = g_paramters[P_BATCH].value;\n NdbScanOperation::LockMode lm;\n switch(g_paramters[P_LOCK].value){\n case 0:\n lm = NdbScanOperation::LM_CommittedRead;\n break;\n case 1:\n lm = NdbScanOperation::LM_Read;\n break;\n case 2:\n lm = NdbScanOperation::LM_Exclusive;\n break;\n default:\n abort();\n }\n\n if(g_paramters[P_ACCESS].value == 0){\n pOp = pTrans->getNdbScanOperation(g_tablename);\n assert(pOp);\n rs = pOp->readTuples(lm, bat, par);\n } else {\n if(g_paramters[P_RESET].value == 0 || pIOp == 0)\n {\n\tpOp= pIOp= pTrans->getNdbIndexScanOperation(g_indexname, g_tablename);\n\tbool ord = g_paramters[P_ACCESS].value == 2;\n\trs = pIOp->readTuples(lm, bat, par, ord);\n }\n else\n {\n\tpIOp->reset_bounds();\n }\n\n switch(g_paramters[P_BOUND].value){\n case 0: \/\/ All\n\tbreak;\n case 1: \/\/ None\n\tpIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, 0);\n\tbreak;\n case 2: { \/\/ 1 row\n default: \n\tassert(g_table->getNoOfPrimaryKeys() == 1); \/\/ only impl. so far\n\tint tot = g_paramters[P_ROWS].value;\n\tint row = rand() % tot;\n#if 0\n\tfix_eq_bound(pIOp, row);\n#else\n\tpIOp->setBound((Uint32)0, NdbIndexScanOperation::BoundEQ, &row);\n#endif\n\tbreak;\n }\n }\n if(g_paramters[P_RESET].value == 2)\n\tgoto execute;\n }\n assert(pOp);\n assert(rs);\n \n switch(g_paramters[P_FILT].value){\n case 0: \/\/ All\n check = pOp->interpret_exit_ok();\n break;\n case 1: \/\/ None\n check = pOp->interpret_exit_nok();\n break;\n case 2: { \/\/ 1 row\n default: \n assert(g_table->getNoOfPrimaryKeys() == 1); \/\/ only impl. so far\n abort();\n#if 0\n int tot = g_paramters[P_ROWS].value;\n int row = rand() % tot;\n NdbScanFilter filter(pOp) ; \n filter.begin(NdbScanFilter::AND);\n fix_eq(filter, pOp, row);\n filter.end();\n break;\n#endif\n }\n }\n if(check != 0){\n err(pOp->getNdbError());\n return -1;\n }\n assert(check == 0);\n\n if(g_paramters[P_RESET].value == 1)\n g_paramters[P_RESET].value = 2;\n \n for(int i = 0; igetNoOfColumns(); i++){\n pOp->getValue(i);\n }\nexecute:\n int rows = 0;\n check = pTrans->execute(NoCommit);\n assert(check == 0);\n int fetch = g_paramters[P_FETCH].value;\n while((check = rs->nextResult(true)) == 0){\n do {\n\trows++;\n } while(!fetch && ((check = rs->nextResult(false)) == 0));\n if(check == -1){\n err(pTrans->getNdbError());\n return -1;\n }\n assert(check == 2);\n }\n\n if(check == -1){\n err(pTrans->getNdbError());\n return -1;\n }\n assert(check == 1);\n if(g_paramters[P_RESET].value == 0)\n {\n pTrans->close();\n pTrans = 0;\n }\n stop = NdbTick_CurrentMillisecond();\n \n int time_passed= (int)(stop - start1);\n sample_rows += rows;\n sum_time+= time_passed;\n tot_rows+= rows;\n \n if(sample_rows >= tot)\n {\n int sample_time = (int)(stop - sample_start);\n g_info << \"Found \" << sample_rows << \" rows\" << endl;\n g_err.println(\"Time: %d ms = %u rows\/sec\", sample_time,\n\t\t (1000*sample_rows)\/sample_time);\n sample_rows = 0;\n sample_start = stop;\n }\n }\n \n g_err.println(\"Avg time: %d ms = %u rows\/sec\", sum_time\/tot_rows,\n (1000*tot_rows)\/sum_time);\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ File: GameDQNBridge.cpp\n\/\/ Description: Implement the bridge class between game and DQN\n\/\/ Date: 2015-07-04\n\/\/ License: Apache\n\/\/ Feel free to contact me if there's any questions\n\/\/\n\n#include \"GameDQNBridge.h\"\n#include \"defaults.h\"\n\n#include \n#include \n#include \n#include \n\nGameDQNBridge::GameDQNBridge(ALEInterface& ale, qlearning::DQN& dqn, const bool update)\n : ale_(ale), dqn_(dqn), update_(update) {}\n\ndouble GameDQNBridge::play(double epsilon) {\n\tqlearning::ALE ale;\n std::deque past;\n double total = 0.0;\n for (int frame = 0; !ale_.game_over(); frame++) {\n const auto current = ale.PreprocessScreen(ale_.getScreen());\n past.push_back(current);\n if (past.size() < qlearning::ICount) {\n for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) {\n total += ale_.act(PLAYER_A_NOOP);\n }\n } else {\n if (past.size() > qlearning::ICount) {\n past.pop_front();\n }\n qlearning::IFrames input;\n std::copy(past.begin(), past.end(), input.begin());\n const Action action = dqn_.SelectAction(input, epsilon);\n double recent = 0.0;\n for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) {\n recent += ale_.act(action);\n }\n total += recent;\n const double reward = (recent == 0 ? 0 : recent \/= std::abs(recent));\n if (update_) {\n const auto trans = ale_.game_over() ? qlearning::Trans(input, action, reward, boost::none) : qlearning::Trans(input, action, reward, ale.PreprocessScreen(ale_.getScreen()));\n dqn_.AddTrans(trans);\n if (dqn_.get_size() > memory_threshold) {\n dqn_.Update();\n }\n }\n }\n }\n ale_.reset_game();\n return total;\n}\nAdd comments\/\/ File: GameDQNBridge.cpp\n\/\/ Description: Implement the bridge class between game and DQN\n\/\/ Date: 2015-07-04\n\/\/ License: Apache\n\/\/ Feel free to contact me if there's any questions\n\/\/\n\n#include \"GameDQNBridge.h\"\n#include \"defaults.h\"\n\n#include \n#include \n#include \n#include \n\nGameDQNBridge::GameDQNBridge(ALEInterface& ale, qlearning::DQN& dqn, const bool update)\n : ale_(ale), dqn_(dqn), update_(update) {}\n\ndouble GameDQNBridge::play(double epsilon) {\n\tqlearning::ALE ale;\n std::deque past;\t\t\/\/frame sequence\n double total = 0.0;\n for (int frame = 0; !ale_.game_over(); frame++) {\n const auto current = ale.PreprocessScreen(ale_.getScreen());\n past.push_back(current);\n \/\/fill frame sequence\n if (past.size() < qlearning::ICount) {\n for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) {\n total += ale_.act(PLAYER_A_NOOP);\n }\n } else {\n\t\t\t\/\/pop history frame\n if (past.size() > qlearning::ICount) {\n past.pop_front();\n }\n qlearning::IFrames input;\n std::copy(past.begin(), past.end(), input.begin());\n \/\/get action\n const Action action = dqn_.SelectAction(input, epsilon);\n \/\/get recent score\n double recent = 0.0;\n for (int i = 0; i < skip_frame + 1 && !ale_.game_over(); i++) {\n recent += ale_.act(action);\n }\n total += recent;\n const double reward = (recent == 0 ? 0 : recent \/= std::abs(recent));\n \/\/update solver\n if (update_) {\n const auto trans = ale_.game_over() ? qlearning::Trans(input, action, reward, boost::none) : qlearning::Trans(input, action, reward, ale.PreprocessScreen(ale_.getScreen()));\n dqn_.AddTrans(trans);\n if (dqn_.get_size() > memory_threshold) {\n dqn_.Update();\n }\n }\n }\n }\n ale_.reset_game();\n return total;\n}\n<|endoftext|>"} {"text":"#include \"engine\/fs\/file_system.h\"\n#include \"engine\/fs\/memory_file_device.h\"\n#include \"engine\/iallocator.h\"\n#include \"engine\/math_utils.h\"\n#include \"engine\/string.h\"\n\n\nnamespace Lumix\n{\n\tnamespace FS\n\t{\n\t\tclass LUMIX_ENGINE_API MemoryFile final : public IFile\n\t\t{\n\t\tpublic:\n\t\t\tMemoryFile(IFile* file, MemoryFileDevice& device, IAllocator& allocator)\n\t\t\t\t: m_device(device)\n\t\t\t\t, m_buffer(nullptr)\n\t\t\t\t, m_size(0)\n\t\t\t\t, m_capacity(0)\n\t\t\t\t, m_pos(0)\n\t\t\t\t, m_file(file) \n\t\t\t\t, m_write(false)\n\t\t\t\t, m_allocator(allocator)\n\t\t\t{\n\t\t\t}\n\n\t\t\t~MemoryFile() \n\t\t\t{ \n\t\t\t\tif (m_file)\n\t\t\t\t{\n\t\t\t\t\tm_file->release();\n\t\t\t\t}\n\t\t\t\tm_allocator.deallocate(m_buffer);\n\t\t\t}\n\n\n\t\t\tIFileDevice& getDevice() override\n\t\t\t{\n\t\t\t\treturn m_device;\n\t\t\t}\n\n\t\t\tbool open(const Path& path, Mode mode) override\n\t\t\t{\n\t\t\t\tASSERT(!m_buffer); \/\/ reopen is not supported currently\n\n\t\t\t\tm_write = !!(mode & Mode::WRITE);\n\t\t\t\tif(m_file)\n\t\t\t\t{\n\t\t\t\t\tif(m_file->open(path, mode))\n\t\t\t\t\t{\n\t\t\t\t\t\tif(mode & Mode::READ)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_capacity = m_size = m_file->size();\n\t\t\t\t\t\t\tm_buffer = (u8*)m_allocator.allocate(sizeof(u8) * m_size);\n\t\t\t\t\t\t\tm_file->read(m_buffer, m_size);\n\t\t\t\t\t\t\tm_pos = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(mode & Mode::WRITE)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tvoid close() override\n\t\t\t{\n\t\t\t\tif(m_file)\n\t\t\t\t{\n\t\t\t\t\tif(m_write)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_file->seek(SeekMode::BEGIN, 0);\n\t\t\t\t\t\tm_file->write(m_buffer, m_size);\n\t\t\t\t\t}\n\t\t\t\t\tm_file->close();\n\t\t\t\t}\n\n\t\t\t\tm_allocator.deallocate(m_buffer);\n\t\t\t\tm_buffer = nullptr;\n\t\t\t}\n\n\t\t\tbool read(void* buffer, size_t size) override\n\t\t\t{\n\t\t\t\tsize_t amount = m_pos + size < m_size ? size : m_size - m_pos;\n\t\t\t\tcopyMemory(buffer, m_buffer + m_pos, (int)amount);\n\t\t\t\tm_pos += amount;\n\t\t\t\treturn amount == size;\n\t\t\t}\n\n\t\t\tbool write(const void* buffer, size_t size) override\n\t\t\t{\n\t\t\t\tsize_t pos = m_pos;\n\t\t\t\tsize_t cap = m_capacity;\n\t\t\t\tsize_t sz = m_size;\n\t\t\t\tif(pos + size > cap)\n\t\t\t\t{\n\t\t\t\t\tsize_t new_cap = Math::maximum(cap * 2, pos + size);\n\t\t\t\t\tu8* new_data = (u8*)m_allocator.allocate(sizeof(u8) * new_cap);\n\t\t\t\t\tcopyMemory(new_data, m_buffer, (int)sz);\n\t\t\t\t\tm_allocator.deallocate(m_buffer);\n\t\t\t\t\tm_buffer = new_data;\n\t\t\t\t\tm_capacity = new_cap;\n\t\t\t\t}\n\n\t\t\t\tcopyMemory(m_buffer + pos, buffer, (int)size);\n\t\t\t\tm_pos += size;\n\t\t\t\tm_size = pos + size > sz ? pos + size : sz;\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tconst void* getBuffer() const override\n\t\t\t{\n\t\t\t\treturn m_buffer;\n\t\t\t}\n\n\t\t\tsize_t size() override\n\t\t\t{\n\t\t\t\treturn m_size;\n\t\t\t}\n\n\t\t\tbool seek(SeekMode base, size_t pos) override\n\t\t\t{\n\t\t\t\tswitch(base)\n\t\t\t\t{\n\t\t\t\tcase SeekMode::BEGIN:\n\t\t\t\t\tASSERT(pos <= (i32)m_size);\n\t\t\t\t\tm_pos = pos;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SeekMode::CURRENT:\n\t\t\t\t\tASSERT(0 <= i32(m_pos + pos) && i32(m_pos + pos) <= i32(m_size));\n\t\t\t\t\tm_pos += pos;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SeekMode::END:\n\t\t\t\t\tASSERT(pos <= (i32)m_size);\n\t\t\t\t\tm_pos = m_size - pos;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tASSERT(0);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbool ret = m_pos <= m_size;\n\t\t\t\tm_pos = Math::minimum(m_pos, m_size);\n\t\t\t\treturn ret;\n\t\t\t}\n\n\t\t\tsize_t pos() override\n\t\t\t{\n\t\t\t\treturn m_pos;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tIAllocator& m_allocator;\n\t\t\tMemoryFileDevice& m_device;\n\t\t\tu8* m_buffer;\n\t\t\tsize_t m_size;\n\t\t\tsize_t m_capacity;\n\t\t\tsize_t m_pos;\n\t\t\tIFile* m_file;\n\t\t\tbool m_write;\n\t\t};\n\n\t\tvoid MemoryFileDevice::destroyFile(IFile* file)\n\t\t{\n\t\t\tLUMIX_DELETE(m_allocator, file);\n\t\t}\n\n\t\tIFile* MemoryFileDevice::createFile(IFile* child)\n\t\t{\n\t\t\treturn LUMIX_NEW(m_allocator, MemoryFile)(child, *this, m_allocator);\n\t\t}\n\t} \/\/ namespace FS\n} \/\/ namespace Lumix\nfixed - terrain material fails to load#include \"engine\/fs\/file_system.h\"\n#include \"engine\/fs\/memory_file_device.h\"\n#include \"engine\/iallocator.h\"\n#include \"engine\/math_utils.h\"\n#include \"engine\/string.h\"\n\n\nnamespace Lumix\n{\n\tnamespace FS\n\t{\n\t\tclass LUMIX_ENGINE_API MemoryFile final : public IFile\n\t\t{\n\t\tpublic:\n\t\t\tMemoryFile(IFile* file, MemoryFileDevice& device, IAllocator& allocator)\n\t\t\t\t: m_device(device)\n\t\t\t\t, m_buffer(nullptr)\n\t\t\t\t, m_size(0)\n\t\t\t\t, m_capacity(0)\n\t\t\t\t, m_pos(0)\n\t\t\t\t, m_file(file) \n\t\t\t\t, m_write(false)\n\t\t\t\t, m_allocator(allocator)\n\t\t\t{\n\t\t\t}\n\n\t\t\t~MemoryFile() \n\t\t\t{ \n\t\t\t\tif (m_file)\n\t\t\t\t{\n\t\t\t\t\tm_file->release();\n\t\t\t\t}\n\t\t\t\tm_allocator.deallocate(m_buffer);\n\t\t\t}\n\n\n\t\t\tIFileDevice& getDevice() override\n\t\t\t{\n\t\t\t\treturn m_device;\n\t\t\t}\n\n\t\t\tbool open(const Path& path, Mode mode) override\n\t\t\t{\n\t\t\t\tASSERT(!m_buffer); \/\/ reopen is not supported currently\n\n\t\t\t\tm_write = !!(mode & Mode::WRITE);\n\t\t\t\tif(m_file)\n\t\t\t\t{\n\t\t\t\t\tif(m_file->open(path, mode))\n\t\t\t\t\t{\n\t\t\t\t\t\tif(mode & Mode::READ)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_capacity = m_size = m_file->size();\n\t\t\t\t\t\t\tm_buffer = (u8*)m_allocator.allocate(sizeof(u8) * m_size);\n\t\t\t\t\t\t\tm_file->read(m_buffer, m_size);\n\t\t\t\t\t\t\tm_file->close();\n\t\t\t\t\t\t\tm_pos = 0;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(mode & Mode::WRITE)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tvoid close() override\n\t\t\t{\n\t\t\t\tif(m_file)\n\t\t\t\t{\n\t\t\t\t\tif(m_write)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_file->seek(SeekMode::BEGIN, 0);\n\t\t\t\t\t\tm_file->write(m_buffer, m_size);\n\t\t\t\t\t\tm_file->close();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tm_allocator.deallocate(m_buffer);\n\t\t\t\tm_buffer = nullptr;\n\t\t\t}\n\n\t\t\tbool read(void* buffer, size_t size) override\n\t\t\t{\n\t\t\t\tsize_t amount = m_pos + size < m_size ? size : m_size - m_pos;\n\t\t\t\tcopyMemory(buffer, m_buffer + m_pos, (int)amount);\n\t\t\t\tm_pos += amount;\n\t\t\t\treturn amount == size;\n\t\t\t}\n\n\t\t\tbool write(const void* buffer, size_t size) override\n\t\t\t{\n\t\t\t\tsize_t pos = m_pos;\n\t\t\t\tsize_t cap = m_capacity;\n\t\t\t\tsize_t sz = m_size;\n\t\t\t\tif(pos + size > cap)\n\t\t\t\t{\n\t\t\t\t\tsize_t new_cap = Math::maximum(cap * 2, pos + size);\n\t\t\t\t\tu8* new_data = (u8*)m_allocator.allocate(sizeof(u8) * new_cap);\n\t\t\t\t\tcopyMemory(new_data, m_buffer, (int)sz);\n\t\t\t\t\tm_allocator.deallocate(m_buffer);\n\t\t\t\t\tm_buffer = new_data;\n\t\t\t\t\tm_capacity = new_cap;\n\t\t\t\t}\n\n\t\t\t\tcopyMemory(m_buffer + pos, buffer, (int)size);\n\t\t\t\tm_pos += size;\n\t\t\t\tm_size = pos + size > sz ? pos + size : sz;\n\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tconst void* getBuffer() const override\n\t\t\t{\n\t\t\t\treturn m_buffer;\n\t\t\t}\n\n\t\t\tsize_t size() override\n\t\t\t{\n\t\t\t\treturn m_size;\n\t\t\t}\n\n\t\t\tbool seek(SeekMode base, size_t pos) override\n\t\t\t{\n\t\t\t\tswitch(base)\n\t\t\t\t{\n\t\t\t\tcase SeekMode::BEGIN:\n\t\t\t\t\tASSERT(pos <= (i32)m_size);\n\t\t\t\t\tm_pos = pos;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SeekMode::CURRENT:\n\t\t\t\t\tASSERT(0 <= i32(m_pos + pos) && i32(m_pos + pos) <= i32(m_size));\n\t\t\t\t\tm_pos += pos;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SeekMode::END:\n\t\t\t\t\tASSERT(pos <= (i32)m_size);\n\t\t\t\t\tm_pos = m_size - pos;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tASSERT(0);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tbool ret = m_pos <= m_size;\n\t\t\t\tm_pos = Math::minimum(m_pos, m_size);\n\t\t\t\treturn ret;\n\t\t\t}\n\n\t\t\tsize_t pos() override\n\t\t\t{\n\t\t\t\treturn m_pos;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tIAllocator& m_allocator;\n\t\t\tMemoryFileDevice& m_device;\n\t\t\tu8* m_buffer;\n\t\t\tsize_t m_size;\n\t\t\tsize_t m_capacity;\n\t\t\tsize_t m_pos;\n\t\t\tIFile* m_file;\n\t\t\tbool m_write;\n\t\t};\n\n\t\tvoid MemoryFileDevice::destroyFile(IFile* file)\n\t\t{\n\t\t\tLUMIX_DELETE(m_allocator, file);\n\t\t}\n\n\t\tIFile* MemoryFileDevice::createFile(IFile* child)\n\t\t{\n\t\t\treturn LUMIX_NEW(m_allocator, MemoryFile)(child, *this, m_allocator);\n\t\t}\n\t} \/\/ namespace FS\n} \/\/ namespace Lumix\n<|endoftext|>"} {"text":"#include \"engine\/config\/precompiled.h\"\n\n#if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS)\n#include \"engine\/system\/system.h\"\n\n#include \n\nDEA_START()\n\nstruct window_platform\n{\n\tHWND hwnd;\n\tLPCWSTR name;\n};\n\n\/* Translation unit locals *\/\nnamespace\n{\n\tvoid close_windows(pod_vector &windows, pod_vector &windows_to_close)\n\t{\n\t\tfor (auto window_to_close = windows_to_close.get_begin(); window_to_close != windows_to_close.get_end(); ++window_to_close)\n\t\t{\n\t\t\tfor (auto window = windows.get_begin(); window != windows.get_end(); ++window)\n\t\t\t{\n\t\t\t\tif (*window_to_close == window->wnd->hwnd)\n\t\t\t\t{\n\t\t\t\t\tdestroy_window(*window, false);\n\t\t\t\t\twindows.remove_it(window);\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twindows_to_close.clear();\n\t}\n}\n\npod_vector *windows_to_close = NULL;\n\nvoid init_system_data()\n{\n\t\/* TODO: Memory manager *\/\n\twindows_to_close = new pod_vector(1);\n}\n\nvoid destroy_system_data()\n{\n\t\/* TODO: Memory manager *\/\n\tif (windows_to_close)\n\t\tdelete windows_to_close;\n}\n\nvoid error_popup(const char *msg, const bool kill_program)\n{\n\tdea_assert(msg && \"error_popup: msg is NULL\");\n\n\tMessageBoxA(NULL, msg, kill_program ? \"Fatal Error\" : \"Error\", MB_OK | MB_ICONERROR);\n\tif (kill_program)\n\t\tExitProcess(~(UINT)0);\n}\n\nLRESULT CALLBACK wnd_proc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam)\n{\n\t\/* Unused parametres, can't get rid of these *\/\n\t(void *)hwnd;\n\t(void *)wparam;\n\t(void *)lparam;\n\n\tswitch (umessage)\n\t{\n\t\tcase WM_DESTROY:\n\t\t{\n\t\t\t\/* We don't want to do anything as we manually destroy windows *\/\n\t\t\treturn 0;\n\t\t}\n\t\tcase WM_CLOSE:\n\t\t{\n\t\t\tif (windows_to_close)\n\t\t\t{\n\t\t\t\twindows_to_close->push_back(hwnd);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/* TODO: Localization\/Error number *\/\n\t\t\t\terror_popup(\"Error closing a window\", false);\n\t\t\t}\n\t\t\t\n\t\t\treturn 0;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\treturn DefWindowProc(hwnd, umessage, wparam, lparam);\n\t\t}\n\t}\n}\n\nvoid create_window(const uint width, const uint height, const float pos_x, const float pos_y, const wchar_t *name, const bool fullscreen, window &out_wnd)\n{\n\tint position_x = 0;\n\tint position_y = 0;\n\n\tHINSTANCE hinstance = GetModuleHandle(NULL);\n\n\t\/* TODO: Memory manager *\/\n\tout_wnd.wnd = new window_platform;\n\tout_wnd.wnd->hwnd = NULL;\n\tout_wnd.wnd->name = name;\n\tout_wnd.width = width;\n\tout_wnd.height = height;\n\n\t\/* Setup the windows class with default settings *\/\n\tWNDCLASSEX wc;\n\tmemset(&wc, 0, sizeof(wc));\n\twc.cbSize = sizeof(wc);\n\twc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;\n\twc.lpfnWndProc = wnd_proc;\n\twc.cbClsExtra = 0;\n\twc.cbWndExtra = 0;\n\twc.hInstance = hinstance;\n\twc.hIcon = LoadIcon(NULL, IDI_WINLOGO);\n\twc.hIconSm = wc.hIcon;\n\twc.hCursor = LoadCursor(NULL, IDC_ARROW);\n\twc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);\n\twc.lpszMenuName = NULL;\n\twc.lpszClassName = name;\n\n\t\/\/ Register the window class.\n\tif (RegisterClassEx(&wc) == 0)\n\t{\n\t\t\/* TODO: Localization\/Error number *\/\n\t\terror_popup(\"Failed to register window class\", true);\n\t}\n\n\tif (!fullscreen)\n\t{\n\t\tposition_x = (int)((GetSystemMetrics(SM_CXSCREEN) - width) * pos_x);\n\t\tposition_y = (int)((GetSystemMetrics(SM_CYSCREEN) - height) * pos_y);\n\t}\n\telse\n\t{\n\t\tDEVMODE screen_settings;\n\t\tmemset(&screen_settings, 0, sizeof(screen_settings));\n\t\tscreen_settings.dmSize = sizeof(screen_settings);\n\t\tscreen_settings.dmPelsHeight = (unsigned long)height;\n\t\tscreen_settings.dmPelsWidth = (unsigned long)width;\n\t\tscreen_settings.dmBitsPerPel = 32;\n\t\tscreen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;\n\n\t\tChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN);\n\t}\n\n\tDWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;\n\tDWORD exStyle = 0;\n\n\t\/\/ Create the window with the screen settings and get the handle to it.\n\tout_wnd.wnd->hwnd = CreateWindowEx(exStyle,\n\t name,\n\t name,\n\t style,\n\t position_x, position_y, \n\t (int)width, (int)height, \n\t NULL, \n\t NULL, \n\t hinstance, \n\t NULL);\n\n\tif (out_wnd.wnd->hwnd == NULL)\n\t{\n\t\t\/* TODO: Localization\/Error number *\/\n\t\terror_popup(\"Failed to create a window\", true);\n\t}\n\n\tShowWindow(out_wnd.wnd->hwnd, SW_SHOW);\n}\n\nvoid destroy_window(window &wnd, const bool fullscreen)\n{\n\tdea_assert(wnd.wnd && \"destroy_window: Platform specific window pointer is NULL\");\n\n\tif (fullscreen)\n\t{\n\t\tChangeDisplaySettings(NULL, 0);\n\t}\n\n\tDestroyWindow(wnd.wnd->hwnd);\n\twnd.wnd->hwnd = NULL;\n\n\tHINSTANCE hinstance = GetModuleHandle(NULL);\n\tUnregisterClass(wnd.wnd->name, hinstance);\n\thinstance = NULL;\n\n\t\/* TODO: Memory manager *\/\n\tdelete wnd.wnd;\n}\n\nvoid focus_window(window &wnd)\n{\n\tdea_assert(wnd.wnd && wnd.wnd->hwnd);\n\tSetForegroundWindow(wnd.wnd->hwnd);\n\tSetFocus(wnd.wnd->hwnd);\n}\n\nvoid run(pod_vector &windows)\n{\n\tMSG msg;\n\tZeroMemory(&msg, sizeof(MSG));\n\n\tbool running = true;\n\twhile (running)\n\t{\n\t\tif (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))\n\t\t{\n\t\t\tTranslateMessage(&msg);\n\t\t\tDispatchMessage(&msg);\n\t\t}\n\n\t\tif (msg.message == WM_QUIT)\n\t\t{\n\t\t\trunning = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (windows_to_close && !windows_to_close->empty())\n\t\t\t{\n\t\t\t\tclose_windows(windows, *windows_to_close);\n\n\t\t\t\tif (windows.empty())\n\t\t\t\t\trunning = false;\n\t\t\t}\n\n\t\t\t\/* Run frame *\/\t\n\t\t}\n\t}\n}\n\nDEA_END()\n\n#endif \/\/ DEA_PLATFORM == DEA_PLATFORM_WINDOWSSystem: Just a bit of re-organizing.#include \"engine\/config\/precompiled.h\"\n\n#if (DEA_PLATFORM == DEA_PLATFORM_WINDOWS)\n#include \"engine\/system\/system.h\"\n\n#include \n\nDEA_START()\n\nstruct window_platform\n{\n\tHWND hwnd;\n\tLPCWSTR name;\n};\n\n\/* Translation unit locals *\/\nnamespace\n{\n\tvoid close_windows(pod_vector &windows, pod_vector &windows_to_close)\n\t{\n\t\tfor (auto window_to_close = windows_to_close.get_begin(); window_to_close != windows_to_close.get_end(); ++window_to_close)\n\t\t{\n\t\t\tfor (auto window = windows.get_begin(); window != windows.get_end(); ++window)\n\t\t\t{\n\t\t\t\tif (*window_to_close == window->wnd->hwnd)\n\t\t\t\t{\n\t\t\t\t\tdestroy_window(*window, false);\n\t\t\t\t\twindows.remove_it(window);\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twindows_to_close.clear();\n\t}\n\n\t\/* Could use a better implementation *\/\n\tpod_vector *windows_to_close = NULL;\n\n\tLRESULT CALLBACK wnd_proc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam)\n\t{\n\t\t\/* Unused parametres, can't get rid of these *\/\n\t\t(void *)hwnd;\n\t\t(void *)wparam;\n\t\t(void *)lparam;\n\n\t\tswitch (umessage)\n\t\t{\n\t\tcase WM_DESTROY:\n\t\t{\n\t\t\t\/* We don't want to do anything as we manually destroy windows *\/\n\t\t\treturn 0;\n\t\t}\n\t\tcase WM_CLOSE:\n\t\t{\n\t\t\tif (windows_to_close)\n\t\t\t{\n\t\t\t\twindows_to_close->push_back(hwnd);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/* TODO: Localization\/Error number *\/\n\t\t\t\terror_popup(\"Error closing a window\", false);\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\treturn DefWindowProc(hwnd, umessage, wparam, lparam);\n\t\t}\n\t\t}\n\t}\n}\n\nvoid init_system_data()\n{\n\t\/* TODO: Memory manager *\/\n\twindows_to_close = new pod_vector(1);\n}\n\nvoid destroy_system_data()\n{\n\t\/* TODO: Memory manager *\/\n\tif (windows_to_close)\n\t\tdelete windows_to_close;\n}\n\nvoid error_popup(const char *msg, const bool kill_program)\n{\n\tdea_assert(msg && \"error_popup: msg is NULL\");\n\n\tMessageBoxA(NULL, msg, kill_program ? \"Fatal Error\" : \"Error\", MB_OK | MB_ICONERROR);\n\tif (kill_program)\n\t\tExitProcess(~(UINT)0);\n}\n\n\/* TODO: Create a string class for the name *\/\nvoid create_window(const uint width, const uint height, const float pos_x, const float pos_y, const wchar_t *name, const bool fullscreen, window &out_wnd)\n{\n\tint position_x = 0;\n\tint position_y = 0;\n\n\tHINSTANCE hinstance = GetModuleHandle(NULL);\n\n\t\/* TODO: Memory manager *\/\n\tout_wnd.wnd = new window_platform;\n\tout_wnd.wnd->hwnd = NULL;\n\tout_wnd.wnd->name = name;\n\tout_wnd.width = width;\n\tout_wnd.height = height;\n\n\t\/* Setup the windows class with default settings *\/\n\tWNDCLASSEX wc;\n\tmemset(&wc, 0, sizeof(wc));\n\twc.cbSize = sizeof(wc);\n\twc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;\n\twc.lpfnWndProc = wnd_proc;\n\twc.cbClsExtra = 0;\n\twc.cbWndExtra = 0;\n\twc.hInstance = hinstance;\n\twc.hIcon = LoadIcon(NULL, IDI_WINLOGO);\n\twc.hIconSm = wc.hIcon;\n\twc.hCursor = LoadCursor(NULL, IDC_ARROW);\n\twc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);\n\twc.lpszMenuName = NULL;\n\twc.lpszClassName = name;\n\n\t\/\/ Register the window class.\n\tif (RegisterClassEx(&wc) == 0)\n\t{\n\t\t\/* TODO: Localization\/Error number *\/\n\t\terror_popup(\"Failed to register window class\", true);\n\t}\n\n\tif (!fullscreen)\n\t{\n\t\tposition_x = (int)((GetSystemMetrics(SM_CXSCREEN) - width) * pos_x);\n\t\tposition_y = (int)((GetSystemMetrics(SM_CYSCREEN) - height) * pos_y);\n\t}\n\telse\n\t{\n\t\tDEVMODE screen_settings;\n\t\tmemset(&screen_settings, 0, sizeof(screen_settings));\n\t\tscreen_settings.dmSize = sizeof(screen_settings);\n\t\tscreen_settings.dmPelsHeight = (unsigned long)height;\n\t\tscreen_settings.dmPelsWidth = (unsigned long)width;\n\t\tscreen_settings.dmBitsPerPel = 32;\n\t\tscreen_settings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;\n\n\t\tChangeDisplaySettings(&screen_settings, CDS_FULLSCREEN);\n\t}\n\n\tDWORD style = WS_OVERLAPPEDWINDOW | WS_VISIBLE;\n\tDWORD exStyle = 0;\n\n\t\/\/ Create the window with the screen settings and get the handle to it.\n\tout_wnd.wnd->hwnd = CreateWindowEx(exStyle,\n\t name,\n\t name,\n\t style,\n\t position_x, position_y, \n\t (int)width, (int)height, \n\t NULL, \n\t NULL, \n\t hinstance, \n\t NULL);\n\n\tif (out_wnd.wnd->hwnd == NULL)\n\t{\n\t\t\/* TODO: Localization\/Error number *\/\n\t\terror_popup(\"Failed to create a window\", true);\n\t}\n\n\tShowWindow(out_wnd.wnd->hwnd, SW_SHOW);\n}\n\nvoid destroy_window(window &wnd, const bool fullscreen)\n{\n\tdea_assert(wnd.wnd && \"destroy_window: Platform specific window pointer is NULL\");\n\n\tif (fullscreen)\n\t{\n\t\tChangeDisplaySettings(NULL, 0);\n\t}\n\n\tDestroyWindow(wnd.wnd->hwnd);\n\twnd.wnd->hwnd = NULL;\n\n\tHINSTANCE hinstance = GetModuleHandle(NULL);\n\tUnregisterClass(wnd.wnd->name, hinstance);\n\thinstance = NULL;\n\n\t\/* TODO: Memory manager *\/\n\tdelete wnd.wnd;\n}\n\nvoid focus_window(window &wnd)\n{\n\tdea_assert(wnd.wnd && wnd.wnd->hwnd);\n\tSetForegroundWindow(wnd.wnd->hwnd);\n\tSetFocus(wnd.wnd->hwnd);\n}\n\nvoid run(pod_vector &windows)\n{\n\tMSG msg;\n\tZeroMemory(&msg, sizeof(MSG));\n\n\tbool running = true;\n\twhile (running)\n\t{\n\t\tif (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))\n\t\t{\n\t\t\tTranslateMessage(&msg);\n\t\t\tDispatchMessage(&msg);\n\t\t}\n\n\t\tif (msg.message == WM_QUIT)\n\t\t{\n\t\t\trunning = false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (windows_to_close && !windows_to_close->empty())\n\t\t\t{\n\t\t\t\tclose_windows(windows, *windows_to_close);\n\n\t\t\t\tif (windows.empty())\n\t\t\t\t\trunning = false;\n\t\t\t}\n\n\t\t\t\/* Run frame *\/\t\n\t\t}\n\t}\n}\n\nDEA_END()\n\n#endif \/\/ DEA_PLATFORM == DEA_PLATFORM_WINDOWS<|endoftext|>"} {"text":"#include \"util\/funcs.h\"\n#include \"util\/bitmap.h\"\n#include \"night_atmosphere.h\"\n#include \"util\/file-system.h\"\n#include \"util\/token.h\"\n#include \"resource.h\"\n#include \"util\/sound.h\"\n#include \"globals.h\"\n#include \n\nusing namespace std;\n\n\/*\nstatic int screenX(){\n\treturn 320;\n}\n\nstatic int screenY(){\n\treturn 240;\n}\n*\/\n\nNightAtmosphere::NightAtmosphere():\nAtmosphere(),\ndarkness(128),\nlightning(false){\n\n lamp = new Bitmap(Filesystem::find(Filesystem::RelativePath(\"sprites\/lamp.png\")).path());\n thunder = Resource::getSound(\"sounds\/thunder.wav\");\n \/*\n addLight(500, 30, 50, 30, Bitmap::makeColor(32,32,0), 0);\n addLight(300, 30, 70, 30, Bitmap::makeColor(0,32,192), 128);\n *\/\n}\n\nNightAtmosphere::~NightAtmosphere(){\n for (vector::iterator it = lights.begin(); it != lights.end(); it++){\n delete (*it);\n }\n delete lamp;\n}\n\n\/* lights should not overlap! the effect completely messes up if they do\n *\/\nvoid NightAtmosphere::drawLight(Bitmap * original, Bitmap * work, const int x, const int y, const int lower_width, const int upper_width, const int black, const int dark_alpha, const int light, const int light_alpha, bool draw_light){\n int center_x = x;\n \/\/ int center_x = screenX();\n \n \/*\n const int black = Bitmap::makeColor(0,0,0);\n const int light = Bitmap::makeColor(32,32,0);\n const int light_alpha = 0;\n const int dark_alpha = 128;\n *\/\n\n int where_x = center_x - lower_width;\n int total = lower_width * 2;\n if (where_x < 0){\n total += where_x;\n where_x = 0;\n }\n if (total <= 0){\n return;\n }\n\n int left = total - lower_width * 2;\n int middle = total - lower_width;\n int right = total;\n if (center_x - lower_width > 0){\n left = 0;\n middle = lower_width;\n right = lower_width * 2;\n }\n\n Bitmap save(*original, where_x, 0, total, work->getWidth());\n int top = y;\n\n if (draw_light){\n Bitmap::transBlender(0, 0, 0, dark_alpha);\n Bitmap::drawingMode(Bitmap::MODE_TRANS);\n \/*\n int top = -save.getHeight() \/ 3;\n top = 30;\n *\/\n int lamp_height = save.getHeight() - top;\n\n \/* y = tan(theta) * x *\/\n int lamp_top = (int)(((double)lower_width * 2.0 \/ (double)lamp_height) * (double)upper_width);\n\n \/\/ int top = 0;\n save.triangle(left, top, middle, top, left, save.getHeight(), black);\n save.triangle(right, top, middle, top, right, save.getHeight(), black);\n int nwidth = (int)((double) lamp_top \/ ((double) lamp_height \/ (double) lower_width));\n save.triangle(middle, top, middle - nwidth, top + lamp_top, middle + nwidth, top + lamp_top, black);\n\n save.rectangleFill(0, 0, right, top, black);\n Bitmap::drawingMode(Bitmap::MODE_SOLID);\n int xwidth = (int)((double) lamp_height \/ ((double)(save.getHeight() - top) \/ (double) lower_width));\n save.light(middle, top, xwidth, lamp_height, lamp_top, light_alpha, dark_alpha, light, black);\n lamp->draw(middle - 8, top, save);\n } else {\n lamp->draw(middle - 8, top, save);\n }\n save.draw(where_x, 0, *work);\n}\n\nint NightAtmosphere::getSkyColor() const {\n if (lightning){\n return Bitmap::makeColor(255, 255, 255);\n } else {\n return Bitmap::makeColor(0, 0, 0);\n }\n}\n\nint NightAtmosphere::getSkyDarkness() const {\n if (lightning){\n return lightningFade;\n } else {\n return 255 - darkness;\n }\n}\n\nvoid NightAtmosphere::drawFront(Bitmap * work, int x){\n Bitmap::transBlender(0, 0, 0, getSkyDarkness());\n work->applyTrans(getSkyColor());\n}\n\nvoid NightAtmosphere::drawBackground(Bitmap * work, int x){\n}\n\t\nvoid NightAtmosphere::drawScreen(Bitmap * work, int x){\n}\n\nvoid NightAtmosphere::addLight(const int x, const int y, const int lower_width, const int upper_width, const int color, const int alpha){\n lights.push_back(new Light(x, y, lower_width, upper_width, color, alpha));\n}\n\nvoid NightAtmosphere::drawForeground(Bitmap * work, int x){\n const int sky = getSkyColor();\n Bitmap save = Bitmap::temporaryBitmap(work->getWidth(), work->getHeight());\n work->Blit(save);\n Bitmap::transBlender(0, 0, 0, getSkyDarkness());\n work->applyTrans(sky);\n\n for (vector::iterator it = lights.begin(); it != lights.end(); it++){\n Light * light = *it;\n int my_x = light->x - x;\n int my_y = light->y;\n drawLight(&save, work, my_x, my_y, light->lower_width, light->upper_width, sky, darkness, light->color, light->alpha, ! lightning);\n }\n}\n\nvoid NightAtmosphere::act(const Scene & level){\n if (lightning){\n if (lightningFade > 0){\n lightningFade *= 0.7;\n } else {\n lightning = false;\n }\n if (thunderPause == 0){\n thunder->play();\n thunderPause -= 1;\n } else if (thunderPause > 0){\n thunderPause -= 1;\n }\n } else if (Util::rnd(300) == 0){\n lightning = true;\n lightningFade = 255;\n thunderPause = 2 + Util::rnd(6);\n \/\/ thunder->play();\n }\n}\n\nvoid NightAtmosphere::processLight(Token * token){\n int x;\n *token >> x;\n addLight(x, 30, 50, 30, Bitmap::makeColor(32,32,0), 0);\n}\n \nvoid NightAtmosphere::interpret(Token * message){\n Token * night = message->findToken(\"message\/night\");\n if (night != NULL){\n vector lights = night->findTokens(\"night\/lamp\");\n for (vector::iterator it = lights.begin(); it != lights.end(); it++){\n Token * token = *it;\n try{\n processLight(token);\n } catch (const TokenException & e){\n Global::debug(0) << \"Could not add light to night atmosphere: \" << e.getReason() << endl;\n }\n }\n }\n}\ndelay thunder more#include \"util\/funcs.h\"\n#include \"util\/bitmap.h\"\n#include \"night_atmosphere.h\"\n#include \"util\/file-system.h\"\n#include \"util\/token.h\"\n#include \"resource.h\"\n#include \"util\/sound.h\"\n#include \"globals.h\"\n#include \n\nusing namespace std;\n\n\/*\nstatic int screenX(){\n\treturn 320;\n}\n\nstatic int screenY(){\n\treturn 240;\n}\n*\/\n\nNightAtmosphere::NightAtmosphere():\nAtmosphere(),\ndarkness(128),\nlightning(false),\nthunder(NULL),\nthunderPause(-1){\n\n lamp = new Bitmap(Filesystem::find(Filesystem::RelativePath(\"sprites\/lamp.png\")).path());\n thunder = Resource::getSound(\"sounds\/thunder.wav\");\n \/*\n addLight(500, 30, 50, 30, Bitmap::makeColor(32,32,0), 0);\n addLight(300, 30, 70, 30, Bitmap::makeColor(0,32,192), 128);\n *\/\n}\n\nNightAtmosphere::~NightAtmosphere(){\n for (vector::iterator it = lights.begin(); it != lights.end(); it++){\n delete (*it);\n }\n delete lamp;\n}\n\n\/* lights should not overlap! the effect completely messes up if they do\n *\/\nvoid NightAtmosphere::drawLight(Bitmap * original, Bitmap * work, const int x, const int y, const int lower_width, const int upper_width, const int black, const int dark_alpha, const int light, const int light_alpha, bool draw_light){\n int center_x = x;\n \/\/ int center_x = screenX();\n \n \/*\n const int black = Bitmap::makeColor(0,0,0);\n const int light = Bitmap::makeColor(32,32,0);\n const int light_alpha = 0;\n const int dark_alpha = 128;\n *\/\n\n int where_x = center_x - lower_width;\n int total = lower_width * 2;\n if (where_x < 0){\n total += where_x;\n where_x = 0;\n }\n if (total <= 0){\n return;\n }\n\n int left = total - lower_width * 2;\n int middle = total - lower_width;\n int right = total;\n if (center_x - lower_width > 0){\n left = 0;\n middle = lower_width;\n right = lower_width * 2;\n }\n\n Bitmap save(*original, where_x, 0, total, work->getWidth());\n int top = y;\n\n if (draw_light){\n Bitmap::transBlender(0, 0, 0, dark_alpha);\n Bitmap::drawingMode(Bitmap::MODE_TRANS);\n \/*\n int top = -save.getHeight() \/ 3;\n top = 30;\n *\/\n int lamp_height = save.getHeight() - top;\n\n \/* y = tan(theta) * x *\/\n int lamp_top = (int)(((double)lower_width * 2.0 \/ (double)lamp_height) * (double)upper_width);\n\n \/\/ int top = 0;\n save.triangle(left, top, middle, top, left, save.getHeight(), black);\n save.triangle(right, top, middle, top, right, save.getHeight(), black);\n int nwidth = (int)((double) lamp_top \/ ((double) lamp_height \/ (double) lower_width));\n save.triangle(middle, top, middle - nwidth, top + lamp_top, middle + nwidth, top + lamp_top, black);\n\n save.rectangleFill(0, 0, right, top, black);\n Bitmap::drawingMode(Bitmap::MODE_SOLID);\n int xwidth = (int)((double) lamp_height \/ ((double)(save.getHeight() - top) \/ (double) lower_width));\n save.light(middle, top, xwidth, lamp_height, lamp_top, light_alpha, dark_alpha, light, black);\n lamp->draw(middle - 8, top, save);\n } else {\n lamp->draw(middle - 8, top, save);\n }\n save.draw(where_x, 0, *work);\n}\n\nint NightAtmosphere::getSkyColor() const {\n if (lightning){\n return Bitmap::makeColor(255, 255, 255);\n } else {\n return Bitmap::makeColor(0, 0, 0);\n }\n}\n\nint NightAtmosphere::getSkyDarkness() const {\n if (lightning){\n return lightningFade;\n } else {\n return 255 - darkness;\n }\n}\n\nvoid NightAtmosphere::drawFront(Bitmap * work, int x){\n Bitmap::transBlender(0, 0, 0, getSkyDarkness());\n work->applyTrans(getSkyColor());\n}\n\nvoid NightAtmosphere::drawBackground(Bitmap * work, int x){\n}\n\t\nvoid NightAtmosphere::drawScreen(Bitmap * work, int x){\n}\n\nvoid NightAtmosphere::addLight(const int x, const int y, const int lower_width, const int upper_width, const int color, const int alpha){\n lights.push_back(new Light(x, y, lower_width, upper_width, color, alpha));\n}\n\nvoid NightAtmosphere::drawForeground(Bitmap * work, int x){\n const int sky = getSkyColor();\n Bitmap save = Bitmap::temporaryBitmap(work->getWidth(), work->getHeight());\n work->Blit(save);\n Bitmap::transBlender(0, 0, 0, getSkyDarkness());\n work->applyTrans(sky);\n\n for (vector::iterator it = lights.begin(); it != lights.end(); it++){\n Light * light = *it;\n int my_x = light->x - x;\n int my_y = light->y;\n drawLight(&save, work, my_x, my_y, light->lower_width, light->upper_width, sky, darkness, light->color, light->alpha, ! lightning);\n }\n}\n\nvoid NightAtmosphere::act(const Scene & level){\n if (lightning){\n if (lightningFade > 0){\n lightningFade *= 0.7;\n } else {\n lightning = false;\n }\n } else if (Util::rnd(300) == 0){\n lightning = true;\n lightningFade = 255;\n thunderPause = 20 + Util::rnd(4);\n \/\/ thunder->play();\n }\n\n if (thunderPause == 0){\n thunder->play();\n thunderPause -= 1;\n } else if (thunderPause > 0){\n thunderPause -= 1;\n }\n}\n\nvoid NightAtmosphere::processLight(Token * token){\n int x;\n *token >> x;\n addLight(x, 30, 50, 30, Bitmap::makeColor(32,32,0), 0);\n}\n \nvoid NightAtmosphere::interpret(Token * message){\n Token * night = message->findToken(\"message\/night\");\n if (night != NULL){\n vector lights = night->findTokens(\"night\/lamp\");\n for (vector::iterator it = lights.begin(); it != lights.end(); it++){\n Token * token = *it;\n try{\n processLight(token);\n } catch (const TokenException & e){\n Global::debug(0) << \"Could not add light to night atmosphere: \" << e.getReason() << endl;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\r\n * This file is part of `et engine`\r\n * Copyright 2009-2015 by Sergey Reznik\r\n * Please, modify content only if you know what are you doing.\r\n *\r\n *\/\r\n\r\n#include \r\n\r\n#if (ET_PLATFORM_WIN)\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nstatic bool shouldInitializeTime = true;\r\n\r\nstatic uint64_t performanceFrequency = 0;\r\nstatic uint64_t initialCounter = 0;\r\n\r\nstatic const ET_STRING_TYPE currentFolder = ET_STRING_FROM_CONST_CHAR(\".\");\r\nstatic const ET_STRING_TYPE previousFolder = ET_STRING_FROM_CONST_CHAR(\"..\");\r\nstatic const ET_STRING_TYPE allFilesMask = ET_STRING_FROM_CONST_CHAR(\"*.*\");\r\n\r\nvoid initTime()\r\n{\r\n\tLARGE_INTEGER c = { };\r\n\tLARGE_INTEGER f = { };\r\n\r\n\tshouldInitializeTime = false;\r\n\r\n\tQueryPerformanceCounter(&c);\r\n\tQueryPerformanceFrequency(&f);\r\n\r\n\tinitialCounter = c.QuadPart;\r\n\tperformanceFrequency = f.QuadPart;\r\n}\r\n\r\nuint64_t et::queryContiniousTimeInMilliSeconds()\r\n{\r\n\tif (shouldInitializeTime)\r\n\t\tinitTime();\r\n\r\n\tLARGE_INTEGER c = { };\r\n\tQueryPerformanceCounter(&c);\r\n\r\n\treturn 1000 * (c.QuadPart - initialCounter) \/ performanceFrequency;\r\n}\r\n\r\nfloat et::queryContiniousTimeInSeconds()\r\n{\r\n\treturn static_cast(queryContiniousTimeInMilliSeconds()) \/ 1000.0f;\r\n}\r\n\r\nuint64_t et::queryCurrentTimeInMicroSeconds()\r\n{\r\n\tLARGE_INTEGER c = { };\r\n\tQueryPerformanceCounter(&c);\r\n\treturn 1000000 * c.QuadPart \/ performanceFrequency;\r\n}\r\n\r\nconst char et::pathDelimiter = '\\\\';\r\nconst char et::invalidPathDelimiter = '\/';\r\n\r\nstd::string et::applicationPath()\r\n{\r\n\tchar ExePath[MAX_PATH] = { };\r\n\tGetModuleFileNameA(nullptr, ExePath, MAX_PATH);\r\n\treturn getFilePath(normalizeFilePath(ExePath));\r\n}\r\n\r\nbool et::fileExists(const std::string& name)\r\n{\r\n\tauto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(name).c_str());\r\n\treturn (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY);\r\n}\r\n\r\nbool et::folderExists(const std::string& folder)\r\n{\r\n\tauto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(folder).c_str());\r\n\treturn (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);\r\n}\r\n\r\nvoid et::findFiles(const std::string& folder, const std::string& mask, bool recursive, StringList& list)\r\n{\r\n\tET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder));\r\n\tET_STRING_TYPE searchPath = normalizedFolder + ET_STRING_TO_PARAM_TYPE(mask);\r\n\r\n\tStringList folderList;\r\n\tif (recursive)\r\n\t{\r\n\t\tET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask;\r\n\r\n\t\tWIN32_FIND_DATA folders = { };\r\n\t\tHANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders);\r\n\t\tif (folderSearch != INVALID_HANDLE_VALUE)\r\n\t\t{\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tbool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;\r\n\t\t\t\tET_STRING_TYPE name(folders.cFileName);\r\n\t\t\t\tif (isFolder && (name != currentFolder) && (name != previousFolder))\r\n\t\t\t\t\tfolderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name));\r\n\r\n\t\t\t}\r\n\t\t\twhile (FindNextFile(folderSearch, &folders));\r\n\t\t\tFindClose(folderSearch);\r\n\t\t}\r\n\t}\r\n\r\n\tWIN32_FIND_DATA data = { };\r\n\tHANDLE search = FindFirstFile(searchPath.c_str(), &data);\r\n\tif (search != INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\tdo\r\n\t\t{\r\n\t\t\tbool isAcceptable = \r\n\t\t\t\t((data.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) == FILE_ATTRIBUTE_NORMAL) || \r\n\t\t\t\t((data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) == FILE_ATTRIBUTE_ARCHIVE) ||\r\n\t\t\t\t((data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY);\r\n\r\n\t\t\tET_STRING_TYPE name(data.cFileName);\r\n\r\n\t\t\tif (isAcceptable && (name != currentFolder) && (name != previousFolder))\r\n\t\t\t\tlist.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name));\r\n\t\t}\r\n\t\twhile (FindNextFile(search, &data));\r\n\t\tFindClose(search);\r\n\t}\r\n\r\n\tif (recursive)\r\n\t{\r\n\t\tfor (const std::string& i : folderList)\r\n\t\t\tfindFiles(i, mask, recursive, list);\r\n\t}\r\n}\r\n\r\nstd::string et::applicationPackagePath()\r\n{\r\n\tET_CHAR_TYPE buffer[MAX_PATH] = { };\r\n\tGetCurrentDirectory(MAX_PATH, buffer);\r\n\treturn addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer));\r\n}\r\n\r\nstd::string et::applicationDataFolder()\r\n{\r\n\tET_CHAR_TYPE buffer[MAX_PATH] = { };\r\n\tGetCurrentDirectory(MAX_PATH, buffer);\r\n\treturn addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer));\r\n}\r\n\r\nstd::string et::documentsBaseFolder()\r\n{\r\n\twchar_t* path = nullptr;\r\n\tSHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &path);\r\n\r\n\tif (path == nullptr) \r\n\t\treturn emptyString;\r\n\r\n\tstd::string result = addTrailingSlash(unicodeToUtf8(path));\r\n\tCoTaskMemFree(path);\r\n\treturn result;\r\n}\r\n\r\nstd::string et::libraryBaseFolder()\r\n{\r\n\twchar_t* path = nullptr;\r\n\tSHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path);\r\n\r\n\tif (path == nullptr) \r\n\t\treturn emptyString;\r\n\r\n\tstd::string result = addTrailingSlash(unicodeToUtf8(path));\r\n\tCoTaskMemFree(path);\r\n\treturn result;\r\n}\r\n\r\nbool et::createDirectory(const std::string& name, bool recursive)\r\n{\r\n\tif (recursive)\r\n\t{\r\n\t\tchar delim[] = {pathDelimiter, 0};\r\n\t\tbool gotError = false;\r\n\t\tStringList components = split(name, std::string(delim));\r\n\t\tstd::string path;\r\n\t\tfor (auto& dir : components)\r\n\t\t{\r\n\t\t\tpath += dir + \"\\\\\";\r\n\t\t\tif (!folderExists(path))\r\n\t\t\t\tgotError |= ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(path).c_str(), nullptr) == 0;\r\n\t\t}\r\n\r\n\t\treturn !gotError;\r\n\t}\r\n\r\n\treturn ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(name).c_str(), nullptr) == 0;\r\n}\r\n\r\nbool et::removeFile(const std::string& name)\r\n{\r\n\tET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name);\r\n\taName.resize(aName.size() + 1);\r\n\taName.back() = 0;\r\n\r\n\tSHFILEOPSTRUCT fop = { };\r\n\r\n\tfop.wFunc = FO_DELETE;\r\n\tfop.pFrom = aName.c_str();\r\n\tfop.fFlags = FOF_NO_UI;\r\n\r\n\treturn SHFileOperation(&fop) == 0;\r\n}\r\n\r\nbool et::copyFile(const std::string& from, const std::string& to)\r\n{\r\n\tET_STRING_TYPE aFrom= ET_STRING_TO_PARAM_TYPE(from);\r\n\tET_STRING_TYPE aTo = ET_STRING_TO_PARAM_TYPE(to);\r\n\taFrom.resize(aFrom.size() + 1);\r\n\taTo.resize(aTo.size() + 1);\r\n\taFrom.back() = 0;\r\n\taTo.back() = 0;\r\n\r\n\tSHFILEOPSTRUCT fop = { };\r\n\r\n\tfop.wFunc = FO_COPY;\r\n\tfop.pFrom = aFrom.c_str();\r\n\tfop.pTo = aTo.c_str();\r\n\tfop.fFlags = FOF_NO_UI;\r\n\r\n\treturn SHFileOperation(&fop) == 0;\r\n}\r\n\r\nbool et::removeDirectory(const std::string& name)\r\n{\r\n\tET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name);\r\n\taName.resize(aName.size() + 1);\r\n\taName.back() = 0;\r\n\r\n\tSHFILEOPSTRUCT fop = { };\r\n\r\n\tfop.wFunc = FO_DELETE;\r\n\tfop.pFrom = aName.c_str();\r\n\tfop.fFlags = FOF_NO_UI;\r\n\r\n\treturn SHFileOperation(&fop) == 0;\r\n}\r\n\r\nvoid et::findSubfolders(const std::string& folder, bool recursive, StringList& list)\r\n{\r\n\tStringList folderList;\r\n\t\r\n\tET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder));\r\n\tET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask;\r\n\r\n\tWIN32_FIND_DATA folders = { };\r\n\tHANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders);\r\n\tif (folderSearch != INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\tdo\r\n\t\t{\r\n\t\t\tET_STRING_TYPE name(folders.cFileName);\r\n\t\t\tbool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;\r\n\t\t\tif (isFolder && (name != currentFolder) && (name != previousFolder))\r\n\t\t\t{\r\n\t\t\t\tfolderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + \r\n\t\t\t\t\tname + ET_STRING_FROM_CONST_CHAR(\"\\\\\")));\r\n\t\t\t}\r\n\t\t}\r\n\t\twhile (FindNextFile(folderSearch, &folders));\r\n\t\tFindClose(folderSearch);\r\n\t}\r\n\r\n\tif (recursive)\r\n\t{\r\n\t\tfor (const std::string& i : folderList)\r\n\t\t\tfindSubfolders(i, true, list);\r\n\t}\r\n\r\n\tlist.insert(list.end(), folderList.begin(), folderList.end());\r\n}\r\n\r\nvoid et::openUrl(const std::string& url)\r\n{\r\n\tShellExecute(nullptr, ET_STRING_FROM_CONST_CHAR(\"open\"), \r\n\t\tET_STRING_TO_PARAM_TYPE(url).c_str(), 0, 0, SW_SHOWNORMAL);\r\n}\r\n\r\nstd::string et::unicodeToUtf8(const std::wstring& w)\r\n{\r\n\tint mbcWidth = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, 0, 0, 0, 0);\r\n\r\n\tif (mbcWidth == 0)\r\n\t\treturn emptyString;\r\n\r\n\tDataStorage result(mbcWidth + 1, 0);\r\n\tWideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, result.data(), static_cast(result.size()), 0, 0);\r\n\r\n\treturn std::string(result.data());\r\n}\r\n\r\nstd::wstring et::utf8ToUnicode(const std::string& mbcs)\r\n{\r\n\tint uWidth = MultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, 0, 0);\r\n\tif (uWidth == 0)\r\n\t{\r\n\t\tswitch (GetLastError())\r\n\t\t{\r\n\t\tcase ERROR_INSUFFICIENT_BUFFER:\r\n\t\t\tstd::cout << \"A supplied buffer size was not large enough, \"\r\n\t\t\t\t\"or it was incorrectly set to NULL.\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tcase ERROR_INVALID_FLAGS:\r\n\t\t\tstd::cout << \"The values supplied for flags were not valid.\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tcase ERROR_INVALID_PARAMETER:\r\n\t\t\tstd::cout << \"Any of the parameter values was invalid.\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tcase ERROR_NO_UNICODE_TRANSLATION:\r\n\t\t\tstd::cout << \"Invalid Unicode was found in a string\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tdefault:\r\n\t\t\tstd::cout << \"Failed to convert utf-8 to wchar_t\" << std::endl;\r\n\t\t}\r\n\r\n\t\treturn std::wstring();\r\n\t}\r\n\r\n\tDataStorage result(uWidth + 1, 0);\r\n\tMultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, result.data(), static_cast(result.size()));\r\n\r\n\treturn std::wstring(result.data());\r\n}\r\n\r\nstd::string et::applicationIdentifierForCurrentProject()\r\n\t{ return \"com.et.app\"; }\r\n\r\nuint64_t et::getFileDate(const std::string& path)\r\n{\r\n\tWIN32_FIND_DATA findData = { };\r\n\tHANDLE search = FindFirstFile(ET_STRING_TO_PARAM_TYPE(path).c_str(), &findData);\r\n\tFindClose(search);\r\n\r\n\treturn findData.ftLastWriteTime.dwLowDateTime |\r\n\t\t(static_cast(findData.ftLastWriteTime.dwHighDateTime) << 32);\r\n}\r\n\r\nstd::vector et::availableScreens()\r\n{\r\n\tstd::vector result;\r\n\t\r\n\tEnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) -> BOOL\r\n\t{\r\n\t\tMONITORINFO info = { sizeof(MONITORINFO) };\r\n\r\n\t\tGetMonitorInfo(hMonitor, &info);\r\n\r\n\t\trecti screenRect(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right - info.rcMonitor.left,\r\n\t\t\tinfo.rcMonitor.bottom - info.rcMonitor.top);\r\n\r\n\t\trecti workarea(info.rcWork.left, info.rcWork.top, info.rcWork.right - info.rcWork.left,\r\n\t\t\tinfo.rcWork.bottom - info.rcWork.top);\r\n\r\n\t\tstd::vector* r = reinterpret_cast*>(dwData);\r\n\t\tr->emplace_back(screenRect, workarea, 1);\r\n\t\treturn 1;\r\n\t}, \r\n\treinterpret_cast(&result));\r\n\r\n\treturn result;\r\n}\r\n\r\nstd::string et::selectFile(const StringList&, SelectFileMode mode, const std::string& defaultName)\r\n{\r\n\tET_STRING_TYPE defaultFileName = ET_STRING_TO_PARAM_TYPE(defaultName);\r\n\r\n\tDataStorage defaultFileNameData(etMax(size_t(MAX_PATH), defaultFileName.size()) + 1, 0);\r\n\tetCopyMemory(defaultFileNameData.data(), defaultFileName.data(), defaultFileName.size());\r\n\r\n\tOPENFILENAME of = { };\r\n\tof.lStructSize = sizeof(of);\r\n\tof.hInstance = GetModuleHandle(nullptr);\r\n\tof.Flags = OFN_DONTADDTORECENT | OFN_ENABLESIZING | OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;\r\n\tof.lpstrFile = defaultFileNameData.data();\r\n\tof.nMaxFile = MAX_PATH;\r\n\r\n#if (_UNICODE)\r\n\tof.lpstrFilter = L\"All Files\\0*.*\\0\\0\";\r\n#else\r\n\tof.lpstrFilter = \"All Files\\0*.*\\0\\0\";\r\n#endif\r\n\r\n\tauto func = (mode == SelectFileMode::Save) ? GetSaveFileName : GetOpenFileName;\r\n\r\n\treturn func(&of) ? ET_STRING_TO_OUTPUT_TYPE(of.lpstrFile) : emptyString;\r\n}\r\n\r\nvoid et::alert(const std::string& title, const std::string& message, const std::string&, AlertType type)\r\n{\r\n\tUINT alType = MB_ICONINFORMATION;\r\n\r\n\tswitch (type)\r\n\t{\r\n\tcase AlertType::Warning: \r\n\t\t{\r\n\t\t\talType = MB_ICONWARNING;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\tcase AlertType::Error: \r\n\t\t{\r\n\t\t\talType = MB_ICONERROR;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\tMessageBoxA(nullptr, message.c_str(), title.c_str(), alType);\r\n}\r\n\r\n#endif \/\/ ET_PLATFORM_WIN\r\ncurrentScreen function added to windows\/*\r\n * This file is part of `et engine`\r\n * Copyright 2009-2015 by Sergey Reznik\r\n * Please, modify content only if you know what are you doing.\r\n *\r\n *\/\r\n\r\n#include \r\n\r\n#if (ET_PLATFORM_WIN)\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nstatic bool shouldInitializeTime = true;\r\n\r\nstatic uint64_t performanceFrequency = 0;\r\nstatic uint64_t initialCounter = 0;\r\n\r\nstatic const ET_STRING_TYPE currentFolder = ET_STRING_FROM_CONST_CHAR(\".\");\r\nstatic const ET_STRING_TYPE previousFolder = ET_STRING_FROM_CONST_CHAR(\"..\");\r\nstatic const ET_STRING_TYPE allFilesMask = ET_STRING_FROM_CONST_CHAR(\"*.*\");\r\n\r\nvoid initTime()\r\n{\r\n\tLARGE_INTEGER c = { };\r\n\tLARGE_INTEGER f = { };\r\n\r\n\tshouldInitializeTime = false;\r\n\r\n\tQueryPerformanceCounter(&c);\r\n\tQueryPerformanceFrequency(&f);\r\n\r\n\tinitialCounter = c.QuadPart;\r\n\tperformanceFrequency = f.QuadPart;\r\n}\r\n\r\nuint64_t et::queryContiniousTimeInMilliSeconds()\r\n{\r\n\tif (shouldInitializeTime)\r\n\t\tinitTime();\r\n\r\n\tLARGE_INTEGER c = { };\r\n\tQueryPerformanceCounter(&c);\r\n\r\n\treturn 1000 * (c.QuadPart - initialCounter) \/ performanceFrequency;\r\n}\r\n\r\nfloat et::queryContiniousTimeInSeconds()\r\n{\r\n\treturn static_cast(queryContiniousTimeInMilliSeconds()) \/ 1000.0f;\r\n}\r\n\r\nuint64_t et::queryCurrentTimeInMicroSeconds()\r\n{\r\n\tLARGE_INTEGER c = { };\r\n\tQueryPerformanceCounter(&c);\r\n\treturn 1000000 * c.QuadPart \/ performanceFrequency;\r\n}\r\n\r\nconst char et::pathDelimiter = '\\\\';\r\nconst char et::invalidPathDelimiter = '\/';\r\n\r\nstd::string et::applicationPath()\r\n{\r\n\tchar ExePath[MAX_PATH] = { };\r\n\tGetModuleFileNameA(nullptr, ExePath, MAX_PATH);\r\n\treturn getFilePath(normalizeFilePath(ExePath));\r\n}\r\n\r\nbool et::fileExists(const std::string& name)\r\n{\r\n\tauto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(name).c_str());\r\n\treturn (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY);\r\n}\r\n\r\nbool et::folderExists(const std::string& folder)\r\n{\r\n\tauto attr = GetFileAttributes(ET_STRING_TO_PARAM_TYPE(folder).c_str());\r\n\treturn (attr != INVALID_FILE_ATTRIBUTES) && ((attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY);\r\n}\r\n\r\nvoid et::findFiles(const std::string& folder, const std::string& mask, bool recursive, StringList& list)\r\n{\r\n\tET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder));\r\n\tET_STRING_TYPE searchPath = normalizedFolder + ET_STRING_TO_PARAM_TYPE(mask);\r\n\r\n\tStringList folderList;\r\n\tif (recursive)\r\n\t{\r\n\t\tET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask;\r\n\r\n\t\tWIN32_FIND_DATA folders = { };\r\n\t\tHANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders);\r\n\t\tif (folderSearch != INVALID_HANDLE_VALUE)\r\n\t\t{\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tbool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;\r\n\t\t\t\tET_STRING_TYPE name(folders.cFileName);\r\n\t\t\t\tif (isFolder && (name != currentFolder) && (name != previousFolder))\r\n\t\t\t\t\tfolderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name));\r\n\r\n\t\t\t}\r\n\t\t\twhile (FindNextFile(folderSearch, &folders));\r\n\t\t\tFindClose(folderSearch);\r\n\t\t}\r\n\t}\r\n\r\n\tWIN32_FIND_DATA data = { };\r\n\tHANDLE search = FindFirstFile(searchPath.c_str(), &data);\r\n\tif (search != INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\tdo\r\n\t\t{\r\n\t\t\tbool isAcceptable = \r\n\t\t\t\t((data.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) == FILE_ATTRIBUTE_NORMAL) || \r\n\t\t\t\t((data.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE) == FILE_ATTRIBUTE_ARCHIVE) ||\r\n\t\t\t\t((data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == FILE_ATTRIBUTE_READONLY);\r\n\r\n\t\t\tET_STRING_TYPE name(data.cFileName);\r\n\r\n\t\t\tif (isAcceptable && (name != currentFolder) && (name != previousFolder))\r\n\t\t\t\tlist.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + name));\r\n\t\t}\r\n\t\twhile (FindNextFile(search, &data));\r\n\t\tFindClose(search);\r\n\t}\r\n\r\n\tif (recursive)\r\n\t{\r\n\t\tfor (const std::string& i : folderList)\r\n\t\t\tfindFiles(i, mask, recursive, list);\r\n\t}\r\n}\r\n\r\nstd::string et::applicationPackagePath()\r\n{\r\n\tET_CHAR_TYPE buffer[MAX_PATH] = { };\r\n\tGetCurrentDirectory(MAX_PATH, buffer);\r\n\treturn addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer));\r\n}\r\n\r\nstd::string et::applicationDataFolder()\r\n{\r\n\tET_CHAR_TYPE buffer[MAX_PATH] = { };\r\n\tGetCurrentDirectory(MAX_PATH, buffer);\r\n\treturn addTrailingSlash(ET_STRING_TO_OUTPUT_TYPE(buffer));\r\n}\r\n\r\nstd::string et::documentsBaseFolder()\r\n{\r\n\twchar_t* path = nullptr;\r\n\tSHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &path);\r\n\r\n\tif (path == nullptr) \r\n\t\treturn emptyString;\r\n\r\n\tstd::string result = addTrailingSlash(unicodeToUtf8(path));\r\n\tCoTaskMemFree(path);\r\n\treturn result;\r\n}\r\n\r\nstd::string et::libraryBaseFolder()\r\n{\r\n\twchar_t* path = nullptr;\r\n\tSHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path);\r\n\r\n\tif (path == nullptr) \r\n\t\treturn emptyString;\r\n\r\n\tstd::string result = addTrailingSlash(unicodeToUtf8(path));\r\n\tCoTaskMemFree(path);\r\n\treturn result;\r\n}\r\n\r\nbool et::createDirectory(const std::string& name, bool recursive)\r\n{\r\n\tif (recursive)\r\n\t{\r\n\t\tchar delim[] = {pathDelimiter, 0};\r\n\t\tbool gotError = false;\r\n\t\tStringList components = split(name, std::string(delim));\r\n\t\tstd::string path;\r\n\t\tfor (auto& dir : components)\r\n\t\t{\r\n\t\t\tpath += dir + \"\\\\\";\r\n\t\t\tif (!folderExists(path))\r\n\t\t\t\tgotError |= ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(path).c_str(), nullptr) == 0;\r\n\t\t}\r\n\r\n\t\treturn !gotError;\r\n\t}\r\n\r\n\treturn ::CreateDirectory(ET_STRING_TO_PARAM_TYPE(name).c_str(), nullptr) == 0;\r\n}\r\n\r\nbool et::removeFile(const std::string& name)\r\n{\r\n\tET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name);\r\n\taName.resize(aName.size() + 1);\r\n\taName.back() = 0;\r\n\r\n\tSHFILEOPSTRUCT fop = { };\r\n\r\n\tfop.wFunc = FO_DELETE;\r\n\tfop.pFrom = aName.c_str();\r\n\tfop.fFlags = FOF_NO_UI;\r\n\r\n\treturn SHFileOperation(&fop) == 0;\r\n}\r\n\r\nbool et::copyFile(const std::string& from, const std::string& to)\r\n{\r\n\tET_STRING_TYPE aFrom= ET_STRING_TO_PARAM_TYPE(from);\r\n\tET_STRING_TYPE aTo = ET_STRING_TO_PARAM_TYPE(to);\r\n\taFrom.resize(aFrom.size() + 1);\r\n\taTo.resize(aTo.size() + 1);\r\n\taFrom.back() = 0;\r\n\taTo.back() = 0;\r\n\r\n\tSHFILEOPSTRUCT fop = { };\r\n\r\n\tfop.wFunc = FO_COPY;\r\n\tfop.pFrom = aFrom.c_str();\r\n\tfop.pTo = aTo.c_str();\r\n\tfop.fFlags = FOF_NO_UI;\r\n\r\n\treturn SHFileOperation(&fop) == 0;\r\n}\r\n\r\nbool et::removeDirectory(const std::string& name)\r\n{\r\n\tET_STRING_TYPE aName = ET_STRING_TO_PARAM_TYPE(name);\r\n\taName.resize(aName.size() + 1);\r\n\taName.back() = 0;\r\n\r\n\tSHFILEOPSTRUCT fop = { };\r\n\r\n\tfop.wFunc = FO_DELETE;\r\n\tfop.pFrom = aName.c_str();\r\n\tfop.fFlags = FOF_NO_UI;\r\n\r\n\treturn SHFileOperation(&fop) == 0;\r\n}\r\n\r\nvoid et::findSubfolders(const std::string& folder, bool recursive, StringList& list)\r\n{\r\n\tStringList folderList;\r\n\t\r\n\tET_STRING_TYPE normalizedFolder = ET_STRING_TO_PARAM_TYPE(addTrailingSlash(folder));\r\n\tET_STRING_TYPE foldersSearchPath = normalizedFolder + allFilesMask;\r\n\r\n\tWIN32_FIND_DATA folders = { };\r\n\tHANDLE folderSearch = FindFirstFile(foldersSearchPath.c_str(), &folders);\r\n\tif (folderSearch != INVALID_HANDLE_VALUE)\r\n\t{\r\n\t\tdo\r\n\t\t{\r\n\t\t\tET_STRING_TYPE name(folders.cFileName);\r\n\t\t\tbool isFolder = (folders.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY;\r\n\t\t\tif (isFolder && (name != currentFolder) && (name != previousFolder))\r\n\t\t\t{\r\n\t\t\t\tfolderList.push_back(ET_STRING_TO_OUTPUT_TYPE(normalizedFolder + \r\n\t\t\t\t\tname + ET_STRING_FROM_CONST_CHAR(\"\\\\\")));\r\n\t\t\t}\r\n\t\t}\r\n\t\twhile (FindNextFile(folderSearch, &folders));\r\n\t\tFindClose(folderSearch);\r\n\t}\r\n\r\n\tif (recursive)\r\n\t{\r\n\t\tfor (const std::string& i : folderList)\r\n\t\t\tfindSubfolders(i, true, list);\r\n\t}\r\n\r\n\tlist.insert(list.end(), folderList.begin(), folderList.end());\r\n}\r\n\r\nvoid et::openUrl(const std::string& url)\r\n{\r\n\tShellExecute(nullptr, ET_STRING_FROM_CONST_CHAR(\"open\"), \r\n\t\tET_STRING_TO_PARAM_TYPE(url).c_str(), 0, 0, SW_SHOWNORMAL);\r\n}\r\n\r\nstd::string et::unicodeToUtf8(const std::wstring& w)\r\n{\r\n\tint mbcWidth = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, 0, 0, 0, 0);\r\n\r\n\tif (mbcWidth == 0)\r\n\t\treturn emptyString;\r\n\r\n\tDataStorage result(mbcWidth + 1, 0);\r\n\tWideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, result.data(), static_cast(result.size()), 0, 0);\r\n\r\n\treturn std::string(result.data());\r\n}\r\n\r\nstd::wstring et::utf8ToUnicode(const std::string& mbcs)\r\n{\r\n\tint uWidth = MultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, 0, 0);\r\n\tif (uWidth == 0)\r\n\t{\r\n\t\tswitch (GetLastError())\r\n\t\t{\r\n\t\tcase ERROR_INSUFFICIENT_BUFFER:\r\n\t\t\tstd::cout << \"A supplied buffer size was not large enough, \"\r\n\t\t\t\t\"or it was incorrectly set to NULL.\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tcase ERROR_INVALID_FLAGS:\r\n\t\t\tstd::cout << \"The values supplied for flags were not valid.\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tcase ERROR_INVALID_PARAMETER:\r\n\t\t\tstd::cout << \"Any of the parameter values was invalid.\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tcase ERROR_NO_UNICODE_TRANSLATION:\r\n\t\t\tstd::cout << \"Invalid Unicode was found in a string\" << std::endl;\r\n\t\t\tbreak;\r\n\r\n\t\tdefault:\r\n\t\t\tstd::cout << \"Failed to convert utf-8 to wchar_t\" << std::endl;\r\n\t\t}\r\n\r\n\t\treturn std::wstring();\r\n\t}\r\n\r\n\tDataStorage result(uWidth + 1, 0);\r\n\tMultiByteToWideChar(CP_UTF8, 0, mbcs.c_str(), -1, result.data(), static_cast(result.size()));\r\n\r\n\treturn std::wstring(result.data());\r\n}\r\n\r\nstd::string et::applicationIdentifierForCurrentProject()\r\n\t{ return \"com.et.app\"; }\r\n\r\nuint64_t et::getFileDate(const std::string& path)\r\n{\r\n\tWIN32_FIND_DATA findData = { };\r\n\tHANDLE search = FindFirstFile(ET_STRING_TO_PARAM_TYPE(path).c_str(), &findData);\r\n\tFindClose(search);\r\n\r\n\treturn findData.ftLastWriteTime.dwLowDateTime |\r\n\t\t(static_cast(findData.ftLastWriteTime.dwHighDateTime) << 32);\r\n}\r\n\r\nstd::vector et::availableScreens()\r\n{\r\n\tstd::vector result;\r\n\t\r\n\tEnumDisplayMonitors(nullptr, nullptr, [](HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) -> BOOL\r\n\t{\r\n\t\tMONITORINFO info = { sizeof(MONITORINFO) };\r\n\r\n\t\tGetMonitorInfo(hMonitor, &info);\r\n\r\n\t\trecti screenRect(info.rcMonitor.left, info.rcMonitor.top, info.rcMonitor.right - info.rcMonitor.left,\r\n\t\t\tinfo.rcMonitor.bottom - info.rcMonitor.top);\r\n\r\n\t\trecti workarea(info.rcWork.left, info.rcWork.top, info.rcWork.right - info.rcWork.left,\r\n\t\t\tinfo.rcWork.bottom - info.rcWork.top);\r\n\r\n\t\tstd::vector* r = reinterpret_cast*>(dwData);\r\n\t\tr->emplace_back(screenRect, workarea, 1);\r\n\t\treturn 1;\r\n\t}, \r\n\treinterpret_cast(&result));\r\n\r\n\treturn result;\r\n}\r\n\r\net::Screen et::currentScreen()\r\n{\r\n\treturn availableScreens().front();\r\n}\r\n\r\nstd::string et::selectFile(const StringList&, SelectFileMode mode, const std::string& defaultName)\r\n{\r\n\tET_STRING_TYPE defaultFileName = ET_STRING_TO_PARAM_TYPE(defaultName);\r\n\r\n\tDataStorage defaultFileNameData(etMax(size_t(MAX_PATH), defaultFileName.size()) + 1, 0);\r\n\tetCopyMemory(defaultFileNameData.data(), defaultFileName.data(), defaultFileName.size());\r\n\r\n\tOPENFILENAME of = { };\r\n\tof.lStructSize = sizeof(of);\r\n\tof.hInstance = GetModuleHandle(nullptr);\r\n\tof.Flags = OFN_DONTADDTORECENT | OFN_ENABLESIZING | OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;\r\n\tof.lpstrFile = defaultFileNameData.data();\r\n\tof.nMaxFile = MAX_PATH;\r\n\r\n#if (_UNICODE)\r\n\tof.lpstrFilter = L\"All Files\\0*.*\\0\\0\";\r\n#else\r\n\tof.lpstrFilter = \"All Files\\0*.*\\0\\0\";\r\n#endif\r\n\r\n\tauto func = (mode == SelectFileMode::Save) ? GetSaveFileName : GetOpenFileName;\r\n\r\n\treturn func(&of) ? ET_STRING_TO_OUTPUT_TYPE(of.lpstrFile) : emptyString;\r\n}\r\n\r\nvoid et::alert(const std::string& title, const std::string& message, const std::string&, AlertType type)\r\n{\r\n\tUINT alType = MB_ICONINFORMATION;\r\n\r\n\tswitch (type)\r\n\t{\r\n\tcase AlertType::Warning: \r\n\t\t{\r\n\t\t\talType = MB_ICONWARNING;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\tcase AlertType::Error: \r\n\t\t{\r\n\t\t\talType = MB_ICONERROR;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\tMessageBoxA(nullptr, message.c_str(), title.c_str(), alType);\r\n}\r\n\r\n#endif \/\/ ET_PLATFORM_WIN\r\n<|endoftext|>"} {"text":"#include \"Buttongrid.h\"\n\nButtongrid::Buttongrid(){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n}\n\nButtongrid::Buttongrid(unsigned char size){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tcolumns = size;\n\trows = size;\n\tgridSize = size;\n\t\n\t\/\/Allocate memory for labels\n\tif(gridSize!=NULL){\n\t\tif(labels = (unsigned char**)malloc(gridSize * sizeof(unsigned char*))){\n\t\t\tfor(int i=0; iinit();\n}\n\nButtongrid::Buttongrid(unsigned char r, unsigned char c){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tcolumns = c;\n\trows = r;\n\t\/\/gridSize = size;\n\t\n\t\/\/Allocate memory for labels\n\tif(rows!=NULL){\n\t\tif(labels = (unsigned char**)malloc(rows * sizeof(unsigned char*))){\n\t\t\tfor(int i=0; i= 0 && columns >= 0){\n\t\tchar qty = rows * columns;\n\t\tif(names = (const char**) malloc(qty * 8 * sizeof(char))){\n\t\t\tmemset(names,0,qty*8*sizeof(char));\n\t\t}\n\t}\n\t\n\t\/\/this->init();\n\n}\n\nButtongrid::Buttongrid(unsigned int width, unsigned int height, int backgroundColor, int textColor, int borderColor){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tx = 0;\n\ty = 0;\n\tthis->setSize(width,height);\n\tthis->setColors(backgroundColor,textColor,borderColor);\n\tthis->init();\n}\n\nButtongrid::~Buttongrid(){\n\tif(text) free(text);\n}\n\nvoid Buttongrid::init(){\n\tButton::init();\n\ttype = 0x31;\n\tborderWidth = 2;\n\tcharPos = 0;\n\t\n\t\/\/ Initialize labels with position ID\n\tfor(byte r=1; r<=rows; r++)\n\t{\n\t\tfor(byte c=1; c<=columns; c++)\n\t\t{\n\t\t\tlabels[r-1][c-1] = c+columns*(r-1);\n\t\t\t\/\/Serial.print(\"Row \");\n\t\t\t\/\/Serial.print(r);\n\t\t\t\/\/Serial.print(\" Col \");\n\t\t\t\/\/Serial.print(c);\n\t\t\t\/\/Serial.print(\" Num \");\n\t\t\t\/\/Serial.println(c+columns*(r-1));\n\t\t}\n\t}\n}\n\nvoid Buttongrid::drawGrid(){\n int xPos,yPos,width,height;\n int btnWidth,btnHeight;\n \n xPos = x;\t\n yPos = y;\n width = w;\n height = h;\n btnWidth = w \/ columns;\n btnHeight = h \/ rows;\n \n \/\/--nums background rectangle\n Tft.fillRectangle(xPos,yPos,width,height,bgColor);\n \n\t\/\/-- outer border\n for(byte i=borderWidth; i!=0;i--){\n Tft.drawRectangle(xPos++,yPos++,width--,height--,borderColor);\n width--;\n height--;\n }\n \n \/\/-- horizontal lines\n for(byte j=1;j0){ \t\n\t\t\t\/\/Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK);\n\t\t\tfor(byte i=0; i0){ \t\n\t\t\t\/\/Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK);\n\t\t\tfor(byte i=0; i 0){\n\t\tfor(byte j=1;jbgColor);\n\t\t}\n }\n if(vGap > 0){\n\t\tfor(byte j=1;jbgColor);\n\t\t}\n } \n \n \/\/-- draw contents \n byte colIndex=0;\n byte rowIndex=0;\n for(byte r=1; r<=rows; r++)\n {\n\t for(byte c=1; c<=columns; c++)\n\t {\n\t\t printName(getNumber(r,c));\n\t }\n }\n \n}\n\nvoid Buttongrid::setEventHandler(void (*functionPointer)(Buttongrid *, unsigned char)){\n\teventHandler = functionPointer;\n}\n\nvoid Buttongrid::configure(byte size, byte f){\n\tcolumns = size;\n\trows = size;\n\tgridSize = size;\n\tfont_size = f;\n\tshow();\n}\n\nunsigned char Buttongrid::getColumn(unsigned char num){\n\tunsigned char val = num%columns;\n\treturn val==0 ? columns : val;\n}\n\nunsigned char Buttongrid::getRow(unsigned char num){\n\tnum -= 1;\n\tunsigned char mod = num%columns;\t\t\n\treturn num\/columns + 1;\n}\n\nunsigned char Buttongrid::getNumber(unsigned char row, unsigned char column){\n\tunsigned char val = column + (row - 1) * columns;\n\treturn val;\n}\n\nvoid Buttongrid::setNum(unsigned char id){\n\tint boundX1, boundX2, boundY1, boundY2;\n\tint btnWidth = w\/columns;\n\tint btnHeight = h\/rows;\n\tunsigned char colIndex = getColumn(id)-1;\n\tunsigned char rowIndex = getRow(id)-1;\n\tunsigned char digits = Tft.Get_Digits(id);\n\t\n\t\/\/Calculates initial position of text inside the btnWidth\n\t\/\/considering the number's width and font size.\n\tint xPos = btnWidth\/2 - (digits*FONT_X*font_size)\/2;\/\/btnWidth\/(2) - 6*digits -2;\n\tint yPos = btnHeight\/(2) - 8;\n\t\n\t\/\/Calculates position of the text considering\n\t\/\/its column or row and the btnWidth.\n \txPos = x+(colIndex*btnWidth)+xPos+borderWidth;\n \tyPos = y+yPos+(rowIndex*btnHeight);\n \t\n \t\/\/Draw contents function\n \tTft.drawNumber(id,xPos,yPos,font_size,BLACK);\n}\n\nvoid Buttongrid::setLabel(unsigned char id, unsigned char label){\n\tint boundX1, boundX2, boundY1, boundY2;\n\tint btnWidth = w\/columns;\n\tint btnHeight = h\/rows;\n\tunsigned char colIndex = getColumn(id)-1;\n\tunsigned char rowIndex = getRow(id)-1;\n\tunsigned char digits = Tft.Get_Digits(label);\n\t\n\t\/\/labels[rowIndex][colIndex] = label; <---- No, can't do this! No enough memory to hold strings for each button\n\t\/\/Calculates initial position of text inside the btnWidth\n\t\/\/considering the number's width and font size.\n\t\n\tint xPos = (btnWidth - digits*6*font_size)\/2;\/\/btnWidth\/(2) - 6*digits -2;\n\tint yPos = (btnHeight-FONT_Y*fontSize)\/2;\/\/btnHeight\/(2) - 8;\n\t\n\t\/\/Calculates position of the text considering\n\t\/\/its column or row and the btnWidth.\n\txPos = x+(colIndex*btnWidth)+xPos+borderWidth+hGap;\/\/+(2*borderWidth);\/\/+borderWidth;\n\tyPos = y+(rowIndex*btnHeight)+yPos+borderWidth+vGap;\/\/+(2*borderWidth);\n\n\t\/\/Draw contents function\n\tTft.drawNumber(label,xPos,yPos,font_size,BLACK);\n}\n\nvoid Buttongrid::setName(unsigned char id, const char name[8]){\n\tnames[id] = name;\t\n\treturn;\n}\n\nvoid Buttongrid::setName(unsigned char id, char number){\n\t\/\/names[id] = ;\t\n\treturn;\n}\n\nvoid Buttongrid::printName(unsigned char id){\n\tconst char* name = names[id];\t\n\t\/\/ Calculate characters in name\n\tint n;\n\tfor(n=0;n<8;n++){\n\t\tif(name[n] == 0) break;\n\t}\n\n\tSerial.print(n);\n\tSerial.print(\" characters for id: \");\n\tSerial.print(id);\n\tSerial.print(\" \");\n\tSerial.println(names[id]);\n\n\t\/\/setNum(id);\n\tsetLabel(id,labels[getRow(id)-1][getColumn(id)-1]);\n\treturn;\n\t\n\t\/\/ If name is empty draw the id, else draw the name\n\tif(n==0){\n\t\tsetNum(id);\n\t}else{\n\t\t\/\/i++;\n\t\tint boundX1, boundX2, boundY1, boundY2;\n\t\tint btnWidth = w\/columns;\n\t\tint btnHeight = h\/rows;\n\t\tunsigned char colIndex = getColumn(id)-1;\n\t\tunsigned char rowIndex = getRow(id)-1;\n\t\n\t\tint xPos = btnWidth\/2 - (n*FONT_X*font_size)\/2;\n\t\tint yPos = btnHeight\/(2) - 8;\t\n\t\n\t\txPos = x+(colIndex*btnWidth)+xPos+3*borderWidth;\n\t\tyPos = y+yPos+(rowIndex*btnHeight);\t\n\t\n\t\tTft.drawString((char*)names[id],xPos, yPos, font_size, fgColor);\n\t}\t\n\t\n\treturn;\t\n}\n\nvoid Buttongrid::clear(){\n\tdrawGrid();\n\tlastPressed = 0;\n}\n \n\/\/Overriden virtual methods\n\nbool Buttongrid::checkTouch(Point* p){\n\tint boundX1, boundX2, boundY1, boundY2;\n\tint btnWidth = w\/columns;\n\tint btnHeight = h\/rows;\n\tbool pressed = false;\n\tif(lastMillis + debounceTime < millis()){ \n\t\tif((p->x > x+borderWidth) && (p->x < x+w-borderWidth) && (p->y > y+borderWidth) && (p->y < y+h-borderWidth)){\n\t\t\t\/\/num coordinates\n\t\t\tfor(int r = 1;(r <= rows)&&(!pressed); r++)\n\t\t\t{\n\t\t\t\t\/\/ Determine the bounding y's for this row\n\t\t\t\tboundY1 = y+(btnHeight)*(r-1)+borderWidth;\n\t\t\t\tboundY2 = y+(btnHeight)*r-borderWidth;\n\t\t\t\tfor(int c = 1;(c <= columns)&&(!pressed);c++)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Determine the bounding x's for this column\n\t\t\t\t\tboundX1 = x + (btnWidth)*(c-1) + borderWidth;\n\t\t\t\t\tboundX2 = x + (btnWidth)*c - borderWidth;\n\t\t\t\t\tint num = columns*(r - 1) + c;\n\t\t\t\t\tif((p->x > boundX1) && (p->x < boundX2) && (p->y > boundY1) && (p->y < boundY2)){\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ Restore last button pressed appearance\n\t\t\t\t\t\tif(clearLastPressed && lastPressed != 0){\n\t\t\t\t\t\t\tint lastX = x + (btnWidth)*(getColumn(lastPressed)-1) + borderWidth;\n\t\t\t\t\t\t\tint lastY = y+(btnHeight)*(getRow(lastPressed)-1)+borderWidth;\n\t\t\t\t\t\t\tif(HIGHLIGHT == 1){\n\t\t\t\t\t\t\t\tTft.fillRectangle(lastX,lastY,btnWidth-borderWidth-1,btnHeight-borderWidth-1,bgColor);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/\/setLabel(lastPressed,labels[getRow(lastPressed)-1][getColumn(lastPressed)-1]);\n\t\t\t\t\t\t\tprintName(lastPressed);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ Highlight currently pressed button\n\t\t\t\t\t\tif(HIGHLIGHT == 1){\n\t\t\t\t\t\t\tTft.fillRectangle(boundX1,boundY1,btnWidth-borderWidth-1,btnHeight-borderWidth-1,highlightColor);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/setNum(num);\n\t\t\t\t\t\t\/\/setLabel(num,labels[r-1][c-1]);\n\t\t\t\t\t\tprintName(num);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ Call event handler with pressed button id\n\t\t\t\t\t\teventHandler(this,num);\n\t\t\t\t\t\tpressed = true;\n\t\t\t\t\t\tlastPressed = num;\n\t\t\t\t\t}\n\t\t\t\t}\/\/ -- columns for loop\n\t\t\t}\/\/ --rows for loop\n\t\t}\/\/ -- if touch within widget area\n\t\ttouched = !touched;\n\t\tlastMillis = millis();\t\t\n\t}\/\/ -- debounce\n\treturn true; \/\/ <--- False means block further event checking.\n}\n\nvoid Buttongrid::show(){\n\tdrawGrid();\n\tupdate();\n}\n\nvoid Buttongrid::update(){\n\treturn;\n}\nRemoved Serial prints from printName in ButtonGrid#include \"Buttongrid.h\"\n\nButtongrid::Buttongrid(){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n}\n\nButtongrid::Buttongrid(unsigned char size){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tcolumns = size;\n\trows = size;\n\tgridSize = size;\n\t\n\t\/\/Allocate memory for labels\n\tif(gridSize!=NULL){\n\t\tif(labels = (unsigned char**)malloc(gridSize * sizeof(unsigned char*))){\n\t\t\tfor(int i=0; iinit();\n}\n\nButtongrid::Buttongrid(unsigned char r, unsigned char c){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tcolumns = c;\n\trows = r;\n\t\/\/gridSize = size;\n\t\n\t\/\/Allocate memory for labels\n\tif(rows!=NULL){\n\t\tif(labels = (unsigned char**)malloc(rows * sizeof(unsigned char*))){\n\t\t\tfor(int i=0; i= 0 && columns >= 0){\n\t\tchar qty = rows * columns;\n\t\tif(names = (const char**) malloc(qty * 8 * sizeof(char))){\n\t\t\tmemset(names,0,qty*8*sizeof(char));\n\t\t}\n\t}\n\t\n\t\/\/this->init();\n\n}\n\nButtongrid::Buttongrid(unsigned int width, unsigned int height, int backgroundColor, int textColor, int borderColor){\n\tif(text = (char *)malloc(DISPLAY_SIZE+1)) memset(text,0,DISPLAY_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tx = 0;\n\ty = 0;\n\tthis->setSize(width,height);\n\tthis->setColors(backgroundColor,textColor,borderColor);\n\tthis->init();\n}\n\nButtongrid::~Buttongrid(){\n\tif(text) free(text);\n}\n\nvoid Buttongrid::init(){\n\tButton::init();\n\ttype = 0x31;\n\tborderWidth = 2;\n\tcharPos = 0;\n\t\n\t\/\/ Initialize labels with position ID\n\tfor(byte r=1; r<=rows; r++)\n\t{\n\t\tfor(byte c=1; c<=columns; c++)\n\t\t{\n\t\t\tlabels[r-1][c-1] = c+columns*(r-1);\n\t\t\t\/\/Serial.print(\"Row \");\n\t\t\t\/\/Serial.print(r);\n\t\t\t\/\/Serial.print(\" Col \");\n\t\t\t\/\/Serial.print(c);\n\t\t\t\/\/Serial.print(\" Num \");\n\t\t\t\/\/Serial.println(c+columns*(r-1));\n\t\t}\n\t}\n}\n\nvoid Buttongrid::drawGrid(){\n int xPos,yPos,width,height;\n int btnWidth,btnHeight;\n \n xPos = x;\t\n yPos = y;\n width = w;\n height = h;\n btnWidth = w \/ columns;\n btnHeight = h \/ rows;\n \n \/\/--nums background rectangle\n Tft.fillRectangle(xPos,yPos,width,height,bgColor);\n \n\t\/\/-- outer border\n for(byte i=borderWidth; i!=0;i--){\n Tft.drawRectangle(xPos++,yPos++,width--,height--,borderColor);\n width--;\n height--;\n }\n \n \/\/-- horizontal lines\n for(byte j=1;j0){ \t\n\t\t\t\/\/Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK);\n\t\t\tfor(byte i=0; i0){ \t\n\t\t\t\/\/Tft.fillRectangle(xPos,y-vGap+btnHeight*j+1,width,btnHeight-1,BLACK);\n\t\t\tfor(byte i=0; i 0){\n\t\tfor(byte j=1;jbgColor);\n\t\t}\n }\n if(vGap > 0){\n\t\tfor(byte j=1;jbgColor);\n\t\t}\n } \n \n \/\/-- draw contents \n byte colIndex=0;\n byte rowIndex=0;\n for(byte r=1; r<=rows; r++)\n {\n\t for(byte c=1; c<=columns; c++)\n\t {\n\t\t printName(getNumber(r,c));\n\t }\n }\n \n}\n\nvoid Buttongrid::setEventHandler(void (*functionPointer)(Buttongrid *, unsigned char)){\n\teventHandler = functionPointer;\n}\n\nvoid Buttongrid::configure(byte size, byte f){\n\tcolumns = size;\n\trows = size;\n\tgridSize = size;\n\tfont_size = f;\n\tshow();\n}\n\nunsigned char Buttongrid::getColumn(unsigned char num){\n\tunsigned char val = num%columns;\n\treturn val==0 ? columns : val;\n}\n\nunsigned char Buttongrid::getRow(unsigned char num){\n\tnum -= 1;\n\tunsigned char mod = num%columns;\t\t\n\treturn num\/columns + 1;\n}\n\nunsigned char Buttongrid::getNumber(unsigned char row, unsigned char column){\n\tunsigned char val = column + (row - 1) * columns;\n\treturn val;\n}\n\nvoid Buttongrid::setNum(unsigned char id){\n\tint boundX1, boundX2, boundY1, boundY2;\n\tint btnWidth = w\/columns;\n\tint btnHeight = h\/rows;\n\tunsigned char colIndex = getColumn(id)-1;\n\tunsigned char rowIndex = getRow(id)-1;\n\tunsigned char digits = Tft.Get_Digits(id);\n\t\n\t\/\/Calculates initial position of text inside the btnWidth\n\t\/\/considering the number's width and font size.\n\tint xPos = btnWidth\/2 - (digits*FONT_X*font_size)\/2;\/\/btnWidth\/(2) - 6*digits -2;\n\tint yPos = btnHeight\/(2) - 8;\n\t\n\t\/\/Calculates position of the text considering\n\t\/\/its column or row and the btnWidth.\n \txPos = x+(colIndex*btnWidth)+xPos+borderWidth;\n \tyPos = y+yPos+(rowIndex*btnHeight);\n \t\n \t\/\/Draw contents function\n \tTft.drawNumber(id,xPos,yPos,font_size,BLACK);\n}\n\nvoid Buttongrid::setLabel(unsigned char id, unsigned char label){\n\tint boundX1, boundX2, boundY1, boundY2;\n\tint btnWidth = w\/columns;\n\tint btnHeight = h\/rows;\n\tunsigned char colIndex = getColumn(id)-1;\n\tunsigned char rowIndex = getRow(id)-1;\n\tunsigned char digits = Tft.Get_Digits(label);\n\t\n\t\/\/labels[rowIndex][colIndex] = label; <---- No, can't do this! No enough memory to hold strings for each button\n\t\/\/Calculates initial position of text inside the btnWidth\n\t\/\/considering the number's width and font size.\n\t\n\tint xPos = (btnWidth - digits*6*font_size)\/2;\/\/btnWidth\/(2) - 6*digits -2;\n\tint yPos = (btnHeight-FONT_Y*fontSize)\/2;\/\/btnHeight\/(2) - 8;\n\t\n\t\/\/Calculates position of the text considering\n\t\/\/its column or row and the btnWidth.\n\txPos = x+(colIndex*btnWidth)+xPos+borderWidth+hGap;\/\/+(2*borderWidth);\/\/+borderWidth;\n\tyPos = y+(rowIndex*btnHeight)+yPos+borderWidth+vGap;\/\/+(2*borderWidth);\n\n\t\/\/Draw contents function\n\tTft.drawNumber(label,xPos,yPos,font_size,BLACK);\n}\n\nvoid Buttongrid::setName(unsigned char id, const char name[8]){\n\tnames[id] = name;\t\n\treturn;\n}\n\nvoid Buttongrid::setName(unsigned char id, char number){\n\t\/\/names[id] = ;\t\n\treturn;\n}\n\nvoid Buttongrid::printName(unsigned char id){\n\tconst char* name = names[id];\t\n\t\/\/ Calculate characters in name\n\tint n;\n\tfor(n=0;n<8;n++){\n\t\tif(name[n] == 0) break;\n\t}\n\n\t\/\/Serial.print(n);\n\t\/\/Serial.print(\" characters for id: \");\n\t\/\/Serial.print(id);\n\t\/\/Serial.print(\" \");\n\t\/\/Serial.println(names[id]);\n\n\t\/\/setNum(id);\n\tsetLabel(id,labels[getRow(id)-1][getColumn(id)-1]);\n\treturn;\n\t\n\t\/\/ If name is empty draw the id, else draw the name\n\tif(n==0){\n\t\tsetNum(id);\n\t}else{\n\t\t\/\/i++;\n\t\tint boundX1, boundX2, boundY1, boundY2;\n\t\tint btnWidth = w\/columns;\n\t\tint btnHeight = h\/rows;\n\t\tunsigned char colIndex = getColumn(id)-1;\n\t\tunsigned char rowIndex = getRow(id)-1;\n\t\n\t\tint xPos = btnWidth\/2 - (n*FONT_X*font_size)\/2;\n\t\tint yPos = btnHeight\/(2) - 8;\t\n\t\n\t\txPos = x+(colIndex*btnWidth)+xPos+3*borderWidth;\n\t\tyPos = y+yPos+(rowIndex*btnHeight);\t\n\t\n\t\tTft.drawString((char*)names[id],xPos, yPos, font_size, fgColor);\n\t}\t\n\t\n\treturn;\t\n}\n\nvoid Buttongrid::clear(){\n\tdrawGrid();\n\tlastPressed = 0;\n}\n \n\/\/Overriden virtual methods\n\nbool Buttongrid::checkTouch(Point* p){\n\tint boundX1, boundX2, boundY1, boundY2;\n\tint btnWidth = w\/columns;\n\tint btnHeight = h\/rows;\n\tbool pressed = false;\n\tif(lastMillis + debounceTime < millis()){ \n\t\tif((p->x > x+borderWidth) && (p->x < x+w-borderWidth) && (p->y > y+borderWidth) && (p->y < y+h-borderWidth)){\n\t\t\t\/\/num coordinates\n\t\t\tfor(int r = 1;(r <= rows)&&(!pressed); r++)\n\t\t\t{\n\t\t\t\t\/\/ Determine the bounding y's for this row\n\t\t\t\tboundY1 = y+(btnHeight)*(r-1)+borderWidth;\n\t\t\t\tboundY2 = y+(btnHeight)*r-borderWidth;\n\t\t\t\tfor(int c = 1;(c <= columns)&&(!pressed);c++)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Determine the bounding x's for this column\n\t\t\t\t\tboundX1 = x + (btnWidth)*(c-1) + borderWidth;\n\t\t\t\t\tboundX2 = x + (btnWidth)*c - borderWidth;\n\t\t\t\t\tint num = columns*(r - 1) + c;\n\t\t\t\t\tif((p->x > boundX1) && (p->x < boundX2) && (p->y > boundY1) && (p->y < boundY2)){\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ Restore last button pressed appearance\n\t\t\t\t\t\tif(clearLastPressed && lastPressed != 0){\n\t\t\t\t\t\t\tint lastX = x + (btnWidth)*(getColumn(lastPressed)-1) + borderWidth;\n\t\t\t\t\t\t\tint lastY = y+(btnHeight)*(getRow(lastPressed)-1)+borderWidth;\n\t\t\t\t\t\t\tif(HIGHLIGHT == 1){\n\t\t\t\t\t\t\t\tTft.fillRectangle(lastX,lastY,btnWidth-borderWidth-1,btnHeight-borderWidth-1,bgColor);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/\/setLabel(lastPressed,labels[getRow(lastPressed)-1][getColumn(lastPressed)-1]);\n\t\t\t\t\t\t\tprintName(lastPressed);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ Highlight currently pressed button\n\t\t\t\t\t\tif(HIGHLIGHT == 1){\n\t\t\t\t\t\t\tTft.fillRectangle(boundX1,boundY1,btnWidth-borderWidth-1,btnHeight-borderWidth-1,highlightColor);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/setNum(num);\n\t\t\t\t\t\t\/\/setLabel(num,labels[r-1][c-1]);\n\t\t\t\t\t\tprintName(num);\n\t\t\t\t\t\t\n\t\t\t\t\t\t\/\/ Call event handler with pressed button id\n\t\t\t\t\t\teventHandler(this,num);\n\t\t\t\t\t\tpressed = true;\n\t\t\t\t\t\tlastPressed = num;\n\t\t\t\t\t}\n\t\t\t\t}\/\/ -- columns for loop\n\t\t\t}\/\/ --rows for loop\n\t\t}\/\/ -- if touch within widget area\n\t\ttouched = !touched;\n\t\tlastMillis = millis();\t\t\n\t}\/\/ -- debounce\n\treturn true; \/\/ <--- False means block further event checking.\n}\n\nvoid Buttongrid::show(){\n\tdrawGrid();\n\tupdate();\n}\n\nvoid Buttongrid::update(){\n\treturn;\n}\n<|endoftext|>"} {"text":"#include \"chimera\/render\/BSPTree.hpp\"\n#include \n\ntemplate void swapFace(T& a, T& b) {\n T c = b;\n b = a;\n a = c;\n}\n\nglm::vec3 aprox(const glm::vec3& dado) {\n return glm::vec3((fabs(dado.x) < EPSILON) ? 0.0f : dado.x, (fabs(dado.y) < EPSILON) ? 0.0f : dado.y,\n (fabs(dado.z) < EPSILON) ? 0.0f : dado.z);\n}\n\nglm::vec3 intersect(const glm::vec3& linestart, const glm::vec3& lineend, const glm::vec3& vertex,\n const glm::vec3& normal, float& percentage) {\n\n float num = glm::dot(normal, linestart);\n glm::vec3 direction = lineend - linestart;\n\n float linelength = glm::dot(normal, direction);\n float D = -glm::dot(normal, vertex); \/\/ direção inversa\n\n percentage = -(num + D) \/ linelength;\n\n glm::vec3 intersection = linestart + percentage * direction;\n return aprox(intersection);\n}\n\nvoid splitTriangle(const glm::vec3& fx, Chimera::Triangle* _pTriangle, Chimera::Triangle* _partition,\n std::vector* _pListPolygon) {\n glm::vec3& a = _pTriangle->vertex[0].position;\n glm::vec3& b = _pTriangle->vertex[1].position;\n glm::vec3& c = _pTriangle->vertex[2].position;\n\n \/\/ acerto para vertex do tex final igualar a rotacao do triangulo\n Chimera::VertexData* pVertex_a = nullptr;\n Chimera::VertexData* pVertex_b = nullptr;\n Chimera::VertexData* pVertex_c = nullptr;\n\n \/\/ Normaliza Triangulo para que o corte do hiper-plano esteja nos segmentos de reta CA e CB (corte em a e b)\n if (fx.x * fx.z >= 0) { \/\/ corte em a e c\n swapFace(b, c);\n swapFace(a, b);\n\n pVertex_a = &_pTriangle->vertex[2]; \/\/ old c\n pVertex_b = &_pTriangle->vertex[0]; \/\/ old a\n pVertex_c = &_pTriangle->vertex[1]; \/\/ old b\n\n } else if (fx.y * fx.z >= 0) { \/\/ corte em b e c\n swapFace(a, c);\n swapFace(a, b);\n \/\/--\n pVertex_a = &_pTriangle->vertex[1]; \/\/ old b\n pVertex_b = &_pTriangle->vertex[2]; \/\/ old c\n pVertex_c = &_pTriangle->vertex[0]; \/\/ old a\n\n } else { \/\/ Cortre em a e b\n\n pVertex_a = &_pTriangle->vertex[0]; \/\/ old a\n pVertex_b = &_pTriangle->vertex[1]; \/\/ old b\n pVertex_c = &_pTriangle->vertex[2]; \/\/ old c\n }\n\n float propAC = 0.0;\n float propBC = 0.0;\n glm::vec3 A = intersect(a, c, _partition->vertex[0].position, _partition->normal(), propAC);\n glm::vec3 B = intersect(b, c, _partition->vertex[0].position, _partition->normal(), propBC);\n\n \/\/ PA texture coord\n glm::vec2 deltaA = (pVertex_c->texture - pVertex_a->texture) * propAC;\n glm::vec2 texA = pVertex_a->texture + deltaA;\n\n \/\/ PB texture coord\n glm::vec2 deltaB = (pVertex_c->texture - pVertex_b->texture) * propBC;\n glm::vec2 texB = pVertex_b->texture + deltaB;\n\n \/\/-- T1\n Chimera::Triangle T1(a, b, A);\n T1.vertex[0].texture = pVertex_a->texture; \/\/ a old b\n T1.vertex[1].texture = pVertex_b->texture; \/\/ b old c\n T1.vertex[2].texture = texA; \/\/ A\n\n \/\/-- T2\n Chimera::Triangle T2(b, B, A);\n T2.vertex[0].texture = pVertex_b->texture; \/\/ b old c\n T2.vertex[1].texture = texB; \/\/ B\n T2.vertex[2].texture = texA; \/\/ A\n\n \/\/ -- T3\n Chimera::Triangle T3(A, B, c);\n T3.vertex[0].texture = texA; \/\/ A\n T3.vertex[1].texture = texB; \/\/ B\n T3.vertex[2].texture = pVertex_c->texture; \/\/ c old a\n\n for (int i = 0; i < 3; i++) {\n T1.vertex[i].normal = _pTriangle->vertex[i].normal;\n T2.vertex[i].normal = _pTriangle->vertex[i].normal;\n T3.vertex[i].normal = _pTriangle->vertex[i].normal;\n }\n\n _pListPolygon->push_back(T1);\n _pListPolygon->push_back(T2);\n _pListPolygon->push_back(T3);\n}\n\nSIDE classifyPoly(Chimera::Triangle* plane, Chimera::Triangle* poly, glm::vec3& _resultTest) {\n \/\/ ref: http:\/\/www.cs.utah.edu\/~jsnider\/SeniorProj\/BSP\/default.htm\n unsigned short infront = 0;\n unsigned short behind = 0;\n unsigned short onPlane = 0;\n float result[3];\n\n for (unsigned short a = 0; a < 3; a++) {\n glm::vec3 direction = plane->vertex[0].position - poly->vertex[a].position;\n result[a] = glm::dot(direction, plane->normal());\n if (result[a] > EPSILON) {\n behind++;\n } else if (result[a] < -EPSILON) {\n infront++;\n } else {\n onPlane++;\n infront++;\n behind++;\n }\n }\n\n _resultTest.x = result[0];\n _resultTest.y = result[1];\n _resultTest.z = result[2];\n\n if (onPlane == 3)\n return SIDE::CP_ONPLANE;\n\n if (behind == 3)\n return SIDE::CP_BACK;\n\n if (infront == 3)\n return SIDE::CP_FRONT;\n\n return SIDE::CP_SPANNING;\n}\n\nBSPTreeNode* bsptreeBuild(std::vector* _pListPolygon) {\n if (_pListPolygon->empty() == true)\n return nullptr;\n \/\/ tree->partition\n BSPTreeNode* tree = new BSPTreeNode(_pListPolygon->back());\n _pListPolygon->pop_back();\n tree->polygons.push_back(tree->partition);\n\n std::vector front_list;\n std::vector back_list;\n\n while (_pListPolygon->empty() == false) {\n\n Chimera::Triangle poly = _pListPolygon->back();\n _pListPolygon->pop_back();\n glm::vec3 result;\n SIDE teste = classifyPoly(&tree->partition, &poly, result);\n\n if (teste == SIDE::CP_BACK)\n back_list.push_back(poly);\n else if (teste == SIDE::CP_FRONT)\n front_list.push_back(poly);\n else if (teste == SIDE::CP_ONPLANE)\n tree->polygons.push_back(poly);\n else \/\/ CP_SPANNING\n splitTriangle(result, &poly, &tree->partition, _pListPolygon);\n }\n tree->front = bsptreeBuild(&front_list);\n tree->back = bsptreeBuild(&back_list);\n return tree;\n}\n\n\/\/------PARSER METODOS------\n\nSIDE classifyPoint(Chimera::Triangle* plane, glm::vec3* eye) {\n \/\/ ref: http:\/\/www.cs.utah.edu\/~jsnider\/SeniorProj\/BSP\/default.htm\n float result;\n glm::vec3* vec1 = (glm::vec3*)&plane->vertex[0];\n glm::vec3 dir = (*vec1) - (*eye);\n result = glm::dot(dir, plane->normal());\n\n if (result < -EPSILON)\n return SIDE::CP_FRONT;\n\n if (result > EPSILON)\n return SIDE::CP_BACK;\n\n return SIDE::CP_ONPLANE;\n}\n\nvoid drawPolygon(BSPTreeNode* tree, std::vector* _pOutVertex, bool logdata, bool frontSide) {\n \/\/ tree->arrayTriangle.DrawPolygons(); \/\/ Abaixo equivale a esta linha\n for (auto it = tree->polygons.begin(); it != tree->polygons.end(); it++) {\n Chimera::Triangle t = (*it);\n\n \/\/ if (t.getSerial() == 10) \/\/ 8, 9, 10\n \/\/ continue;\n\n _pOutVertex->push_back(t.vertex[0]);\n _pOutVertex->push_back(t.vertex[1]);\n _pOutVertex->push_back(t.vertex[2]);\n\n \/\/ FIXME: remover depois de concluir o algoritmo\n if (logdata == true) {\n if (frontSide == true)\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Face F: %d\", t.getSerial());\n else\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Face B: %d\", t.getSerial());\n }\n }\n}\n\nvoid traverseTree(BSPTreeNode* tree, glm::vec3* eye, std::vector* _pOutVertex, bool logdata) {\n \/\/ ref: https:\/\/web.cs.wpi.edu\/~matt\/courses\/cs563\/talks\/bsp\/document.html\n if (tree == nullptr)\n return;\n\n SIDE result = classifyPoint(&tree->partition, eye);\n if (result == SIDE::CP_FRONT) {\n\n traverseTree(tree->back, eye, _pOutVertex, logdata);\n drawPolygon(tree, _pOutVertex, logdata, true);\n traverseTree(tree->front, eye, _pOutVertex, logdata);\n\n } else if (result == SIDE::CP_BACK) {\n\n traverseTree(tree->front, eye, _pOutVertex, logdata);\n drawPolygon(tree, _pOutVertex, logdata, false);\n traverseTree(tree->back, eye, _pOutVertex, logdata);\n\n } else { \/\/ result == SIDE::CP_ONPLANE\n \/\/ the eye point is on the partition plane...\n traverseTree(tree->front, eye, _pOutVertex, logdata);\n traverseTree(tree->back, eye, _pOutVertex, logdata);\n }\n}\n\nvoid bsptreeDraw(BSPTreeNode* _pRoot, glm::vec3* eye, std::vector* _pOutVertex, bool logdata) {\n traverseTree(_pRoot, eye, _pOutVertex, logdata);\n}\n\nbool getIntersect(glm::vec3* linestart, glm::vec3* lineend, glm::vec3* vertex, glm::vec3* normal,\n glm::vec3* intersection, float* percentage) {\n glm::vec3 direction, L1;\n float linelength, dist_from_plane;\n\n direction.x = lineend->x - linestart->x;\n direction.y = lineend->y - linestart->y;\n direction.z = lineend->z - linestart->z;\n\n linelength = glm::dot(direction, *normal);\n\n if (fabsf(linelength) < 0.0001) {\n return false;\n }\n\n L1.x = vertex->x - linestart->x;\n L1.y = vertex->y - linestart->y;\n L1.z = vertex->z - linestart->z;\n\n dist_from_plane = glm::dot(L1, *normal);\n *percentage = dist_from_plane \/ linelength;\n\n if (*percentage < 0.0f) {\n return false;\n } else if (*percentage > 1.0f) {\n return false;\n }\n\n intersection->x = linestart->x + direction.x * (*percentage);\n intersection->y = linestart->y + direction.y * (*percentage);\n intersection->z = linestart->z + direction.z * (*percentage);\n return true;\n}melhoria#include \"chimera\/render\/BSPTree.hpp\"\n#include \n\ntemplate void swapFace(T& a, T& b) {\n T c = b;\n b = a;\n a = c;\n}\n\nglm::vec3 aprox(const glm::vec3& dado) {\n return glm::vec3((fabs(dado.x) < EPSILON) ? 0.0f : dado.x, (fabs(dado.y) < EPSILON) ? 0.0f : dado.y,\n (fabs(dado.z) < EPSILON) ? 0.0f : dado.z);\n}\n\nbool intersect(const glm::vec3& linestart, const glm::vec3& lineend, const glm::vec3& vertex, const glm::vec3& normal,\n glm::vec3& intersection, float& percentage) {\n\n glm::vec3 direction = lineend - linestart;\n float linelength = glm::dot(direction, normal);\n if (fabsf(linelength) < 0.0001)\n return false;\n\n glm::vec3 L1 = vertex - linestart;\n\n float dist_from_plane = glm::dot(L1, normal);\n percentage = dist_from_plane \/ linelength;\n\n if (percentage < 0.0f)\n return false;\n else if (percentage > 1.0f)\n return false;\n\n intersection = linestart + (direction * percentage);\n return true;\n}\n\nvoid splitTriangle(const glm::vec3& fx, Chimera::Triangle* _pTriangle, Chimera::Triangle* _partition,\n std::vector* _pListPolygon) {\n glm::vec3& a = _pTriangle->vertex[0].position;\n glm::vec3& b = _pTriangle->vertex[1].position;\n glm::vec3& c = _pTriangle->vertex[2].position;\n\n \/\/ acerto para vertex do tex final igualar a rotacao do triangulo\n Chimera::VertexData* pVertex_a = nullptr;\n Chimera::VertexData* pVertex_b = nullptr;\n Chimera::VertexData* pVertex_c = nullptr;\n\n \/\/ Normaliza Triangulo para que o corte do hiper-plano esteja nos segmentos de reta CA e CB (corte em a e b)\n if (fx.x * fx.z >= 0) { \/\/ corte em a e c\n swapFace(b, c);\n swapFace(a, b);\n\n pVertex_a = &_pTriangle->vertex[2]; \/\/ old c\n pVertex_b = &_pTriangle->vertex[0]; \/\/ old a\n pVertex_c = &_pTriangle->vertex[1]; \/\/ old b\n\n } else if (fx.y * fx.z >= 0) { \/\/ corte em b e c\n swapFace(a, c);\n swapFace(a, b);\n \/\/--\n pVertex_a = &_pTriangle->vertex[1]; \/\/ old b\n pVertex_b = &_pTriangle->vertex[2]; \/\/ old c\n pVertex_c = &_pTriangle->vertex[0]; \/\/ old a\n\n } else { \/\/ Cortre em a e b\n\n pVertex_a = &_pTriangle->vertex[0]; \/\/ old a\n pVertex_b = &_pTriangle->vertex[1]; \/\/ old b\n pVertex_c = &_pTriangle->vertex[2]; \/\/ old c\n }\n\n float propAC = 0.0;\n float propBC = 0.0;\n glm::vec3 A, B;\n intersect(a, c, _partition->vertex[0].position, _partition->normal(), A, propAC);\n intersect(b, c, _partition->vertex[0].position, _partition->normal(), B, propBC);\n\n \/\/ PA texture coord\n glm::vec2 deltaA = (pVertex_c->texture - pVertex_a->texture) * propAC;\n glm::vec2 texA = pVertex_a->texture + deltaA;\n\n \/\/ PB texture coord\n glm::vec2 deltaB = (pVertex_c->texture - pVertex_b->texture) * propBC;\n glm::vec2 texB = pVertex_b->texture + deltaB;\n\n \/\/-- T1\n Chimera::Triangle T1(a, b, A);\n T1.vertex[0].texture = pVertex_a->texture; \/\/ a old b\n T1.vertex[1].texture = pVertex_b->texture; \/\/ b old c\n T1.vertex[2].texture = texA; \/\/ A\n\n \/\/-- T2\n Chimera::Triangle T2(b, B, A);\n T2.vertex[0].texture = pVertex_b->texture; \/\/ b old c\n T2.vertex[1].texture = texB; \/\/ B\n T2.vertex[2].texture = texA; \/\/ A\n\n \/\/ -- T3\n Chimera::Triangle T3(A, B, c);\n T3.vertex[0].texture = texA; \/\/ A\n T3.vertex[1].texture = texB; \/\/ B\n T3.vertex[2].texture = pVertex_c->texture; \/\/ c old a\n\n for (int i = 0; i < 3; i++) {\n T1.vertex[i].normal = _pTriangle->vertex[i].normal;\n T2.vertex[i].normal = _pTriangle->vertex[i].normal;\n T3.vertex[i].normal = _pTriangle->vertex[i].normal;\n }\n\n _pListPolygon->push_back(T1);\n _pListPolygon->push_back(T2);\n _pListPolygon->push_back(T3);\n}\n\nSIDE classifyPoly(Chimera::Triangle* plane, Chimera::Triangle* poly, glm::vec3& _resultTest) {\n \/\/ ref: http:\/\/www.cs.utah.edu\/~jsnider\/SeniorProj\/BSP\/default.htm\n unsigned short infront = 0;\n unsigned short behind = 0;\n unsigned short onPlane = 0;\n float result[3];\n\n for (unsigned short a = 0; a < 3; a++) {\n glm::vec3 direction = plane->vertex[0].position - poly->vertex[a].position;\n result[a] = glm::dot(direction, plane->normal());\n if (result[a] > EPSILON) {\n behind++;\n } else if (result[a] < -EPSILON) {\n infront++;\n } else {\n onPlane++;\n infront++;\n behind++;\n }\n }\n\n _resultTest.x = result[0];\n _resultTest.y = result[1];\n _resultTest.z = result[2];\n\n if (onPlane == 3)\n return SIDE::CP_ONPLANE;\n\n if (behind == 3)\n return SIDE::CP_BACK;\n\n if (infront == 3)\n return SIDE::CP_FRONT;\n\n return SIDE::CP_SPANNING;\n}\n\nBSPTreeNode* bsptreeBuild(std::vector* _pListPolygon) {\n if (_pListPolygon->empty() == true)\n return nullptr;\n \/\/ tree->partition\n BSPTreeNode* tree = new BSPTreeNode(_pListPolygon->back());\n _pListPolygon->pop_back();\n tree->polygons.push_back(tree->partition);\n\n std::vector front_list;\n std::vector back_list;\n\n while (_pListPolygon->empty() == false) {\n\n Chimera::Triangle poly = _pListPolygon->back();\n _pListPolygon->pop_back();\n glm::vec3 result;\n SIDE teste = classifyPoly(&tree->partition, &poly, result);\n\n if (teste == SIDE::CP_BACK)\n back_list.push_back(poly);\n else if (teste == SIDE::CP_FRONT)\n front_list.push_back(poly);\n else if (teste == SIDE::CP_ONPLANE)\n tree->polygons.push_back(poly);\n else \/\/ CP_SPANNING\n splitTriangle(result, &poly, &tree->partition, _pListPolygon);\n }\n tree->front = bsptreeBuild(&front_list);\n tree->back = bsptreeBuild(&back_list);\n return tree;\n}\n\n\/\/------PARSER METODOS------\n\nSIDE classifyPoint(Chimera::Triangle* plane, glm::vec3* eye) {\n \/\/ ref: http:\/\/www.cs.utah.edu\/~jsnider\/SeniorProj\/BSP\/default.htm\n float result;\n glm::vec3* vec1 = (glm::vec3*)&plane->vertex[0];\n glm::vec3 dir = (*vec1) - (*eye);\n result = glm::dot(dir, plane->normal());\n\n if (result < -EPSILON)\n return SIDE::CP_FRONT;\n\n if (result > EPSILON)\n return SIDE::CP_BACK;\n\n return SIDE::CP_ONPLANE;\n}\n\nvoid drawPolygon(BSPTreeNode* tree, std::vector* _pOutVertex, bool logdata, bool frontSide) {\n \/\/ tree->arrayTriangle.DrawPolygons(); \/\/ Abaixo equivale a esta linha\n for (auto it = tree->polygons.begin(); it != tree->polygons.end(); it++) {\n Chimera::Triangle t = (*it);\n\n \/\/ if (t.getSerial() == 10) \/\/ 8, 9, 10\n \/\/ continue;\n\n _pOutVertex->push_back(t.vertex[0]);\n _pOutVertex->push_back(t.vertex[1]);\n _pOutVertex->push_back(t.vertex[2]);\n\n \/\/ FIXME: remover depois de concluir o algoritmo\n if (logdata == true) {\n if (frontSide == true)\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Face F: %d\", t.getSerial());\n else\n SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, \"Face B: %d\", t.getSerial());\n }\n }\n}\n\nvoid traverseTree(BSPTreeNode* tree, glm::vec3* eye, std::vector* _pOutVertex, bool logdata) {\n \/\/ ref: https:\/\/web.cs.wpi.edu\/~matt\/courses\/cs563\/talks\/bsp\/document.html\n if (tree == nullptr)\n return;\n\n SIDE result = classifyPoint(&tree->partition, eye);\n if (result == SIDE::CP_FRONT) {\n\n traverseTree(tree->back, eye, _pOutVertex, logdata);\n drawPolygon(tree, _pOutVertex, logdata, true);\n traverseTree(tree->front, eye, _pOutVertex, logdata);\n\n } else if (result == SIDE::CP_BACK) {\n\n traverseTree(tree->front, eye, _pOutVertex, logdata);\n drawPolygon(tree, _pOutVertex, logdata, false);\n traverseTree(tree->back, eye, _pOutVertex, logdata);\n\n } else { \/\/ result == SIDE::CP_ONPLANE\n \/\/ the eye point is on the partition plane...\n traverseTree(tree->front, eye, _pOutVertex, logdata);\n traverseTree(tree->back, eye, _pOutVertex, logdata);\n }\n}\n\nvoid bsptreeDraw(BSPTreeNode* _pRoot, glm::vec3* eye, std::vector* _pOutVertex, bool logdata) {\n traverseTree(_pRoot, eye, _pOutVertex, logdata);\n}\n<|endoftext|>"} {"text":"Reverse prefetch field trial defaults<|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\/gtk\/menu_gtk.h\"\n\n#include \"app\/gfx\/gtk_util.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/gtk\/standard_menus.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nusing gtk_util::ConvertAcceleratorsFromWindowsStyle;\n\nbool MenuGtk::block_activation_ = false;\n\nMenuGtk::MenuGtk(MenuGtk::Delegate* delegate,\n const MenuCreateMaterial* menu_data,\n GtkAccelGroup* accel_group)\n : delegate_(delegate),\n dummy_accel_group_(gtk_accel_group_new()),\n menu_(gtk_menu_new()),\n factory_(this) {\n ConnectSignalHandlers();\n BuildMenuIn(menu_.get(), menu_data, accel_group);\n}\n\nMenuGtk::MenuGtk(MenuGtk::Delegate* delegate, bool load)\n : delegate_(delegate),\n dummy_accel_group_(NULL),\n menu_(gtk_menu_new()),\n factory_(this) {\n ConnectSignalHandlers();\n if (load)\n BuildMenuFromDelegate();\n}\n\nMenuGtk::~MenuGtk() {\n menu_.Destroy();\n STLDeleteContainerPointers(submenus_we_own_.begin(), submenus_we_own_.end());\n if (dummy_accel_group_)\n g_object_unref(dummy_accel_group_);\n}\n\nvoid MenuGtk::ConnectSignalHandlers() {\n \/\/ We connect afterwards because OnMenuShow calls SetMenuItemInfo, which may\n \/\/ take a long time or even start a nested message loop.\n g_signal_connect(menu_.get(), \"show\", G_CALLBACK(OnMenuShow), this);\n g_signal_connect(menu_.get(), \"hide\", G_CALLBACK(OnMenuHidden), this);\n}\n\nvoid MenuGtk::AppendMenuItemWithLabel(int command_id,\n const std::string& label) {\n std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label);\n GtkWidget* menu_item =\n gtk_menu_item_new_with_mnemonic(converted_label.c_str());\n AppendMenuItem(command_id, menu_item);\n}\n\nvoid MenuGtk::AppendMenuItemWithIcon(int command_id,\n const std::string& label,\n const SkBitmap& icon) {\n GtkWidget* menu_item = BuildMenuItemWithImage(label, icon);\n AppendMenuItem(command_id, menu_item);\n}\n\nvoid MenuGtk::AppendCheckMenuItemWithLabel(int command_id,\n const std::string& label) {\n std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label);\n GtkWidget* menu_item =\n gtk_check_menu_item_new_with_mnemonic(converted_label.c_str());\n AppendMenuItem(command_id, menu_item);\n}\n\nvoid MenuGtk::AppendSeparator() {\n GtkWidget* menu_item = gtk_separator_menu_item_new();\n gtk_widget_show(menu_item);\n gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item);\n}\n\nvoid MenuGtk::AppendMenuItem(int command_id, GtkWidget* menu_item) {\n g_object_set_data(G_OBJECT(menu_item), \"menu-id\",\n reinterpret_cast(command_id));\n\n g_signal_connect(G_OBJECT(menu_item), \"activate\",\n G_CALLBACK(OnMenuItemActivated), this);\n\n gtk_widget_show(menu_item);\n gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item);\n}\n\nvoid MenuGtk::Popup(GtkWidget* widget, GdkEvent* event) {\n DCHECK(event->type == GDK_BUTTON_PRESS)\n << \"Non-button press event sent to RunMenuAt\";\n\n GdkEventButton* event_button = reinterpret_cast(event);\n Popup(widget, event_button->button, event_button->time);\n}\n\nvoid MenuGtk::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) {\n gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL,\n WidgetMenuPositionFunc,\n widget,\n button_type, timestamp);\n}\n\nvoid MenuGtk::PopupAsContext(guint32 event_time) {\n \/\/ TODO(estade): |button| value of 3 (6th argument) is not strictly true,\n \/\/ but does it matter?\n gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, NULL, NULL, 3, event_time);\n}\n\nvoid MenuGtk::PopupAsContextAt(guint32 event_time, gfx::Point point) {\n gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL,\n PointMenuPositionFunc, &point, 3, event_time);\n}\n\nvoid MenuGtk::PopupAsFromKeyEvent(GtkWidget* widget) {\n Popup(widget, 0, gtk_get_current_event_time());\n gtk_menu_shell_select_first(GTK_MENU_SHELL(menu_.get()), FALSE);\n}\n\nvoid MenuGtk::Cancel() {\n gtk_menu_popdown(GTK_MENU(menu_.get()));\n}\n\nvoid MenuGtk::BuildMenuIn(GtkWidget* menu,\n const MenuCreateMaterial* menu_data,\n GtkAccelGroup* accel_group) {\n \/\/ We keep track of the last menu item in order to group radio items.\n GtkWidget* last_menu_item = NULL;\n for (; menu_data->type != MENU_END; ++menu_data) {\n GtkWidget* menu_item = NULL;\n\n std::string label;\n if (menu_data->label_argument) {\n label = l10n_util::GetStringFUTF8(\n menu_data->label_id,\n l10n_util::GetStringUTF16(menu_data->label_argument));\n } else if (menu_data->label_id) {\n label = l10n_util::GetStringUTF8(menu_data->label_id);\n } else if (menu_data->type != MENU_SEPARATOR) {\n label = delegate_->GetLabel(menu_data->id);\n DCHECK(!label.empty());\n }\n\n label = ConvertAcceleratorsFromWindowsStyle(label);\n\n switch (menu_data->type) {\n case MENU_RADIO:\n if (GTK_IS_RADIO_MENU_ITEM(last_menu_item)) {\n menu_item = gtk_radio_menu_item_new_with_mnemonic_from_widget(\n GTK_RADIO_MENU_ITEM(last_menu_item), label.c_str());\n } else {\n menu_item = gtk_radio_menu_item_new_with_mnemonic(\n NULL, label.c_str());\n }\n break;\n case MENU_CHECKBOX:\n menu_item = gtk_check_menu_item_new_with_mnemonic(label.c_str());\n break;\n case MENU_SEPARATOR:\n menu_item = gtk_separator_menu_item_new();\n break;\n case MENU_NORMAL:\n default:\n menu_item = gtk_menu_item_new_with_mnemonic(label.c_str());\n break;\n }\n\n if (menu_data->submenu) {\n GtkWidget* submenu = gtk_menu_new();\n BuildMenuIn(submenu, menu_data->submenu, accel_group);\n gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu);\n } else if (menu_data->custom_submenu) {\n gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item),\n menu_data->custom_submenu->menu_.get());\n submenus_we_own_.push_back(menu_data->custom_submenu);\n }\n\n if (menu_data->accel_key) {\n \/\/ If we ever want to let the user do any key remaping, we'll need to\n \/\/ change the following so we make a gtk_accel_map which keeps the actual\n \/\/ keys.\n gtk_widget_add_accelerator(menu_item,\n \"activate\",\n menu_data->only_show || !accel_group ?\n dummy_accel_group_ : accel_group,\n menu_data->accel_key,\n GdkModifierType(menu_data->accel_modifiers),\n GTK_ACCEL_VISIBLE);\n }\n\n g_object_set_data(G_OBJECT(menu_item), \"menu-data\",\n const_cast(menu_data));\n\n g_signal_connect(G_OBJECT(menu_item), \"activate\",\n G_CALLBACK(OnMenuItemActivated), this);\n\n gtk_widget_show(menu_item);\n gtk_menu_append(menu, menu_item);\n last_menu_item = menu_item;\n }\n}\n\nGtkWidget* MenuGtk::BuildMenuItemWithImage(const std::string& label,\n const SkBitmap& icon) {\n std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label);\n GtkWidget* menu_item =\n gtk_image_menu_item_new_with_mnemonic(converted_label.c_str());\n\n GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon);\n gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item),\n gtk_image_new_from_pixbuf(pixbuf));\n g_object_unref(pixbuf);\n if (delegate_->AlwaysShowImages())\n gtk_util::SetAlwaysShowImage(menu_item);\n\n return menu_item;\n}\n\nvoid MenuGtk::BuildMenuFromDelegate() {\n \/\/ Note that the menu IDs start at 1, not 0.\n for (int i = 1; i <= delegate_->GetItemCount(); ++i) {\n GtkWidget* menu_item = NULL;\n\n if (delegate_->IsItemSeparator(i)) {\n menu_item = gtk_separator_menu_item_new();\n } else if (delegate_->HasIcon(i)) {\n const SkBitmap* icon = delegate_->GetIcon(i);\n menu_item = BuildMenuItemWithImage(delegate_->GetLabel(i), *icon);\n } else {\n menu_item = gtk_menu_item_new_with_label(delegate_->GetLabel(i).c_str());\n }\n\n AppendMenuItem(i, menu_item);\n }\n}\n\n\/\/ static\nvoid MenuGtk::OnMenuItemActivated(GtkMenuItem* menuitem, MenuGtk* menu) {\n if (block_activation_)\n return;\n\n \/\/ We receive activation messages when highlighting a menu that has a\n \/\/ submenu. Ignore them.\n if (gtk_menu_item_get_submenu(menuitem))\n return;\n\n const MenuCreateMaterial* data =\n reinterpret_cast(\n g_object_get_data(G_OBJECT(menuitem), \"menu-data\"));\n\n int id;\n if (data) {\n id = data->id;\n } else {\n id = reinterpret_cast(g_object_get_data(G_OBJECT(menuitem),\n \"menu-id\"));\n }\n\n \/\/ The menu item can still be activated by hotkeys even if it is disabled.\n if (menu->delegate_->IsCommandEnabled(id))\n menu->delegate_->ExecuteCommand(id);\n}\n\n\/\/ static\nvoid MenuGtk::WidgetMenuPositionFunc(GtkMenu* menu,\n int* x,\n int* y,\n gboolean* push_in,\n void* void_widget) {\n GtkWidget* widget = GTK_WIDGET(void_widget);\n GtkRequisition menu_req;\n\n gtk_widget_size_request(GTK_WIDGET(menu), &menu_req);\n\n gdk_window_get_origin(widget->window, x, y);\n GdkScreen *screen = gtk_widget_get_screen(widget);\n gint monitor = gdk_screen_get_monitor_at_point(screen, *x, *y);\n\n GdkRectangle screen_rect;\n gdk_screen_get_monitor_geometry(screen, monitor,\n &screen_rect);\n\n if (GTK_WIDGET_NO_WINDOW(widget)) {\n *x += widget->allocation.x;\n *y += widget->allocation.y;\n }\n *y += widget->allocation.height;\n\n bool start_align =\n !!g_object_get_data(G_OBJECT(widget), \"left-align-popup\");\n if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT)\n start_align = !start_align;\n\n if (!start_align)\n *x += widget->allocation.width - menu_req.width;\n\n \/\/ If the menu would run off the bottom of the screen, and there is more\n \/\/ screen space up than down, then pop upwards.\n if (*y + menu_req.height >= screen_rect.height &&\n *y > screen_rect.height \/ 2) {\n *y -= menu_req.height;\n }\n\n *push_in = FALSE;\n}\n\n\/\/ static\nvoid MenuGtk::PointMenuPositionFunc(GtkMenu* menu,\n int* x,\n int* y,\n gboolean* push_in,\n gpointer userdata) {\n *push_in = TRUE;\n\n gfx::Point* point = reinterpret_cast(userdata);\n *x = point->x();\n *y = point->y();\n}\n\nvoid MenuGtk::UpdateMenu() {\n gtk_container_foreach(GTK_CONTAINER(menu_.get()), SetMenuItemInfo, this);\n}\n\n\/\/ static\nvoid MenuGtk::OnMenuShow(GtkWidget* widget, MenuGtk* menu) {\n MessageLoop::current()->PostTask(FROM_HERE,\n menu->factory_.NewRunnableMethod(&MenuGtk::UpdateMenu));\n}\n\n\/\/ static\nvoid MenuGtk::OnMenuHidden(GtkWidget* widget, MenuGtk* menu) {\n menu->delegate_->StoppedShowing();\n}\n\n\/\/ static\nvoid MenuGtk::SetMenuItemInfo(GtkWidget* widget, gpointer userdata) {\n if (GTK_IS_SEPARATOR_MENU_ITEM(widget)) {\n \/\/ We need to explicitly handle this case because otherwise we'll ask the\n \/\/ menu delegate about something with an invalid id.\n return;\n }\n\n MenuGtk* menu = reinterpret_cast(userdata);\n int id;\n const MenuCreateMaterial* data =\n reinterpret_cast(\n g_object_get_data(G_OBJECT(widget), \"menu-data\"));\n if (data) {\n id = data->id;\n } else {\n id = reinterpret_cast(g_object_get_data(G_OBJECT(widget),\n \"menu-id\"));\n }\n\n if (GTK_IS_CHECK_MENU_ITEM(widget)) {\n GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM(widget);\n\n \/\/ gtk_check_menu_item_set_active() will send the activate signal. Touching\n \/\/ the underlying \"active\" property will also call the \"activate\" handler\n \/\/ for this menu item. So we prevent the \"activate\" handler from\n \/\/ being called while we set the checkbox.\n \/\/ Why not use one of the glib signal-blocking functions? Because when we\n \/\/ toggle a radio button, it will deactivate one of the other radio buttons,\n \/\/ which we don't have a pointer to.\n \/\/ Wny not make this a member variable? Because \"menu\" is a pointer to the\n \/\/ root of the MenuGtk and we want to disable *all* MenuGtks, including\n \/\/ submenus.\n block_activation_ = true;\n gtk_check_menu_item_set_active(item, menu->delegate_->IsItemChecked(id));\n block_activation_ = false;\n }\n\n if (GTK_IS_MENU_ITEM(widget)) {\n gtk_widget_set_sensitive(\n widget, menu->delegate_->IsCommandEnabled(id));\n\n GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget));\n if (submenu) {\n gtk_container_foreach(GTK_CONTAINER(submenu), &SetMenuItemInfo,\n userdata);\n }\n }\n}\nGTK: Fix popup menu positioning.\/\/ 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\/gtk\/menu_gtk.h\"\n\n#include \"app\/gfx\/gtk_util.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/stl_util-inl.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/gtk\/standard_menus.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nusing gtk_util::ConvertAcceleratorsFromWindowsStyle;\n\nbool MenuGtk::block_activation_ = false;\n\nMenuGtk::MenuGtk(MenuGtk::Delegate* delegate,\n const MenuCreateMaterial* menu_data,\n GtkAccelGroup* accel_group)\n : delegate_(delegate),\n dummy_accel_group_(gtk_accel_group_new()),\n menu_(gtk_menu_new()),\n factory_(this) {\n ConnectSignalHandlers();\n BuildMenuIn(menu_.get(), menu_data, accel_group);\n}\n\nMenuGtk::MenuGtk(MenuGtk::Delegate* delegate, bool load)\n : delegate_(delegate),\n dummy_accel_group_(NULL),\n menu_(gtk_menu_new()),\n factory_(this) {\n ConnectSignalHandlers();\n if (load)\n BuildMenuFromDelegate();\n}\n\nMenuGtk::~MenuGtk() {\n menu_.Destroy();\n STLDeleteContainerPointers(submenus_we_own_.begin(), submenus_we_own_.end());\n if (dummy_accel_group_)\n g_object_unref(dummy_accel_group_);\n}\n\nvoid MenuGtk::ConnectSignalHandlers() {\n \/\/ We connect afterwards because OnMenuShow calls SetMenuItemInfo, which may\n \/\/ take a long time or even start a nested message loop.\n g_signal_connect(menu_.get(), \"show\", G_CALLBACK(OnMenuShow), this);\n g_signal_connect(menu_.get(), \"hide\", G_CALLBACK(OnMenuHidden), this);\n}\n\nvoid MenuGtk::AppendMenuItemWithLabel(int command_id,\n const std::string& label) {\n std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label);\n GtkWidget* menu_item =\n gtk_menu_item_new_with_mnemonic(converted_label.c_str());\n AppendMenuItem(command_id, menu_item);\n}\n\nvoid MenuGtk::AppendMenuItemWithIcon(int command_id,\n const std::string& label,\n const SkBitmap& icon) {\n GtkWidget* menu_item = BuildMenuItemWithImage(label, icon);\n AppendMenuItem(command_id, menu_item);\n}\n\nvoid MenuGtk::AppendCheckMenuItemWithLabel(int command_id,\n const std::string& label) {\n std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label);\n GtkWidget* menu_item =\n gtk_check_menu_item_new_with_mnemonic(converted_label.c_str());\n AppendMenuItem(command_id, menu_item);\n}\n\nvoid MenuGtk::AppendSeparator() {\n GtkWidget* menu_item = gtk_separator_menu_item_new();\n gtk_widget_show(menu_item);\n gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item);\n}\n\nvoid MenuGtk::AppendMenuItem(int command_id, GtkWidget* menu_item) {\n g_object_set_data(G_OBJECT(menu_item), \"menu-id\",\n reinterpret_cast(command_id));\n\n g_signal_connect(G_OBJECT(menu_item), \"activate\",\n G_CALLBACK(OnMenuItemActivated), this);\n\n gtk_widget_show(menu_item);\n gtk_menu_shell_append(GTK_MENU_SHELL(menu_.get()), menu_item);\n}\n\nvoid MenuGtk::Popup(GtkWidget* widget, GdkEvent* event) {\n DCHECK(event->type == GDK_BUTTON_PRESS)\n << \"Non-button press event sent to RunMenuAt\";\n\n GdkEventButton* event_button = reinterpret_cast(event);\n Popup(widget, event_button->button, event_button->time);\n}\n\nvoid MenuGtk::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) {\n gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL,\n WidgetMenuPositionFunc,\n widget,\n button_type, timestamp);\n}\n\nvoid MenuGtk::PopupAsContext(guint32 event_time) {\n \/\/ TODO(estade): |button| value of 3 (6th argument) is not strictly true,\n \/\/ but does it matter?\n gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL, NULL, NULL, 3, event_time);\n}\n\nvoid MenuGtk::PopupAsContextAt(guint32 event_time, gfx::Point point) {\n gtk_menu_popup(GTK_MENU(menu_.get()), NULL, NULL,\n PointMenuPositionFunc, &point, 3, event_time);\n}\n\nvoid MenuGtk::PopupAsFromKeyEvent(GtkWidget* widget) {\n Popup(widget, 0, gtk_get_current_event_time());\n gtk_menu_shell_select_first(GTK_MENU_SHELL(menu_.get()), FALSE);\n}\n\nvoid MenuGtk::Cancel() {\n gtk_menu_popdown(GTK_MENU(menu_.get()));\n}\n\nvoid MenuGtk::BuildMenuIn(GtkWidget* menu,\n const MenuCreateMaterial* menu_data,\n GtkAccelGroup* accel_group) {\n \/\/ We keep track of the last menu item in order to group radio items.\n GtkWidget* last_menu_item = NULL;\n for (; menu_data->type != MENU_END; ++menu_data) {\n GtkWidget* menu_item = NULL;\n\n std::string label;\n if (menu_data->label_argument) {\n label = l10n_util::GetStringFUTF8(\n menu_data->label_id,\n l10n_util::GetStringUTF16(menu_data->label_argument));\n } else if (menu_data->label_id) {\n label = l10n_util::GetStringUTF8(menu_data->label_id);\n } else if (menu_data->type != MENU_SEPARATOR) {\n label = delegate_->GetLabel(menu_data->id);\n DCHECK(!label.empty());\n }\n\n label = ConvertAcceleratorsFromWindowsStyle(label);\n\n switch (menu_data->type) {\n case MENU_RADIO:\n if (GTK_IS_RADIO_MENU_ITEM(last_menu_item)) {\n menu_item = gtk_radio_menu_item_new_with_mnemonic_from_widget(\n GTK_RADIO_MENU_ITEM(last_menu_item), label.c_str());\n } else {\n menu_item = gtk_radio_menu_item_new_with_mnemonic(\n NULL, label.c_str());\n }\n break;\n case MENU_CHECKBOX:\n menu_item = gtk_check_menu_item_new_with_mnemonic(label.c_str());\n break;\n case MENU_SEPARATOR:\n menu_item = gtk_separator_menu_item_new();\n break;\n case MENU_NORMAL:\n default:\n menu_item = gtk_menu_item_new_with_mnemonic(label.c_str());\n break;\n }\n\n if (menu_data->submenu) {\n GtkWidget* submenu = gtk_menu_new();\n BuildMenuIn(submenu, menu_data->submenu, accel_group);\n gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu);\n } else if (menu_data->custom_submenu) {\n gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item),\n menu_data->custom_submenu->menu_.get());\n submenus_we_own_.push_back(menu_data->custom_submenu);\n }\n\n if (menu_data->accel_key) {\n \/\/ If we ever want to let the user do any key remaping, we'll need to\n \/\/ change the following so we make a gtk_accel_map which keeps the actual\n \/\/ keys.\n gtk_widget_add_accelerator(menu_item,\n \"activate\",\n menu_data->only_show || !accel_group ?\n dummy_accel_group_ : accel_group,\n menu_data->accel_key,\n GdkModifierType(menu_data->accel_modifiers),\n GTK_ACCEL_VISIBLE);\n }\n\n g_object_set_data(G_OBJECT(menu_item), \"menu-data\",\n const_cast(menu_data));\n\n g_signal_connect(G_OBJECT(menu_item), \"activate\",\n G_CALLBACK(OnMenuItemActivated), this);\n\n gtk_widget_show(menu_item);\n gtk_menu_append(menu, menu_item);\n last_menu_item = menu_item;\n }\n}\n\nGtkWidget* MenuGtk::BuildMenuItemWithImage(const std::string& label,\n const SkBitmap& icon) {\n std::string converted_label = ConvertAcceleratorsFromWindowsStyle(label);\n GtkWidget* menu_item =\n gtk_image_menu_item_new_with_mnemonic(converted_label.c_str());\n\n GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&icon);\n gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item),\n gtk_image_new_from_pixbuf(pixbuf));\n g_object_unref(pixbuf);\n if (delegate_->AlwaysShowImages())\n gtk_util::SetAlwaysShowImage(menu_item);\n\n return menu_item;\n}\n\nvoid MenuGtk::BuildMenuFromDelegate() {\n \/\/ Note that the menu IDs start at 1, not 0.\n for (int i = 1; i <= delegate_->GetItemCount(); ++i) {\n GtkWidget* menu_item = NULL;\n\n if (delegate_->IsItemSeparator(i)) {\n menu_item = gtk_separator_menu_item_new();\n } else if (delegate_->HasIcon(i)) {\n const SkBitmap* icon = delegate_->GetIcon(i);\n menu_item = BuildMenuItemWithImage(delegate_->GetLabel(i), *icon);\n } else {\n menu_item = gtk_menu_item_new_with_label(delegate_->GetLabel(i).c_str());\n }\n\n AppendMenuItem(i, menu_item);\n }\n}\n\n\/\/ static\nvoid MenuGtk::OnMenuItemActivated(GtkMenuItem* menuitem, MenuGtk* menu) {\n if (block_activation_)\n return;\n\n \/\/ We receive activation messages when highlighting a menu that has a\n \/\/ submenu. Ignore them.\n if (gtk_menu_item_get_submenu(menuitem))\n return;\n\n const MenuCreateMaterial* data =\n reinterpret_cast(\n g_object_get_data(G_OBJECT(menuitem), \"menu-data\"));\n\n int id;\n if (data) {\n id = data->id;\n } else {\n id = reinterpret_cast(g_object_get_data(G_OBJECT(menuitem),\n \"menu-id\"));\n }\n\n \/\/ The menu item can still be activated by hotkeys even if it is disabled.\n if (menu->delegate_->IsCommandEnabled(id))\n menu->delegate_->ExecuteCommand(id);\n}\n\n\/\/ static\nvoid MenuGtk::WidgetMenuPositionFunc(GtkMenu* menu,\n int* x,\n int* y,\n gboolean* push_in,\n void* void_widget) {\n GtkWidget* widget = GTK_WIDGET(void_widget);\n GtkRequisition menu_req;\n\n gtk_widget_size_request(GTK_WIDGET(menu), &menu_req);\n\n gdk_window_get_origin(widget->window, x, y);\n GdkScreen *screen = gtk_widget_get_screen(widget);\n gint monitor = gdk_screen_get_monitor_at_point(screen, *x, *y);\n\n GdkRectangle screen_rect;\n gdk_screen_get_monitor_geometry(screen, monitor,\n &screen_rect);\n\n if (GTK_WIDGET_NO_WINDOW(widget)) {\n *x += widget->allocation.x;\n *y += widget->allocation.y;\n }\n *y += widget->allocation.height;\n\n bool start_align =\n !!g_object_get_data(G_OBJECT(widget), \"left-align-popup\");\n if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT)\n start_align = !start_align;\n\n if (!start_align)\n *x += widget->allocation.width - menu_req.width;\n\n \/\/ If the menu would run off the bottom of the screen, and there is more\n \/\/ screen space up than down, then pop upwards.\n if (*y + menu_req.height >= screen_rect.height &&\n *y > screen_rect.height \/ 2) {\n *y -= menu_req.height;\n }\n\n *push_in = FALSE;\n}\n\n\/\/ static\nvoid MenuGtk::PointMenuPositionFunc(GtkMenu* menu,\n int* x,\n int* y,\n gboolean* push_in,\n gpointer userdata) {\n *push_in = TRUE;\n\n gfx::Point* point = reinterpret_cast(userdata);\n *x = point->x();\n *y = point->y();\n\n GtkRequisition menu_req;\n gtk_widget_size_request(GTK_WIDGET(menu), &menu_req);\n GdkScreen* screen = gdk_screen_get_default();\n gint screen_height = gdk_screen_get_height(screen);\n\n if (*y + menu_req.height >= screen_height)\n *y -= menu_req.height;\n}\n\nvoid MenuGtk::UpdateMenu() {\n gtk_container_foreach(GTK_CONTAINER(menu_.get()), SetMenuItemInfo, this);\n}\n\n\/\/ static\nvoid MenuGtk::OnMenuShow(GtkWidget* widget, MenuGtk* menu) {\n MessageLoop::current()->PostTask(FROM_HERE,\n menu->factory_.NewRunnableMethod(&MenuGtk::UpdateMenu));\n}\n\n\/\/ static\nvoid MenuGtk::OnMenuHidden(GtkWidget* widget, MenuGtk* menu) {\n menu->delegate_->StoppedShowing();\n}\n\n\/\/ static\nvoid MenuGtk::SetMenuItemInfo(GtkWidget* widget, gpointer userdata) {\n if (GTK_IS_SEPARATOR_MENU_ITEM(widget)) {\n \/\/ We need to explicitly handle this case because otherwise we'll ask the\n \/\/ menu delegate about something with an invalid id.\n return;\n }\n\n MenuGtk* menu = reinterpret_cast(userdata);\n int id;\n const MenuCreateMaterial* data =\n reinterpret_cast(\n g_object_get_data(G_OBJECT(widget), \"menu-data\"));\n if (data) {\n id = data->id;\n } else {\n id = reinterpret_cast(g_object_get_data(G_OBJECT(widget),\n \"menu-id\"));\n }\n\n if (GTK_IS_CHECK_MENU_ITEM(widget)) {\n GtkCheckMenuItem* item = GTK_CHECK_MENU_ITEM(widget);\n\n \/\/ gtk_check_menu_item_set_active() will send the activate signal. Touching\n \/\/ the underlying \"active\" property will also call the \"activate\" handler\n \/\/ for this menu item. So we prevent the \"activate\" handler from\n \/\/ being called while we set the checkbox.\n \/\/ Why not use one of the glib signal-blocking functions? Because when we\n \/\/ toggle a radio button, it will deactivate one of the other radio buttons,\n \/\/ which we don't have a pointer to.\n \/\/ Wny not make this a member variable? Because \"menu\" is a pointer to the\n \/\/ root of the MenuGtk and we want to disable *all* MenuGtks, including\n \/\/ submenus.\n block_activation_ = true;\n gtk_check_menu_item_set_active(item, menu->delegate_->IsItemChecked(id));\n block_activation_ = false;\n }\n\n if (GTK_IS_MENU_ITEM(widget)) {\n gtk_widget_set_sensitive(\n widget, menu->delegate_->IsCommandEnabled(id));\n\n GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget));\n if (submenu) {\n gtk_container_foreach(GTK_CONTAINER(submenu), &SetMenuItemInfo,\n userdata);\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/net\/referrer.h\"\n\n#include \"base\/logging.h\"\n\nnamespace chrome_browser_net {\n\nvoid Referrer::SuggestHost(const std::string& host) {\n \/\/ Limit how large our list can get, in case we start make mistakes about\n \/\/ what hostnames are in sub-resources (example: Some advertisments have\n \/\/ a link to the ad agency, and then provide a \"surprising\" redirect to\n \/\/ the advertised entity, which appears to be a subresource on the page\n \/\/ hosting the ad).\n static const size_t kMaxSuggestions = 8;\n\n if (host.empty())\n return;\n if (kMaxSuggestions <= size()) {\n DeleteLeastUseful();\n DCHECK(kMaxSuggestions > size());\n }\n \/\/ Add in the new suggestion.\n (*this)[host];\n}\n\nvoid Referrer::DeleteLeastUseful() {\n std::string least_useful_name;\n \/\/ We use longs for durations because we will use multiplication on them.\n int64 least_useful_latency; \/\/ Duration in milliseconds.\n int64 least_useful_lifetime; \/\/ Duration in milliseconds.\n\n const base::Time kNow(base::Time::Now()); \/\/ Avoid multiple calls.\n for (HostNameMap::iterator it = this->begin(); it != this->end(); ++it) {\n int64 lifetime = (kNow - it->second.birth_time()).InMilliseconds();\n int64 latency = it->second.latency().InMilliseconds();\n if (!least_useful_name.empty()) {\n if (!latency && !least_useful_latency) {\n \/\/ Older name is less useful.\n if (lifetime <= least_useful_lifetime)\n continue;\n } else {\n \/\/ Compare the ratios latency\/lifetime vs.\n \/\/ least_useful_latency\/least_useful_lifetime by cross multiplying (to\n \/\/ avoid integer division hassles). Overflow's won't happen until\n \/\/ both latency and lifetime pass about 49 days.\n if (latency * least_useful_lifetime >=\n least_useful_latency * lifetime) {\n continue;\n }\n }\n }\n least_useful_name = it->first;\n least_useful_latency = latency;\n least_useful_lifetime = lifetime;\n }\n erase(least_useful_name);\n}\n\nvoid Referrer::AccrueValue(const base::TimeDelta& delta,\n const std::string host) {\n DCHECK(this->find(host) != this->end());\n (*this)[host].AccrueValue(delta);\n}\n\n} \/\/ namespace chrome_browser_net\nfix linux opt build Set initial values to 0.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/net\/referrer.h\"\n\n#include \"base\/logging.h\"\n\nnamespace chrome_browser_net {\n\nvoid Referrer::SuggestHost(const std::string& host) {\n \/\/ Limit how large our list can get, in case we start make mistakes about\n \/\/ what hostnames are in sub-resources (example: Some advertisments have\n \/\/ a link to the ad agency, and then provide a \"surprising\" redirect to\n \/\/ the advertised entity, which appears to be a subresource on the page\n \/\/ hosting the ad).\n static const size_t kMaxSuggestions = 8;\n\n if (host.empty())\n return;\n if (kMaxSuggestions <= size()) {\n DeleteLeastUseful();\n DCHECK(kMaxSuggestions > size());\n }\n \/\/ Add in the new suggestion.\n (*this)[host];\n}\n\nvoid Referrer::DeleteLeastUseful() {\n std::string least_useful_name;\n \/\/ We use longs for durations because we will use multiplication on them.\n int64 least_useful_latency = 0; \/\/ Duration in milliseconds.\n int64 least_useful_lifetime = 0; \/\/ Duration in milliseconds.\n\n const base::Time kNow(base::Time::Now()); \/\/ Avoid multiple calls.\n for (HostNameMap::iterator it = this->begin(); it != this->end(); ++it) {\n int64 lifetime = (kNow - it->second.birth_time()).InMilliseconds();\n int64 latency = it->second.latency().InMilliseconds();\n if (!least_useful_name.empty()) {\n if (!latency && !least_useful_latency) {\n \/\/ Older name is less useful.\n if (lifetime <= least_useful_lifetime)\n continue;\n } else {\n \/\/ Compare the ratios latency\/lifetime vs.\n \/\/ least_useful_latency\/least_useful_lifetime by cross multiplying (to\n \/\/ avoid integer division hassles). Overflow's won't happen until\n \/\/ both latency and lifetime pass about 49 days.\n if (latency * least_useful_lifetime >=\n least_useful_latency * lifetime) {\n continue;\n }\n }\n }\n least_useful_name = it->first;\n least_useful_latency = latency;\n least_useful_lifetime = lifetime;\n }\n erase(least_useful_name);\n}\n\nvoid Referrer::AccrueValue(const base::TimeDelta& delta,\n const std::string host) {\n DCHECK(this->find(host) != this->end());\n (*this)[host].AccrueValue(delta);\n}\n\n} \/\/ namespace chrome_browser_net\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\/options_util.h\"\n\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/download\/download_manager.h\"\n#include \"chrome\/browser\/host_content_settings_map.h\"\n#include \"chrome\/browser\/host_zoom_map.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n\n\/\/ static\nvoid OptionsUtil::ResetToDefaults(Profile* profile) {\n \/\/ TODO(tc): It would be nice if we could generate this list automatically so\n \/\/ changes to any of the options pages doesn't require updating this list\n \/\/ manually.\n PrefService* prefs = profile->GetPrefs();\n const wchar_t* kUserPrefs[] = {\n prefs::kAcceptLanguages,\n prefs::kAlternateErrorPagesEnabled,\n prefs::kClearSiteDataOnExit,\n prefs::kCookieBehavior,\n prefs::kDefaultCharset,\n prefs::kDnsPrefetchingEnabled,\n#if defined(OS_LINUX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)\n prefs::kCertRevocationCheckingEnabled,\n prefs::kSSL2Enabled,\n prefs::kSSL3Enabled,\n prefs::kTLS1Enabled,\n#endif\n#if defined(OS_CHROMEOS)\n prefs::kTimeZone,\n prefs::kTapToClickEnabled,\n prefs::kVertEdgeScrollEnabled,\n prefs::kTouchpadSpeedFactor,\n prefs::kTouchpadSensitivity,\n#endif\n prefs::kDownloadDefaultDirectory,\n prefs::kDownloadExtensionsToOpen,\n prefs::kEnableSpellCheck,\n prefs::kAutoFillEnabled,\n prefs::kHomePage,\n prefs::kHomePageIsNewTabPage,\n prefs::kMixedContentFiltering,\n prefs::kPrivacyFilterRules,\n prefs::kPromptForDownload,\n prefs::kPasswordManagerEnabled,\n prefs::kRestoreOnStartup,\n prefs::kSafeBrowsingEnabled,\n prefs::kSearchSuggestEnabled,\n prefs::kShowHomeButton,\n prefs::kSpellCheckDictionary,\n prefs::kURLsToRestoreOnStartup,\n prefs::kWebKitDefaultFixedFontSize,\n prefs::kWebKitDefaultFontSize,\n prefs::kWebKitFixedFontFamily,\n prefs::kWebKitJavaEnabled,\n prefs::kWebKitJavascriptEnabled,\n prefs::kWebKitLoadsImagesAutomatically,\n prefs::kWebKitPluginsEnabled,\n prefs::kWebKitSansSerifFontFamily,\n prefs::kWebKitSerifFontFamily,\n };\n profile->GetDownloadManager()->ResetAutoOpenFiles();\n profile->GetHostContentSettingsMap()->ResetToDefaults();\n profile->GetHostZoomMap()->ResetToDefaults();\n for (size_t i = 0; i < arraysize(kUserPrefs); ++i)\n prefs->ClearPref(kUserPrefs[i]);\n\n PrefService* local_state = g_browser_process->local_state();\n \/\/ Note that we don't reset the kMetricsReportingEnabled preference here\n \/\/ because the reset will reset it to the default setting specified in Chrome\n \/\/ source, not the default setting selected by the user on the web page where\n \/\/ they downloaded Chrome. This means that if the user ever resets their\n \/\/ settings they'll either inadvertedly enable this logging or disable it.\n \/\/ One is undesirable for them, one is undesirable for us. For now, we just\n \/\/ don't reset it.\n const wchar_t* kLocalStatePrefs[] = {\n prefs::kApplicationLocale,\n };\n for (size_t i = 0; i < arraysize(kLocalStatePrefs); ++i)\n local_state->ClearPref(kLocalStatePrefs[i]);\n}\n\n\/\/ static\nbool OptionsUtil::ResolveMetricsReportingEnabled(bool enabled) {\n GoogleUpdateSettings::SetCollectStatsConsent(enabled);\n bool update_pref = GoogleUpdateSettings::GetCollectStatsConsent();\n\n if (enabled != update_pref) {\n DLOG(INFO) <<\n \"OptionsUtil: Unable to set crash report status to \" <<\n enabled;\n }\n\n \/\/ Only change the pref if GoogleUpdateSettings::GetCollectStatsConsent\n \/\/ succeeds.\n enabled = update_pref;\n\n MetricsService* metrics = g_browser_process->metrics_service();\n DCHECK(metrics);\n if (metrics) {\n metrics->SetUserPermitsUpload(enabled);\n if (enabled)\n metrics->Start();\n else\n metrics->Stop();\n }\n\n return enabled;\n}\nMake \"Reset to Defaults\" reset geolocation permissions too\/\/ 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\/options_util.h\"\n\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/download\/download_manager.h\"\n#include \"chrome\/browser\/geolocation\/geolocation_content_settings_map.h\"\n#include \"chrome\/browser\/host_content_settings_map.h\"\n#include \"chrome\/browser\/host_zoom_map.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n\n\/\/ static\nvoid OptionsUtil::ResetToDefaults(Profile* profile) {\n \/\/ TODO(tc): It would be nice if we could generate this list automatically so\n \/\/ changes to any of the options pages doesn't require updating this list\n \/\/ manually.\n PrefService* prefs = profile->GetPrefs();\n const wchar_t* kUserPrefs[] = {\n prefs::kAcceptLanguages,\n prefs::kAlternateErrorPagesEnabled,\n prefs::kClearSiteDataOnExit,\n prefs::kCookieBehavior,\n prefs::kDefaultCharset,\n prefs::kDnsPrefetchingEnabled,\n#if defined(OS_LINUX) || defined(OS_FREEBSD) || defined(OS_OPENBSD)\n prefs::kCertRevocationCheckingEnabled,\n prefs::kSSL2Enabled,\n prefs::kSSL3Enabled,\n prefs::kTLS1Enabled,\n#endif\n#if defined(OS_CHROMEOS)\n prefs::kTimeZone,\n prefs::kTapToClickEnabled,\n prefs::kVertEdgeScrollEnabled,\n prefs::kTouchpadSpeedFactor,\n prefs::kTouchpadSensitivity,\n#endif\n prefs::kDownloadDefaultDirectory,\n prefs::kDownloadExtensionsToOpen,\n prefs::kEnableSpellCheck,\n prefs::kAutoFillEnabled,\n prefs::kHomePage,\n prefs::kHomePageIsNewTabPage,\n prefs::kMixedContentFiltering,\n prefs::kPrivacyFilterRules,\n prefs::kPromptForDownload,\n prefs::kPasswordManagerEnabled,\n prefs::kRestoreOnStartup,\n prefs::kSafeBrowsingEnabled,\n prefs::kSearchSuggestEnabled,\n prefs::kShowHomeButton,\n prefs::kSpellCheckDictionary,\n prefs::kURLsToRestoreOnStartup,\n prefs::kWebKitDefaultFixedFontSize,\n prefs::kWebKitDefaultFontSize,\n prefs::kWebKitFixedFontFamily,\n prefs::kWebKitJavaEnabled,\n prefs::kWebKitJavascriptEnabled,\n prefs::kWebKitLoadsImagesAutomatically,\n prefs::kWebKitPluginsEnabled,\n prefs::kWebKitSansSerifFontFamily,\n prefs::kWebKitSerifFontFamily,\n };\n profile->GetDownloadManager()->ResetAutoOpenFiles();\n profile->GetHostContentSettingsMap()->ResetToDefaults();\n profile->GetGeolocationContentSettingsMap()->ResetToDefault();\n profile->GetHostZoomMap()->ResetToDefaults();\n for (size_t i = 0; i < arraysize(kUserPrefs); ++i)\n prefs->ClearPref(kUserPrefs[i]);\n\n PrefService* local_state = g_browser_process->local_state();\n \/\/ Note that we don't reset the kMetricsReportingEnabled preference here\n \/\/ because the reset will reset it to the default setting specified in Chrome\n \/\/ source, not the default setting selected by the user on the web page where\n \/\/ they downloaded Chrome. This means that if the user ever resets their\n \/\/ settings they'll either inadvertedly enable this logging or disable it.\n \/\/ One is undesirable for them, one is undesirable for us. For now, we just\n \/\/ don't reset it.\n const wchar_t* kLocalStatePrefs[] = {\n prefs::kApplicationLocale,\n };\n for (size_t i = 0; i < arraysize(kLocalStatePrefs); ++i)\n local_state->ClearPref(kLocalStatePrefs[i]);\n}\n\n\/\/ static\nbool OptionsUtil::ResolveMetricsReportingEnabled(bool enabled) {\n GoogleUpdateSettings::SetCollectStatsConsent(enabled);\n bool update_pref = GoogleUpdateSettings::GetCollectStatsConsent();\n\n if (enabled != update_pref) {\n DLOG(INFO) <<\n \"OptionsUtil: Unable to set crash report status to \" <<\n enabled;\n }\n\n \/\/ Only change the pref if GoogleUpdateSettings::GetCollectStatsConsent\n \/\/ succeeds.\n enabled = update_pref;\n\n MetricsService* metrics = g_browser_process->metrics_service();\n DCHECK(metrics);\n if (metrics) {\n metrics->SetUserPermitsUpload(enabled);\n if (enabled)\n metrics->Start();\n else\n metrics->Stop();\n }\n\n return enabled;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (C) 2005-2007 SIPez LLC.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ SYSTEM INCLUDES\n#include \n\n\/\/ APPLICATION INCLUDES\n#include \n#include \"sipXmediaFactoryImpl.h\"\n#include \"CpPhoneMediaInterface.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mi\/CpMediaInterfaceFactoryFactory.h\"\n\n#ifdef INCLUDE_RTCP \/* [ *\/\n#include \n#endif \/* INCLUDE_RTCP ] *\/\n\n#ifdef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n#include \n#endif\n\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ GLOBAL FUNCTION\n\n#define MAX_MANAGED_FLOW_GRAPHS 16\n\n\/\/ STATIC VARIABLE INITIALIZATIONS\nint sipXmediaFactoryImpl::miInstanceCount=0;\n\nCpMediaInterfaceFactory* spFactory = NULL;\nint siInstanceCount=0;\n\n#ifndef DISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY\nextern \"C\" CpMediaInterfaceFactory* cpDefaultMediaFactoryFactory(OsConfigDb* pConfigDb)\n{\n \/\/ TODO: Add locking\n\n if (spFactory == NULL)\n {\n spFactory = new CpMediaInterfaceFactory();\n spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb));\n } \n siInstanceCount++ ;\n \n \/\/ Assert some sane value\n assert(siInstanceCount < 11) ;\n return spFactory;\n}\n\nextern \"C\" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb)\n{\n return(cpDefaultMediaFactoryFactory(pConfigDb));\n}\n#endif\n\nextern \"C\" void sipxDestroyMediaFactoryFactory()\n{\n \/\/ TODO: Add locking\n\n if (siInstanceCount > 0)\n {\n siInstanceCount-- ;\n if (siInstanceCount == 0)\n {\n if (spFactory)\n {\n delete spFactory ;\n spFactory = NULL ;\n }\n }\n }\n}\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nsipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb)\n{ \n int maxFlowGraph = -1 ; \n UtlString strInBandDTMF ;\n \n if (pConfigDb)\n {\n pConfigDb->get(\"PHONESET_MAX_ACTIVE_CALLS_ALLOWED\", maxFlowGraph) ;\n pConfigDb->get(\"PHONESET_SEND_INBAND_DTMF\", strInBandDTMF) ;\n strInBandDTMF.toUpper() ;\n\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::sipXmediaFactoryImpl maxFlowGraph = %d\",\n maxFlowGraph);\n }\n\n \/\/ Max Flow graphs\n if (maxFlowGraph <=0 ) \n {\n maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS;\n }\n\n \/\/ Start audio subsystem if still not started.\n if (miInstanceCount == 0)\n {\n mpStartUp(8000, 80, 16*maxFlowGraph, pConfigDb, \n mnCodecPaths, mpCodecPaths);\n }\n\n \/\/ Should we send inband DTMF by default? \n if (strInBandDTMF.compareTo(\"DISABLE\") == 0)\n {\n MpCallFlowGraph::setInbandDTMF(false) ;\n }\n else\n {\n MpCallFlowGraph::setInbandDTMF(true) ;\n }\n\n \/\/ init the media processing task\n mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); \n\n#ifdef INCLUDE_RTCP \/* [ *\/\n mpiRTCPControl = CRTCManager::getRTCPControl();\n#endif \/* INCLUDE_RTCP ] *\/\n\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStartTasks(); \n#else\n if (OS_SUCCESS != startNetInTask()) {\n OsSysLog::add(FAC_MP, PRI_ERR,\n \"Could not start NetInTask!!\");\n }\n#endif\n }\n\n miGain = 7 ;\n ++miInstanceCount;\n\n \/\/ We are missing synchronization -- give the tasks time to start\n OsTask::delay(100) ;\n}\n\n\n\/\/ Destructor\nsipXmediaFactoryImpl::~sipXmediaFactoryImpl()\n{\n \/\/ TODO: Shutdown\n --miInstanceCount;\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStopTasks();\n#else\n shutdownNetInTask();\n#endif\n mpShutdown();\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\nCpMediaInterface* sipXmediaFactoryImpl::createMediaInterface( const char* publicAddress,\n const char* localAddress,\n int numCodecs,\n SdpCodec* sdpCodecArray[],\n const char* locale,\n int expeditedIpTos,\n const char* szStunServer,\n int iStunPort,\n int iStunKeepAliveSecs,\n const char* szTurnServer,\n int iTurnPort,\n const char* szTurnUsername,\n const char* szTurnPassword,\n int iTurnKeepAlivePeriodSecs,\n UtlBoolean bEnableICE) \n{\n return new CpPhoneMediaInterface(this, publicAddress, localAddress, \n numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer,\n iStunPort, iStunKeepAliveSecs, szTurnServer, iTurnPort, \n szTurnUsername, szTurnPassword, iTurnKeepAlivePeriodSecs, \n bEnableICE) ;\n}\n\n\nOsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) \n{\n OsStatus rc = OS_SUCCESS ;\n MpCodec_setVolume(iVolume) ;\n\n return rc ;\n}\n\nOsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS ;\n DmaTask::setCallDevice(device.data()) ;\n return rc ; \n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) \n{\n OsStatus rc ;\n\n miGain = iGain ;\n rc = MpCodec_setGain(miGain) ;\n return rc ;\n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS ;\n DmaTask::setInputDevice(device.data()) ;\n#ifdef WIN32\n dmaSignalMicDeviceChange();\n#endif\n return rc ; \n}\n\nOsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) \n{\n if (bMute)\n {\n MpCodec_setGain(0) ;\n }\n else\n {\n MpCodec_setGain(miGain) ;\n }\n return OS_SUCCESS ;\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioAECMode(const MEDIA_AEC_MODE mode)\n{\n if (MpCallFlowGraph::setAECMode((FLOWGRAPH_AEC_MODE)mode)) {\n return OS_SUCCESS;\n }else {\n return OS_NOT_SUPPORTED; \n }\n}\n\nOsStatus sipXmediaFactoryImpl::enableAGC(UtlBoolean bEnable) {\n if (MpCallFlowGraph::setAGC(bEnable)) {\n return OS_SUCCESS;\n }else {\n return OS_NOT_SUPPORTED; \n }\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioNoiseReductionMode(const MEDIA_NOISE_REDUCTION_MODE mode) {\n if (mode == MEDIA_NOISE_REDUCTION_DISABLED) {\n if (MpCallFlowGraph::setAudioNoiseReduction(FALSE)) {\n return OS_SUCCESS;\n }\n } else {\n if (MpCallFlowGraph::setAudioNoiseReduction(TRUE)) {\n return OS_SUCCESS;\n }\n }\n return OS_NOT_SUPPORTED;\n}\n\nOsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecList* pFactory, \n const UtlString& sAudioPreferences,\n const UtlString& sVideoPreferences,\n int videoFormat,\n int* iRejected)\n{\n OsStatus rc = OS_FAILED;\n\n *iRejected = 0;\n\n if (pFactory)\n {\n pFactory->clearCodecs();\n\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sAudioPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sAudioPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: supported codecs = %s with NumReject %d\",\n sAudioPreferences.data(), *iRejected);\n \n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n MpCodecFactory *pCodecFactory = MpCodecFactory::getMpCodecFactory();\n pCodecFactory->addCodecsToList(*pFactory);\n\n *iRejected = 0;\n rc = OS_SUCCESS;\n }\n\n\n#ifdef VIDEO \/\/ [\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sVideoPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sVideoPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: supported codecs = %s with NumReject %d\",\n sVideoPreferences.data(), *iRejected);\n\n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n SdpCodec::SdpCodecTypes videoCodecs[] = {};\n const int numVideoCodecs = sizeof(videoCodecs)\/sizeof(SdpCodec::SdpCodecTypes);\n\n *iRejected = pFactory->addCodecs(numVideoCodecs, videoCodecs);\n rc = OS_SUCCESS;\n }\n#endif \/\/ VIDEO ]\n\n } \n\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) \n{\n return OS_NOT_SUPPORTED ;\n}\n\n\n\/* ============================ ACCESSORS ================================= *\/\n\nOsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const\n{\n OsStatus rc = OS_SUCCESS ;\n\n iVolume = MpCodec_getVolume() ;\n if (iVolume==-1) {\n rc = OS_FAILED;\n iVolume = 0;\n }\n return rc ;\n}\n\nOsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS ;\n\n device = DmaTask::getCallDevice() ;\n return rc ;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const\n{\n OsStatus rc = OS_SUCCESS ;\n\n iGain = MpCodec_getGain() ;\n return rc ;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS ;\n\n device = DmaTask::getMicDevice() ;\n return rc ;\n}\n\n\nOsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoQuality(int quality)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getLocalAudioConnectionId(int& connectionId) const \n{\n connectionId = -1 ;\n\n return OS_NOT_SUPPORTED ;\n\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\n\n\n\nReformat sipXmediaFactoryImpl code. Logic itself is unchanged.\/\/\n\/\/ Copyright (C) 2005-2007 SIPez LLC.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ SYSTEM INCLUDES\n#include \n\n\/\/ APPLICATION INCLUDES\n#include \n#include \"sipXmediaFactoryImpl.h\"\n#include \"CpPhoneMediaInterface.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mi\/CpMediaInterfaceFactoryFactory.h\"\n\n#ifdef INCLUDE_RTCP \/* [ *\/\n#include \n#endif \/* INCLUDE_RTCP ] *\/\n\n#ifdef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n#include \n#endif\n\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ GLOBAL FUNCTION\n\n#define MAX_MANAGED_FLOW_GRAPHS 16\n\n\/\/ STATIC VARIABLE INITIALIZATIONS\nint sipXmediaFactoryImpl::miInstanceCount=0;\n\nCpMediaInterfaceFactory* spFactory = NULL;\nint siInstanceCount=0;\n\n#ifndef DISABLE_DEFAULT_PHONE_MEDIA_INTERFACE_FACTORY\nextern \"C\" CpMediaInterfaceFactory* cpDefaultMediaFactoryFactory(OsConfigDb* pConfigDb)\n{\n \/\/ TODO: Add locking\n\n if (spFactory == NULL)\n {\n spFactory = new CpMediaInterfaceFactory();\n spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb));\n } \n siInstanceCount++;\n\n \/\/ Assert some sane value\n assert(siInstanceCount < 11);\n return spFactory;\n}\n\nextern \"C\" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb)\n{\n return(cpDefaultMediaFactoryFactory(pConfigDb));\n}\n#endif\n\nextern \"C\" void sipxDestroyMediaFactoryFactory()\n{\n \/\/ TODO: Add locking\n\n if (siInstanceCount > 0)\n {\n siInstanceCount--;\n if (siInstanceCount == 0)\n {\n if (spFactory)\n {\n delete spFactory;\n spFactory = NULL;\n }\n }\n }\n}\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nsipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb)\n{ \n int maxFlowGraph = -1; \n UtlString strInBandDTMF;\n\n if (pConfigDb)\n {\n pConfigDb->get(\"PHONESET_MAX_ACTIVE_CALLS_ALLOWED\", maxFlowGraph);\n pConfigDb->get(\"PHONESET_SEND_INBAND_DTMF\", strInBandDTMF);\n strInBandDTMF.toUpper();\n\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::sipXmediaFactoryImpl\"\n \" maxFlowGraph = %d\",\n maxFlowGraph);\n }\n\n \/\/ Max Flow graphs\n if (maxFlowGraph <=0 ) \n {\n maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS;\n }\n\n \/\/ Start audio subsystem if still not started.\n if (miInstanceCount == 0)\n {\n mpStartUp(8000, 80, 16*maxFlowGraph, pConfigDb, \n mnCodecPaths, mpCodecPaths);\n }\n\n \/\/ Should we send inband DTMF by default? \n if (strInBandDTMF.compareTo(\"DISABLE\") == 0)\n {\n MpCallFlowGraph::setInbandDTMF(false);\n }\n else\n {\n MpCallFlowGraph::setInbandDTMF(true);\n }\n\n \/\/ init the media processing task\n mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); \n\n#ifdef INCLUDE_RTCP \/* [ *\/\n mpiRTCPControl = CRTCManager::getRTCPControl();\n#endif \/* INCLUDE_RTCP ] *\/\n\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStartTasks(); \n#else\n if (OS_SUCCESS != startNetInTask()) \n {\n OsSysLog::add(FAC_MP, PRI_ERR, \"Could not start NetInTask!!\");\n }\n#endif\n }\n\n miGain = 7;\n ++miInstanceCount;\n\n \/\/ We are missing synchronization -- give the tasks time to start\n OsTask::delay(100);\n}\n\n\n\/\/ Destructor\nsipXmediaFactoryImpl::~sipXmediaFactoryImpl()\n{\n \/\/ TODO: Shutdown\n --miInstanceCount;\n if (miInstanceCount == 0)\n {\n#ifndef ENABLE_TOPOLOGY_FLOWGRAPH_INTERFACE_FACTORY\n mpStopTasks();\n#else\n shutdownNetInTask();\n#endif\n mpShutdown();\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\nCpMediaInterface* sipXmediaFactoryImpl::createMediaInterface(const char* publicAddress,\n const char* localAddress,\n int numCodecs,\n SdpCodec* sdpCodecArray[],\n const char* locale,\n int expeditedIpTos,\n const char* szStunServer,\n int iStunPort,\n int iStunKeepAliveSecs,\n const char* szTurnServer,\n int iTurnPort,\n const char* szTurnUsername,\n const char* szTurnPassword,\n int iTurnKeepAlivePeriodSecs,\n UtlBoolean bEnableICE) \n{\n return new CpPhoneMediaInterface(this, publicAddress, localAddress, \n numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer,\n iStunPort, iStunKeepAliveSecs, szTurnServer, iTurnPort, \n szTurnUsername, szTurnPassword, iTurnKeepAlivePeriodSecs, \n bEnableICE);\n}\n\n\nOsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) \n{\n OsStatus rc = OS_SUCCESS;\n MpCodec_setVolume(iVolume);\n\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS;\n DmaTask::setCallDevice(device.data());\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) \n{\n OsStatus rc;\n\n miGain = iGain;\n rc = MpCodec_setGain(miGain);\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) \n{\n OsStatus rc = OS_SUCCESS;\n DmaTask::setInputDevice(device.data());\n#ifdef WIN32\n dmaSignalMicDeviceChange();\n#endif\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) \n{\n if (bMute)\n {\n MpCodec_setGain(0);\n }\n else\n {\n MpCodec_setGain(miGain);\n }\n return OS_SUCCESS;\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioAECMode(const MEDIA_AEC_MODE mode)\n{\n if (MpCallFlowGraph::setAECMode((FLOWGRAPH_AEC_MODE)mode))\n {\n return OS_SUCCESS;\n }\n else\n {\n return OS_NOT_SUPPORTED;\n }\n}\n\nOsStatus sipXmediaFactoryImpl::enableAGC(UtlBoolean bEnable) \n{\n if (MpCallFlowGraph::setAGC(bEnable)) \n {\n return OS_SUCCESS;\n }\n else \n {\n return OS_NOT_SUPPORTED; \n }\n}\n\nOsStatus sipXmediaFactoryImpl::setAudioNoiseReductionMode(const MEDIA_NOISE_REDUCTION_MODE mode) \n{\n if (mode == MEDIA_NOISE_REDUCTION_DISABLED)\n {\n if (MpCallFlowGraph::setAudioNoiseReduction(FALSE))\n {\n return OS_SUCCESS;\n }\n }\n else\n {\n if (MpCallFlowGraph::setAudioNoiseReduction(TRUE))\n {\n return OS_SUCCESS;\n }\n }\n return OS_NOT_SUPPORTED;\n}\n\nOsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecList* pFactory, \n const UtlString& sAudioPreferences,\n const UtlString& sVideoPreferences,\n int videoFormat,\n int* iRejected)\n{\n OsStatus rc = OS_FAILED;\n\n *iRejected = 0;\n\n if (pFactory)\n {\n pFactory->clearCodecs();\n\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sAudioPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sAudioPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: \"\n \"supported codecs = %s with NumReject %d\",\n sAudioPreferences.data(), *iRejected);\n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n MpCodecFactory *pCodecFactory = MpCodecFactory::getMpCodecFactory();\n pCodecFactory->addCodecsToList(*pFactory);\n\n *iRejected = 0;\n rc = OS_SUCCESS;\n }\n\n#ifdef VIDEO \/\/ [\n \/\/ If preferred codecs supplied - add them, else add all supported\n \/\/ codecs.\n if (sVideoPreferences.length() > 0)\n {\n *iRejected = pFactory->addCodecs(sVideoPreferences);\n OsSysLog::add(FAC_MP, PRI_DEBUG, \n \"sipXmediaFactoryImpl::buildCodecFactory: \"\n \"supported codecs = %s with NumReject %d\",\n sVideoPreferences.data(), *iRejected);\n rc = OS_SUCCESS;\n }\n else\n {\n \/\/ Build up the supported codecs\n SdpCodec::SdpCodecTypes videoCodecs[] = {};\n const int numVideoCodecs = sizeof(videoCodecs)\/sizeof(SdpCodec::SdpCodecTypes);\n\n *iRejected = pFactory->addCodecs(numVideoCodecs, videoCodecs);\n rc = OS_SUCCESS;\n }\n#endif \/\/ VIDEO ]\n }\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) \n{\n return OS_NOT_SUPPORTED;\n}\n\n\n\/* ============================ ACCESSORS ================================= *\/\n\nOsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const\n{\n OsStatus rc = OS_SUCCESS;\n\n iVolume = MpCodec_getVolume();\n if (iVolume==-1)\n {\n rc = OS_FAILED;\n iVolume = 0;\n }\n return rc;\n}\n\nOsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS;\n device = DmaTask::getCallDevice();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const\n{\n OsStatus rc = OS_SUCCESS;\n iGain = MpCodec_getGain();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const\n{\n OsStatus rc = OS_SUCCESS;\n device = DmaTask::getMicDevice();\n return rc;\n}\n\n\nOsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoQuality(int quality)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate)\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const\n{\n return OS_NOT_YET_IMPLEMENTED;\n}\n\nOsStatus sipXmediaFactoryImpl::getLocalAudioConnectionId(int& connectionId) const \n{\n connectionId = -1;\n return OS_NOT_SUPPORTED;\n\n}\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ FUNCTIONS ================================= *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by malachi on 12\/27\/17.\n\/\/\n\n#include \n\n#include \"..\/coap-dispatcher.h\"\n#include \"..\/coap-uripath-dispatcher.h\"\n#include \"test-data.h\"\n#include \"test-observer.h\"\n\nusing namespace moducom::coap;\nusing namespace moducom::coap::experimental;\nusing namespace moducom::pipeline;\n\n\n\nextern dispatcher_handler_factory_fn test_sub_factories[];\n\nIDispatcherHandler* context_handler_factory(FactoryDispatcherHandlerContext& ctx)\n{\n IncomingContext& context = ctx.incoming_context;\n\n#ifdef FEATURE_MCCOAP_INLINE_TOKEN\n return new (ctx.handler_memory.data()) ContextDispatcherHandler(context);\n#else\n static moducom::dynamic::PoolBase token_pool;\n return new (ctx.handler_memory.data()) ContextDispatcherHandler(context, token_pool);\n#endif\n}\n\n\nIDispatcherHandler* test_factory1(FactoryDispatcherHandlerContext& ctx)\n{\n return new (ctx.handler_memory.data()) Buffer16BitDeltaObserver(IsInterestedBase::Never);\n}\n\n\n\/*\n\/\/ Does not work because compiler struggles to cast back down to IMessageObserver\n\/\/ for some reason\ntemplate \nIDispatcherHandler* uri_helper3(MemoryChunk chunk)\n{\n return new (chunk.data()) UriPathDispatcherHandler(uri_path, *observer);\n}\n*\/\n\ntemplate \nstruct array_helper\n{\n static CONSTEXPR int count() { return 0; }\n};\n\ntemplate \nstruct array_helper\n{\n typedef T element_t;\n static CONSTEXPR ptrdiff_t count() { return N; }\n};\n\n\n\/*\ntemplate \nint _array_helper_count(TArray array)\n{\n array_helper array_descriptor;\n\n return array_helper::count();\n} *\/\n\ntemplate \nCONSTEXPR int _array_helper_count(T (&) [size]) { return size; }\n\ntemplate \nCONSTEXPR T* _array_helper_contents(T (&t) [size]) { return t; }\n\n\n\/*\ntemplate \nIDispatcherHandler* uri_plus_factory_dispatcher(MemoryChunk chunk)\n{\n\n} *\/\n\nIDispatcherHandler* test_factory2(FactoryDispatcherHandlerContext& ctx)\n{\n MemoryChunk& uri_handler_chunk = ctx.handler_memory;\n MemoryChunk v1_handler_chunk = ctx.handler_memory.remainder(sizeof(SingleUriPathObserver));\n MemoryChunk v1_handler_inner_chunk = v1_handler_chunk.remainder(sizeof(FactoryDispatcherHandler));\n\n FactoryDispatcherHandler* fdh = new (v1_handler_chunk.data()) FactoryDispatcherHandler(\n v1_handler_inner_chunk,\n ctx.incoming_context,\n test_sub_factories, 1);\n\n \/\/ TODO: will need some way to invoke fdh destructor\n return new (uri_handler_chunk.data()) SingleUriPathObserver(\"v1\", *fdh);\n}\n\nextern CONSTEXPR char STR_TEST[] = \"TEST\";\n\n\n\/*\ntemplate \nCONSTEXPR dispatcher_handler_factory_fn uri_helper_helper(T a [size], const char* name)\n{\n return &uri_plus_factory_dispatcher;\n}; *\/\n\n\ntemplate \ndispatcher_handler_factory_fn uri_helper2(const TArray& array)\n{\n typedef array_helper array_helper_t;\n\n int count = _array_helper_count(array);\n const void* contents = _array_helper_contents(array);\n\n \/\/ really needs real constexpr from C++11 to work\n \/\/return &uri_plus_factory_dispatcher;\n\n \/*\n MemoryChunk& uri_handler_chunk = chunk;\n MemoryChunk sub_handler_chunk = chunk.remainder(sizeof(UriPathDispatcherHandler));\n MemoryChunk sub_handler_inner_chunk = sub_handler_chunk.remainder(sizeof(FactoryDispatcherHandler));\n\n FactoryDispatcherHandler* fdh = new (sub_handler_chunk.data()) FactoryDispatcherHandler(\n sub_handler_inner_chunk,\n array, count);\n\n return new (uri_handler_chunk.data()) UriPathDispatcherHandler(uri_path, *fdh); *\/\n};\n\n\ndispatcher_handler_factory_fn test_factories[] =\n{\n context_handler_factory,\n test_factory1,\n test_factory2,\n uri_plus_factory_dispatcher\n};\n\n\nclass TestDispatcherHandler2 : public DispatcherHandlerBase\n{\npublic:\n void on_payload(const MemoryChunk::readonly_t& payload_part,\n bool last_chunk) OVERRIDE\n {\n REQUIRE(payload_part[0] == 0x10);\n REQUIRE(payload_part[1] == 0x11);\n REQUIRE(payload_part[2] == 0x12);\n REQUIRE(payload_part.length() == 7);\n }\n};\n\n\nextern CONSTEXPR char POS_HANDLER_URI[] = \"POS\";\n\nextern TestDispatcherHandler2 pos_handler;\nTestDispatcherHandler2 pos_handler;\n\n\ndispatcher_handler_factory_fn test_sub_factories[] =\n{\n uri_plus_observer_dispatcher\n};\n\nTEST_CASE(\"CoAP dispatcher tests\", \"[coap-dispatcher]\")\n{\n SECTION(\"Test 1\")\n {\n MemoryChunk chunk(buffer_16bit_delta, sizeof(buffer_16bit_delta));\n\n Buffer16BitDeltaObserver dispatcherHandler;\n Dispatcher dispatcher;\n \/\/layer3::MemoryChunk<128> chunk;\n\n dispatcher.head(&dispatcherHandler);\n dispatcher.dispatch(chunk);\n\n\n \/\/ Dummy test just so we can set a breakpoint here\n REQUIRE(chunk.length() == sizeof(buffer_16bit_delta));\n }\n SECTION(\"Factory\")\n {\n MemoryChunk chunk(buffer_plausible, sizeof(buffer_plausible));\n\n \/\/ in-place new holder\n \/\/ FIX: OK all those virtual function tables seem to be bloating\n \/\/ our handlers way, way up...\n layer3::MemoryChunk<512> dispatcherBuffer;\n IncomingContext context;\n\n FactoryDispatcherHandler fdh(dispatcherBuffer, context, test_factories);\n Dispatcher dispatcher;\n\n \/\/ doesn't fully test new UriPath handler because Buffer16BitDeltaObserver\n \/\/ is not stateless (and shouldn't be expected to be) but because of that\n \/\/ setting it to \"Currently\" makes it unable to test its own options properly\n dispatcher.head(&fdh);\n dispatcher.dispatch(chunk);\n }\n SECTION(\"Array experimentation\")\n {\n int array[] = { 1, 2, 3 };\n\n int count = _array_helper_count(array);\n\n REQUIRE(count == 3);\n }\n SECTION(\"Size ofs\")\n {\n int size1 = sizeof(IMessageObserver);\n#ifdef FEATURE_DISCRETE_OBSERVERS\n int size2 = sizeof(IOptionAndPayloadObserver);\n int size3 = sizeof(IOptionObserver);\n#endif\n int size4 = sizeof(IDispatcherHandler);\n int size5 = sizeof(IIsInterested);\n int size6 = sizeof(DispatcherHandlerBase);\n int size7 = sizeof(SingleUriPathObserver);\n int size8 = sizeof(FactoryDispatcherHandler);\n }\n}\nBegin phasing out old Dispatcher in favor of DecoderSubject\/\/\n\/\/ Created by malachi on 12\/27\/17.\n\/\/\n\n#include \n\n#include \"..\/coap-dispatcher.h\"\n#include \"..\/coap-uripath-dispatcher.h\"\n#include \"test-data.h\"\n#include \"test-observer.h\"\n\nusing namespace moducom::coap;\nusing namespace moducom::coap::experimental;\nusing namespace moducom::pipeline;\n\n\n\nextern dispatcher_handler_factory_fn test_sub_factories[];\n\nIDispatcherHandler* context_handler_factory(FactoryDispatcherHandlerContext& ctx)\n{\n IncomingContext& context = ctx.incoming_context;\n\n#ifdef FEATURE_MCCOAP_INLINE_TOKEN\n return new (ctx.handler_memory.data()) ContextDispatcherHandler(context);\n#else\n static moducom::dynamic::PoolBase token_pool;\n return new (ctx.handler_memory.data()) ContextDispatcherHandler(context, token_pool);\n#endif\n}\n\n\nIDispatcherHandler* test_factory1(FactoryDispatcherHandlerContext& ctx)\n{\n return new (ctx.handler_memory.data()) Buffer16BitDeltaObserver(IsInterestedBase::Never);\n}\n\n\n\/*\n\/\/ Does not work because compiler struggles to cast back down to IMessageObserver\n\/\/ for some reason\ntemplate \nIDispatcherHandler* uri_helper3(MemoryChunk chunk)\n{\n return new (chunk.data()) UriPathDispatcherHandler(uri_path, *observer);\n}\n*\/\n\ntemplate \nstruct array_helper\n{\n static CONSTEXPR int count() { return 0; }\n};\n\ntemplate \nstruct array_helper\n{\n typedef T element_t;\n static CONSTEXPR ptrdiff_t count() { return N; }\n};\n\n\n\/*\ntemplate \nint _array_helper_count(TArray array)\n{\n array_helper array_descriptor;\n\n return array_helper::count();\n} *\/\n\ntemplate \nCONSTEXPR int _array_helper_count(T (&) [size]) { return size; }\n\ntemplate \nCONSTEXPR T* _array_helper_contents(T (&t) [size]) { return t; }\n\n\n\/*\ntemplate \nIDispatcherHandler* uri_plus_factory_dispatcher(MemoryChunk chunk)\n{\n\n} *\/\n\nIDispatcherHandler* test_factory2(FactoryDispatcherHandlerContext& ctx)\n{\n MemoryChunk& uri_handler_chunk = ctx.handler_memory;\n MemoryChunk v1_handler_chunk = ctx.handler_memory.remainder(sizeof(SingleUriPathObserver));\n MemoryChunk v1_handler_inner_chunk = v1_handler_chunk.remainder(sizeof(FactoryDispatcherHandler));\n\n FactoryDispatcherHandler* fdh = new (v1_handler_chunk.data()) FactoryDispatcherHandler(\n v1_handler_inner_chunk,\n ctx.incoming_context,\n test_sub_factories, 1);\n\n \/\/ TODO: will need some way to invoke fdh destructor\n return new (uri_handler_chunk.data()) SingleUriPathObserver(\"v1\", *fdh);\n}\n\nextern CONSTEXPR char STR_TEST[] = \"TEST\";\n\n\n\/*\ntemplate \nCONSTEXPR dispatcher_handler_factory_fn uri_helper_helper(T a [size], const char* name)\n{\n return &uri_plus_factory_dispatcher;\n}; *\/\n\n\ntemplate \ndispatcher_handler_factory_fn uri_helper2(const TArray& array)\n{\n typedef array_helper array_helper_t;\n\n int count = _array_helper_count(array);\n const void* contents = _array_helper_contents(array);\n\n \/\/ really needs real constexpr from C++11 to work\n \/\/return &uri_plus_factory_dispatcher;\n\n \/*\n MemoryChunk& uri_handler_chunk = chunk;\n MemoryChunk sub_handler_chunk = chunk.remainder(sizeof(UriPathDispatcherHandler));\n MemoryChunk sub_handler_inner_chunk = sub_handler_chunk.remainder(sizeof(FactoryDispatcherHandler));\n\n FactoryDispatcherHandler* fdh = new (sub_handler_chunk.data()) FactoryDispatcherHandler(\n sub_handler_inner_chunk,\n array, count);\n\n return new (uri_handler_chunk.data()) UriPathDispatcherHandler(uri_path, *fdh); *\/\n};\n\n\ndispatcher_handler_factory_fn test_factories[] =\n{\n context_handler_factory,\n test_factory1,\n test_factory2,\n uri_plus_factory_dispatcher\n};\n\n\nclass TestDispatcherHandler2 : public DispatcherHandlerBase\n{\npublic:\n void on_payload(const MemoryChunk::readonly_t& payload_part,\n bool last_chunk) OVERRIDE\n {\n REQUIRE(payload_part[0] == 0x10);\n REQUIRE(payload_part[1] == 0x11);\n REQUIRE(payload_part[2] == 0x12);\n REQUIRE(payload_part.length() == 7);\n }\n};\n\n\nextern CONSTEXPR char POS_HANDLER_URI[] = \"POS\";\n\nextern TestDispatcherHandler2 pos_handler;\nTestDispatcherHandler2 pos_handler;\n\n\ndispatcher_handler_factory_fn test_sub_factories[] =\n{\n uri_plus_observer_dispatcher\n};\n\nTEST_CASE(\"CoAP dispatcher tests\", \"[coap-dispatcher]\")\n{\n SECTION(\"Factory\")\n {\n MemoryChunk chunk(buffer_plausible, sizeof(buffer_plausible));\n\n \/\/ in-place new holder\n \/\/ FIX: OK all those virtual function tables seem to be bloating\n \/\/ our handlers way, way up...\n layer3::MemoryChunk<512> dispatcherBuffer;\n IncomingContext context;\n\n FactoryDispatcherHandler fdh(dispatcherBuffer, context, test_factories);\n Dispatcher dispatcher;\n\n \/\/ doesn't fully test new UriPath handler because Buffer16BitDeltaObserver\n \/\/ is not stateless (and shouldn't be expected to be) but because of that\n \/\/ setting it to \"Currently\" makes it unable to test its own options properly\n dispatcher.head(&fdh);\n dispatcher.dispatch(chunk);\n }\n SECTION(\"Array experimentation\")\n {\n int array[] = { 1, 2, 3 };\n\n int count = _array_helper_count(array);\n\n REQUIRE(count == 3);\n }\n SECTION(\"Size ofs\")\n {\n int size1 = sizeof(IMessageObserver);\n#ifdef FEATURE_DISCRETE_OBSERVERS\n int size2 = sizeof(IOptionAndPayloadObserver);\n int size3 = sizeof(IOptionObserver);\n#endif\n int size4 = sizeof(IDispatcherHandler);\n int size5 = sizeof(IIsInterested);\n int size6 = sizeof(DispatcherHandlerBase);\n int size7 = sizeof(SingleUriPathObserver);\n int size8 = sizeof(FactoryDispatcherHandler);\n }\n}\n<|endoftext|>"} {"text":"\/*-----------------------------------------------------------------------------\n\n Copyright 2017 Hopsan Group\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 The full license is available in the file LICENSE.\n For details about the 'Hopsan Group' or information about Authors and\n Contributors see the HOPSANGROUP and AUTHORS files that are located in\n the Hopsan source code root directory.\n\n-----------------------------------------------------------------------------*\/\n\n#ifndef FMIWRAPPER_HPP\n#define FMIWRAPPER_HPP\n\n#include \"ComponentEssentials.h\"\n#include \"ComponentUtilities.h\"\n\n#include \"FMI\/fmi_import_context.h\"\n#include \n#include \n#include \n\n\/\/!\n\/\/! @file FMIWrapper.hpp\n\/\/! @author Robert Braun \n\/\/! @date 2021-01-27\n\/\/! @brief Wrapper component for functional mockup units (.fmu)\n\/\/!\n\nusing namespace hopsan;\n\nvoid jmLogger(jm_callbacks *c, jm_string module, jm_log_level_enu_t log_level, jm_string message)\n{\n (void)module;\n hopsan::Component* pComponent = (hopsan::Component*)(c->context);\n if (pComponent) {\n switch (log_level) {\n case jm_log_level_fatal:\n pComponent->addFatalMessage(message);\n break;\n case jm_log_level_error:\n pComponent->addErrorMessage(message);\n break;\n case jm_log_level_warning:\n pComponent->addWarningMessage(message);\n break;\n \/\/ Typically the jm logger info messages are not something we want to see in Hopsan, so show them as debug type\n case jm_log_level_verbose:\n case jm_log_level_info:\n case jm_log_level_debug:\n pComponent->addDebugMessage(message);\n break;\n default:\n break;\n }\n }\n}\n\nvoid fmiLogger(fmi2ComponentEnvironment pComponentEnvironment, fmi2_string_t instanceName, fmi2_status_t status, fmi2_string_t category, fmi2_string_t message, ...)\n{\n hopsan::Component* pComponent = (hopsan::Component*)pComponentEnvironment;\n if (pComponent == NULL) {\n return;\n }\n\n char buffer[512];\n va_list args;\n va_start(args, message);\n vsnprintf(buffer, 512, message, args);\n va_end(args);\n\n switch (status) {\n \/\/ Typically info messages are not something we want to see in Hopsan, so show them as debug type\n case fmi2_status_ok:\n pComponent->addDebugMessage(buffer);\n break;\n case fmi2_status_warning:\n pComponent->addWarningMessage(buffer);\n break;\n case fmi2_status_error:\n pComponent->addErrorMessage(buffer);\n break;\n case fmi2_status_fatal:\n pComponent->addFatalMessage(buffer);\n break;\n default:\n \/\/ Discard\n break;\n }\n}\n\n\n\nclass FMIWrapper : public ComponentSignal\n{\nprivate:\n TempDirectoryHandle *mpTempDir;\n HString mFmuPath, mLastFmuPath;\n std::map mOutputs;\n std::map mInputs;\n std::map mRealParameters;\n std::map mBoolParameters;\n std::map mIntParameters;\n std::map mStringParameters;\n std::vector mPorts;\n\n jm_callbacks callbacks;\n jm_status_enu_t status;\n fmi_import_context_t* context;\n fmi_version_enu_t version;\n fmi2_callback_functions_t fmiCallbackFunctions;\n fmi2_status_t fmistatus;\n fmi2_import_t* fmu;\n\n\npublic:\n static Component *Creator()\n {\n return new FMIWrapper();\n }\n\n void configure()\n {\n addConstant(\"path\", \"Path to functional mockup unit (FMU)\", \"\", mFmuPath);\n setReconfigurationParameter(\"path\");\n }\n\n void reconfigure()\n {\n if(mFmuPath == mLastFmuPath) {\n return; \/\/Path did not change, do nothing\n }\n mLastFmuPath = mFmuPath;\n\n deconfigure(); \/\/Make sure to unload FMU and free memory before loading a new one\n\n for(int i=0; igetName());\n }\n std::vector parameters;\n this->getParameterNames(parameters);\n for(int i=0; iunRegisterParameter(parameters[i]);\n }\n }\n mPorts.clear();\n mOutputs.clear();\n mInputs.clear();\n mRealParameters.clear();\n mStringParameters.clear();\n mBoolParameters.clear();\n mIntParameters.clear();\n\n callbacks.malloc = malloc;\n callbacks.calloc = calloc;\n callbacks.realloc = realloc;\n callbacks.free = free;\n callbacks.logger = jmLogger;\n callbacks.log_level = jm_log_level_debug;\n callbacks.context = static_cast(this);\n\n context = fmi_import_allocate_context(&callbacks);\n\n addInfoMessage(\"Loading FMU from \"+mFmuPath+\"...\");\n\n mpTempDir = new TempDirectoryHandle(\"fmu\");\n if(!mpTempDir->isValid()) {\n addErrorMessage(\"Unable to create temp directory: \"+mpTempDir->path());\n return;\n }\n\n addDebugMessage(\"Using temporary directory: \"+mpTempDir->path());\n\n version = fmi_import_get_fmi_version(context, mFmuPath.c_str(), mpTempDir->path().c_str());\n if(version != fmi_version_2_0_enu) {\n \/\/! @todo Implement FMI 1.0 support\n addErrorMessage(\"The code only supports version 2.0\");\n return;\n }\n\n addDebugMessage(\"FMU version: 2.0\");\n\n fmu = fmi2_import_parse_xml(context, mpTempDir->path().c_str(), NULL);\n if(!fmu) {\n addErrorMessage(\"Parsing model description failed\");\n return;\n }\n\n addDebugMessage(\"Successfully parsed model description\");\n\n if(fmi2_import_get_fmu_kind(fmu) == fmi2_fmu_kind_me) {\n addErrorMessage(\"Only FMI for co-simulation is supported\");\n return;\n }\n\n addDebugMessage(\"FMU supports FMI for co-simulation\");\n\n fmi2_fmu_kind_enu_t fmuKind = fmi2_import_get_fmu_kind(fmu);\n if (fmuKind == fmi2_fmu_kind_me_and_cs) {\n fmuKind = fmi2_fmu_kind_cs;\n }\n\n \/\/Loop through variables in FMU and generate the lists\n fmi2_import_variable_list_t *pVarList = fmi2_import_get_variable_list(fmu,0);\n for(size_t i=0; ipath()+\"\/resources\";\n fmi2_boolean_t visible = fmi2_false;\n jm_status_enu_t jmstatus = fmi2_import_instantiate(fmu, instanceName.c_str(), fmi2_cosimulation, resourceDir.c_str(), visible);\n if (jmstatus == jm_status_error) {\n stopSimulation(\"Failed to instantiate FMU\");\n return;\n }\n\n addInfoMessage(\"Successfully instantiated FMU\");\n\n }\n\n void initialize()\n {\n addInfoMessage(\"Initializing FMU 2.0 import\");\n\n std::map::iterator itr;\n for(itr = mRealParameters.begin(); itr != mRealParameters.end(); itr++) {\n fmistatus = fmi2_import_set_real(fmu, &itr->first, 1, &itr->second);\n }\n std::map::iterator its;\n for(its = mStringParameters.begin(); its != mStringParameters.end(); ++its) {\n const char* value = its->second.c_str();\n fmistatus = fmi2_import_set_string(fmu, &its->first, 1, &value);\n }\n std::map::iterator itb;\n for(itb = mBoolParameters.begin(); itb != mBoolParameters.end(); ++itb) {\n int value = int(itb->second);\n fmistatus = fmi2_import_set_boolean(fmu, &its->first, 1, &value);\n }\n std::map::iterator iti;\n for(iti = mIntParameters.begin(); iti != mIntParameters.end(); ++iti) {\n fmistatus = fmi2_import_set_integer(fmu, &its->first, 1, &iti->second);\n }\n\n \/\/Setup experiment\n fmistatus = fmi2_import_setup_experiment(fmu, fmi2_false, 0, mTime, fmi2_false, 10);\n if(fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_setup_experiment() failed\");\n return;\n }\n\n \/\/Enter initialization mode\n fmistatus = fmi2_import_enter_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_enter_initialization_mode() failed\");\n return;\n }\n\n \/\/Exit initialization mode\n fmistatus = fmi2_import_exit_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_exit_initialization_mode() failed\");\n return;\n }\n }\n\n void simulateOneTimestep()\n {\n \/\/Read inputs\n std::map::iterator it;\n for(it = mInputs.begin(); it != mInputs.end(); it++) {\n fmistatus = fmi2_import_set_real(fmu, &it->first, 1, it->second);\n }\n\n \/\/Take step\n fmistatus = fmi2_import_do_step(fmu, mTime, mTimestep, true);\n if (fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_do_step failed\");\n return;\n }\n\n \/\/Write outputs\n for(it = mOutputs.begin(); it != mOutputs.end(); it++) {\n fmistatus = fmi2_import_get_real(fmu, &it->first, 1, it->second);\n }\n }\n\n void finalize()\n {\n if(fmu) {\n fmistatus = fmi2_import_terminate(fmu);\n }\n }\n\n void deconfigure()\n {\n if(fmu) {\n fmi2_import_free_instance(fmu);\n fmi2_import_destroy_dllfmu(fmu);\n fmi2_import_free(fmu);\n fmu = NULL;\n }\n\n if(context) {\n fmi_import_free_context(context);\n context = NULL;\n }\n\n delete mpTempDir;\n }\n};\n\n#endif \/\/ FMIWRAPPER_HPP\nCorrect calling sequence for finalize in FMIWrapper\/*-----------------------------------------------------------------------------\n\n Copyright 2017 Hopsan Group\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 The full license is available in the file LICENSE.\n For details about the 'Hopsan Group' or information about Authors and\n Contributors see the HOPSANGROUP and AUTHORS files that are located in\n the Hopsan source code root directory.\n\n-----------------------------------------------------------------------------*\/\n\n#ifndef FMIWRAPPER_HPP\n#define FMIWRAPPER_HPP\n\n#include \"ComponentEssentials.h\"\n#include \"ComponentUtilities.h\"\n\n#include \"FMI\/fmi_import_context.h\"\n#include \n#include \n#include \n\n\/\/!\n\/\/! @file FMIWrapper.hpp\n\/\/! @author Robert Braun \n\/\/! @date 2021-01-27\n\/\/! @brief Wrapper component for functional mockup units (.fmu)\n\/\/!\n\nusing namespace hopsan;\n\nvoid jmLogger(jm_callbacks *c, jm_string module, jm_log_level_enu_t log_level, jm_string message)\n{\n (void)module;\n hopsan::Component* pComponent = (hopsan::Component*)(c->context);\n if (pComponent) {\n switch (log_level) {\n case jm_log_level_fatal:\n pComponent->addFatalMessage(message);\n break;\n case jm_log_level_error:\n pComponent->addErrorMessage(message);\n break;\n case jm_log_level_warning:\n pComponent->addWarningMessage(message);\n break;\n \/\/ Typically the jm logger info messages are not something we want to see in Hopsan, so show them as debug type\n case jm_log_level_verbose:\n case jm_log_level_info:\n case jm_log_level_debug:\n pComponent->addDebugMessage(message);\n break;\n default:\n break;\n }\n }\n}\n\nvoid fmiLogger(fmi2ComponentEnvironment pComponentEnvironment, fmi2_string_t instanceName, fmi2_status_t status, fmi2_string_t category, fmi2_string_t message, ...)\n{\n hopsan::Component* pComponent = (hopsan::Component*)pComponentEnvironment;\n if (pComponent == NULL) {\n return;\n }\n\n char buffer[512];\n va_list args;\n va_start(args, message);\n vsnprintf(buffer, 512, message, args);\n va_end(args);\n\n switch (status) {\n \/\/ Typically info messages are not something we want to see in Hopsan, so show them as debug type\n case fmi2_status_ok:\n pComponent->addDebugMessage(buffer);\n break;\n case fmi2_status_warning:\n pComponent->addWarningMessage(buffer);\n break;\n case fmi2_status_error:\n pComponent->addErrorMessage(buffer);\n break;\n case fmi2_status_fatal:\n pComponent->addFatalMessage(buffer);\n break;\n default:\n \/\/ Discard\n break;\n }\n}\n\n\n\nclass FMIWrapper : public ComponentSignal\n{\nprivate:\n TempDirectoryHandle *mpTempDir;\n HString mFmuPath, mLastFmuPath;\n std::map mOutputs;\n std::map mInputs;\n std::map mRealParameters;\n std::map mBoolParameters;\n std::map mIntParameters;\n std::map mStringParameters;\n std::vector mPorts;\n\n jm_callbacks callbacks;\n jm_status_enu_t status;\n fmi_import_context_t* context;\n fmi_version_enu_t version;\n fmi2_callback_functions_t fmiCallbackFunctions;\n fmi2_status_t fmistatus;\n fmi2_import_t* fmu;\n\n\npublic:\n static Component *Creator()\n {\n return new FMIWrapper();\n }\n\n void configure()\n {\n addConstant(\"path\", \"Path to functional mockup unit (FMU)\", \"\", mFmuPath);\n setReconfigurationParameter(\"path\");\n }\n\n void reconfigure()\n {\n if(mFmuPath == mLastFmuPath) {\n return; \/\/Path did not change, do nothing\n }\n mLastFmuPath = mFmuPath;\n\n deconfigure(); \/\/Make sure to unload FMU and free memory before loading a new one\n\n for(int i=0; igetName());\n }\n std::vector parameters;\n this->getParameterNames(parameters);\n for(int i=0; iunRegisterParameter(parameters[i]);\n }\n }\n mPorts.clear();\n mOutputs.clear();\n mInputs.clear();\n mRealParameters.clear();\n mStringParameters.clear();\n mBoolParameters.clear();\n mIntParameters.clear();\n\n callbacks.malloc = malloc;\n callbacks.calloc = calloc;\n callbacks.realloc = realloc;\n callbacks.free = free;\n callbacks.logger = jmLogger;\n callbacks.log_level = jm_log_level_debug;\n callbacks.context = static_cast(this);\n\n context = fmi_import_allocate_context(&callbacks);\n\n addInfoMessage(\"Loading FMU from \"+mFmuPath+\"...\");\n\n mpTempDir = new TempDirectoryHandle(\"fmu\");\n if(!mpTempDir->isValid()) {\n addErrorMessage(\"Unable to create temp directory: \"+mpTempDir->path());\n return;\n }\n\n addDebugMessage(\"Using temporary directory: \"+mpTempDir->path());\n\n version = fmi_import_get_fmi_version(context, mFmuPath.c_str(), mpTempDir->path().c_str());\n if(version != fmi_version_2_0_enu) {\n \/\/! @todo Implement FMI 1.0 support\n addErrorMessage(\"The code only supports version 2.0\");\n return;\n }\n\n addDebugMessage(\"FMU version: 2.0\");\n\n fmu = fmi2_import_parse_xml(context, mpTempDir->path().c_str(), NULL);\n if(!fmu) {\n addErrorMessage(\"Parsing model description failed\");\n return;\n }\n\n addDebugMessage(\"Successfully parsed model description\");\n\n if(fmi2_import_get_fmu_kind(fmu) == fmi2_fmu_kind_me) {\n addErrorMessage(\"Only FMI for co-simulation is supported\");\n return;\n }\n\n addDebugMessage(\"FMU supports FMI for co-simulation\");\n\n fmi2_fmu_kind_enu_t fmuKind = fmi2_import_get_fmu_kind(fmu);\n if (fmuKind == fmi2_fmu_kind_me_and_cs) {\n fmuKind = fmi2_fmu_kind_cs;\n }\n\n \/\/Loop through variables in FMU and generate the lists\n fmi2_import_variable_list_t *pVarList = fmi2_import_get_variable_list(fmu,0);\n for(size_t i=0; ipath()+\"\/resources\";\n fmi2_boolean_t visible = fmi2_false;\n jm_status_enu_t jmstatus = fmi2_import_instantiate(fmu, instanceName.c_str(), fmi2_cosimulation, resourceDir.c_str(), visible);\n if (jmstatus == jm_status_error) {\n stopSimulation(\"Failed to instantiate FMU\");\n return;\n }\n\n addInfoMessage(\"Successfully instantiated FMU\");\n\n }\n\n void initialize()\n {\n addInfoMessage(\"Initializing FMU 2.0 import\");\n\n std::map::iterator itr;\n for(itr = mRealParameters.begin(); itr != mRealParameters.end(); itr++) {\n fmistatus = fmi2_import_set_real(fmu, &itr->first, 1, &itr->second);\n }\n std::map::iterator its;\n for(its = mStringParameters.begin(); its != mStringParameters.end(); ++its) {\n const char* value = its->second.c_str();\n fmistatus = fmi2_import_set_string(fmu, &its->first, 1, &value);\n }\n std::map::iterator itb;\n for(itb = mBoolParameters.begin(); itb != mBoolParameters.end(); ++itb) {\n int value = int(itb->second);\n fmistatus = fmi2_import_set_boolean(fmu, &its->first, 1, &value);\n }\n std::map::iterator iti;\n for(iti = mIntParameters.begin(); iti != mIntParameters.end(); ++iti) {\n fmistatus = fmi2_import_set_integer(fmu, &its->first, 1, &iti->second);\n }\n\n \/\/Setup experiment\n fmistatus = fmi2_import_setup_experiment(fmu, fmi2_false, 0, mTime, fmi2_false, 10);\n if(fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_setup_experiment() failed\");\n return;\n }\n\n \/\/Enter initialization mode\n fmistatus = fmi2_import_enter_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_enter_initialization_mode() failed\");\n return;\n }\n\n \/\/Exit initialization mode\n fmistatus = fmi2_import_exit_initialization_mode(fmu);\n if(fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_exit_initialization_mode() failed\");\n return;\n }\n }\n\n void simulateOneTimestep()\n {\n \/\/Read inputs\n std::map::iterator it;\n for(it = mInputs.begin(); it != mInputs.end(); it++) {\n fmistatus = fmi2_import_set_real(fmu, &it->first, 1, it->second);\n }\n\n \/\/Take step\n fmistatus = fmi2_import_do_step(fmu, mTime, mTimestep, true);\n if (fmistatus != fmi2_status_ok) {\n stopSimulation(\"fmi2_import_do_step failed\");\n return;\n }\n\n \/\/Write outputs\n for(it = mOutputs.begin(); it != mOutputs.end(); it++) {\n fmistatus = fmi2_import_get_real(fmu, &it->first, 1, it->second);\n }\n }\n\n void finalize()\n {\n if(fmu) {\n fmistatus = fmi2_import_reset(fmu);\n }\n }\n\n void deconfigure()\n {\n if(fmu) {\n fmistatus = fmi2_import_terminate(fmu);\n fmi2_import_free_instance(fmu);\n fmi2_import_destroy_dllfmu(fmu);\n fmi2_import_free(fmu);\n fmu = NULL;\n }\n\n if(context) {\n fmi_import_free_context(context);\n context = NULL;\n }\n\n delete mpTempDir;\n }\n};\n\n#endif \/\/ FMIWRAPPER_HPP\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ this function takes a line that may contain a name and\/or email address,\n\/\/ and returns just the name, while fixing the \"bad cases\".\nstd::string contributor_name(const std::string& line)\n{\n string result;\n size_t position_of_email_address = line.find_first_of('<');\n if(position_of_email_address != string::npos)\n {\n \/\/ there is an e-mail address.\n \n \/\/ Hauke once committed as \"John Smith\", fix that.\n if(line.find(\"hauke.heibel\") != string::npos)\n result = \"Hauke Heibel\";\n else\n {\n \/\/ just remove the e-mail address\n result = line.substr(0, position_of_email_address);\n }\n }\n else\n {\n \/\/ there is no e-mail address.\n \n if(line.find(\"convert-repo\") != string::npos)\n result = \"\";\n else\n result = line;\n }\n\n \/\/ remove trailing spaces\n size_t length = result.length();\n while(length >= 1 && result[length-1] == ' ') result.erase(--length);\n\n return result;\n}\n\n\/\/ parses hg churn output to generate a contributors map.\nmap contributors_map_from_churn_output(const char *filename)\n{\n map contributors_map;\n\n string line;\n ifstream churn_out;\n churn_out.open(filename, ios::in);\n while(!getline(churn_out,line).eof())\n {\n \/\/ remove the histograms \"******\" that hg churn may draw at the end of some lines\n size_t first_star = line.find_first_of('*');\n if(first_star != string::npos) line.erase(first_star);\n \n \/\/ remove trailing spaces\n size_t length = line.length();\n while(length >= 1 && line[length-1] == ' ') line.erase(--length);\n\n \/\/ now the last space indicates where the number starts\n size_t last_space = line.find_last_of(' ');\n \n \/\/ get the number (of changesets or of modified lines for each contributor)\n int number;\n istringstream(line.substr(last_space+1)) >> number;\n\n \/\/ get the name of the contributor\n line.erase(last_space); \n string name = contributor_name(line);\n \n map::iterator it = contributors_map.find(name);\n \/\/ if new contributor, insert\n if(it == contributors_map.end())\n contributors_map.insert(pair(name, number));\n \/\/ if duplicate, just add the number\n else\n it->second += number;\n }\n churn_out.close();\n\n return contributors_map;\n}\n\nstruct contributor\n{\n string name;\n int changedlines;\n int changesets;\n string url;\n string misc;\n \n contributor() : changedlines(0), changesets(0) {}\n \n bool operator < (const contributor& other)\n {\n return changedlines > other.changedlines;\n }\n};\n\nvoid add_online_info_into_contributors_list(list& contributors_list, const char *filename)\n{\n string line;\n ifstream online_info;\n online_info.open(filename, ios::in);\n while(!getline(online_info,line).eof())\n {\n string hgname, realname, url, misc;\n \n size_t last_bar = line.find_last_of('|');\n if(last_bar == string::npos) continue;\n if(last_bar < line.length())\n misc = line.substr(last_bar+1);\n line.erase(last_bar);\n \n last_bar = line.find_last_of('|');\n if(last_bar == string::npos) continue;\n if(last_bar < line.length())\n url = line.substr(last_bar+1);\n line.erase(last_bar);\n\n last_bar = line.find_last_of('|');\n if(last_bar == string::npos) continue;\n if(last_bar < line.length())\n realname = line.substr(last_bar+1);\n line.erase(last_bar);\n\n hgname = line;\n \n \/\/ remove the example line\n if(hgname.find(\"MercurialName\") != string::npos) continue;\n \n list::iterator it;\n for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it)\n {}\n \n if(it == contributors_list.end())\n {\n contributor c;\n c.name = realname;\n c.url = url;\n c.misc = misc;\n contributors_list.push_back(c);\n }\n else\n {\n it->name = realname;\n it->url = url;\n it->misc = misc;\n }\n }\n}\n\nostream& operator<<(ostream& stream, const contributor& c)\n{\n stream << c.name << \"|\" << c.changedlines << \"|\" << c.changesets << \"|\" << c.url << \"|\" << c.misc;\n}\n\nint main()\n{\n \/\/ parse the hg churn output files\n map contributors_map_for_changedlines = contributors_map_from_churn_output(\"churn-changedlines.out\");\n map contributors_map_for_changesets = contributors_map_from_churn_output(\"churn-changesets.out\");\n \n \/\/ merge into the contributors list\n list contributors_list;\n map::iterator it;\n for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it)\n {\n contributor c;\n c.name = it->first;\n c.changedlines = it->second;\n c.changesets = contributors_map_for_changesets.find(it->first)->second;\n contributors_list.push_back(c);\n }\n \n add_online_info_into_contributors_list(contributors_list, \"online-info.out\");\n \n contributors_list.sort();\n \n cout << \"{| cellpadding=\\\"5\\\"\\n\";\n cout << \"!\\n\";\n cout << \"! Lines changed\\n(changesets)\\n\";\n cout << \"! Misc\\n\";\n\n list::iterator itc;\n int i = 0;\n for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc)\n {\n if(itc->name.length() == 0) continue;\n if(i%2) cout << \"|-\\n\";\n else cout << \"|- style=\\\"background:#FFFFD0\\\"\\n\";\n if(itc->url.length())\n cout << \"| [\" << itc->url << \" \" << itc->name << \"]\\n\";\n else\n cout << \"| \" << itc->name << \"\\n\";\n if(itc->changedlines)\n cout << \"| \" << itc->changedlines << \" (\" << itc->changesets << \")\\n\";\n else\n cout << \"| (no own changesets) \\n\";\n cout << \"| \" << itc->misc << \"\\n\";\n i++;\n }\n cout << \"|}\" << endl;\n}\n* sort by last name alphabetically * replace (no own changesets) by (no information)#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ this function takes a line that may contain a name and\/or email address,\n\/\/ and returns just the name, while fixing the \"bad cases\".\nstd::string contributor_name(const std::string& line)\n{\n string result;\n size_t position_of_email_address = line.find_first_of('<');\n if(position_of_email_address != string::npos)\n {\n \/\/ there is an e-mail address.\n \n \/\/ Hauke once committed as \"John Smith\", fix that.\n if(line.find(\"hauke.heibel\") != string::npos)\n result = \"Hauke Heibel\";\n else\n {\n \/\/ just remove the e-mail address\n result = line.substr(0, position_of_email_address);\n }\n }\n else\n {\n \/\/ there is no e-mail address.\n \n if(line.find(\"convert-repo\") != string::npos)\n result = \"\";\n else\n result = line;\n }\n\n \/\/ remove trailing spaces\n size_t length = result.length();\n while(length >= 1 && result[length-1] == ' ') result.erase(--length);\n\n return result;\n}\n\n\/\/ parses hg churn output to generate a contributors map.\nmap contributors_map_from_churn_output(const char *filename)\n{\n map contributors_map;\n\n string line;\n ifstream churn_out;\n churn_out.open(filename, ios::in);\n while(!getline(churn_out,line).eof())\n {\n \/\/ remove the histograms \"******\" that hg churn may draw at the end of some lines\n size_t first_star = line.find_first_of('*');\n if(first_star != string::npos) line.erase(first_star);\n \n \/\/ remove trailing spaces\n size_t length = line.length();\n while(length >= 1 && line[length-1] == ' ') line.erase(--length);\n\n \/\/ now the last space indicates where the number starts\n size_t last_space = line.find_last_of(' ');\n \n \/\/ get the number (of changesets or of modified lines for each contributor)\n int number;\n istringstream(line.substr(last_space+1)) >> number;\n\n \/\/ get the name of the contributor\n line.erase(last_space); \n string name = contributor_name(line);\n \n map::iterator it = contributors_map.find(name);\n \/\/ if new contributor, insert\n if(it == contributors_map.end())\n contributors_map.insert(pair(name, number));\n \/\/ if duplicate, just add the number\n else\n it->second += number;\n }\n churn_out.close();\n\n return contributors_map;\n}\n\n\/\/ find the last name, i.e. the last word.\n\/\/ for \"van den Schbling\" types of last names, that's not a problem, that's actually what we want.\nstring lastname(const string& name)\n{\n size_t last_space = name.find_last_of(' ');\n if(last_space >= name.length()-1) return name;\n else return name.substr(last_space+1);\n}\n\nstruct contributor\n{\n string name;\n int changedlines;\n int changesets;\n string url;\n string misc;\n \n contributor() : changedlines(0), changesets(0) {}\n \n bool operator < (const contributor& other)\n {\n return lastname(name).compare(lastname(other.name)) < 0;\n }\n};\n\nvoid add_online_info_into_contributors_list(list& contributors_list, const char *filename)\n{\n string line;\n ifstream online_info;\n online_info.open(filename, ios::in);\n while(!getline(online_info,line).eof())\n {\n string hgname, realname, url, misc;\n \n size_t last_bar = line.find_last_of('|');\n if(last_bar == string::npos) continue;\n if(last_bar < line.length())\n misc = line.substr(last_bar+1);\n line.erase(last_bar);\n \n last_bar = line.find_last_of('|');\n if(last_bar == string::npos) continue;\n if(last_bar < line.length())\n url = line.substr(last_bar+1);\n line.erase(last_bar);\n\n last_bar = line.find_last_of('|');\n if(last_bar == string::npos) continue;\n if(last_bar < line.length())\n realname = line.substr(last_bar+1);\n line.erase(last_bar);\n\n hgname = line;\n \n \/\/ remove the example line\n if(hgname.find(\"MercurialName\") != string::npos) continue;\n \n list::iterator it;\n for(it=contributors_list.begin(); it != contributors_list.end() && it->name != hgname; ++it)\n {}\n \n if(it == contributors_list.end())\n {\n contributor c;\n c.name = realname;\n c.url = url;\n c.misc = misc;\n contributors_list.push_back(c);\n }\n else\n {\n it->name = realname;\n it->url = url;\n it->misc = misc;\n }\n }\n}\n\nint main()\n{\n \/\/ parse the hg churn output files\n map contributors_map_for_changedlines = contributors_map_from_churn_output(\"churn-changedlines.out\");\n map contributors_map_for_changesets = contributors_map_from_churn_output(\"churn-changesets.out\");\n \n \/\/ merge into the contributors list\n list contributors_list;\n map::iterator it;\n for(it=contributors_map_for_changedlines.begin(); it != contributors_map_for_changedlines.end(); ++it)\n {\n contributor c;\n c.name = it->first;\n c.changedlines = it->second;\n c.changesets = contributors_map_for_changesets.find(it->first)->second;\n contributors_list.push_back(c);\n }\n \n add_online_info_into_contributors_list(contributors_list, \"online-info.out\");\n \n contributors_list.sort();\n \n cout << \"{| cellpadding=\\\"5\\\"\\n\";\n cout << \"!\\n\";\n cout << \"! Lines changed\\n(changesets)\\n\";\n cout << \"!\\n\";\n\n list::iterator itc;\n int i = 0;\n for(itc=contributors_list.begin(); itc != contributors_list.end(); ++itc)\n {\n if(itc->name.length() == 0) continue;\n if(i%2) cout << \"|-\\n\";\n else cout << \"|- style=\\\"background:#FFFFD0\\\"\\n\";\n if(itc->url.length())\n cout << \"| [\" << itc->url << \" \" << itc->name << \"]\\n\";\n else\n cout << \"| \" << itc->name << \"\\n\";\n if(itc->changedlines)\n cout << \"| \" << itc->changedlines << \" (\" << itc->changesets << \")\\n\";\n else\n cout << \"| (no information)\\n\";\n cout << \"| \" << itc->misc << \"\\n\";\n i++;\n }\n cout << \"|}\" << endl;\n}\n<|endoftext|>"} {"text":"Removed empty file<|endoftext|>"} {"text":"\/*\n * Copyright 2020 Google LLC\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"src\/gpu\/GrGpuResourcePriv.h\"\n#include \"src\/gpu\/d3d\/GrD3DGpu.h\"\n#include \"src\/gpu\/d3d\/GrD3DTextureResource.h\"\n\nvoid GrD3DTextureResource::setResourceState(const GrD3DGpu* gpu,\n D3D12_RESOURCE_STATES newResourceState) {\n D3D12_RESOURCE_STATES currentResourceState = this->currentState();\n if (newResourceState == currentResourceState) {\n return;\n }\n\n D3D12_RESOURCE_TRANSITION_BARRIER barrier;\n barrier.pResource = this->d3dResource();\n barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;\n barrier.StateBefore = currentResourceState;\n barrier.StateAfter = newResourceState;\n gpu->addResourceBarriers(this->resource(), 1, &barrier);\n\n this->updateResourceState(newResourceState);\n}\n\nbool GrD3DTextureResource::InitTextureResourceInfo(GrD3DGpu* gpu, const D3D12_RESOURCE_DESC& desc,\n D3D12_RESOURCE_STATES initialState,\n GrProtected isProtected,\n D3D12_CLEAR_VALUE* clearValue,\n GrD3DTextureResourceInfo* info) {\n if (0 == desc.Width || 0 == desc.Height) {\n return false;\n }\n \/\/ TODO: We don't support protected memory at the moment\n if (isProtected == GrProtected::kYes) {\n return false;\n }\n \/\/ If MipLevels is 0, for some formats the API will automatically calculate the maximum\n \/\/ number of levels supported and use that -- we don't support that.\n SkASSERT(desc.MipLevels > 0);\n\n ID3D12Resource* resource = nullptr;\n\n D3D12_HEAP_PROPERTIES heapProperties = {};\n heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;\n heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;\n heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;\n heapProperties.CreationNodeMask = 1;\n heapProperties.VisibleNodeMask = 1;\n HRESULT hr = gpu->device()->CreateCommittedResource(\n &heapProperties,\n D3D12_HEAP_FLAG_NONE,\n &desc,\n initialState,\n clearValue,\n IID_PPV_ARGS(&resource));\n if (!SUCCEEDED(hr)) {\n return false;\n }\n\n info->fResource.reset(resource);\n info->fResourceState = initialState;\n info->fFormat = desc.Format;\n info->fLevelCount = desc.MipLevels;\n info->fSampleQualityPattern = desc.SampleDesc.Quality;\n info->fProtected = isProtected;\n\n return true;\n}\n\nstd::pair> GrD3DTextureResource::CreateMSAA(\n GrD3DGpu* gpu, SkISize dimensions, int sampleCnt, const GrD3DTextureResourceInfo& info,\n SkColor4f clearColor) {\n GrD3DTextureResourceInfo msInfo;\n sk_sp msState;\n\n \/\/ create msaa surface\n D3D12_RESOURCE_DESC msTextureDesc = {};\n msTextureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;\n msTextureDesc.Alignment = 0; \/\/ Default alignment (64KB)\n msTextureDesc.Width = dimensions.fWidth;\n msTextureDesc.Height = dimensions.fHeight;\n msTextureDesc.DepthOrArraySize = 1;\n msTextureDesc.MipLevels = 1;\n msTextureDesc.Format = info.fFormat;\n msTextureDesc.SampleDesc.Count = sampleCnt;\n msTextureDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;\n msTextureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; \/\/ Use default for dxgi format\n msTextureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;\n\n D3D12_CLEAR_VALUE clearValue = {};\n clearValue.Format = info.fFormat;\n clearValue.Color[0] = clearColor.fR;\n clearValue.Color[1] = clearColor.fG;\n clearValue.Color[2] = clearColor.fB;\n clearValue.Color[3] = clearColor.fA;\n\n if (!InitTextureResourceInfo(gpu, msTextureDesc, D3D12_RESOURCE_STATE_RENDER_TARGET,\n info.fProtected, &clearValue, &msInfo)) {\n return {};\n }\n\n msState.reset(new GrD3DResourceState(\n static_cast(msInfo.fResourceState)));\n\n return std::make_pair(msInfo, msState);\n}\n\nGrD3DTextureResource::~GrD3DTextureResource() {\n \/\/ Should have been reset() before\n SkASSERT(!fResource);\n}\n\nvoid GrD3DTextureResource::prepareForPresent(GrD3DGpu* gpu) {\n this->setResourceState(gpu, D3D12_RESOURCE_STATE_PRESENT);\n}\n\nvoid GrD3DTextureResource::releaseResource(GrD3DGpu* gpu) {\n \/\/ TODO: do we need to migrate resource state if we change queues?\n if (fResource) {\n fResource->removeOwningTexture();\n fResource.reset(nullptr);\n }\n}\n\nvoid GrD3DTextureResource::setResourceRelease(sk_sp releaseHelper) {\n SkASSERT(fResource);\n \/\/ Forward the release proc on to GrD3DTextureResource::Resource\n fResource->setRelease(std::move(releaseHelper));\n}\n\nvoid GrD3DTextureResource::Resource::freeGPUData() const {\n this->invokeReleaseProc();\n fResource.reset(); \/\/ Release our ref to the resource\n}\nMake sure we release all refs in GrD3DTextureResource::releaseResource.\/*\n * Copyright 2020 Google LLC\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"src\/gpu\/GrGpuResourcePriv.h\"\n#include \"src\/gpu\/d3d\/GrD3DGpu.h\"\n#include \"src\/gpu\/d3d\/GrD3DTextureResource.h\"\n\nvoid GrD3DTextureResource::setResourceState(const GrD3DGpu* gpu,\n D3D12_RESOURCE_STATES newResourceState) {\n D3D12_RESOURCE_STATES currentResourceState = this->currentState();\n if (newResourceState == currentResourceState) {\n return;\n }\n\n D3D12_RESOURCE_TRANSITION_BARRIER barrier;\n barrier.pResource = this->d3dResource();\n barrier.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;\n barrier.StateBefore = currentResourceState;\n barrier.StateAfter = newResourceState;\n gpu->addResourceBarriers(this->resource(), 1, &barrier);\n\n this->updateResourceState(newResourceState);\n}\n\nbool GrD3DTextureResource::InitTextureResourceInfo(GrD3DGpu* gpu, const D3D12_RESOURCE_DESC& desc,\n D3D12_RESOURCE_STATES initialState,\n GrProtected isProtected,\n D3D12_CLEAR_VALUE* clearValue,\n GrD3DTextureResourceInfo* info) {\n if (0 == desc.Width || 0 == desc.Height) {\n return false;\n }\n \/\/ TODO: We don't support protected memory at the moment\n if (isProtected == GrProtected::kYes) {\n return false;\n }\n \/\/ If MipLevels is 0, for some formats the API will automatically calculate the maximum\n \/\/ number of levels supported and use that -- we don't support that.\n SkASSERT(desc.MipLevels > 0);\n\n ID3D12Resource* resource = nullptr;\n\n D3D12_HEAP_PROPERTIES heapProperties = {};\n heapProperties.Type = D3D12_HEAP_TYPE_DEFAULT;\n heapProperties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;\n heapProperties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;\n heapProperties.CreationNodeMask = 1;\n heapProperties.VisibleNodeMask = 1;\n HRESULT hr = gpu->device()->CreateCommittedResource(\n &heapProperties,\n D3D12_HEAP_FLAG_NONE,\n &desc,\n initialState,\n clearValue,\n IID_PPV_ARGS(&resource));\n if (!SUCCEEDED(hr)) {\n return false;\n }\n\n info->fResource.reset(resource);\n info->fResourceState = initialState;\n info->fFormat = desc.Format;\n info->fLevelCount = desc.MipLevels;\n info->fSampleQualityPattern = desc.SampleDesc.Quality;\n info->fProtected = isProtected;\n\n return true;\n}\n\nstd::pair> GrD3DTextureResource::CreateMSAA(\n GrD3DGpu* gpu, SkISize dimensions, int sampleCnt, const GrD3DTextureResourceInfo& info,\n SkColor4f clearColor) {\n GrD3DTextureResourceInfo msInfo;\n sk_sp msState;\n\n \/\/ create msaa surface\n D3D12_RESOURCE_DESC msTextureDesc = {};\n msTextureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;\n msTextureDesc.Alignment = 0; \/\/ Default alignment (64KB)\n msTextureDesc.Width = dimensions.fWidth;\n msTextureDesc.Height = dimensions.fHeight;\n msTextureDesc.DepthOrArraySize = 1;\n msTextureDesc.MipLevels = 1;\n msTextureDesc.Format = info.fFormat;\n msTextureDesc.SampleDesc.Count = sampleCnt;\n msTextureDesc.SampleDesc.Quality = DXGI_STANDARD_MULTISAMPLE_QUALITY_PATTERN;\n msTextureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; \/\/ Use default for dxgi format\n msTextureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;\n\n D3D12_CLEAR_VALUE clearValue = {};\n clearValue.Format = info.fFormat;\n clearValue.Color[0] = clearColor.fR;\n clearValue.Color[1] = clearColor.fG;\n clearValue.Color[2] = clearColor.fB;\n clearValue.Color[3] = clearColor.fA;\n\n if (!InitTextureResourceInfo(gpu, msTextureDesc, D3D12_RESOURCE_STATE_RENDER_TARGET,\n info.fProtected, &clearValue, &msInfo)) {\n return {};\n }\n\n msState.reset(new GrD3DResourceState(\n static_cast(msInfo.fResourceState)));\n\n return std::make_pair(msInfo, msState);\n}\n\nGrD3DTextureResource::~GrD3DTextureResource() {\n \/\/ Should have been reset() before\n SkASSERT(!fResource);\n SkASSERT(!fInfo.fResource);\n}\n\nvoid GrD3DTextureResource::prepareForPresent(GrD3DGpu* gpu) {\n this->setResourceState(gpu, D3D12_RESOURCE_STATE_PRESENT);\n}\n\nvoid GrD3DTextureResource::releaseResource(GrD3DGpu* gpu) {\n \/\/ TODO: do we need to migrate resource state if we change queues?\n if (fResource) {\n fResource->removeOwningTexture();\n fResource.reset();\n }\n fInfo.fResource.reset();\n}\n\nvoid GrD3DTextureResource::setResourceRelease(sk_sp releaseHelper) {\n SkASSERT(fResource);\n \/\/ Forward the release proc on to GrD3DTextureResource::Resource\n fResource->setRelease(std::move(releaseHelper));\n}\n\nvoid GrD3DTextureResource::Resource::freeGPUData() const {\n this->invokeReleaseProc();\n fResource.reset(); \/\/ Release our ref to the resource\n}\n<|endoftext|>"} {"text":"\/*-\n * Copyright (c) 2012 Michael Marner \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 * 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 *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * 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 AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n\n#include \"MatrixSwitch.h\"\n\n\nnamespace wcl\n{\n\n\tMatrixSwitch::MatrixSwitch(const std::string& ipAddress, unsigned int switchID)\n\t\t: mIP(ipAddress), mSwitchID(switchID)\n\t{\n\t\t\/\/ nothing to do here...\n\t}\n\n\tMatrixSwitch::~MatrixSwitch()\n\t{\n\t\t\/\/ nothing to do here either...\n\t}\n\n\n\tbool MatrixSwitch::route(unsigned int inputID, unsigned int outputID)\n\t{\n\t\t\/\/ note: I don't know how many simultaneous connections\n\t\t\/\/ the matrix switch supports. So, rather than connect\n\t\t\/\/ on creation and disconnect on destruction, we'll just\n\t\t\/\/ create a socket each method call.\n\n\t\tif (inputID < 1 && inputID >36 && outputID < 1 && outputID > 36)\n\t\t\treturn false;\n\n\t\t\/\/ connects on port 23 always\n\t\twcl::TCPSocket s(mIP, 23);\n\n\t\tchar message[14];\n\t\tmessage[13] = 0;\n\n\t\tsprintf(message, \"*%3d0004%2d%2d!\", mSwitchID, outputID, inputID);\n\t\ts.writeUntil(message, 13);\n\t\ts.close();\n\n return true;\n\t}\n\n\n\tbool MatrixSwitch::disconnect(unsigned int outputID)\n\t{\n\t\tif (outputID < 1 && outputID > 36)\n\t\t\treturn false;\n\n\t\t\/\/ connects on port 23 always\n\t\twcl::TCPSocket s(mIP, 23);\n\n\t\tchar message[14];\n\t\tmessage[13] = 0;\n\n\t\tsprintf(message, \"*%3d0004%2d%2d!\", mSwitchID, outputID, 0);\n\t\ts.writeUntil(message, 13);\n\t\ts.close();\n\n return true;\n\t}\n\n};\n\nFix return value when routing.\/*-\n * Copyright (c) 2012 Michael Marner \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 * 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 *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * 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 AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n\n#include \"MatrixSwitch.h\"\n\n\nnamespace wcl\n{\n\n\tMatrixSwitch::MatrixSwitch(const std::string& ipAddress, unsigned int switchID)\n\t\t: mIP(ipAddress), mSwitchID(switchID)\n\t{\n\t\t\/\/ nothing to do here...\n\t}\n\n\tMatrixSwitch::~MatrixSwitch()\n\t{\n\t\t\/\/ nothing to do here either...\n\t}\n\n\n\tbool MatrixSwitch::route(unsigned int inputID, unsigned int outputID)\n\t{\n\t\t\/\/ note: I don't know how many simultaneous connections\n\t\t\/\/ the matrix switch supports. So, rather than connect\n\t\t\/\/ on creation and disconnect on destruction, we'll just\n\t\t\/\/ create a socket each method call.\n\n\t\tif (inputID < 1 && inputID >36 && outputID < 1 && outputID > 36)\n\t\t\treturn false;\n\n\t\t\/\/ connects on port 23 always\n\t\twcl::TCPSocket s(mIP, 23);\n\n\t\tchar message[14];\n\t\tmessage[13] = 0;\n\n\t\tsprintf(message, \"*%3d0004%2d%2d!\", mSwitchID, outputID, inputID);\n\t\ts.writeUntil(message, 13);\n\t\ts.close();\n\t\treturn true;\n\t}\n\n\n\tbool MatrixSwitch::disconnect(unsigned int outputID)\n\t{\n\t\tif (outputID < 1 && outputID > 36)\n\t\t\treturn false;\n\n\t\t\/\/ connects on port 23 always\n\t\twcl::TCPSocket s(mIP, 23);\n\n\t\tchar message[14];\n\t\tmessage[13] = 0;\n\n\t\tsprintf(message, \"*%3d0004%2d%2d!\", mSwitchID, outputID, 0);\n\t\ts.writeUntil(message, 13);\n\t\ts.close();\n\t\treturn true;\n\t}\n\n};\n\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP\n#define STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n namespace math {\n\n \/**\n * Return the log mixture density with specified mixing proportion\n * and log densities.\n *\n *\n * @param theta vector of mixing proportions in [0, 1].\n * @param lambda vector of log densities.\n * @return log mixture of densities in specified proportion\n *\/\n template \n typename return_type::type\n log_mix(const T_theta& theta,\n const T_lam& lambda) {\n static const std::string function = \"log_mix\";\n typedef typename stan::partials_return_type::type\n T_partials_return;\n\n const size_t N = theta.size();\n\n for (size_t n = 0; n < N; ++n) {\n check_not_nan(function, \"lambda\", lambda[n]);\n check_not_nan(function, \"theta\", theta[n]);\n check_finite(function, \"lambda\", lambda[n]);\n check_finite(function, \"theta\", theta[n]);\n check_bounded(function, \"theta\", theta[n], 0, 1);\n }\n check_consistent_sizes(function, \"theta\", theta, \"lambda\", lambda);\n\n Eigen::Matrix theta_dbl(N, 1);\n scalar_seq_view theta_vec(theta);\n for (size_t n = 0; n < N; ++n)\n theta_dbl[n] = value_of(theta_vec[n]);\n\n Eigen::Matrix lambda_dbl(N, 1);\n scalar_seq_view lam_vec(lambda);\n for (size_t n = 0; n < N; ++n)\n lambda_dbl[n] = value_of(lam_vec[n]);\n\n \/**\n * Vector containing log-prob of each density, log_sum_exp applied as\n * part of return call.\n *\/\n Eigen::Matrix logp_tmp(N, 1);\n logp_tmp = log(theta_dbl) + lambda_dbl;\n\n \/**\n * Calculate derivatives\n *\/\n Eigen::Matrix exp_lambda_dbl(N, 1);\n \/**\n * Exp-normalise to prevent overflow, as: \n * (exp(x-a) * exp(a)) \/ (exp(y-a) * exp(a)) = exp(x-a) \/ exp(y-a)\n *\/\n double max_val = max(lambda_dbl);\n for (size_t n = 0; n < N; ++n)\n exp_lambda_dbl[n] = exp((lambda_dbl[n] - max_val));\n \n T_partials_return dot_exp_lam_theta = dot_product(exp_lambda_dbl,\n theta_dbl);\n\n Eigen::Matrix theta_deriv(N, 1);\n theta_deriv = exp_lambda_dbl \/ dot_exp_lam_theta;\n\n Eigen::Matrix lam_deriv(N, 1);\n for (size_t n = 0; n < N; ++n)\n lam_deriv[n] = (exp_lambda_dbl[n] * theta_dbl[n]) \/ dot_exp_lam_theta;\n\n operands_and_partials ops_partials(theta, lambda);\n if (!(is_constant_struct::value\n && is_constant_struct::value)) {\n if (!is_constant_struct::value)\n ops_partials.edge1_.partials_ = theta_deriv;\n\n if (!is_constant_struct::value)\n ops_partials.edge2_.partials_ = lam_deriv;\n }\n\n return ops_partials.build(log_sum_exp(logp_tmp));\n }\n }\n}\n#endif\nFinal tidying#ifndef STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP\n#define STAN_MATH_PRIM_MAT_FUN_LOG_MIX_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n namespace math {\n\n \/**\n * Return the log mixture density with specified mixing proportion\n * and log densities.\n *\n *\n * @param theta vector of mixing proportions in [0, 1].\n * @param lambda vector of log densities.\n * @return log mixture of densities in specified proportion\n *\/\n template \n typename return_type::type\n log_mix(const T_theta& theta,\n const T_lam& lambda) {\n static const std::string function = \"log_mix\";\n typedef typename stan::partials_return_type::type\n T_partials_return;\n\n const size_t N = theta.size();\n\n for (size_t n = 0; n < N; ++n) {\n check_not_nan(function, \"lambda\", lambda[n]);\n check_not_nan(function, \"theta\", theta[n]);\n check_finite(function, \"lambda\", lambda[n]);\n check_finite(function, \"theta\", theta[n]);\n check_bounded(function, \"theta\", theta[n], 0, 1);\n }\n check_consistent_sizes(function, \"theta\", theta, \"lambda\", lambda);\n\n Eigen::Matrix theta_dbl(N, 1);\n scalar_seq_view theta_vec(theta);\n for (size_t n = 0; n < N; ++n)\n theta_dbl[n] = value_of(theta_vec[n]);\n\n Eigen::Matrix lambda_dbl(N, 1);\n scalar_seq_view lam_vec(lambda);\n for (size_t n = 0; n < N; ++n)\n lambda_dbl[n] = value_of(lam_vec[n]);\n\n \/**\n * Vector containing log-prob of each density, log_sum_exp applied as\n * part of return call.\n *\/\n Eigen::Matrix logp_tmp(N, 1);\n logp_tmp = log(theta_dbl) + lambda_dbl;\n\n \/**\n * Calculate derivatives\n *\n * Exp-normalise to prevent overflow, as: \n * (exp(x-a) * exp(a)) \/ (exp(y-a) * exp(a)) = exp(x-a) \/ exp(y-a)\n *\/\n Eigen::Matrix exp_lambda_dbl(N, 1);\n double max_val = max(lambda_dbl);\n for (size_t n = 0; n < N; ++n)\n exp_lambda_dbl[n] = exp((lambda_dbl[n] - max_val));\n\n T_partials_return dot_exp_lam_theta = dot_product(exp_lambda_dbl,\n theta_dbl);\n\n Eigen::Matrix theta_deriv(N, 1);\n theta_deriv = exp_lambda_dbl \/ dot_exp_lam_theta;\n\n Eigen::Matrix lam_deriv(N, 1);\n for (size_t n = 0; n < N; ++n)\n lam_deriv[n] = (exp_lambda_dbl[n] * theta_dbl[n]) \/ dot_exp_lam_theta;\n\n operands_and_partials ops_partials(theta, lambda);\n if (!(is_constant_struct::value\n && is_constant_struct::value)) {\n if (!is_constant_struct::value)\n ops_partials.edge1_.partials_ = theta_deriv;\n\n if (!is_constant_struct::value)\n ops_partials.edge2_.partials_ = lam_deriv;\n }\n\n return ops_partials.build(log_sum_exp(logp_tmp));\n }\n }\n}\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: StorageNativeInputStream.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 09:41:37 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n\n#if HAVE_CONFIG_H\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#include \"hsqldb\/HStorageAccess.h\"\n#include \"hsqldb\/HStorageMap.hxx\"\n#include \"hsqldb\/StorageNativeInputStream.h\"\n\n#include \"jvmaccess\/virtualmachine.hxx\"\n#include \"com\/sun\/star\/lang\/XSingleComponentFactory.hpp\"\n\n#include \n#include \n\n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::document;\nusing namespace ::com::sun::star::embed;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::connectivity::hsqldb;\n\n#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )\n\/*****************************************************************************\/\n\/* exception macros *\/\n\n#define ThrowException(env, type, msg) { \\\n env->ThrowNew(env->FindClass(type), msg); }\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: openStream\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode)\n{\n#if OSL_DEBUG_LEVEL > 1\n {\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".input\"));\n ::rtl::OString sName = ::rtl::OUStringToOString(sOrgName,RTL_TEXTENCODING_ASCII_US);\n getStreams()[sOrgName] = fopen( sName.getStr(), \"a+\" );\n }\n#endif\n StorageContainer::registerStream(env,name,key,mode);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2(env,obj_this,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[BII)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len)\n{\n return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2_3BII(env,obj_this,name,key,buffer,off,len);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: close\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n {\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".input\"));\n fclose( getStreams()[sOrgName] );\n getStreams().erase(sOrgName);\n }\n#endif\n StorageContainer::revokeStream(env,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: skip\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n)\n{\n if ( n < 0 )\n ThrowException( env,\n \"java\/io\/IOException\",\n \"n < 0\");\n\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n if ( pHelper.get() )\n {\n Reference xIn = pHelper->getInputStream();\n if ( xIn.is() )\n {\n try\n {\n sal_Int64 nBytesSkipped = 0;\n sal_Int64 tmpLongVal = n;\n sal_Int32 tmpIntVal;\n\n try\n {\n do {\n if (tmpLongVal >= ::std::numeric_limits::max() )\n tmpIntVal = ::std::numeric_limits::max();\n else \/\/ Casting is safe here.\n tmpIntVal = static_cast(tmpLongVal);\n\n tmpLongVal -= tmpIntVal;\n\n xIn->skipBytes(tmpIntVal);\n\n } while (tmpLongVal > 0);\n }\n catch(Exception& e )\n {\n }\n\n return n - tmpLongVal;\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : skip();\");\n StorageContainer::throwJavaException(e,env);\n }\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: available\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n Reference xIn = pHelper.get() ? pHelper->getInputStream() : Reference();\n if ( xIn.is() )\n {\n try\n {\n return xIn->available();\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : available();\");\n StorageContainer::throwJavaException(e,env);\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[B)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer)\n{\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();\n OSL_ENSURE(xIn.is(),\"Input stream is NULL!\");\n sal_Int32 nBytesRead = 0;\n if ( xIn.is() )\n {\n jsize nLen = env->GetArrayLength(buffer);\n Sequence< ::sal_Int8 > aData(nLen);\n\n try\n {\n nBytesRead = xIn->readBytes(aData,nLen);\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : skip();\");\n StorageContainer::throwJavaException(e,env);\n }\n\n \/\/ Casting bytesRead to an int is okay, since the user can\n \/\/ only pass in an integer length to read, so the bytesRead\n \/\/ must <= len.\n \/\/\n if (nBytesRead <= 0) {\n return -1;\n }\n OSL_ENSURE(nLen >= nBytesRead,\"Buffer is too small!\");\n OSL_ENSURE(aData.getLength() >= nBytesRead,\"Buffer is too small!\");\n env->SetByteArrayRegion(buffer,0,nBytesRead,&aData[0]);\n#if OSL_DEBUG_LEVEL > 1\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".input\"));\n fwrite(&aData[0],sizeof(sal_Int8),nBytesRead,getStreams()[sOrgName]);\n#endif\n }\n return nBytesRead;\n}\n\/\/ -----------------------------------------------------------------------------\nINTEGRATION: CWS dba28 (1.3.22); FILE MERGED 2005\/03\/30 11:27:29 fs 1.3.22.3: RESYNC: (1.3-1.4); FILE MERGED 2005\/03\/23 14:58:31 fs 1.3.22.2: #i45314# logging facilities 2005\/03\/21 12:53:33 fs 1.3.22.1: copying the changes from CWS dba26 herein, since they're needed to fix i45314\/*************************************************************************\n *\n * $RCSfile: StorageNativeInputStream.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-03-30 11:52:05 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT 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): Ocke Janssen\n *\n *\n ************************************************************************\/\n\n#if HAVE_CONFIG_H\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#ifndef CONNECTIVITY_HSQLDB_STORAGEACCESS_HXX\n#include \"hsqldb\/HStorageAccess.hxx\"\n#endif\n#include \"hsqldb\/HStorageMap.hxx\"\n#include \"hsqldb\/StorageNativeInputStream.h\"\n\n#include \"jvmaccess\/virtualmachine.hxx\"\n#ifndef _COM_SUN_STAR_LANG_XSINGLECOMPONENTFACTORY_HPP_\n#include \n#endif\n\n#ifndef CONNECTIVITY_HSQLDB_ACCESSLOG_HXX\n#include \"accesslog.hxx\"\n#endif\n\n#include \n\n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::document;\nusing namespace ::com::sun::star::embed;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::connectivity::hsqldb;\n\n#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )\n\/*****************************************************************************\/\n\/* exception macros *\/\n\n#define ThrowException(env, type, msg) { \\\n env->ThrowNew(env->FindClass(type), msg); }\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: openStream\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode)\n{\n#if OSL_DEBUG_LEVEL > 1\n {\n OperationLogFile( env, name, \"input\" ).logOperation( \"openStream\" );\n LogFile( env, name, \"input\" ).create();\n }\n#endif\n StorageContainer::registerStream(env,name,key,mode);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"input\" ).logOperation( \"read()\" );\n\n DataLogFile aDataLog( env, name, \"input\" );\n return read_from_storage_stream( env, obj_this, name, key, &aDataLog );\n#else\n return read_from_storage_stream( env, obj_this, name, key );\n#endif\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[BII)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"input\" ).logOperation( \"read( byte[], int, int )\" );\n\n DataLogFile aDataLog( env, name, \"input\" );\n return read_from_storage_stream_into_buffer( env, obj_this, name, key, buffer, off, len, &aDataLog );\n#else\n return read_from_storage_stream_into_buffer(env,obj_this,name,key,buffer,off,len);\n#endif\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: close\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile aOpLog( env, name, \"input\" );\n aOpLog.logOperation( \"close\" );\n aOpLog.close();\n\n LogFile aDataLog( env, name, \"input\" );\n aDataLog.close();\n#endif\n StorageContainer::revokeStream(env,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: skip\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile( env, name, \"input\" ).logOperation( \"skip()\" );\n#endif\n\n if ( n < 0 )\n ThrowException( env,\n \"java\/io\/IOException\",\n \"n < 0\");\n\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n if ( pHelper.get() )\n {\n Reference xIn = pHelper->getInputStream();\n if ( xIn.is() )\n {\n try\n {\n sal_Int64 nBytesSkipped = 0;\n sal_Int64 tmpLongVal = n;\n sal_Int32 tmpIntVal;\n\n try\n {\n do {\n if (tmpLongVal >= ::std::numeric_limits::max() )\n tmpIntVal = ::std::numeric_limits::max();\n else \/\/ Casting is safe here.\n tmpIntVal = static_cast(tmpLongVal);\n\n tmpLongVal -= tmpIntVal;\n\n xIn->skipBytes(tmpIntVal);\n\n } while (tmpLongVal > 0);\n }\n catch(Exception& e )\n {\n }\n\n return n - tmpLongVal;\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : skip();\");\n StorageContainer::throwJavaException(e,env);\n }\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: available\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile aOpLog( env, name, \"input\" );\n aOpLog.logOperation( \"available\" );\n#endif\n\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n Reference xIn = pHelper.get() ? pHelper->getInputStream() : Reference();\n if ( xIn.is() )\n {\n try\n {\n jint nAvailable = xIn->available();\n#if OSL_DEBUG_LEVEL > 1\n aOpLog.logReturn( nAvailable );\n#endif\n return nAvailable;\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : available();\");\n StorageContainer::throwJavaException(e,env);\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[B)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer)\n{\n#if OSL_DEBUG_LEVEL > 1\n OperationLogFile aOpLog( env, name, \"input\" );\n aOpLog.logOperation( \"read( byte[] )\" );\n\n DataLogFile aDataLog( env, name, \"input\" );\n#endif\n\n ::boost::shared_ptr pHelper = StorageContainer::getRegisteredStream(env,name,key);\n Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();\n OSL_ENSURE(xIn.is(),\"Input stream is NULL!\");\n jint nBytesRead = 0;\n if ( xIn.is() )\n {\n jsize nLen = env->GetArrayLength(buffer);\n Sequence< ::sal_Int8 > aData(nLen);\n\n try\n {\n nBytesRead = xIn->readBytes(aData,nLen);\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : skip();\");\n StorageContainer::throwJavaException(e,env);\n }\n\n \/\/ Casting bytesRead to an int is okay, since the user can\n \/\/ only pass in an integer length to read, so the bytesRead\n \/\/ must <= len.\n \/\/\n if (nBytesRead <= 0) {\n#if OSL_DEBUG_LEVEL > 1\n aOpLog.logReturn( (jint)-1 );\n#endif\n return -1;\n }\n OSL_ENSURE(nLen >= nBytesRead,\"Buffer is too small!\");\n OSL_ENSURE(aData.getLength() >= nBytesRead,\"Buffer is too small!\");\n env->SetByteArrayRegion(buffer,0,nBytesRead,&aData[0]);\n#if OSL_DEBUG_LEVEL > 1\n aDataLog.write( &aData[0], nBytesRead );\n#endif\n }\n#if OSL_DEBUG_LEVEL > 1\n aOpLog.logReturn( nBytesRead );\n#endif\n return nBytesRead;\n}\n\/\/ -----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"fix tree by commenting out histograms<|endoftext|>"} {"text":"\n\/\/ Copyright 2010-2012 University of Washington. All Rights Reserved.\n\/\/ LICENSE_PLACEHOLDER\n\/\/ This software was created with Government support under DE\n\/\/ AC05-76RL01830 awarded by the United States Department of\n\/\/ Energy. The Government has certain rights in the software.\n\n\n#include \"Grappa.hpp\"\n#include \"CompletionEvent.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"Collective.hpp\"\n#include \"Statistics.hpp\"\n\n#include \n\nDECLARE_uint64( num_starting_workers );\nDEFINE_uint64( num_test_workers, 4, \"Number of workers for the tests\");\nDEFINE_uint64( iters_per_task, 10000, \"Iterations per task\" );\nDEFINE_string( test_type, \"yields\", \"options: {yields,sequential_updates, sequential_updates16\" ); \nDEFINE_uint64( private_array_size, 1, \"Size of private array of 8-bytes for each task\" );\n\nusing namespace Grappa;\n\nCompletionEvent * final;\nCompletionEvent * task_barrier;\n\nstruct SixteenBytes {\n uint64_t val1;\n uint64_t val2;\n};\n\nstruct Cacheline {\n uint64_t val;\n char padding[56];\n};\n\nuint64_t * values8;\nSixteenBytes * values16;\n\n\/\/ Performance output of the test, not used as cumulative statistics\n\/\/ Initial value 0 should make merge just use Core 0's\nGRAPPA_DEFINE_STAT( SimpleStatistic, context_switch_test_runtime_avg, 0 );\nGRAPPA_DEFINE_STAT( SimpleStatistic, context_switch_test_runtime_max, 0 );\nGRAPPA_DEFINE_STAT( SimpleStatistic, context_switch_test_runtime_min, 0 );\n\n\n\/\/ core-shared counter for counting progress\nuint64_t numst;\nuint64_t waitCount; \/\/ TODO: for traces, change to SimpleStatistic\nbool running;\n\n\nvoid user_main( void * args ) {\n srand((unsigned int)Grappa_walltime());\n\n \/\/ must have enough threads because they all join a barrier\n CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers );\n\n if (FLAGS_test_type.compare(\"yields\")==0) {\n LOG(INFO) << ( \"Test yields\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n \n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n running = false;\n\n final = new CompletionEvent(FLAGS_num_test_workers);\n task_barrier = new CompletionEvent(FLAGS_num_test_workers);\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !running ) {\n Grappa::Statistics::reset();\n start = Grappa_walltime();\n running = true;\n }\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n \n LOG(INFO) << ( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n LOG(INFO) << \"took time \" << runtime;\n\n Grappa::barrier();\n LOG(INFO) << ( \"all done\" );\n\n \/\/ sort out timing \n\n double r_sum = Grappa::allreduce( runtime );\n double r_min = Grappa::allreduce( runtime );\n double r_max = Grappa::allreduce( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n });\n \n context_switch_test_runtime_avg = r.runtime_avg;\n context_switch_test_runtime_max = r.runtime_max;\n context_switch_test_runtime_min = r.runtime_min;\n Grappa::Statistics::merge_and_print();\n\n\/\/ Streams overlap\n\/\/ BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n\/\/ << \", cores_time_max = \" << r.runtime_max\n\/\/ << \", cores_time_min = \" << r.runtime_min);\n }\n } else if (FLAGS_test_type.compare(\"cvwakes\")==0) {\n LOG(INFO) << ( \"Test cv wakes\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n\n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n\n ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers];\n bool * asleep = new bool[FLAGS_num_test_workers];\n for( int i=0; icomplete();\n task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !running ) {\n \/\/ can safely reset statistics here because\n \/\/ no messages are sent between cores in the\n \/\/ timed portion\n Grappa::Statistics::reset();\n start = Grappa_walltime();\n running = true;\n }\n\n uint64_t tid = numst++;\n \n uint64_t partner = (tid + FLAGS_num_test_workers\/2)%FLAGS_num_test_workers;\n uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; \n\n \/\/ do the work\n while( waitCount++ < total_iters ) {\n if ( asleep[partner] ) { \/\/ TODO also test just wake up case\n Grappa::signal( &cvs[partner] );\n }\n asleep[tid] = true;\n Grappa::wait( &cvs[tid] );\n asleep[tid] = false;\n }\n\n \/\/ only first \n if ( running ) {\n final->complete(); \/\/ signal to finish as soon as the parent task gets scheduled \n running = false;\n }\n });\n }\n \n LOG(INFO) << ( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n LOG(INFO) << \"took time \" << runtime;\n\n \/\/ wake all\n for (int i=0; i( runtime );\n double r_min = Grappa::allreduce( runtime );\n double r_max = Grappa::allreduce( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n });\n \n context_switch_test_runtime_avg = r.runtime_avg;\n context_switch_test_runtime_max = r.runtime_max;\n context_switch_test_runtime_min = r.runtime_min;\n Grappa::Statistics::merge_and_print();\n\n\/\/ Streams overlap\n\/\/ BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n\/\/ << \", cores_time_max = \" << r.runtime_max\n\/\/ << \", cores_time_min = \" << r.runtime_min);\n }\n \n } else if (FLAGS_test_type.compare(\"sequential_updates\")==0) {\n LOG(INFO) << ( \"Test sequential_updates\" );\n {\n\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else if (FLAGS_test_type.compare(\"sequential_updates16\")==0) {\n\n LOG(INFO) << ( \"Test sequential_updates16\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values16 = new SixteenBytes[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else if (FLAGS_test_type.compare(\"private_array\")==0) {\n\n LOG(INFO) << ( \"Test private_array\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n LOG(INFO) << \"result = \" << values8[rand()%FLAGS_num_starting_workers];\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else if (FLAGS_test_type.compare(\"private_array_bycache\")==0) {\n\n LOG(INFO) << ( \"Test private_array_bycache\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n LOG(INFO) << \"result = \" << values8[rand()%FLAGS_num_starting_workers];\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else {\n CHECK( false ); \/\/ Unrecognized test_type\n }\n\n\n DVLOG(5) << ( \"user main is exiting\" );\n}\n\n\n\nint main (int argc, char** argv) {\n\n Grappa_init( &argc, &argv ); \n\n Grappa_activate();\n\n DVLOG(1) << \"Spawning user main Thread....\";\n Grappa_run_user_main( &user_main, (void*)NULL );\n VLOG(5) << \"run_user_main returned\";\n CHECK( Grappa_done() );\n\n Grappa_finish( 0 );\n}\n\n\nremove private barrier from switch test since scheduler already won't run the threads until parent suspends\n\/\/ Copyright 2010-2012 University of Washington. All Rights Reserved.\n\/\/ LICENSE_PLACEHOLDER\n\/\/ This software was created with Government support under DE\n\/\/ AC05-76RL01830 awarded by the United States Department of\n\/\/ Energy. The Government has certain rights in the software.\n\n\n#include \"Grappa.hpp\"\n#include \"CompletionEvent.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"Collective.hpp\"\n#include \"Statistics.hpp\"\n\n#include \n\nDECLARE_uint64( num_starting_workers );\nDEFINE_uint64( num_test_workers, 4, \"Number of workers for the tests\");\nDEFINE_uint64( iters_per_task, 10000, \"Iterations per task\" );\nDEFINE_string( test_type, \"yields\", \"options: {yields,sequential_updates, sequential_updates16\" ); \nDEFINE_uint64( private_array_size, 1, \"Size of private array of 8-bytes for each task\" );\n\nusing namespace Grappa;\n\nCompletionEvent * final;\nCompletionEvent * task_barrier;\n\nstruct SixteenBytes {\n uint64_t val1;\n uint64_t val2;\n};\n\nstruct Cacheline {\n uint64_t val;\n char padding[56];\n};\n\nuint64_t * values8;\nSixteenBytes * values16;\n\n\/\/ Performance output of the test, not used as cumulative statistics\n\/\/ Initial value 0 should make merge just use Core 0's\nGRAPPA_DEFINE_STAT( SimpleStatistic, context_switch_test_runtime_avg, 0 );\nGRAPPA_DEFINE_STAT( SimpleStatistic, context_switch_test_runtime_max, 0 );\nGRAPPA_DEFINE_STAT( SimpleStatistic, context_switch_test_runtime_min, 0 );\n\n\n\/\/ core-shared counter for counting progress\nuint64_t numst;\nuint64_t waitCount; \/\/ TODO: for traces, change to SimpleStatistic\nbool running;\n\n\nvoid user_main( void * args ) {\n srand((unsigned int)Grappa_walltime());\n\n \/\/ must have enough threads because they all join a barrier\n CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers );\n\n if (FLAGS_test_type.compare(\"yields\")==0) {\n LOG(INFO) << ( \"Test yields\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n \n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n running = false;\n\n final = new CompletionEvent(FLAGS_num_test_workers);\n task_barrier = new CompletionEvent(FLAGS_num_test_workers);\n\n for ( uint64_t t=0; tcomplete();\n \/\/ task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !running ) {\n Grappa::Statistics::reset();\n start = Grappa_walltime();\n running = true;\n }\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n \n LOG(INFO) << ( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n LOG(INFO) << \"took time \" << runtime;\n\n Grappa::barrier();\n LOG(INFO) << ( \"all done\" );\n\n \/\/ sort out timing \n\n double r_sum = Grappa::allreduce( runtime );\n double r_min = Grappa::allreduce( runtime );\n double r_max = Grappa::allreduce( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n });\n \n context_switch_test_runtime_avg = r.runtime_avg;\n context_switch_test_runtime_max = r.runtime_max;\n context_switch_test_runtime_min = r.runtime_min;\n Grappa::Statistics::merge_and_print();\n\n\/\/ Streams overlap\n\/\/ BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n\/\/ << \", cores_time_max = \" << r.runtime_max\n\/\/ << \", cores_time_min = \" << r.runtime_min);\n }\n } else if (FLAGS_test_type.compare(\"cvwakes\")==0) {\n LOG(INFO) << ( \"Test cv wakes\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n\n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n\n ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers];\n bool * asleep = new bool[FLAGS_num_test_workers];\n for( int i=0; icomplete();\n \/\/task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !running ) {\n \/\/ can safely reset statistics here because\n \/\/ no messages are sent between cores in the\n \/\/ timed portion\n Grappa::Statistics::reset();\n start = Grappa_walltime();\n running = true;\n }\n\n uint64_t tid = numst++;\n \n uint64_t partner = (tid + FLAGS_num_test_workers\/2)%FLAGS_num_test_workers;\n uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; \n\n \/\/ do the work\n while( waitCount++ < total_iters ) {\n if ( asleep[partner] ) { \/\/ TODO also test just wake up case\n Grappa::signal( &cvs[partner] );\n }\n asleep[tid] = true;\n Grappa::wait( &cvs[tid] );\n asleep[tid] = false;\n }\n\n \/\/ only first \n if ( running ) {\n final->complete(); \/\/ signal to finish as soon as the parent task gets scheduled \n running = false;\n }\n });\n }\n \n LOG(INFO) << ( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n LOG(INFO) << \"took time \" << runtime;\n\n \/\/ wake all\n for (int i=0; i( runtime );\n double r_min = Grappa::allreduce( runtime );\n double r_max = Grappa::allreduce( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n });\n \n context_switch_test_runtime_avg = r.runtime_avg;\n context_switch_test_runtime_max = r.runtime_max;\n context_switch_test_runtime_min = r.runtime_min;\n Grappa::Statistics::merge_and_print();\n\n\/\/ Streams overlap\n\/\/ BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n\/\/ << \", cores_time_max = \" << r.runtime_max\n\/\/ << \", cores_time_min = \" << r.runtime_min);\n }\n \n } else if (FLAGS_test_type.compare(\"sequential_updates\")==0) {\n LOG(INFO) << ( \"Test sequential_updates\" );\n {\n\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else if (FLAGS_test_type.compare(\"sequential_updates16\")==0) {\n\n LOG(INFO) << ( \"Test sequential_updates16\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values16 = new SixteenBytes[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else if (FLAGS_test_type.compare(\"private_array\")==0) {\n\n LOG(INFO) << ( \"Test private_array\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n LOG(INFO) << \"result = \" << values8[rand()%FLAGS_num_starting_workers];\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else if (FLAGS_test_type.compare(\"private_array_bycache\")==0) {\n\n LOG(INFO) << ( \"Test private_array_bycache\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; tcomplete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; icomplete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n LOG(INFO) << \"result = \" << values8[rand()%FLAGS_num_starting_workers];\n\n double runtime = end-start;\n LOG(INFO) << \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task);\n }\n } else {\n CHECK( false ); \/\/ Unrecognized test_type\n }\n\n\n DVLOG(5) << ( \"user main is exiting\" );\n}\n\n\n\nint main (int argc, char** argv) {\n\n Grappa_init( &argc, &argv ); \n\n Grappa_activate();\n\n DVLOG(1) << \"Spawning user main Thread....\";\n Grappa_run_user_main( &user_main, (void*)NULL );\n VLOG(5) << \"run_user_main returned\";\n CHECK( Grappa_done() );\n\n Grappa_finish( 0 );\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 \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"build\/build_config.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\n\/\/ In-process plugin test runner. See OutOfProcessPPAPITest below for the\n\/\/ out-of-process version.\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = \/.\n \/\/ MIME type = application\/x-ppapi-\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n\n \/\/ Smooth scrolling confuses the scrollbar test.\n launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n std::string query(\"testcase=\");\n query += test_case;\n replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(\n test_server.GetURL(\"files\/test_case.html?testcase=\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n\n \/\/ See comment above TestingInstance in ppapi\/test\/testing_instance.h.\n \/\/ Basically it sets a series of numbered cookies. The value of \"...\" means\n \/\/ it's still working and we should continue to wait, any other value\n \/\/ indicates completion (in this case it will start with \"PASS\" or \"FAIL\").\n \/\/ This keeps us from timing out on cookie waits for long tests.\n int progress_number = 0;\n std::string progress;\n while (true) {\n std::string cookie_name = StringPrintf(\"PPAPI_PROGRESS_%d\",\n progress_number);\n progress = WaitUntilCookieNonEmpty(tab.get(), test_url,\n cookie_name.c_str(), TestTimeouts::large_test_timeout_ms());\n if (progress != \"...\")\n break;\n progress_number++;\n }\n\n if (progress_number == 0) {\n \/\/ Failing the first time probably means the plugin wasn't loaded.\n ASSERT_FALSE(progress.empty())\n << \"Plugin couldn't be loaded. Make sure the PPAPI test plugin is \"\n << \"built, in the right place, and doesn't have any missing symbols.\";\n } else {\n ASSERT_FALSE(progress.empty()) << \"Test timed out.\";\n }\n\n EXPECT_STREQ(\"PASS\", progress.c_str());\n }\n};\n\n\/\/ Variant of PPAPITest that runs plugins out-of-process to test proxy\n\/\/ codepaths.\nclass OutOfProcessPPAPITest : public PPAPITest {\n public:\n OutOfProcessPPAPITest() {\n \/\/ Run PPAPI out-of-process to exercise proxy implementations.\n launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess);\n }\n};\n\n\/\/ Use these macros to run the tests for a specific interface.\n\/\/ Most interfaces should be tested with both macros.\n#define TEST_PPAPI_IN_PROCESS(test_name) \\\n TEST_F(PPAPITest, test_name) { \\\n RunTest(#test_name); \\\n }\n#define TEST_PPAPI_OUT_OF_PROCESS(test_name) \\\n TEST_F(OutOfProcessPPAPITest, test_name) { \\\n RunTest(#test_name); \\\n }\n\n\/\/ Similar macros that test over HTTP.\n#define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \\\n TEST_F(PPAPITest, test_name) { \\\n RunTestViaHTTP(#test_name); \\\n }\n#define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \\\n TEST_F(OutOfProcessPPAPITest, test_name) { \\\n RunTestViaHTTP(#test_name); \\\n }\n\n\n\/\/\n\/\/ Interface tests.\n\/\/\n\nTEST_PPAPI_IN_PROCESS(Broker)\nTEST_PPAPI_OUT_OF_PROCESS(Broker)\n\nTEST_PPAPI_IN_PROCESS(Core)\nTEST_PPAPI_OUT_OF_PROCESS(Core)\n\nTEST_PPAPI_IN_PROCESS(CursorControl)\nTEST_PPAPI_OUT_OF_PROCESS(CursorControl)\n\nTEST_PPAPI_IN_PROCESS(Instance)\n\/\/ http:\/\/crbug.com\/91729\nTEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance)\n\nTEST_PPAPI_IN_PROCESS(Graphics2D)\nTEST_PPAPI_OUT_OF_PROCESS(Graphics2D)\n\nTEST_PPAPI_IN_PROCESS(ImageData)\nTEST_PPAPI_OUT_OF_PROCESS(ImageData)\n\nTEST_PPAPI_IN_PROCESS(Buffer)\nTEST_PPAPI_OUT_OF_PROCESS(Buffer)\n\nTEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader)\n\n\/\/ http:\/\/crbug.com\/89961\n#if defined(OS_WIN)\n\/\/ It often takes too long time (and fails otherwise) on Windows.\n#define MAYBE_URLLoader DISABLED_URLLoader\n#else\n#define MAYBE_URLLoader FAILS_URLLoader\n#endif\n\nTEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\nTEST_PPAPI_IN_PROCESS(PaintAggregator)\nTEST_PPAPI_OUT_OF_PROCESS(PaintAggregator)\n\nTEST_PPAPI_IN_PROCESS(Scrollbar)\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_PPAPI_IN_PROCESS(URLUtil)\nTEST_PPAPI_OUT_OF_PROCESS(URLUtil)\n\nTEST_PPAPI_IN_PROCESS(CharSet)\nTEST_PPAPI_OUT_OF_PROCESS(CharSet)\n\nTEST_PPAPI_IN_PROCESS(Crypto)\nTEST_PPAPI_OUT_OF_PROCESS(Crypto)\n\nTEST_PPAPI_IN_PROCESS(Var)\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_Var) {\n RunTest(\"Var\");\n}\n\nTEST_PPAPI_IN_PROCESS(VarDeprecated)\n\/\/ Disabled because it times out: http:\/\/crbug.com\/89961\n\/\/TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated)\n\n\/\/ Windows defines 'PostMessage', so we have to undef it.\n#ifdef PostMessage\n#undef PostMessage\n#endif\nTEST_PPAPI_IN_PROCESS(PostMessage)\n#if !defined(OS_WIN)\n\/\/ Times out on Windows XP: http:\/\/crbug.com\/95557\nTEST_PPAPI_OUT_OF_PROCESS(PostMessage)\n#endif\n\nTEST_PPAPI_IN_PROCESS(Memory)\nTEST_PPAPI_OUT_OF_PROCESS(Memory)\n\nTEST_PPAPI_IN_PROCESS(VideoDecoder)\nTEST_PPAPI_OUT_OF_PROCESS(VideoDecoder)\n\n\/\/ http:\/\/crbug.com\/90039 and http:\/\/crbug.com\/83443 (Mac)\nTEST_F(PPAPITest, FAILS_FileIO) {\n RunTestViaHTTP(\"FileIO\");\n}\n\/\/ http:\/\/crbug.com\/101154\nTEST_F(OutOfProcessPPAPITest, DISABLED_FileIO) {\n RunTestViaHTTP(\"FileIO\");\n}\n\nTEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef)\n\/\/ Disabled because it times out: http:\/\/crbug.com\/89961\n\/\/TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef)\n\nTEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem)\nTEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem)\n\n\/\/ http:\/\/crbug.com\/96767\n#if !defined(OS_MACOSX)\nTEST_F(PPAPITest, FLAKY_FlashFullscreen) {\n RunTestViaHTTP(\"FlashFullscreen\");\n}\nTEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) {\n RunTestViaHTTP(\"FlashFullscreen\");\n}\n\/\/ New implementation only honors fullscreen requests within a context of\n\/\/ a user gesture. Since we do not yet have an infrastructure for testing\n\/\/ those under ppapi_tests, the tests below time out when run automtically.\n\/\/ To test the code, run them manually following the directions here:\n\/\/ www.chromium.org\/developers\/design-documents\/pepper-plugin-implementation\n\/\/ and click on the plugin area (gray square) to force fullscreen mode and\n\/\/ get the test unstuck.\nTEST_F(PPAPITest, DISABLED_Fullscreen) {\n RunTestViaHTTP(\"Fullscreen\");\n}\nTEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) {\n RunTestViaHTTP(\"Fullscreen\");\n}\n#endif\n\nTEST_PPAPI_IN_PROCESS(FlashClipboard)\nTEST_PPAPI_OUT_OF_PROCESS(FlashClipboard)\n\n#if defined(OS_POSIX)\n#define MAYBE_DirectoryReader FLAKY_DirectoryReader\n#else\n#define MAYBE_DirectoryReader DirectoryReader\n#endif\n\n\/\/ Flaky on Mac + Linux, maybe http:\/\/codereview.chromium.org\/7094008\nTEST_F(PPAPITest, MAYBE_DirectoryReader) {\n RunTestViaHTTP(\"DirectoryReader\");\n}\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) {\n RunTestViaHTTP(\"DirectoryReader\");\n}\n\n#if defined(ENABLE_P2P_APIS)\n\/\/ Flaky. http:\/\/crbug.com\/84294\nTEST_F(PPAPITest, FLAKY_Transport) {\n RunTest(\"Transport\");\n}\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_Transport) {\n RunTestViaHTTP(\"Transport\");\n}\n#endif \/\/ ENABLE_P2P_APIS\n\nTEST_PPAPI_IN_PROCESS(UMA)\n\/\/ There is no proxy.\nTEST_F(OutOfProcessPPAPITest, FAILS_UMA) {\n RunTest(\"UMA\");\n}\n\nTEST_PPAPI_IN_PROCESS(FAILS_NetAddressPrivate)\nTEST_PPAPI_OUT_OF_PROCESS(FAILS_NetAddressPrivate)\nReenable PPB_NetAddress_Private test.\/\/ 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 \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"build\/build_config.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\n\/\/ In-process plugin test runner. See OutOfProcessPPAPITest below for the\n\/\/ out-of-process version.\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = \/.\n \/\/ MIME type = application\/x-ppapi-\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n\n \/\/ Smooth scrolling confuses the scrollbar test.\n launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n std::string query(\"testcase=\");\n query += test_case;\n replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(\n test_server.GetURL(\"files\/test_case.html?testcase=\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n\n \/\/ See comment above TestingInstance in ppapi\/test\/testing_instance.h.\n \/\/ Basically it sets a series of numbered cookies. The value of \"...\" means\n \/\/ it's still working and we should continue to wait, any other value\n \/\/ indicates completion (in this case it will start with \"PASS\" or \"FAIL\").\n \/\/ This keeps us from timing out on cookie waits for long tests.\n int progress_number = 0;\n std::string progress;\n while (true) {\n std::string cookie_name = StringPrintf(\"PPAPI_PROGRESS_%d\",\n progress_number);\n progress = WaitUntilCookieNonEmpty(tab.get(), test_url,\n cookie_name.c_str(), TestTimeouts::large_test_timeout_ms());\n if (progress != \"...\")\n break;\n progress_number++;\n }\n\n if (progress_number == 0) {\n \/\/ Failing the first time probably means the plugin wasn't loaded.\n ASSERT_FALSE(progress.empty())\n << \"Plugin couldn't be loaded. Make sure the PPAPI test plugin is \"\n << \"built, in the right place, and doesn't have any missing symbols.\";\n } else {\n ASSERT_FALSE(progress.empty()) << \"Test timed out.\";\n }\n\n EXPECT_STREQ(\"PASS\", progress.c_str());\n }\n};\n\n\/\/ Variant of PPAPITest that runs plugins out-of-process to test proxy\n\/\/ codepaths.\nclass OutOfProcessPPAPITest : public PPAPITest {\n public:\n OutOfProcessPPAPITest() {\n \/\/ Run PPAPI out-of-process to exercise proxy implementations.\n launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess);\n }\n};\n\n\/\/ Use these macros to run the tests for a specific interface.\n\/\/ Most interfaces should be tested with both macros.\n#define TEST_PPAPI_IN_PROCESS(test_name) \\\n TEST_F(PPAPITest, test_name) { \\\n RunTest(#test_name); \\\n }\n#define TEST_PPAPI_OUT_OF_PROCESS(test_name) \\\n TEST_F(OutOfProcessPPAPITest, test_name) { \\\n RunTest(#test_name); \\\n }\n\n\/\/ Similar macros that test over HTTP.\n#define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \\\n TEST_F(PPAPITest, test_name) { \\\n RunTestViaHTTP(#test_name); \\\n }\n#define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \\\n TEST_F(OutOfProcessPPAPITest, test_name) { \\\n RunTestViaHTTP(#test_name); \\\n }\n\n\n\/\/\n\/\/ Interface tests.\n\/\/\n\nTEST_PPAPI_IN_PROCESS(Broker)\nTEST_PPAPI_OUT_OF_PROCESS(Broker)\n\nTEST_PPAPI_IN_PROCESS(Core)\nTEST_PPAPI_OUT_OF_PROCESS(Core)\n\nTEST_PPAPI_IN_PROCESS(CursorControl)\nTEST_PPAPI_OUT_OF_PROCESS(CursorControl)\n\nTEST_PPAPI_IN_PROCESS(Instance)\n\/\/ http:\/\/crbug.com\/91729\nTEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance)\n\nTEST_PPAPI_IN_PROCESS(Graphics2D)\nTEST_PPAPI_OUT_OF_PROCESS(Graphics2D)\n\nTEST_PPAPI_IN_PROCESS(ImageData)\nTEST_PPAPI_OUT_OF_PROCESS(ImageData)\n\nTEST_PPAPI_IN_PROCESS(Buffer)\nTEST_PPAPI_OUT_OF_PROCESS(Buffer)\n\nTEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader)\n\n\/\/ http:\/\/crbug.com\/89961\n#if defined(OS_WIN)\n\/\/ It often takes too long time (and fails otherwise) on Windows.\n#define MAYBE_URLLoader DISABLED_URLLoader\n#else\n#define MAYBE_URLLoader FAILS_URLLoader\n#endif\n\nTEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\nTEST_PPAPI_IN_PROCESS(PaintAggregator)\nTEST_PPAPI_OUT_OF_PROCESS(PaintAggregator)\n\nTEST_PPAPI_IN_PROCESS(Scrollbar)\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_PPAPI_IN_PROCESS(URLUtil)\nTEST_PPAPI_OUT_OF_PROCESS(URLUtil)\n\nTEST_PPAPI_IN_PROCESS(CharSet)\nTEST_PPAPI_OUT_OF_PROCESS(CharSet)\n\nTEST_PPAPI_IN_PROCESS(Crypto)\nTEST_PPAPI_OUT_OF_PROCESS(Crypto)\n\nTEST_PPAPI_IN_PROCESS(Var)\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_Var) {\n RunTest(\"Var\");\n}\n\nTEST_PPAPI_IN_PROCESS(VarDeprecated)\n\/\/ Disabled because it times out: http:\/\/crbug.com\/89961\n\/\/TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated)\n\n\/\/ Windows defines 'PostMessage', so we have to undef it.\n#ifdef PostMessage\n#undef PostMessage\n#endif\nTEST_PPAPI_IN_PROCESS(PostMessage)\n#if !defined(OS_WIN)\n\/\/ Times out on Windows XP: http:\/\/crbug.com\/95557\nTEST_PPAPI_OUT_OF_PROCESS(PostMessage)\n#endif\n\nTEST_PPAPI_IN_PROCESS(Memory)\nTEST_PPAPI_OUT_OF_PROCESS(Memory)\n\nTEST_PPAPI_IN_PROCESS(VideoDecoder)\nTEST_PPAPI_OUT_OF_PROCESS(VideoDecoder)\n\n\/\/ http:\/\/crbug.com\/90039 and http:\/\/crbug.com\/83443 (Mac)\nTEST_F(PPAPITest, FAILS_FileIO) {\n RunTestViaHTTP(\"FileIO\");\n}\n\/\/ http:\/\/crbug.com\/101154\nTEST_F(OutOfProcessPPAPITest, DISABLED_FileIO) {\n RunTestViaHTTP(\"FileIO\");\n}\n\nTEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef)\n\/\/ Disabled because it times out: http:\/\/crbug.com\/89961\n\/\/TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef)\n\nTEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem)\nTEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem)\n\n\/\/ http:\/\/crbug.com\/96767\n#if !defined(OS_MACOSX)\nTEST_F(PPAPITest, FLAKY_FlashFullscreen) {\n RunTestViaHTTP(\"FlashFullscreen\");\n}\nTEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) {\n RunTestViaHTTP(\"FlashFullscreen\");\n}\n\/\/ New implementation only honors fullscreen requests within a context of\n\/\/ a user gesture. Since we do not yet have an infrastructure for testing\n\/\/ those under ppapi_tests, the tests below time out when run automtically.\n\/\/ To test the code, run them manually following the directions here:\n\/\/ www.chromium.org\/developers\/design-documents\/pepper-plugin-implementation\n\/\/ and click on the plugin area (gray square) to force fullscreen mode and\n\/\/ get the test unstuck.\nTEST_F(PPAPITest, DISABLED_Fullscreen) {\n RunTestViaHTTP(\"Fullscreen\");\n}\nTEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) {\n RunTestViaHTTP(\"Fullscreen\");\n}\n#endif\n\nTEST_PPAPI_IN_PROCESS(FlashClipboard)\nTEST_PPAPI_OUT_OF_PROCESS(FlashClipboard)\n\n#if defined(OS_POSIX)\n#define MAYBE_DirectoryReader FLAKY_DirectoryReader\n#else\n#define MAYBE_DirectoryReader DirectoryReader\n#endif\n\n\/\/ Flaky on Mac + Linux, maybe http:\/\/codereview.chromium.org\/7094008\nTEST_F(PPAPITest, MAYBE_DirectoryReader) {\n RunTestViaHTTP(\"DirectoryReader\");\n}\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) {\n RunTestViaHTTP(\"DirectoryReader\");\n}\n\n#if defined(ENABLE_P2P_APIS)\n\/\/ Flaky. http:\/\/crbug.com\/84294\nTEST_F(PPAPITest, FLAKY_Transport) {\n RunTest(\"Transport\");\n}\n\/\/ http:\/\/crbug.com\/89961\nTEST_F(OutOfProcessPPAPITest, FAILS_Transport) {\n RunTestViaHTTP(\"Transport\");\n}\n#endif \/\/ ENABLE_P2P_APIS\n\nTEST_PPAPI_IN_PROCESS(UMA)\n\/\/ There is no proxy.\nTEST_F(OutOfProcessPPAPITest, FAILS_UMA) {\n RunTest(\"UMA\");\n}\n\nTEST_PPAPI_IN_PROCESS(NetAddressPrivate)\nTEST_PPAPI_OUT_OF_PROCESS(NetAddressPrivate)\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (C) 2013-2014 mogemimi.\n\/\/\n\/\/ Distributed under the MIT License.\n\/\/ See accompanying file LICENSE.md or copy at\n\/\/ http:\/\/enginetrouble.net\/pomdog\/LICENSE.md for details.\n\/\/\n\n#include \"DebugNavigator.hpp\"\n#include \"DrawingContext.hpp\"\n\nnamespace Pomdog {\nnamespace UI {\n\/\/-----------------------------------------------------------------------\nDebugNavigator::DebugNavigator(std::shared_ptr const& clockIn)\n\t: Control(Matrix3x2::Identity, 150, 40)\n\t, clock(clockIn)\n\t, duration(DurationSeconds(0))\n\t, frameRateString(\"-- fps\")\n{}\n\/\/-----------------------------------------------------------------------\nvoid DebugNavigator::Draw(DrawingContext & drawingContext)\n{\n\tconstexpr float minFramerate = 15.0f;\n\tconstexpr float maxFramerate = 61.0f;\n\tconstexpr std::uint16_t maxHistories = 20;\n\t\n\t{\n\t\tif (clock->TotalGameTime() - duration > DurationSeconds(0.2))\n\t\t{\n\t\t\tauto frameRate = clock->FrameRate();\n\t\t\tframeRateString = StringFormat(\"%4.2f fps\", frameRate);\n\t\t\tframeRates.push_back(MathHelper::Clamp(frameRate, minFramerate, maxFramerate));\n\t\t\t\n\t\t\tif (frameRates.size() > maxHistories)\n\t\t\t{\n\t\t\t\tframeRates.pop_front();\n\t\t\t}\n\t\t\tduration = clock->TotalGameTime();\n\t\t}\n\t}\n\t\n\tauto transform = Transform() * drawingContext.Top();\n\t{\n\t\tauto graphTransform = Matrix3x2::CreateTranslation(Vector2{0, 16}) * transform;\n\t\n\t\tconstexpr float maxGraphHeight = 26.0f;\n\t\tconstexpr float graphMarginLeft = 1.0f;\n\n\t\tauto graghWidth = (static_cast(Width()) \/ maxHistories);\n\n\t\tstd::int32_t graphX = 0;\n\t\tfor (auto & frameRate: frameRates)\n\t\t{\n\t\t\tauto amount = ((frameRate - minFramerate) \/ (maxFramerate - minFramerate));\n\t\t\tauto graphHeight = std::max(1.0f, maxGraphHeight * amount);\n\n\t\t\tdrawingContext.DrawRectangle(graphTransform, Color::CornflowerBlue,\n\t\t\t\tRectangle(graphX, maxGraphHeight - graphHeight, graghWidth - graphMarginLeft, graphHeight));\n\t\t\tgraphX += graghWidth;\n\t\t}\n\t}\n\n\tdrawingContext.DrawString(transform * Matrix3x2::CreateTranslation(Vector2(5, -2.5f)),\n\t\tColor::White, FontWeight::Bold, FontSize::Medium, frameRateString);\n}\n\/\/-----------------------------------------------------------------------\n}\/\/ namespace UI\n}\/\/ namespace Pomdog\nFix debug navigator\/\/\n\/\/ Copyright (C) 2013-2014 mogemimi.\n\/\/\n\/\/ Distributed under the MIT License.\n\/\/ See accompanying file LICENSE.md or copy at\n\/\/ http:\/\/enginetrouble.net\/pomdog\/LICENSE.md for details.\n\/\/\n\n#include \"DebugNavigator.hpp\"\n#include \"DrawingContext.hpp\"\n\nnamespace Pomdog {\nnamespace UI {\n\/\/-----------------------------------------------------------------------\nDebugNavigator::DebugNavigator(std::shared_ptr const& clockIn)\n\t: Control(Matrix3x2::Identity, 150, 40)\n\t, clock(clockIn)\n\t, duration(DurationSeconds(0))\n\t, frameRateString(\"-- fps\")\n{}\n\/\/-----------------------------------------------------------------------\nvoid DebugNavigator::Draw(DrawingContext & drawingContext)\n{\n\tconstexpr float minFramerate = 10.0f;\n\tconstexpr float maxFramerate = 60.0f;\n\tconstexpr std::uint16_t maxHistories = 20;\n\t\n\t{\n\t\tif (clock->TotalGameTime() - duration > DurationSeconds(0.2))\n\t\t{\n\t\t\tauto frameRate = clock->FrameRate();\n\t\t\tframeRateString = StringFormat(\"%4.2f fps\", frameRate);\n\t\t\tframeRates.push_back(MathHelper::Clamp(frameRate, minFramerate, maxFramerate));\n\t\t\t\n\t\t\tif (frameRates.size() > maxHistories)\n\t\t\t{\n\t\t\t\tframeRates.pop_front();\n\t\t\t}\n\t\t\tduration = clock->TotalGameTime();\n\t\t}\n\t}\n\t\n\tauto transform = Transform() * drawingContext.Top();\n\t{\n\t\tauto graphTransform = Matrix3x2::CreateTranslation(Vector2{0, 16}) * transform;\n\t\n\t\tconstexpr std::uint16_t maxGraphHeight = 26;\n\t\tconstexpr float graphMarginLeft = 1.0f;\n\n\t\tauto graghWidth = (static_cast(Width()) \/ maxHistories);\n\n\t\tstd::int32_t graphX = 0;\n\t\tfor (auto & frameRate: frameRates)\n\t\t{\n\t\t\tauto amount = ((frameRate - minFramerate) \/ (maxFramerate - minFramerate));\n\t\t\tauto graphHeight = MathHelper::Clamp(maxGraphHeight * amount, 1, maxGraphHeight);\n\n\t\t\tdrawingContext.DrawRectangle(graphTransform, Color::CornflowerBlue,\n\t\t\t\tRectangle(graphX, maxGraphHeight - graphHeight, graghWidth - graphMarginLeft, graphHeight));\n\t\t\tgraphX += graghWidth;\n\t\t}\n\t}\n\n\tdrawingContext.DrawString(transform * Matrix3x2::CreateTranslation(Vector2(5, -2.5f)),\n\t\tColor::White, FontWeight::Bold, FontSize::Medium, frameRateString);\n}\n\/\/-----------------------------------------------------------------------\n}\/\/ namespace UI\n}\/\/ namespace Pomdog\n<|endoftext|>"} {"text":"\/\/===-- lldb.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 \"lldb\/lldb-private.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n#if defined (__APPLE__)\n\/\/ Xcode writes this file out in a build step.\n\/\/ cmake builds get this through another mechanism.\n\/\/ Both produce LLDB_REVISION.\n#include \"lldb_revision.h\"\nextern \"C\" const unsigned char liblldb_coreVersionString[];\n#endif\n\n#if defined(LLDB_USE_OSS_VERSION_SCHEME)\n\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"swift\/Basic\/Version.h\"\n\n#endif\n\n\n#if !defined (__APPLE__) || defined(LLDB_USE_OSS_VERSION_SCHEME)\n\n#include \"clang\/Basic\/Version.h\"\n\nstatic const char *\nGetLLDBRevision()\n{\n#ifdef LLDB_REVISION\n static const char *s_revision = LLDB_REVISION;\n#else\n static const char *s_revision = nullptr;\n#endif\n\n if (s_revision != nullptr)\n return s_revision;\n else\n return \"\";\n}\n\n#endif\n\n#if !defined (__APPLE__)\n\nstatic const char *\nGetLLDBRepository()\n{\n#ifdef LLDB_REPOSITORY\n return LLDB_REPOSITORY;\n#else\n return NULL;\n#endif\n\n}\n\n#endif\n\n#if defined(LLDB_USE_OSS_VERSION_SCHEME)\n\n\/\/ TODO remove this function once swift revision is directly exposed.\nstd::string ExtractSwiftRevision(const std::string &fullVersion)\n{\n \/\/ Find spot right before Swift revision.\n const std::string search_prefix = \"Swift \";\n const size_t prefix_start_pos = fullVersion.rfind(search_prefix);\n if (prefix_start_pos == std::string::npos)\n return \"\";\n\n \/\/ Find spot where Swift revision ends.\n const size_t revision_end_pos = fullVersion.rfind(')');\n if (revision_end_pos == std::string::npos)\n return \"\";\n\n \/\/ Return the revision.\n return fullVersion.substr(prefix_start_pos + search_prefix.length(), revision_end_pos - prefix_start_pos - search_prefix.length());\n}\n\nstatic std::string\nGetBuildDate()\n{\n \/\/ The following code helps distinguish between a defined preprocessor\n \/\/ value that gets the default value assigned vs. one with an explicit value.\n#define LLDB_DO_MACRO_EXPAND(macro_value) macro_value ## 1\n#define LLDB_MACRO_EXPAND(macro_value) LLDB_DO_MACRO_EXPAND(macro_value)\n\n#if defined(LLDB_BUILD_DATE)\n return std::string(LLDB_BUILD_DATE);\n#else\n return std::string();\n#endif\n}\n\nstatic const char*\n_GetVersionOSS ()\n{\n static std::string g_version_string;\n if (g_version_string.empty())\n {\n std::string build_string;\n llvm::raw_string_ostream out(build_string);\n\n std::string build_flavor = \"local\";\n#if defined (LLDB_IS_BUILDBOT_BUILD)\n# if (LLDB_IS_BUILDBOT_BUILD != 0)\n build_flavor = \"buildbot\";\n# endif\n#endif\n out << \"lldb-\" << build_flavor;\n\n \/\/ We only run this code when the build date is both set and non-default.\n \/\/ Otherwise this code doesn't compile.\n const std::string build_date(GetBuildDate());\n if (!build_date.empty())\n out << \"-\" << build_date;\n\n out << \" (\";\n\n std::string lldb_revision = GetLLDBRevision();\n if (lldb_revision.length() > 0)\n {\n const size_t MAX_REVISION_LENGTH = 10;\n\n out << \"LLDB \";\n out << lldb_revision.substr(0, MAX_REVISION_LENGTH);\n\n const std::string llvm_revision = clang::getLLVMRevision();\n if (!llvm_revision.empty())\n out << \", LLVM \" << llvm_revision.substr(0, MAX_REVISION_LENGTH);\n\n const std::string clang_revision = clang::getClangRevision();\n if (!clang_revision.empty())\n out << \", Clang \" << clang_revision.substr(0, MAX_REVISION_LENGTH);\n\n \/\/ TODO replace this with a swift::version::GetSwiftRevision() call\n \/\/ once added.\n const std::string swift_revision = ExtractSwiftRevision(swift::version::getSwiftFullVersion());\n if (!swift_revision.empty())\n {\n auto const swift_version = swift::version::getSwiftNumericVersion();\n out << \", Swift-\" << swift_version.first << \".\" << swift_version.second << \" \" << swift_revision.substr(0, MAX_REVISION_LENGTH);\n }\n }\n out << \")\";\n\n g_version_string = out.str();\n }\n return g_version_string.c_str();\n}\n\n#endif\n\n#if defined(__APPLE__) && !defined(LLDB_USE_OSS_VERSION_SCHEME)\n\nstatic const char*\n_GetVersionAppleStandard ()\n{\n static char g_version_string[32];\n if (g_version_string[0] == '\\0')\n {\n const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, \"PROJECT:\");\n\n if (version_string)\n version_string += sizeof(\"PROJECT:\") - 1;\n else\n version_string = \"unknown\";\n\n const char *newline_loc = strchr(version_string, '\\n');\n\n size_t version_len = sizeof(g_version_string) - 1;\n\n if (newline_loc &&\n (newline_loc - version_string < static_cast(version_len)))\n version_len = newline_loc - version_string;\n\n ::snprintf(g_version_string, version_len + 1, \"%s\", version_string);\n }\n \n return g_version_string;\n}\n\n#endif\n\n\nconst char *\nlldb_private::GetVersion ()\n{\n#if defined (__APPLE__)\n# if defined(LLDB_USE_OSS_VERSION_SCHEME)\n return _GetVersionOSS ();\n# else\n return _GetVersionAppleStandard ();\n# endif\n#else\n# if defined(LLDB_USE_OSS_VERSION_SCHEME)\n return _GetVersionOSS ();\n# else\n \/\/ On platforms other than Darwin, report a version number in the same style as the clang tool.\n static std::string g_version_str;\n if (g_version_str.empty())\n {\n g_version_str += \"lldb version \";\n g_version_str += CLANG_VERSION_STRING;\n const char * lldb_repo = GetLLDBRepository();\n if (lldb_repo)\n {\n g_version_str += \" (\";\n g_version_str += lldb_repo;\n }\n\n const char *lldb_rev = GetLLDBRevision();\n if (lldb_rev)\n {\n g_version_str += \" revision \";\n g_version_str += lldb_rev;\n }\n std::string clang_rev (clang::getClangRevision());\n if (clang_rev.length() > 0)\n {\n g_version_str += \" clang revision \";\n g_version_str += clang_rev;\n }\n std::string llvm_rev (clang::getLLVMRevision());\n if (llvm_rev.length() > 0)\n {\n g_version_str += \" llvm revision \";\n g_version_str += llvm_rev;\n }\n\n if (lldb_repo)\n g_version_str += \")\";\n }\n return g_version_str.c_str();\n# endif\n#endif\n}\nadded a comment to clarify a check in previous version fixup code\/\/===-- lldb.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 \"lldb\/lldb-private.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n#if defined (__APPLE__)\n\/\/ Xcode writes this file out in a build step.\n\/\/ cmake builds get this through another mechanism.\n\/\/ Both produce LLDB_REVISION.\n#include \"lldb_revision.h\"\nextern \"C\" const unsigned char liblldb_coreVersionString[];\n#endif\n\n#if defined(LLDB_USE_OSS_VERSION_SCHEME)\n\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"swift\/Basic\/Version.h\"\n\n#endif\n\n\n#if !defined (__APPLE__) || defined(LLDB_USE_OSS_VERSION_SCHEME)\n\n#include \"clang\/Basic\/Version.h\"\n\nstatic const char *\nGetLLDBRevision()\n{\n#ifdef LLDB_REVISION\n static const char *s_revision = LLDB_REVISION;\n#else\n static const char *s_revision = nullptr;\n#endif\n\n \/\/ If LLDB_REVISION is defined but isn't set to a string, it\n \/\/ can still be the equivalent of NULL. Hence we always do\n \/\/ this check below and return an empty string when we don't\n \/\/ otherwise have a valid const string for it.\n if (s_revision != nullptr)\n return s_revision;\n else\n return \"\";\n}\n\n#endif\n\n#if !defined (__APPLE__)\n\nstatic const char *\nGetLLDBRepository()\n{\n#ifdef LLDB_REPOSITORY\n return LLDB_REPOSITORY;\n#else\n return NULL;\n#endif\n\n}\n\n#endif\n\n#if defined(LLDB_USE_OSS_VERSION_SCHEME)\n\n\/\/ TODO remove this function once swift revision is directly exposed.\nstd::string ExtractSwiftRevision(const std::string &fullVersion)\n{\n \/\/ Find spot right before Swift revision.\n const std::string search_prefix = \"Swift \";\n const size_t prefix_start_pos = fullVersion.rfind(search_prefix);\n if (prefix_start_pos == std::string::npos)\n return \"\";\n\n \/\/ Find spot where Swift revision ends.\n const size_t revision_end_pos = fullVersion.rfind(')');\n if (revision_end_pos == std::string::npos)\n return \"\";\n\n \/\/ Return the revision.\n return fullVersion.substr(prefix_start_pos + search_prefix.length(), revision_end_pos - prefix_start_pos - search_prefix.length());\n}\n\nstatic std::string\nGetBuildDate()\n{\n \/\/ The following code helps distinguish between a defined preprocessor\n \/\/ value that gets the default value assigned vs. one with an explicit value.\n#define LLDB_DO_MACRO_EXPAND(macro_value) macro_value ## 1\n#define LLDB_MACRO_EXPAND(macro_value) LLDB_DO_MACRO_EXPAND(macro_value)\n\n#if defined(LLDB_BUILD_DATE)\n return std::string(LLDB_BUILD_DATE);\n#else\n return std::string();\n#endif\n}\n\nstatic const char*\n_GetVersionOSS ()\n{\n static std::string g_version_string;\n if (g_version_string.empty())\n {\n std::string build_string;\n llvm::raw_string_ostream out(build_string);\n\n std::string build_flavor = \"local\";\n#if defined (LLDB_IS_BUILDBOT_BUILD)\n# if (LLDB_IS_BUILDBOT_BUILD != 0)\n build_flavor = \"buildbot\";\n# endif\n#endif\n out << \"lldb-\" << build_flavor;\n\n \/\/ We only run this code when the build date is both set and non-default.\n \/\/ Otherwise this code doesn't compile.\n const std::string build_date(GetBuildDate());\n if (!build_date.empty())\n out << \"-\" << build_date;\n\n out << \" (\";\n\n std::string lldb_revision = GetLLDBRevision();\n if (lldb_revision.length() > 0)\n {\n const size_t MAX_REVISION_LENGTH = 10;\n\n out << \"LLDB \";\n out << lldb_revision.substr(0, MAX_REVISION_LENGTH);\n\n const std::string llvm_revision = clang::getLLVMRevision();\n if (!llvm_revision.empty())\n out << \", LLVM \" << llvm_revision.substr(0, MAX_REVISION_LENGTH);\n\n const std::string clang_revision = clang::getClangRevision();\n if (!clang_revision.empty())\n out << \", Clang \" << clang_revision.substr(0, MAX_REVISION_LENGTH);\n\n \/\/ TODO replace this with a swift::version::GetSwiftRevision() call\n \/\/ once added.\n const std::string swift_revision = ExtractSwiftRevision(swift::version::getSwiftFullVersion());\n if (!swift_revision.empty())\n {\n auto const swift_version = swift::version::getSwiftNumericVersion();\n out << \", Swift-\" << swift_version.first << \".\" << swift_version.second << \" \" << swift_revision.substr(0, MAX_REVISION_LENGTH);\n }\n }\n out << \")\";\n\n g_version_string = out.str();\n }\n return g_version_string.c_str();\n}\n\n#endif\n\n#if defined(__APPLE__) && !defined(LLDB_USE_OSS_VERSION_SCHEME)\n\nstatic const char*\n_GetVersionAppleStandard ()\n{\n static char g_version_string[32];\n if (g_version_string[0] == '\\0')\n {\n const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, \"PROJECT:\");\n\n if (version_string)\n version_string += sizeof(\"PROJECT:\") - 1;\n else\n version_string = \"unknown\";\n\n const char *newline_loc = strchr(version_string, '\\n');\n\n size_t version_len = sizeof(g_version_string) - 1;\n\n if (newline_loc &&\n (newline_loc - version_string < static_cast(version_len)))\n version_len = newline_loc - version_string;\n\n ::snprintf(g_version_string, version_len + 1, \"%s\", version_string);\n }\n \n return g_version_string;\n}\n\n#endif\n\n\nconst char *\nlldb_private::GetVersion ()\n{\n#if defined (__APPLE__)\n# if defined(LLDB_USE_OSS_VERSION_SCHEME)\n return _GetVersionOSS ();\n# else\n return _GetVersionAppleStandard ();\n# endif\n#else\n# if defined(LLDB_USE_OSS_VERSION_SCHEME)\n return _GetVersionOSS ();\n# else\n \/\/ On platforms other than Darwin, report a version number in the same style as the clang tool.\n static std::string g_version_str;\n if (g_version_str.empty())\n {\n g_version_str += \"lldb version \";\n g_version_str += CLANG_VERSION_STRING;\n const char * lldb_repo = GetLLDBRepository();\n if (lldb_repo)\n {\n g_version_str += \" (\";\n g_version_str += lldb_repo;\n }\n\n const char *lldb_rev = GetLLDBRevision();\n if (lldb_rev)\n {\n g_version_str += \" revision \";\n g_version_str += lldb_rev;\n }\n std::string clang_rev (clang::getClangRevision());\n if (clang_rev.length() > 0)\n {\n g_version_str += \" clang revision \";\n g_version_str += clang_rev;\n }\n std::string llvm_rev (clang::getLLVMRevision());\n if (llvm_rev.length() > 0)\n {\n g_version_str += \" llvm revision \";\n g_version_str += llvm_rev;\n }\n\n if (lldb_repo)\n g_version_str += \")\";\n }\n return g_version_str.c_str();\n# endif\n#endif\n}\n<|endoftext|>"} {"text":"\/*\n * (C) Copyright 2015 ETH Zurich Systems Group (http:\/\/www.systems.ethz.ch\/) and others.\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 * Contributors:\n * Markus Pilman \n * Simon Loesing \n * Thomas Etter \n * Kevin Bocksrocker \n * Lucas Braun \n *\/\n#include \"Client.hpp\"\n#include \n#include \"sqlite3.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace mbench {\n\nstd::string cmdString(Commands cmd) {\n switch (cmd) {\n case mbench::Commands::CreateSchema:\n return \"CreateSchema\";\n case mbench::Commands::Populate:\n return \"Populate\";\n case mbench::Commands::BatchOp:\n return \"BatchOp\";\n case mbench::Commands::Q1:\n return \"Q1\";\n case mbench::Commands::Q2:\n return \"Q2\";\n case mbench::Commands::Q3:\n return \"Q3\";\n throw std::runtime_error(\"Invalid command\");\n }\n throw std::runtime_error(\"This has to be dead code\");\n}\n\n} \/\/ namespace mbench\n\n#define sqlOk(code) assertSql(code, __FILE__, __LINE__)\n\nvoid assertSql(int code, const char* file, int line) {\n if (code != SQLITE_OK) {\n auto msg = (boost::format(\"ERROR (%1%:%2%): %3%\") % file % line % sqlite3_errstr(code)).str();\n throw std::runtime_error(msg.c_str());\n }\n}\n\nint main(int argc, const char* argv[]) {\n namespace po = boost::program_options;\n unsigned numThreads = 1;\n unsigned sf;\n unsigned oltpClients;\n bool populate = false;\n unsigned time = 5;\n unsigned numAnalytical;\n unsigned numOps;\n double insProb, delProb, updProb;\n bool noWarmup;\n bool onlyQ1;\n std::string hostStr;\n std::string dbFile(\"out.db\");\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Show help message\")\n (\"hosts,H\", po::value(&hostStr)->required(), \"Adress to servers\")\n (\"scaling-factor,s\", po::value(&sf)->required(), \"Scaling factor\")\n (\"clients,c\", po::value(&oltpClients)->default_value(29), \"Number of get\/put clients (in total)\")\n (\"analytical,a\", po::value(&numAnalytical)->default_value(0), \"Number of analytical clients (in total)\")\n (\"threads,t\", po::value(&numThreads), \"Number of network threads\")\n (\"populate,P\", \"Run population instead of benchmark\")\n (\"db,o\", po::value(&dbFile), \"Output to write to\")\n (\"time\", po::value(&time), \"Number of minutes to run\")\n (\"batch-size,b\", po::value(&numOps)->default_value(100), \"Number of operations per batch\")\n (\"inserts,i\", po::value(&insProb)->default_value(0.166), \"Fraction of insert operations\")\n (\"deletes,d\", po::value(&delProb)->default_value(0.166), \"Fraction of delete operations\")\n (\"update,u\", po::value(&updProb)->default_value(0.166), \"Fraction of update operations\")\n (\"no-warmup\", po::bool_switch(&noWarmup)->default_value(false), \"No warm up time\")\n (\"only-q1,q\", po::bool_switch(&onlyQ1)->default_value(false), \"Execute only q1\")\n ;\n\n po::variables_map vm;\n store(parse_command_line(argc, argv, desc), vm);\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n\n if (vm.count(\"populate\")) {\n populate = true;\n }\n notify(vm);\n if (insProb + updProb + delProb > 1.0) {\n std::cerr << \"sum(insert,delete,update) > 1.0\\n\";\n return 1;\n }\n\n if (oltpClients == 0 && populate) {\n std::cerr << \"can not populate without oltp clients\\n\";\n return 1;\n }\n\n if (!noWarmup)\n time += 2;\n\n std::vector hosts;\n boost::split(hosts, hostStr, boost::is_any_of(\";,\"), boost::token_compress_on);\n\n boost::asio::io_service service;\n boost::asio::io_service::strand ioStrand(service);\n std::vector> clients;\n clients.reserve(oltpClients + numAnalytical);\n boost::asio::ip::tcp::resolver resolver(service);\n std::vector hostPort;\n hostPort.reserve(2);\n\n bool allAnalytical = oltpClients == 0;\n auto hostIter = hosts.begin();\n if (populate) numAnalytical = 0;\n for (unsigned i = 0; i < numAnalytical; ++i) {\n if (hostIter == hosts.end()) hostIter = hosts.begin();\n clients.emplace_back(new mbench::Client(service, ioStrand, sf,\n oltpClients, 0, true, numOps, insProb, delProb,\n updProb, onlyQ1));\n auto& client = *clients.back();\n boost::split(hostPort, *hostIter, boost::is_any_of(\":\"), boost::token_compress_on);\n if (hostPort.size() == 1) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));\n } else if (hostPort.size() == 2) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));\n } else {\n std::cerr << \"Format error while parsing hosts\" << std::endl;\n return 1;\n }\n ++hostIter;\n }\n for (unsigned clientId = 0; clientId < oltpClients; ++clientId) {\n if (hostIter == hosts.end()) hostIter = hosts.begin();\n clients.emplace_back(new mbench::Client(service, ioStrand, sf,\n oltpClients, clientId, false, numOps, insProb,\n delProb, updProb, onlyQ1));\n auto& client = *clients.back();\n boost::split(hostPort, *hostIter, boost::is_any_of(\":\"), boost::token_compress_on);\n if (hostPort.size() == 1) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));\n } else if (hostPort.size() == 2) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));\n } else {\n std::cerr << \"Format error while parsing hosts\" << std::endl;\n return 1;\n }\n ++hostIter;\n }\n auto duration = std::chrono::minutes(time);\n bool timerChosen = true;\n if (populate) {\n std::cout << \"start population\\n\";\n clients[0]->populate(clients);\n } else {\n for (auto& client : clients) {\n if (timerChosen && allAnalytical) {\n client->run(duration, true);\n timerChosen = false;\n }\n else if (timerChosen && !client->isAnalytical()) {\n client->run(duration, true);\n timerChosen = false;\n } else {\n client->run(duration, false);\n }\n }\n }\n\n\n std::cout << \"Will run for \" << time << \" minutes with \" << clients.size() << \" clients\\n\";\n auto startTime = mbench::Clock::now();\n std::vector threads;\n threads.reserve(numThreads - 1);\n for (unsigned i = 0; i < numThreads - 1; ++i) {\n threads.emplace_back([&service](){ service.run(); });\n }\n service.run();\n for (auto& t : threads) {\n t.join();\n }\n if (populate) {\n std::cout << \" \\r\";\n std::cout << \"Done\\n\";\n }\n std::cout << \"Done - writing results\\n\";\n sqlOk(sqlite3_config(SQLITE_CONFIG_SINGLETHREAD));\n sqlite3* db;\n sqlOk(sqlite3_open(dbFile.c_str(), &db));\n sqlOk(sqlite3_exec(db, \"CREATE TABLE results(start int, end int, rt int, tx text, success text, msg text)\",\n nullptr, nullptr, nullptr));\n\n \/\/ Insert data\n sqlOk(sqlite3_exec(db, \"BEGIN TRANSACTION\", nullptr, nullptr, nullptr));\n sqlite3_stmt* stmt;\n sqlOk(sqlite3_prepare_v2(db, \"INSERT INTO results VALUES(?, ?, ?, ?, ?, ?)\", -1, &stmt, nullptr));\n\n for (auto& client : clients) {\n const auto& log = client->log();\n for (const auto& e : log) {\n auto start = int(std::chrono::duration_cast(e.start - startTime).count());\n auto end = int(std::chrono::duration_cast(e.end - startTime).count());\n std::string trans = cmdString(e.transaction);\n std::string success = e.success ? \"true\" : \"false\";\n std::string msg(e.error.data(), e.error.size());\n sqlOk(sqlite3_bind_int(stmt, 1, start));\n sqlOk(sqlite3_bind_int(stmt, 2, end));\n sqlOk(sqlite3_bind_int(stmt, 3, e.responseTime));\n sqlOk(sqlite3_bind_text(stmt, 4, trans.data(), trans.size(), nullptr));\n sqlOk(sqlite3_bind_text(stmt, 5, success.data(), success.size(), nullptr));\n sqlOk(sqlite3_bind_text(stmt, 6, msg.data(), msg.size(), nullptr));\n int s;\n while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {\n if (s == SQLITE_ERROR) {\n throw std::runtime_error(sqlite3_errmsg(db));\n }\n }\n sqlite3_reset(stmt);\n }\n }\n sqlOk(sqlite3_exec(db, \"END TRANSACTION\", nullptr, nullptr, nullptr));\n sqlOk(sqlite3_finalize(stmt));\n\n std::cout << \"Inserted data, calculating results...\\n\";\n std::string cutWarmup = noWarmup ? \"\" : \"start >= 60000000 AND end <= 360000000 AND success LIKE 'true'\";\n std::string getPutTP = (boost::format(\n \"SELECT count(*)\/%1% \"\n \"FROM results \"\n \"WHERE tx LIKE 'BatchOp' \"\n \"AND %2%\"\n ) % double((time - 2)*60) % cutWarmup).str();\n std::string scanTP = (boost::format(\n \"SELECT count(*)\/%1% \"\n \"FROM results \"\n \"WHERE tx LIKE 'Q%%' \"\n \"AND %2%\"\n ) % double((time - 2)) % cutWarmup).str();\n std::string responseTime = (boost::format(\n \"SELECT tx, avg(rt) \"\n \"FROM results \"\n \"WHERE %1% \"\n \"GROUP BY tx;\"\n ) % cutWarmup).str();\n std::cout << \"================\\n\";\n std::cout << \"Get\/Put throughput:\\n\";\n std::cout << \"===================\\n\";\n std::cout << getPutTP << std::endl;\n std::cout << \"---------------------\\n\";\n sqlOk(sqlite3_prepare_v2(db, getPutTP.data(), getPutTP.size() + 1, &stmt, nullptr));\n int s;\n while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {\n if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db));\n double tp = sqlite3_column_double(stmt, 0);\n std::cout << tp << \" \/ second\\n\";\n }\n sqlOk(sqlite3_finalize(stmt));\n sqlOk(sqlite3_prepare_v2(db, scanTP.data(), scanTP.size() + 1, &stmt, nullptr));\n std::cout << \"================\\n\";\n std::cout << \"Scan throughput:\\n\";\n std::cout << \"================\\n\";\n std::cout << scanTP << std::endl;\n std::cout << \"---------------------\\n\";\n while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {\n if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db));\n double tp = sqlite3_column_double(stmt, 0);\n std::cout << tp << \" \/ minute\\n\";\n }\n std::cout << \"================\\n\";\n std::cout << \"Response Times:\\n\";\n std::cout << \"================\\n\";\n std::cout << responseTime << std::endl;\n sqlOk(sqlite3_finalize(stmt));\n sqlOk(sqlite3_prepare_v2(db, responseTime.data(), responseTime.size() + 1, &stmt, nullptr));\n while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {\n if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db));\n auto name = sqlite3_column_text(stmt, 0);\n double rt = sqlite3_column_double(stmt, 1);\n std::cout << name << \": \" << rt\/1000.0 << \" microseconds\" << std::endl;\n }\n std::cout << \"done\";\n sqlite3_close(db);\n return 0;\n}\nfixed writing to sqlite - don't print results.\/*\n * (C) Copyright 2015 ETH Zurich Systems Group (http:\/\/www.systems.ethz.ch\/) and others.\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 * Contributors:\n * Markus Pilman \n * Simon Loesing \n * Thomas Etter \n * Kevin Bocksrocker \n * Lucas Braun \n *\/\n#include \"Client.hpp\"\n#include \n#include \"sqlite3.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace mbench {\n\nstd::string cmdString(Commands cmd) {\n switch (cmd) {\n case mbench::Commands::CreateSchema:\n return \"CreateSchema\";\n case mbench::Commands::Populate:\n return \"Populate\";\n case mbench::Commands::BatchOp:\n return \"BatchOp\";\n case mbench::Commands::Q1:\n return \"Q1\";\n case mbench::Commands::Q2:\n return \"Q2\";\n case mbench::Commands::Q3:\n return \"Q3\";\n throw std::runtime_error(\"Invalid command\");\n }\n throw std::runtime_error(\"This has to be dead code\");\n}\n\n} \/\/ namespace mbench\n\n#define sqlOk(code) assertSql(code, __FILE__, __LINE__)\n\nvoid assertSql(int code, const char* file, int line) {\n if (code != SQLITE_OK) {\n auto msg = (boost::format(\"ERROR (%1%:%2%): %3%\") % file % line % sqlite3_errstr(code)).str();\n throw std::runtime_error(msg.c_str());\n }\n}\n\nint main(int argc, const char* argv[]) {\n namespace po = boost::program_options;\n unsigned numThreads = 1;\n unsigned sf;\n unsigned oltpClients;\n bool populate = false;\n unsigned time = 5;\n unsigned numAnalytical;\n unsigned numOps;\n double insProb, delProb, updProb;\n bool noWarmup;\n bool onlyQ1;\n std::string hostStr;\n std::string dbFile(\"out.db\");\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Show help message\")\n (\"hosts,H\", po::value(&hostStr)->required(), \"Adress to servers\")\n (\"scaling-factor,s\", po::value(&sf)->required(), \"Scaling factor\")\n (\"clients,c\", po::value(&oltpClients)->default_value(29), \"Number of get\/put clients (in total)\")\n (\"analytical,a\", po::value(&numAnalytical)->default_value(0), \"Number of analytical clients (in total)\")\n (\"threads,t\", po::value(&numThreads), \"Number of network threads\")\n (\"populate,P\", \"Run population instead of benchmark\")\n (\"db,o\", po::value(&dbFile), \"Output to write to\")\n (\"time\", po::value(&time), \"Number of minutes to run\")\n (\"batch-size,b\", po::value(&numOps)->default_value(100), \"Number of operations per batch\")\n (\"inserts,i\", po::value(&insProb)->default_value(0.166), \"Fraction of insert operations\")\n (\"deletes,d\", po::value(&delProb)->default_value(0.166), \"Fraction of delete operations\")\n (\"update,u\", po::value(&updProb)->default_value(0.166), \"Fraction of update operations\")\n (\"no-warmup\", po::bool_switch(&noWarmup)->default_value(false), \"No warm up time\")\n (\"only-q1,q\", po::bool_switch(&onlyQ1)->default_value(false), \"Execute only q1\")\n ;\n\n po::variables_map vm;\n store(parse_command_line(argc, argv, desc), vm);\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n\n if (vm.count(\"populate\")) {\n populate = true;\n }\n notify(vm);\n if (insProb + updProb + delProb > 1.0) {\n std::cerr << \"sum(insert,delete,update) > 1.0\\n\";\n return 1;\n }\n\n if (oltpClients == 0 && populate) {\n std::cerr << \"can not populate without oltp clients\\n\";\n return 1;\n }\n\n if (!noWarmup)\n time += 2;\n\n std::vector hosts;\n boost::split(hosts, hostStr, boost::is_any_of(\";,\"), boost::token_compress_on);\n\n boost::asio::io_service service;\n boost::asio::io_service::strand ioStrand(service);\n std::vector> clients;\n clients.reserve(oltpClients + numAnalytical);\n boost::asio::ip::tcp::resolver resolver(service);\n std::vector hostPort;\n hostPort.reserve(2);\n\n bool allAnalytical = oltpClients == 0;\n auto hostIter = hosts.begin();\n if (populate) numAnalytical = 0;\n for (unsigned i = 0; i < numAnalytical; ++i) {\n if (hostIter == hosts.end()) hostIter = hosts.begin();\n clients.emplace_back(new mbench::Client(service, ioStrand, sf,\n oltpClients, 0, true, numOps, insProb, delProb,\n updProb, onlyQ1));\n auto& client = *clients.back();\n boost::split(hostPort, *hostIter, boost::is_any_of(\":\"), boost::token_compress_on);\n if (hostPort.size() == 1) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));\n } else if (hostPort.size() == 2) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));\n } else {\n std::cerr << \"Format error while parsing hosts\" << std::endl;\n return 1;\n }\n ++hostIter;\n }\n for (unsigned clientId = 0; clientId < oltpClients; ++clientId) {\n if (hostIter == hosts.end()) hostIter = hosts.begin();\n clients.emplace_back(new mbench::Client(service, ioStrand, sf,\n oltpClients, clientId, false, numOps, insProb,\n delProb, updProb, onlyQ1));\n auto& client = *clients.back();\n boost::split(hostPort, *hostIter, boost::is_any_of(\":\"), boost::token_compress_on);\n if (hostPort.size() == 1) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));\n } else if (hostPort.size() == 2) {\n boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));\n } else {\n std::cerr << \"Format error while parsing hosts\" << std::endl;\n return 1;\n }\n ++hostIter;\n }\n auto duration = std::chrono::minutes(time);\n bool timerChosen = true;\n if (populate) {\n std::cout << \"start population\\n\";\n clients[0]->populate(clients);\n } else {\n for (auto& client : clients) {\n if (timerChosen && allAnalytical) {\n client->run(duration, true);\n timerChosen = false;\n }\n else if (timerChosen && !client->isAnalytical()) {\n client->run(duration, true);\n timerChosen = false;\n } else {\n client->run(duration, false);\n }\n }\n }\n\n\n std::cout << \"Will run for \" << time << \" minutes with \" << clients.size() << \" clients\\n\";\n auto startTime = mbench::Clock::now();\n std::vector threads;\n threads.reserve(numThreads - 1);\n for (unsigned i = 0; i < numThreads - 1; ++i) {\n threads.emplace_back([&service](){ service.run(); });\n }\n service.run();\n for (auto& t : threads) {\n t.join();\n }\n if (populate) {\n std::cout << \" \\r\";\n std::cout << \"Done\\n\";\n }\n std::cout << \"Done - writing results\\n\";\n sqlOk(sqlite3_config(SQLITE_CONFIG_SINGLETHREAD));\n sqlite3* db;\n sqlOk(sqlite3_open(dbFile.c_str(), &db));\n sqlOk(sqlite3_exec(db, \"CREATE TABLE results(start int, end int, rt int, tx text, success text, msg text)\",\n nullptr, nullptr, nullptr));\n sqlOk(sqlite3_exec(db, \"CREATE TABLE clientArgs(idx int, param text)\", nullptr, nullptr, nullptr));\n\n sqlOk(sqlite3_exec(db, \"BEGIN TRANSACTION\", nullptr, nullptr, nullptr));\n \/\/ Insert arguments\n sqlite3_stmt* stmt;\n sqlOk(sqlite3_prepare_v2(db, \"INSERT INTO clientArgs VALUES(?, ?)\", -1, &stmt, nullptr));\n for (int i = 0; i < argc; ++i) {\n sqlOk(sqlite3_bind_int(stmt, 1, i));\n sqlOk(sqlite3_bind_text(stmt, 2, argv[i], -1, nullptr));\n int s;\n while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {\n if (s == SQLITE_ERROR) {\n throw std::runtime_error(sqlite3_errmsg(db));\n }\n }\n sqlite3_reset(stmt);\n }\n sqlOk(sqlite3_finalize(stmt));\n sqlOk(sqlite3_exec(db, \"END TRANSACTION\", nullptr, nullptr, nullptr));\n \/\/ insert data\n sqlOk(sqlite3_exec(db, \"BEGIN TRANSACTION\", nullptr, nullptr, nullptr));\n sqlOk(sqlite3_prepare_v2(db, \"INSERT INTO results VALUES(?, ?, ?, ?, ?, ?)\", -1, &stmt, nullptr));\n\n for (auto& client : clients) {\n const auto& log = client->log();\n for (const auto& e : log) {\n auto start = int(std::chrono::duration_cast(e.start - startTime).count());\n auto end = int(std::chrono::duration_cast(e.end - startTime).count());\n std::string trans = cmdString(e.transaction);\n std::string success = e.success ? \"true\" : \"false\";\n std::string msg(e.error.data(), e.error.size());\n sqlOk(sqlite3_bind_int(stmt, 1, start));\n sqlOk(sqlite3_bind_int(stmt, 2, end));\n sqlOk(sqlite3_bind_int64(stmt, 3, e.responseTime));\n sqlOk(sqlite3_bind_text(stmt, 4, trans.data(), trans.size(), nullptr));\n sqlOk(sqlite3_bind_text(stmt, 5, success.data(), success.size(), nullptr));\n sqlOk(sqlite3_bind_text(stmt, 6, msg.data(), msg.size(), nullptr));\n int s;\n while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {\n if (s == SQLITE_ERROR) {\n throw std::runtime_error(sqlite3_errmsg(db));\n }\n }\n sqlite3_reset(stmt);\n }\n }\n sqlOk(sqlite3_finalize(stmt));\n sqlOk(sqlite3_exec(db, \"END TRANSACTION\", nullptr, nullptr, nullptr));\n\n std::cout << \"done\\n\";\n sqlite3_close(db);\n return 0;\n}\n<|endoftext|>"} {"text":"No need to rotate U\/V components returned by qengine<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgattr.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2007-04-26 07:59: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\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_dbaccess.hxx\"\n\n\n#ifdef MAC\n#ifdef ITEMID_NUMBERINFO\n#undef ITEMID_NUMBERINFO\n#endif\n#endif\n\n#define ITEMID_NUMBERINFO 0\n\n#ifndef DBAUI_SBATTRDLG_HXX\n#include \"dlgattr.hxx\"\n#endif\n\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SVX_NUMINF_HXX \/\/autogen\n#include \n#endif\n\n\/\/CHINA001 #ifndef _SVX_CHARDLG_HXX \/\/autogen\n\/\/CHINA001 #include \n\/\/CHINA001 #endif\n\n\/\/CHINA001 #ifndef _SVX_NUMFMT_HXX \/\/autogen\n\/\/CHINA001 #include \n\/\/CHINA001 #endif\n#ifndef _SVX_NUMINF_HXX\n#include \n#endif\n\n\/\/CHINA001 #ifndef _SVX_ALIGN_HXX \/\/autogen\n\/\/CHINA001 #include \n\/\/CHINA001 #endif\n\n#ifndef _SVX_DIALOGS_HRC\n#include \n#endif\n\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _DBU_DLG_HRC_\n#include \"dbu_dlg.hrc\"\n#endif\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n#define _ZFORLIST_DECLARE_TABLE\n#ifndef _ZFORLIST_HXX\n#include \n#endif\n#include \/\/CHINA001\n#include \/\/CHINA001\n#ifndef _SFXINTITEM_HXX \/\/CHINA001\n#include \/\/CHINA001\n#endif \/\/CHINA001\n\nusing namespace dbaui;\n\nDBG_NAME(SbaSbAttrDlg)\n\/\/==================================================================\nSbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow)\n : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs )\n ,aTitle(ModuleRes(ST_ROW))\n{\n DBG_CTOR(SbaSbAttrDlg,NULL);\n\n pNumberInfoItem = new SvxNumberInfoItem( pFormatter );\n\n if (bRow)\n SetText(aTitle);\n if( nFlags & TP_ATTR_CHAR )\n {\n\/\/ AddTabPage( RID_SVXPAGE_CHAR_STD,String(ModuleRes(TP_ATTR_CHAR)),SvxCharStdPage::Create, 0 );\n DBG_ERROR( \"found flag TP_ATTR_CHAR\" );\n }\n if( nFlags & TP_ATTR_NUMBER )\n AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)) ); \/\/CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 );\n if( nFlags & TP_ATTR_ALIGN )\n AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)) );\/\/CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 );\n FreeResource();\n}\n\n\/\/ -----------------------------------------------------------------------\nSbaSbAttrDlg::~SbaSbAttrDlg()\n{\n delete pNumberInfoItem;\n\n DBG_DTOR(SbaSbAttrDlg,NULL);\n}\n\n\/\/ -----------------------------------------------------------------------\nvoid SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage )\n{\n SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));\n switch ( nPageId )\n {\n case RID_SVXPAGE_NUMBERFORMAT:\n {\n \/\/CHINA001 ((SvxNumberFormatTabPage&)rTabPage).\n \/\/CHINA001 SetNumberFormatList( *pNumberInfoItem );\n aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO));\n rTabPage.PageCreated(aSet);\n }\n break;\n\n case RID_SVXPAGE_CHAR_STD:\n {\n \/\/ ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem());\n }\n break;\n\n case RID_SVXPAGE_ALIGNMENT:\n {\n \/\/CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT);\n\/\/ aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT));\n\/\/ rTabPage.PageCreated(aSet);\n }\n break;\n\n default:\n break;\n }\n}\n\n\nINTEGRATION: CWS pchfix04 (1.9.32); FILE MERGED 2007\/02\/05 08:45:41 os 1.9.32.1: #i73604# usage of ITEMID_* removed\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgattr.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 15:06:12 $\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_dbaccess.hxx\"\n\n\n#ifndef DBAUI_SBATTRDLG_HXX\n#include \"dlgattr.hxx\"\n#endif\n\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SVX_NUMINF_HXX \/\/autogen\n#include \n#endif\n\n\/\/CHINA001 #ifndef _SVX_CHARDLG_HXX \/\/autogen\n\/\/CHINA001 #include \n\/\/CHINA001 #endif\n\n\/\/CHINA001 #ifndef _SVX_NUMFMT_HXX \/\/autogen\n\/\/CHINA001 #include \n\/\/CHINA001 #endif\n#ifndef _SVX_NUMINF_HXX\n#include \n#endif\n\n\/\/CHINA001 #ifndef _SVX_ALIGN_HXX \/\/autogen\n\/\/CHINA001 #include \n\/\/CHINA001 #endif\n\n#ifndef _SVX_DIALOGS_HRC\n#include \n#endif\n\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _DBU_DLG_HRC_\n#include \"dbu_dlg.hrc\"\n#endif\n#ifndef _SFXITEMSET_HXX\n#include \n#endif\n#define _ZFORLIST_DECLARE_TABLE\n#ifndef _ZFORLIST_HXX\n#include \n#endif\n#include \/\/CHINA001\n#include \/\/CHINA001\n#ifndef _SFXINTITEM_HXX \/\/CHINA001\n#include \/\/CHINA001\n#endif \/\/CHINA001\n\nusing namespace dbaui;\n\nDBG_NAME(SbaSbAttrDlg)\n\/\/==================================================================\nSbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow)\n : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs )\n ,aTitle(ModuleRes(ST_ROW))\n{\n DBG_CTOR(SbaSbAttrDlg,NULL);\n\n pNumberInfoItem = new SvxNumberInfoItem( pFormatter, 0 );\n\n if (bRow)\n SetText(aTitle);\n if( nFlags & TP_ATTR_CHAR )\n {\n\/\/ AddTabPage( RID_SVXPAGE_CHAR_STD,String(ModuleRes(TP_ATTR_CHAR)),SvxCharStdPage::Create, 0 );\n DBG_ERROR( \"found flag TP_ATTR_CHAR\" );\n }\n if( nFlags & TP_ATTR_NUMBER )\n AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)) ); \/\/CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 );\n if( nFlags & TP_ATTR_ALIGN )\n AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)) );\/\/CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 );\n FreeResource();\n}\n\n\/\/ -----------------------------------------------------------------------\nSbaSbAttrDlg::~SbaSbAttrDlg()\n{\n delete pNumberInfoItem;\n\n DBG_DTOR(SbaSbAttrDlg,NULL);\n}\n\n\/\/ -----------------------------------------------------------------------\nvoid SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage )\n{\n SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));\n switch ( nPageId )\n {\n case RID_SVXPAGE_NUMBERFORMAT:\n {\n \/\/CHINA001 ((SvxNumberFormatTabPage&)rTabPage).\n \/\/CHINA001 SetNumberFormatList( *pNumberInfoItem );\n aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO));\n rTabPage.PageCreated(aSet);\n }\n break;\n\n case RID_SVXPAGE_CHAR_STD:\n {\n \/\/ ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem());\n }\n break;\n\n case RID_SVXPAGE_ALIGNMENT:\n {\n \/\/CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT);\n\/\/ aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT));\n\/\/ rTabPage.PageCreated(aSet);\n }\n break;\n\n default:\n break;\n }\n}\n\n\n<|endoftext|>"} {"text":"\/\/---------------------------------------------------------------------------\n\/\/ $Id$ \n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include \n#include \n\n#include \n#include \n\n\/\/TODO:[GK] Clean up open functions, reuse code!\n\nstd::map > PathSearch::path_lists;\nstd::map > PathSearch::suffix_lists;\nstd::string PathSearch::empty(\"\");\n\nvoid\nPathSearch::initialize_classes()\n{\n std::vector v;\n v.push_back(empty);\n path_lists.insert(map_type(std::string(\"PARAMETER\"), v));\n\n v.push_back(std::string(DEAL_II_PATH \"\/lib\/meshes\/\"));\n path_lists.insert(map_type(std::string(\"MESH\"), v));\n\n v.clear();\n v.push_back(empty);\n v.push_back(std::string(\".prm\"));\n suffix_lists.insert(map_type(std::string(\"PARAMETER\"), v));\n \n v.clear();\n v.push_back(empty);\n v.push_back(std::string(\".inp\"));\n v.push_back(std::string(\".xda\"));\n v.push_back(std::string(\".dbmesh\"));\n suffix_lists.insert(map_type(std::string(\"MESH\"), v));\n}\n\nstd::vector&\nPathSearch::get_path_list(const std::string& cls)\n{\n if (path_lists.empty())\n initialize_classes();\n\n Assert(path_lists.count(cls) != 0, ExcNoClass(cls));\n \n return path_lists.find(cls)->second;\n}\n\n\nstd::vector&\nPathSearch::get_suffix_list(const std::string& cls)\n{\n Assert(suffix_lists.count(cls) != 0, ExcNoClass(cls));\n \n return suffix_lists.find(cls)->second;\n}\n\n\nPathSearch::PathSearch(const std::string& cls,\n\t\t const unsigned int debug)\n\t\t:\n\t\tcls(cls),\n\t\tmy_path_list(get_path_list(cls)),\n\t\tmy_suffix_list(get_suffix_list(cls)),\n\t\tdebug(debug)\n{}\n\n\nstd::istream&\nPathSearch::open (const std::string& filename,\n\t\t const std::string& suffix)\n{\n std::vector::const_iterator path;\n const std::vector::const_iterator endp = my_path_list.end();\n\n if (debug > 2)\n deallog << \"PathSearch[\" << cls << \"] \"\n\t << my_path_list.size() << \" directories \"\n\t << std::endl;\n \n\t\t\t\t \/\/ Try without suffix first\n for (path = my_path_list.begin(); path != endp; ++path)\n {\n real_name = *path + filename;\n if (debug > 1)\n\tdeallog << \"PathSearch[\" << cls << \"] trying \"\n\t\t<< real_name << std::endl;\n stream.reset(new std::ifstream(real_name.c_str()));\n if (stream->is_open())\n\t{\n\t if (debug > 0)\n\t deallog << \"PathSearch[\" << cls << \"] opened \"\n\t\t << real_name << std::endl;\n\t return *stream;\n\t}\n }\n\n\t\t\t\t \/\/ Now try with given suffix\n for (path = my_path_list.begin(); path != endp; ++path)\n {\n real_name = *path + filename + suffix;\n if (debug > 1)\n\tdeallog << \"PathSearch[\" << cls << \"] trying \"\n\t\t<< real_name << std::endl;\n stream.reset(new std::ifstream(real_name.c_str()));\n if (stream->is_open())\n\t{\n\t if (debug > 0)\n\t deallog << \"PathSearch[\" << cls << \"] opened \"\n\t\t << real_name << std::endl;\n\t return *stream;\n\t}\n }\n AssertThrow(false, ExcFileNotFound(filename, cls));\n return *stream;\n}\n\n\nstd::istream&\nPathSearch::open (const std::string& filename)\n{\n std::vector::const_iterator suffix;\n std::vector::const_iterator path;\n const std::vector::const_iterator ends = my_suffix_list.end();\n const std::vector::const_iterator endp = my_path_list.end();\n\n if (debug > 2)\n deallog << \"PathSearch[\" << cls << \"] \"\n\t << my_path_list.size() << \" directories \"\n\t << my_suffix_list.size() << \" suffixes\"\n\t << std::endl;\n \n for (suffix = my_suffix_list.begin(); suffix != ends; ++suffix)\n {\n for (path = my_path_list.begin(); path != endp; ++path)\n\t{\n\t real_name = *path + filename + *suffix;\n\t if (debug > 1)\n\t deallog << \"PathSearch[\" << cls << \"] trying \"\n\t\t << real_name << std::endl;\n\t stream.reset(new std::ifstream(real_name.c_str()));\n\t if (stream->is_open())\n\t {\n\t if (debug > 0)\n\t\tdeallog << \"PathSearch[\" << cls << \"] opened \"\n\t\t\t<< real_name << std::endl;\n\t return *stream;\n\t }\n\t}\n }\n AssertThrow(false, ExcFileNotFound(filename, cls));\n return *stream;\n}\n\n\nvoid\nPathSearch::add_class (const std::string& cls)\n{\n\t\t\t\t \/\/ Make sure standard classes are\n\t\t\t\t \/\/ initialized first\n if (path_lists.empty())\n initialize_classes();\n\t\t\t\t \/\/ Add empty path and empty suffix\n\t\t\t\t \/\/ for new class\n std::vector v;\n v.push_back(empty);\n path_lists.insert(map_type(cls, v));\n suffix_lists.insert(map_type(cls, v));\n}\n\n\nvoid\nPathSearch::add_path (const std::string& path,\n\t\t Position pos)\n{\n if (pos == back)\n my_path_list.push_back(path);\n else if (pos == front)\n my_path_list.insert(my_path_list.begin(), path);\n else if (pos == after_none)\n {\n std::vector::iterator\n\ti = std::find(my_path_list.begin(), my_path_list.end(), empty);\n if (i != my_path_list.end())\n\t++i;\n my_path_list.insert(i, path);\n }\n}\n\n\nvoid\nPathSearch::add_suffix (const std::string& suffix,\n\t\t Position pos)\n{\n if (pos == back)\n my_suffix_list.push_back(suffix);\n else if (pos == front)\n my_suffix_list.insert(my_suffix_list.begin(), suffix);\n else if (pos == after_none)\n {\n std::vector::iterator\n\ti = std::find(my_suffix_list.begin(), my_suffix_list.end(), empty);\n if (i != my_suffix_list.end())\n\t++i;\n my_suffix_list.insert(i, suffix);\n }\n}\n\n\nAdd a TODO.\/\/---------------------------------------------------------------------------\n\/\/ $Id$ \n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include \n#include \n\n#include \n#include \n\n\/\/TODO:[GK] Clean up open functions, reuse code!\n\nstd::map > PathSearch::path_lists;\nstd::map > PathSearch::suffix_lists;\nstd::string PathSearch::empty(\"\");\n\nvoid\nPathSearch::initialize_classes()\n{\n std::vector v;\n v.push_back(empty);\n path_lists.insert(map_type(std::string(\"PARAMETER\"), v));\n\n v.push_back(std::string(DEAL_II_PATH \"\/lib\/meshes\/\"));\n path_lists.insert(map_type(std::string(\"MESH\"), v));\n\n v.clear();\n v.push_back(empty);\n v.push_back(std::string(\".prm\"));\n suffix_lists.insert(map_type(std::string(\"PARAMETER\"), v));\n\n\/\/TODO[GK]: instead of listing by hand here, query the GridIn class which formats it can presently read\n v.clear();\n v.push_back(empty);\n v.push_back(std::string(\".inp\"));\n v.push_back(std::string(\".xda\"));\n v.push_back(std::string(\".dbmesh\"));\n suffix_lists.insert(map_type(std::string(\"MESH\"), v));\n}\n\nstd::vector&\nPathSearch::get_path_list(const std::string& cls)\n{\n if (path_lists.empty())\n initialize_classes();\n\n Assert(path_lists.count(cls) != 0, ExcNoClass(cls));\n \n return path_lists.find(cls)->second;\n}\n\n\nstd::vector&\nPathSearch::get_suffix_list(const std::string& cls)\n{\n Assert(suffix_lists.count(cls) != 0, ExcNoClass(cls));\n \n return suffix_lists.find(cls)->second;\n}\n\n\nPathSearch::PathSearch(const std::string& cls,\n\t\t const unsigned int debug)\n\t\t:\n\t\tcls(cls),\n\t\tmy_path_list(get_path_list(cls)),\n\t\tmy_suffix_list(get_suffix_list(cls)),\n\t\tdebug(debug)\n{}\n\n\nstd::istream&\nPathSearch::open (const std::string& filename,\n\t\t const std::string& suffix)\n{\n std::vector::const_iterator path;\n const std::vector::const_iterator endp = my_path_list.end();\n\n if (debug > 2)\n deallog << \"PathSearch[\" << cls << \"] \"\n\t << my_path_list.size() << \" directories \"\n\t << std::endl;\n \n\t\t\t\t \/\/ Try without suffix first\n for (path = my_path_list.begin(); path != endp; ++path)\n {\n real_name = *path + filename;\n if (debug > 1)\n\tdeallog << \"PathSearch[\" << cls << \"] trying \"\n\t\t<< real_name << std::endl;\n stream.reset(new std::ifstream(real_name.c_str()));\n if (stream->is_open())\n\t{\n\t if (debug > 0)\n\t deallog << \"PathSearch[\" << cls << \"] opened \"\n\t\t << real_name << std::endl;\n\t return *stream;\n\t}\n }\n\n\t\t\t\t \/\/ Now try with given suffix\n for (path = my_path_list.begin(); path != endp; ++path)\n {\n real_name = *path + filename + suffix;\n if (debug > 1)\n\tdeallog << \"PathSearch[\" << cls << \"] trying \"\n\t\t<< real_name << std::endl;\n stream.reset(new std::ifstream(real_name.c_str()));\n if (stream->is_open())\n\t{\n\t if (debug > 0)\n\t deallog << \"PathSearch[\" << cls << \"] opened \"\n\t\t << real_name << std::endl;\n\t return *stream;\n\t}\n }\n AssertThrow(false, ExcFileNotFound(filename, cls));\n return *stream;\n}\n\n\nstd::istream&\nPathSearch::open (const std::string& filename)\n{\n std::vector::const_iterator suffix;\n std::vector::const_iterator path;\n const std::vector::const_iterator ends = my_suffix_list.end();\n const std::vector::const_iterator endp = my_path_list.end();\n\n if (debug > 2)\n deallog << \"PathSearch[\" << cls << \"] \"\n\t << my_path_list.size() << \" directories \"\n\t << my_suffix_list.size() << \" suffixes\"\n\t << std::endl;\n \n for (suffix = my_suffix_list.begin(); suffix != ends; ++suffix)\n {\n for (path = my_path_list.begin(); path != endp; ++path)\n\t{\n\t real_name = *path + filename + *suffix;\n\t if (debug > 1)\n\t deallog << \"PathSearch[\" << cls << \"] trying \"\n\t\t << real_name << std::endl;\n\t stream.reset(new std::ifstream(real_name.c_str()));\n\t if (stream->is_open())\n\t {\n\t if (debug > 0)\n\t\tdeallog << \"PathSearch[\" << cls << \"] opened \"\n\t\t\t<< real_name << std::endl;\n\t return *stream;\n\t }\n\t}\n }\n AssertThrow(false, ExcFileNotFound(filename, cls));\n return *stream;\n}\n\n\nvoid\nPathSearch::add_class (const std::string& cls)\n{\n\t\t\t\t \/\/ Make sure standard classes are\n\t\t\t\t \/\/ initialized first\n if (path_lists.empty())\n initialize_classes();\n\t\t\t\t \/\/ Add empty path and empty suffix\n\t\t\t\t \/\/ for new class\n std::vector v;\n v.push_back(empty);\n path_lists.insert(map_type(cls, v));\n suffix_lists.insert(map_type(cls, v));\n}\n\n\nvoid\nPathSearch::add_path (const std::string& path,\n\t\t Position pos)\n{\n if (pos == back)\n my_path_list.push_back(path);\n else if (pos == front)\n my_path_list.insert(my_path_list.begin(), path);\n else if (pos == after_none)\n {\n std::vector::iterator\n\ti = std::find(my_path_list.begin(), my_path_list.end(), empty);\n if (i != my_path_list.end())\n\t++i;\n my_path_list.insert(i, path);\n }\n}\n\n\nvoid\nPathSearch::add_suffix (const std::string& suffix,\n\t\t Position pos)\n{\n if (pos == back)\n my_suffix_list.push_back(suffix);\n else if (pos == front)\n my_suffix_list.insert(my_suffix_list.begin(), suffix);\n else if (pos == after_none)\n {\n std::vector::iterator\n\ti = std::find(my_suffix_list.begin(), my_suffix_list.end(), empty);\n if (i != my_suffix_list.end())\n\t++i;\n my_suffix_list.insert(i, suffix);\n }\n}\n\n\n<|endoftext|>"} {"text":"\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2014 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : field\/test\/container.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ includes, system\n\n#include \/\/ glm::operator<<\n\n\/\/ includes, project\n\n#include \n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n \n \/\/ variables, internal\n \n \/\/ functions, internal\n\n} \/\/ namespace {\n\n#define BOOST_TEST_MAIN\n#include \n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_base_rep)\n{\n scene::object::light::base::rep const lr;\n \n BOOST_CHECK(false == lr.active);\n BOOST_MESSAGE(\"object_light_source_rep:\" << lr << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_directional)\n{\n scene::object::light::directional const l;\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_positional)\n{\n scene::object::light::positional const l;\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_spot)\n{\n scene::object::light::spot const l;\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_area)\n{\n scene::object::light::area l;\n\n l.exponent.set(1);\n l.cutoff. set(12.5);\n \n l.size. set(glm::uvec2(1, 2));\n l.samples. set(glm::uvec2(1, 4));\n\n l.size. set(glm::uvec2(2, 1));\n l.samples. set(glm::uvec2(4, 1));\n\n l.size. set(glm::uvec2(2, 2));\n l.samples. set(glm::uvec2(4, 4));\n\n l.size. set(glm::uvec2( 6, 3));\n l.samples. set(glm::uvec2(10, 5));\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\nfixed: typo\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2014 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : field\/test\/objects_light.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ includes, system\n\n#include \/\/ glm::operator<<\n\n\/\/ includes, project\n\n#include \n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n \n \/\/ variables, internal\n \n \/\/ functions, internal\n\n} \/\/ namespace {\n\n#define BOOST_TEST_MAIN\n#include \n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_base_rep)\n{\n scene::object::light::base::rep const lr;\n \n BOOST_CHECK(false == lr.active);\n BOOST_MESSAGE(\"object_light_source_rep:\" << lr << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_directional)\n{\n scene::object::light::directional const l;\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_positional)\n{\n scene::object::light::positional const l;\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_spot)\n{\n scene::object::light::spot const l;\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\n\nBOOST_AUTO_TEST_CASE(test_scene_object_light_area)\n{\n scene::object::light::area l;\n\n l.exponent.set(1);\n l.cutoff. set(12.5);\n \n l.size. set(glm::uvec2(1, 2));\n l.samples. set(glm::uvec2(1, 4));\n\n l.size. set(glm::uvec2(2, 1));\n l.samples. set(glm::uvec2(4, 1));\n\n l.size. set(glm::uvec2(2, 2));\n l.samples. set(glm::uvec2(4, 4));\n\n l.size. set(glm::uvec2( 6, 3));\n l.samples. set(glm::uvec2(10, 5));\n \n BOOST_CHECK(false == l.active);\n BOOST_MESSAGE(l << '\\n');\n}\n<|endoftext|>"} {"text":"\/*\n * BaseProbe.h\n *\n * Author: slundquist\n *\/\n\n#ifndef BASEPROBE_HPP_\n#define BASEPROBE_HPP_\n\n#include \n#include \n#include \"..\/io\/fileio.hpp\"\n\nnamespace PV {\n\nclass HyPerCol;\nclass HyPerLayer;\n\n\/\/typedef enum {\n\/\/ BufV,\n\/\/ BufActivity\n\/\/} PVBufType;\n\n\/**\n * An abstract base class for the common functionality of layer probes and connection probes.\n *\/\nclass BaseProbe {\n\n\/\/ Methods\npublic:\n \/\/BaseProbe(const char * probeName, HyPerCol * hc);\n virtual ~BaseProbe();\n\n int ioParams(enum ParamsIOFlag ioFlag);\n\n\n \/**\n * A pure virtual function called during HyPerCol::run, during the communicateInitInfo stage.\n * BaseProbe::communicateInitInfo sets up the triggering layer and attaches to the energy probe,\n * if either triggerFlag or energyProbe are set.\n *\/\n virtual int communicateInitInfo() = 0;\n\n \/**\n * Called during HyPerCol::run, during the allocateDataStructures stage.\n * BaseProbe::allocateDataStructures returns immediately, but derived classes that\n * need to allocate storage should override this method.\n *\/\n virtual int allocateDataStructures();\n\n \/**\n * If there is a triggering layer, needUpdate returns true when the triggering layer's\n * nextUpdateTime, modified by the probe's triggerOffset parameter, occurs.\n * If there is not a triggering layer, needUpdate returns false.\n * This behavior can be overridden if a probe uses some criterion other than triggering\n * to choose when output its state.\n *\/\n virtual bool needUpdate(double time, double dt);\n\n \/**\n * Returns the number of value indices the probe can compute (typically the value\n * of the parent HyPerCol's nBatch parameter).\n * BaseProbe::getNumValues() returns the parent HyPerCol's getNBatch(), which can be overridden.\n * Probes derived from BaseProbe can set numValues to zero or a negative number to indicate that\n * getValues() and getNumValues()\n * are not fully implemented for that probe.\n *\/\n int getNumValues() { return numValues; }\n \n \/**\n * The public interface for calling the outputState method.\n * BaseConnection::outputStateWrapper calls outputState() if needUpdate() returns true.\n * This behavior is intended to be general, but the method can be overridden if needed.\n *\/\n virtual int outputStateWrapper(double timef, double dt);\n \n \/**\n * A pure virtual method for writing output to the output file.\n *\/\n virtual int outputState(double timef) = 0;\n virtual int writeTimer(FILE* stream) {return PV_SUCCESS;}\n\n \/**\n * Returns the keyword of the params group associated with this probe.\n *\/\n char const * getKeyword();\n\n \/**\n * Returns the name of the probe, specified in the public constructor.\n *\/\n const char * getName() {return name;}\n \n \/**\n * Returns the name of the targetName parameter for this probe.\n * LayerProbe uses targetName to specify the layer to attach to;\n * BaseConnectionProbe uses it to specify the connection to attach to.\n *\/\n const char * getTargetName() {return targetName;}\n \n \/**\n * Specifies the object responsible calling the probe's destructor.\n * BaseProbe sets owner to the parent HyPerCol during initialization.\n * During the communicateInitInfo stage, layer probes and connection probes\n * change their owner to the layer or connection they attach to.\n *\/\n void const * getOwner() { return owner;}\n \n \/**\n * getValues(double timevalue, double * values) sets the buffer 'values' with the probe's calculated values.\n * It assumes that the values buffer is large enough to hold getNumValues()\n * double-precision values.\n * If 'values' is NULL, the values are still updated internally if needed, but\n * those values are not returned.\n * Internally, getValues() calls calcValues() if needRecalc() is true. It then\n * copies the probeValues buffer to the input argument buffer 'values'.\n * Derived classes should not override or hide this method. Instead, they should override calcValues.\n *\/\n int getValues(double timevalue, double * valuesVector);\n \/**\n * getValues(double timevalue, vector * valuesVector) is a wrapper around\n * getValues(double, double *) that uses C++ vectors. It resizes valuesVector\n * to size getNumValues() and then fills the vector with the values returned by getValues.\n *\/\n int getValues(double timevalue, std::vector * valuesVector);\n \/**\n * getValue() is meant for situations where the caller needs one value\n * that would be returned by getValues(), not the whole buffer.\n * getValue() returns a signaling NaN if index is out of bounds. If index is valid,\n * getValue() calls calcValues() if needRecalc() returns true, and then\n * returns probeValues[index].\n * Derived classes should not override or hide this method. Instead, they should override calcValues.\n *\/\n double getValue(double timevalue, int index);\n\nprotected:\n BaseProbe();\n int initialize(const char * probeName, HyPerCol * hc);\n virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag);\n\n \/** \n * List of parameters for the BaseProbe class\n * @name BaseProbe Parameters\n * @{\n *\/\n\n \/**\n * @brief targetName: the name of the object that the probe attaches to.\n * In LayerProbe, targetName is used to define the targetLayer, and in\n * BaseConnectionProbe, targetName is used to define the targetConn.\n *\/\n virtual void ioParam_targetName(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief message: A string parameter that is typically included in the lines output by the outputState method\n *\/\n virtual void ioParam_message(enum ParamsIOFlag ioFlag);\n\n \/**\n * @brief probeOutputFile: the name of the file that the outputState method writes to.\n * If blank, the output is sent to stdout.\n *\/\n virtual void ioParam_probeOutputFile(enum ParamsIOFlag ioFlag);\n\n \/**\n * @brief triggerFlag: If false, the needUpdate method always returns true,\n * so that outputState is called every timestep. If false, the needUpdate\n * method uses triggerLayerName and triggerOffset to determine if the probe\n * should be triggered.\n *\/\n virtual void ioParam_triggerFlag(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief triggerLayerName: If triggerFlag is true, triggerLayerName specifies the layer\n * to check for triggering.\n *\/\n virtual void ioParam_triggerLayerName(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief triggerOffset: If triggerFlag is true, triggerOffset specifies the\n * time interval *before* the triggerLayer's nextUpdate time that needUpdate() returns true.\n *\/\n virtual void ioParam_triggerOffset(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief energyProbe: If nonblank, specifies the name of a ColumnEnergyProbe\n * that this probe contributes an energy term to.\n *\/\n virtual void ioParam_energyProbe(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief coefficient: If energyProbe is set, the coefficient parameter specifies\n * that ColumnEnergyProbe multiplies the result of this probe's getValues() method\n * by coefficient when computing the error.\n * @details Note that coefficient does not affect the value returned by the getValue() or\n * getValues() method.\n *\/\n virtual void ioParam_coefficient(enum ParamsIOFlag ioFlag);\n \/** @} *\/\n\n virtual int initOutputStream(const char * filename);\n\n \/**\n * A pure virtual method for that should return true if the quantities being measured\n * by the probe have changed since the last time the quantities were calculated.\n * Typically, an implementation of needRecalc() will check the lastUpdateTime of\n * the object being probed, and return true if that value is greater than the\n * lastUpdateTime member variable.\n * needRecalc() is called by getValues(double) (and hence by getValue() and the other\n * flavors of getValues).\n * Note that there is a single needRecalc that applies to all getNumValues() quantities.\n *\/\n virtual bool needRecalc(double timevalue) = 0;\n\n \/**\n * A pure virtual method to calculate the values of the probe. calcValues() can\n * assume that needRecalc() has been called and returned true.\n * It should write the computed values into the buffer of member variable 'probeValues'.\n *\/\n virtual int calcValues(double timevalue) = 0;\n\n \/**\n * If needRecalc() returns true, getValues(double) updates the probeValues buffer\n * (by calling calcValues) and sets lastUpdateTime to the timevalue input argument.\n *\/\n int getValues(double timevalue);\n\n \/**\n * Returns a pointer to parent HyPerCol.\n *\/\n HyPerCol * getParent() {return parent;}\n \n \/**\n * Returns a pointer to the message parameter.\n *\/\n const char * getMessage() {return msgstring;}\n \n \/**\n * The method called by BaseProbe::initialize() to set the message used by\n * the probe's outputState method.\n *\/\n virtual int initMessage(const char * msg);\n \n \/**\n * Returns a pointer to the PV_Stream used by outputState.\n *\/\n PV_Stream * getStream() {return outputstream;}\n \n \/**\n * initNumValues is called by initialize.\n * BaseProbe::initNumValues sets numValues to the parent HyPerCol's getNBatch().\n * Derived classes can override initNumValues to initialize numValues to a different\n * value.\n *\/\n virtual int initNumValues();\n \n \/**\n * Sets the numValues member variable (returned by getNumValues()) and reallocates\n * the probeValues member variable to hold numValues double-precision values.\n * If the reallocation fails, the probeValues buffer is left unchanged, errno is\n * set (by a realloc() call), and PV_FAILURE is returned.\n * Otherwise, PV_SUCCESS is returned.\n *\/\n int setNumValues(int n);\n \n \/**\n * Returns a pointer to the buffer containing the probeValues.\n *\/\n double * getValuesBuffer() { return probeValues; }\n\n \/**\n * Returns the time that calcValues was last called.\n * BaseProbe updates the last update time in getValues() and getValue(),\n * based on the result of needRecalc.\n *\/\n double getLastUpdateTime() { return lastUpdateTime; }\n\nprivate:\n int initialize_base();\n void setParentCol(HyPerCol * hc) {parent = hc;}\n int setProbeName(const char * probeName);\n\n\/\/ Member variables\nprotected:\n PV_Stream * outputstream;\n bool triggerFlag;\n char* triggerLayerName;\n HyPerLayer * triggerLayer;\n double triggerOffset;\n HyPerCol * parent;\n void * owner; \/\/ the object responsible for calling the probe's destructor\n char * name;\n char * targetName;\n char * energyProbe; \/\/ the name of the ColumnEnergyProbe to attach to, if any.\n double coefficient;\n\nprivate:\n char * msgparams; \/\/ the message parameter in the params\n char * msgstring; \/\/ the string that gets printed by outputState (\"\" if message is empty or null; message + \":\" if nonempty\n char * probeOutputFilename;\n int numValues;\n double * probeValues;\n double lastUpdateTime; \/\/ The time of the last time calcValues was called.\n};\n\n}\n\n#endif \/* BASEPROBE_HPP_ *\/\nFixes comment to ioParam_triggerFlag in BaseProbe\/*\n * BaseProbe.h\n *\n * Author: slundquist\n *\/\n\n#ifndef BASEPROBE_HPP_\n#define BASEPROBE_HPP_\n\n#include \n#include \n#include \"..\/io\/fileio.hpp\"\n\nnamespace PV {\n\nclass HyPerCol;\nclass HyPerLayer;\n\n\/\/typedef enum {\n\/\/ BufV,\n\/\/ BufActivity\n\/\/} PVBufType;\n\n\/**\n * An abstract base class for the common functionality of layer probes and connection probes.\n *\/\nclass BaseProbe {\n\n\/\/ Methods\npublic:\n \/\/BaseProbe(const char * probeName, HyPerCol * hc);\n virtual ~BaseProbe();\n\n int ioParams(enum ParamsIOFlag ioFlag);\n\n\n \/**\n * A pure virtual function called during HyPerCol::run, during the communicateInitInfo stage.\n * BaseProbe::communicateInitInfo sets up the triggering layer and attaches to the energy probe,\n * if either triggerFlag or energyProbe are set.\n *\/\n virtual int communicateInitInfo() = 0;\n\n \/**\n * Called during HyPerCol::run, during the allocateDataStructures stage.\n * BaseProbe::allocateDataStructures returns immediately, but derived classes that\n * need to allocate storage should override this method.\n *\/\n virtual int allocateDataStructures();\n\n \/**\n * If there is a triggering layer, needUpdate returns true when the triggering layer's\n * nextUpdateTime, modified by the probe's triggerOffset parameter, occurs.\n * If there is not a triggering layer, needUpdate returns false.\n * This behavior can be overridden if a probe uses some criterion other than triggering\n * to choose when output its state.\n *\/\n virtual bool needUpdate(double time, double dt);\n\n \/**\n * Returns the number of value indices the probe can compute (typically the value\n * of the parent HyPerCol's nBatch parameter).\n * BaseProbe::getNumValues() returns the parent HyPerCol's getNBatch(), which can be overridden.\n * Probes derived from BaseProbe can set numValues to zero or a negative number to indicate that\n * getValues() and getNumValues()\n * are not fully implemented for that probe.\n *\/\n int getNumValues() { return numValues; }\n \n \/**\n * The public interface for calling the outputState method.\n * BaseConnection::outputStateWrapper calls outputState() if needUpdate() returns true.\n * This behavior is intended to be general, but the method can be overridden if needed.\n *\/\n virtual int outputStateWrapper(double timef, double dt);\n \n \/**\n * A pure virtual method for writing output to the output file.\n *\/\n virtual int outputState(double timef) = 0;\n virtual int writeTimer(FILE* stream) {return PV_SUCCESS;}\n\n \/**\n * Returns the keyword of the params group associated with this probe.\n *\/\n char const * getKeyword();\n\n \/**\n * Returns the name of the probe, specified in the public constructor.\n *\/\n const char * getName() {return name;}\n \n \/**\n * Returns the name of the targetName parameter for this probe.\n * LayerProbe uses targetName to specify the layer to attach to;\n * BaseConnectionProbe uses it to specify the connection to attach to.\n *\/\n const char * getTargetName() {return targetName;}\n \n \/**\n * Specifies the object responsible calling the probe's destructor.\n * BaseProbe sets owner to the parent HyPerCol during initialization.\n * During the communicateInitInfo stage, layer probes and connection probes\n * change their owner to the layer or connection they attach to.\n *\/\n void const * getOwner() { return owner;}\n \n \/**\n * getValues(double timevalue, double * values) sets the buffer 'values' with the probe's calculated values.\n * It assumes that the values buffer is large enough to hold getNumValues()\n * double-precision values.\n * If 'values' is NULL, the values are still updated internally if needed, but\n * those values are not returned.\n * Internally, getValues() calls calcValues() if needRecalc() is true. It then\n * copies the probeValues buffer to the input argument buffer 'values'.\n * Derived classes should not override or hide this method. Instead, they should override calcValues.\n *\/\n int getValues(double timevalue, double * valuesVector);\n \/**\n * getValues(double timevalue, vector * valuesVector) is a wrapper around\n * getValues(double, double *) that uses C++ vectors. It resizes valuesVector\n * to size getNumValues() and then fills the vector with the values returned by getValues.\n *\/\n int getValues(double timevalue, std::vector * valuesVector);\n \/**\n * getValue() is meant for situations where the caller needs one value\n * that would be returned by getValues(), not the whole buffer.\n * getValue() returns a signaling NaN if index is out of bounds. If index is valid,\n * getValue() calls calcValues() if needRecalc() returns true, and then\n * returns probeValues[index].\n * Derived classes should not override or hide this method. Instead, they should override calcValues.\n *\/\n double getValue(double timevalue, int index);\n\nprotected:\n BaseProbe();\n int initialize(const char * probeName, HyPerCol * hc);\n virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag);\n\n \/** \n * List of parameters for the BaseProbe class\n * @name BaseProbe Parameters\n * @{\n *\/\n\n \/**\n * @brief targetName: the name of the object that the probe attaches to.\n * In LayerProbe, targetName is used to define the targetLayer, and in\n * BaseConnectionProbe, targetName is used to define the targetConn.\n *\/\n virtual void ioParam_targetName(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief message: A string parameter that is typically included in the lines output by the outputState method\n *\/\n virtual void ioParam_message(enum ParamsIOFlag ioFlag);\n\n \/**\n * @brief probeOutputFile: the name of the file that the outputState method writes to.\n * If blank, the output is sent to stdout.\n *\/\n virtual void ioParam_probeOutputFile(enum ParamsIOFlag ioFlag);\n\n \/**\n * @brief triggerFlag: If false, the needUpdate method always returns true,\n * so that outputState is called every timestep. If true, the needUpdate\n * method uses triggerLayerName and triggerOffset to determine if the probe\n * should be triggered.\n *\/\n virtual void ioParam_triggerFlag(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief triggerLayerName: If triggerFlag is true, triggerLayerName specifies the layer\n * to check for triggering.\n *\/\n virtual void ioParam_triggerLayerName(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief triggerOffset: If triggerFlag is true, triggerOffset specifies the\n * time interval *before* the triggerLayer's nextUpdate time that needUpdate() returns true.\n *\/\n virtual void ioParam_triggerOffset(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief energyProbe: If nonblank, specifies the name of a ColumnEnergyProbe\n * that this probe contributes an energy term to.\n *\/\n virtual void ioParam_energyProbe(enum ParamsIOFlag ioFlag);\n \n \/**\n * @brief coefficient: If energyProbe is set, the coefficient parameter specifies\n * that ColumnEnergyProbe multiplies the result of this probe's getValues() method\n * by coefficient when computing the error.\n * @details Note that coefficient does not affect the value returned by the getValue() or\n * getValues() method.\n *\/\n virtual void ioParam_coefficient(enum ParamsIOFlag ioFlag);\n \/** @} *\/\n\n virtual int initOutputStream(const char * filename);\n\n \/**\n * A pure virtual method for that should return true if the quantities being measured\n * by the probe have changed since the last time the quantities were calculated.\n * Typically, an implementation of needRecalc() will check the lastUpdateTime of\n * the object being probed, and return true if that value is greater than the\n * lastUpdateTime member variable.\n * needRecalc() is called by getValues(double) (and hence by getValue() and the other\n * flavors of getValues).\n * Note that there is a single needRecalc that applies to all getNumValues() quantities.\n *\/\n virtual bool needRecalc(double timevalue) = 0;\n\n \/**\n * A pure virtual method to calculate the values of the probe. calcValues() can\n * assume that needRecalc() has been called and returned true.\n * It should write the computed values into the buffer of member variable 'probeValues'.\n *\/\n virtual int calcValues(double timevalue) = 0;\n\n \/**\n * If needRecalc() returns true, getValues(double) updates the probeValues buffer\n * (by calling calcValues) and sets lastUpdateTime to the timevalue input argument.\n *\/\n int getValues(double timevalue);\n\n \/**\n * Returns a pointer to parent HyPerCol.\n *\/\n HyPerCol * getParent() {return parent;}\n \n \/**\n * Returns a pointer to the message parameter.\n *\/\n const char * getMessage() {return msgstring;}\n \n \/**\n * The method called by BaseProbe::initialize() to set the message used by\n * the probe's outputState method.\n *\/\n virtual int initMessage(const char * msg);\n \n \/**\n * Returns a pointer to the PV_Stream used by outputState.\n *\/\n PV_Stream * getStream() {return outputstream;}\n \n \/**\n * initNumValues is called by initialize.\n * BaseProbe::initNumValues sets numValues to the parent HyPerCol's getNBatch().\n * Derived classes can override initNumValues to initialize numValues to a different\n * value.\n *\/\n virtual int initNumValues();\n \n \/**\n * Sets the numValues member variable (returned by getNumValues()) and reallocates\n * the probeValues member variable to hold numValues double-precision values.\n * If the reallocation fails, the probeValues buffer is left unchanged, errno is\n * set (by a realloc() call), and PV_FAILURE is returned.\n * Otherwise, PV_SUCCESS is returned.\n *\/\n int setNumValues(int n);\n \n \/**\n * Returns a pointer to the buffer containing the probeValues.\n *\/\n double * getValuesBuffer() { return probeValues; }\n\n \/**\n * Returns the time that calcValues was last called.\n * BaseProbe updates the last update time in getValues() and getValue(),\n * based on the result of needRecalc.\n *\/\n double getLastUpdateTime() { return lastUpdateTime; }\n\nprivate:\n int initialize_base();\n void setParentCol(HyPerCol * hc) {parent = hc;}\n int setProbeName(const char * probeName);\n\n\/\/ Member variables\nprotected:\n PV_Stream * outputstream;\n bool triggerFlag;\n char* triggerLayerName;\n HyPerLayer * triggerLayer;\n double triggerOffset;\n HyPerCol * parent;\n void * owner; \/\/ the object responsible for calling the probe's destructor\n char * name;\n char * targetName;\n char * energyProbe; \/\/ the name of the ColumnEnergyProbe to attach to, if any.\n double coefficient;\n\nprivate:\n char * msgparams; \/\/ the message parameter in the params\n char * msgstring; \/\/ the string that gets printed by outputState (\"\" if message is empty or null; message + \":\" if nonempty\n char * probeOutputFilename;\n int numValues;\n double * probeValues;\n double lastUpdateTime; \/\/ The time of the last time calcValues was called.\n};\n\n}\n\n#endif \/* BASEPROBE_HPP_ *\/\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgstreamercameraexposurecontrol_maemo.h\"\n#include \"qgstreamercapturesession_maemo.h\"\n#include \n\n#include \n\nQGstreamerCameraExposureControl::QGstreamerCameraExposureControl(GstElement &camerabin, QGstreamerCaptureSession *session)\n :QCameraExposureControl(session),\n m_camerabin(camerabin),\n m_session(session)\n{\n}\n\nQGstreamerCameraExposureControl::~QGstreamerCameraExposureControl()\n{\n}\n\nQCamera::FlashModes QGstreamerCameraExposureControl::flashMode() const\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n GstFlashMode flashMode = config.flash_mode;\n\n QCamera::FlashModes modes;\n switch (flashMode) {\n case GST_PHOTOGRAPHY_FLASH_MODE_AUTO: modes |= QCamera::FlashAuto; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_OFF: modes |= QCamera::FlashOff; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_ON: modes |= QCamera::FlashOn; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN: modes |= QCamera::FlashFill; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE: modes |= QCamera::FlashRedEyeReduction; break;\n default:\n modes |= QCamera::FlashManual;\n break;\n }\n return modes;\n}\n\nvoid QGstreamerCameraExposureControl::setFlashMode(QCamera::FlashModes mode)\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n\n GstFlashMode flashMode = config.flash_mode;\n if (mode.testFlag(QCamera::FlashAuto)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_AUTO;\n else if (mode.testFlag(QCamera::FlashOff)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_OFF;\n else if (mode.testFlag(QCamera::FlashOn)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_ON;\n else if (mode.testFlag(QCamera::FlashFill)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN;\n else if (mode.testFlag(QCamera::FlashRedEyeReduction)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE;\n\n config.flash_mode = flashMode;\n gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n}\n\nQCamera::FlashModes QGstreamerCameraExposureControl::supportedFlashModes() const\n{\n QCamera::FlashModes modes;\n modes |= QCamera::FlashOff;\n modes |= QCamera::FlashOn;\n modes |= QCamera::FlashAuto;\n modes |= QCamera::FlashRedEyeReduction;\n modes |= QCamera::FlashFill;\n\n return modes;\n}\n\nqreal QGstreamerCameraExposureControl::flashCompensation() const\n{\n return 0;\n}\n\nvoid QGstreamerCameraExposureControl::setFlashCompensation(qreal ev)\n{\n}\n\nqreal QGstreamerCameraExposureControl::flashPower() const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setFlashPower(qreal power)\n{\n}\n\nbool QGstreamerCameraExposureControl::isFlashReady() const\n{\n}\n\nQCamera::ExposureMode QGstreamerCameraExposureControl::exposureMode() const\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n GstSceneMode sceneMode = config.scene_mode;\n\n switch (sceneMode) {\n case GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT: return QCamera::ExposurePortrait;\n case GST_PHOTOGRAPHY_SCENE_MODE_SPORT: return QCamera::ExposureSports;\n case GST_PHOTOGRAPHY_SCENE_MODE_NIGHT: return QCamera::ExposureNight;\n case GST_PHOTOGRAPHY_SCENE_MODE_AUTO: return QCamera::ExposureAuto;\n case GST_PHOTOGRAPHY_SCENE_MODE_MANUAL:\n case GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP: \/\/no direct mapping available so mapping to manual mode\n case GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE: \/\/no direct mapping available so mapping to manual mode\n default:\n return QCamera::ExposureManual;\n }\n}\n\nvoid QGstreamerCameraExposureControl::setExposureMode(QCamera::ExposureMode mode)\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n GstSceneMode sceneMode = config.scene_mode;\n\n if (mode == QCamera::ExposureManual) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_MANUAL;\n else if (mode == QCamera::ExposurePortrait) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT;\n else if (mode == QCamera::ExposureSports) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_SPORT;\n else if (mode == QCamera::ExposureNight) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_NIGHT;\n else if (mode == QCamera::ExposureAuto) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_AUTO;\n\n config.scene_mode = sceneMode;\n gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n}\n\nQCamera::ExposureModes QGstreamerCameraExposureControl::supportedExposureModes() const\n{\n \/\/Similar mode names can be found in gst as GstSceneMode\n QCamera::ExposureModes modes;\n modes |= QCamera::ExposureManual;\n modes |= QCamera::ExposurePortrait;\n modes |= QCamera::ExposureSports;\n modes |= QCamera::ExposureNight;\n modes |= QCamera::ExposureAuto;\n\n \/\/No direct mapping available for GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP and\n \/\/GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE\n\n return modes;\n}\n\nqreal QGstreamerCameraExposureControl::exposureCompensation() const\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n return config.ev_compensation;\n}\n\nvoid QGstreamerCameraExposureControl::setExposureCompensation(qreal ev)\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n config.ev_compensation = ev;\n gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n}\n\nQCamera::MeteringMode QGstreamerCameraExposureControl::meteringMode() const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setMeteringMode(QCamera::MeteringMode mode)\n{\n}\n\nQCamera::MeteringModes QGstreamerCameraExposureControl::supportedMeteringModes() const\n{\n}\n\nint QGstreamerCameraExposureControl::isoSensitivity() const\n{\n}\n\nQList QGstreamerCameraExposureControl::supportedIsoSensitivities(bool *continuous) const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setManualIsoSensitivity(int iso)\n{\n}\n\nvoid QGstreamerCameraExposureControl::setAutoIsoSensitivity()\n{\n}\n\nqreal QGstreamerCameraExposureControl::aperture() const\n{\n}\n\nQList QGstreamerCameraExposureControl::supportedApertures(bool *continuous) const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setManualAperture(qreal aperture)\n{\n}\n\nvoid QGstreamerCameraExposureControl::setAutoAperture()\n{\n}\n\nqreal QGstreamerCameraExposureControl::shutterSpeed() const\n{\n}\n\nQList QGstreamerCameraExposureControl::supportedShutterSpeeds(bool *continuous) const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setManualShutterSpeed(qreal seconds)\n{\n}\n\nvoid QGstreamerCameraExposureControl::setAutoShutterSpeed()\n{\n}\n\nbool QGstreamerCameraExposureControl::isExposureLocked() const\n{\n}\n\nvoid QGstreamerCameraExposureControl::lockExposure()\n{\n}\n\nvoid QGstreamerCameraExposureControl::unlockExposure()\n{\n}\n\nReturning MeteringAverage as an only supported mode\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgstreamercameraexposurecontrol_maemo.h\"\n#include \"qgstreamercapturesession_maemo.h\"\n#include \n\n#include \n\nQGstreamerCameraExposureControl::QGstreamerCameraExposureControl(GstElement &camerabin, QGstreamerCaptureSession *session)\n :QCameraExposureControl(session),\n m_camerabin(camerabin),\n m_session(session)\n{\n}\n\nQGstreamerCameraExposureControl::~QGstreamerCameraExposureControl()\n{\n}\n\nQCamera::FlashModes QGstreamerCameraExposureControl::flashMode() const\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n GstFlashMode flashMode = config.flash_mode;\n\n QCamera::FlashModes modes;\n switch (flashMode) {\n case GST_PHOTOGRAPHY_FLASH_MODE_AUTO: modes |= QCamera::FlashAuto; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_OFF: modes |= QCamera::FlashOff; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_ON: modes |= QCamera::FlashOn; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN: modes |= QCamera::FlashFill; break;\n case GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE: modes |= QCamera::FlashRedEyeReduction; break;\n default:\n modes |= QCamera::FlashManual;\n break;\n }\n return modes;\n}\n\nvoid QGstreamerCameraExposureControl::setFlashMode(QCamera::FlashModes mode)\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n\n GstFlashMode flashMode = config.flash_mode;\n if (mode.testFlag(QCamera::FlashAuto)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_AUTO;\n else if (mode.testFlag(QCamera::FlashOff)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_OFF;\n else if (mode.testFlag(QCamera::FlashOn)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_ON;\n else if (mode.testFlag(QCamera::FlashFill)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN;\n else if (mode.testFlag(QCamera::FlashRedEyeReduction)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE;\n\n config.flash_mode = flashMode;\n gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n}\n\nQCamera::FlashModes QGstreamerCameraExposureControl::supportedFlashModes() const\n{\n QCamera::FlashModes modes;\n modes |= QCamera::FlashOff;\n modes |= QCamera::FlashOn;\n modes |= QCamera::FlashAuto;\n modes |= QCamera::FlashRedEyeReduction;\n modes |= QCamera::FlashFill;\n\n return modes;\n}\n\nqreal QGstreamerCameraExposureControl::flashCompensation() const\n{\n return 0;\n}\n\nvoid QGstreamerCameraExposureControl::setFlashCompensation(qreal ev)\n{\n}\n\nqreal QGstreamerCameraExposureControl::flashPower() const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setFlashPower(qreal power)\n{\n}\n\nbool QGstreamerCameraExposureControl::isFlashReady() const\n{\n}\n\nQCamera::ExposureMode QGstreamerCameraExposureControl::exposureMode() const\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n GstSceneMode sceneMode = config.scene_mode;\n\n switch (sceneMode) {\n case GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT: return QCamera::ExposurePortrait;\n case GST_PHOTOGRAPHY_SCENE_MODE_SPORT: return QCamera::ExposureSports;\n case GST_PHOTOGRAPHY_SCENE_MODE_NIGHT: return QCamera::ExposureNight;\n case GST_PHOTOGRAPHY_SCENE_MODE_AUTO: return QCamera::ExposureAuto;\n case GST_PHOTOGRAPHY_SCENE_MODE_MANUAL:\n case GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP: \/\/no direct mapping available so mapping to manual mode\n case GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE: \/\/no direct mapping available so mapping to manual mode\n default:\n return QCamera::ExposureManual;\n }\n}\n\nvoid QGstreamerCameraExposureControl::setExposureMode(QCamera::ExposureMode mode)\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n GstSceneMode sceneMode = config.scene_mode;\n\n if (mode == QCamera::ExposureManual) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_MANUAL;\n else if (mode == QCamera::ExposurePortrait) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT;\n else if (mode == QCamera::ExposureSports) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_SPORT;\n else if (mode == QCamera::ExposureNight) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_NIGHT;\n else if (mode == QCamera::ExposureAuto) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_AUTO;\n\n config.scene_mode = sceneMode;\n gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n}\n\nQCamera::ExposureModes QGstreamerCameraExposureControl::supportedExposureModes() const\n{\n \/\/Similar mode names can be found in gst as GstSceneMode\n QCamera::ExposureModes modes;\n modes |= QCamera::ExposureManual;\n modes |= QCamera::ExposurePortrait;\n modes |= QCamera::ExposureSports;\n modes |= QCamera::ExposureNight;\n modes |= QCamera::ExposureAuto;\n\n \/\/No direct mapping available for GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP and\n \/\/GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE\n\n return modes;\n}\n\nqreal QGstreamerCameraExposureControl::exposureCompensation() const\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n return config.ev_compensation;\n}\n\nvoid QGstreamerCameraExposureControl::setExposureCompensation(qreal ev)\n{\n GstPhotoSettings config;\n gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n config.ev_compensation = ev;\n gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);\n}\n\nQCamera::MeteringMode QGstreamerCameraExposureControl::meteringMode() const\n{\n return QCamera::MeteringAverage;\n}\n\nvoid QGstreamerCameraExposureControl::setMeteringMode(QCamera::MeteringMode mode)\n{\n \/\/pass\n}\n\nQCamera::MeteringModes QGstreamerCameraExposureControl::supportedMeteringModes() const\n{\n QCamera::MeteringModes modes;\n modes |= QCamera::MeteringAverage;\n return modes;\n}\n\nint QGstreamerCameraExposureControl::isoSensitivity() const\n{\n}\n\nQList QGstreamerCameraExposureControl::supportedIsoSensitivities(bool *continuous) const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setManualIsoSensitivity(int iso)\n{\n}\n\nvoid QGstreamerCameraExposureControl::setAutoIsoSensitivity()\n{\n}\n\nqreal QGstreamerCameraExposureControl::aperture() const\n{\n}\n\nQList QGstreamerCameraExposureControl::supportedApertures(bool *continuous) const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setManualAperture(qreal aperture)\n{\n}\n\nvoid QGstreamerCameraExposureControl::setAutoAperture()\n{\n}\n\nqreal QGstreamerCameraExposureControl::shutterSpeed() const\n{\n}\n\nQList QGstreamerCameraExposureControl::supportedShutterSpeeds(bool *continuous) const\n{\n}\n\nvoid QGstreamerCameraExposureControl::setManualShutterSpeed(qreal seconds)\n{\n}\n\nvoid QGstreamerCameraExposureControl::setAutoShutterSpeed()\n{\n}\n\nbool QGstreamerCameraExposureControl::isExposureLocked() const\n{\n}\n\nvoid QGstreamerCameraExposureControl::lockExposure()\n{\n}\n\nvoid QGstreamerCameraExposureControl::unlockExposure()\n{\n}\n\n<|endoftext|>"} {"text":"Обновление библиотек<|endoftext|>"} {"text":"\/\/ ==========================================================================\n\/\/ NGS: Regions of Interest Analysis\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2012-2013, Bernd Jagla, Institut Pasteur\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\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 Knut Reinert or the FU Berlin nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"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 KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Bernd Jagla \n\/\/ Author: Manuel Holtgrewe \n\/\/ ==========================================================================\n\n#include \"project_interval.h\"\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::pushBed()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::pushBed(TBedRecord const & bedRecord)\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"pushBed()\\n\"\n << \" \";\n writeRecord(std::cerr, bedRecord, seqan::Bed());\n }\n\n \/\/ Handle contig transition, we can unconditionally update rId.\n if (bedRecord.ref != ref)\n finishContig();\n ref = bedRecord.ref;\n\n \/\/ Register new BED record.\n bedRecords.push_back(bedRecord);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Function IntersectBed::writeEmptyBed()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::writeEmptyBed(seqan::BedRecord const & bedRecord)\n{\n seqan::RoiRecord roiRecord;\n roiRecord.ref = bedRecord.ref;\n roiRecord.beginPos = bedRecord.beginPos;\n roiRecord.endPos = bedRecord.endPos;\n roiRecord.strand = bedRecord.strand;\n roiRecord.name = bedRecord.name;\n roiRecord.len = roiRecord.endPos - roiRecord.beginPos;\n roiRecord.countMax = 0;\n for (int i = 0; i < (int)roiRecord.len; ++i)\n appendValue(roiRecord.count, 0);\n\n writeRecord(roiFileOut, roiRecord);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::processFirstBedRecord()\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Return true iff lhs and rhs overlap (both are BED or ROI records).\ntemplate \nbool overlap(TLeft const & lhs, TRight const & rhs)\n{\n return (rhs.beginPos < lhs.endPos) && (lhs.beginPos < rhs.endPos);\n}\n\nvoid IntersectBed::processFirstBedRecord()\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"processFirstBedRecord()\\n\";\n if (!bedRecords.empty())\n {\n std::cerr << \" \";\n writeRecord(std::cerr, bedRecords.front(), seqan::Bed());\n }\n }\n\n \/\/ When computing symmetric difference, we write out the BED record as ROI if there is no overlapping ROI record.\n if (options.mode == IntersectBedOptions::DIFF)\n {\n if (roiRecords.empty() || roiRecords.front().beginPos >= bedRecords.front().endPos)\n {\n writeEmptyBed(bedRecords.front());\n return;\n }\n }\n\n if (roiRecords.empty())\n return;\n\n \/\/ When in DIFF mode: Mark all ROI records overlapping with current front BED record as such and stop.\n typedef std::list::\/*const_*\/iterator TRoiIter;\n if (options.mode == IntersectBedOptions::DIFF)\n {\n for (TRoiIter it = roiRecords.begin(); it != roiRecords.end(); ++it)\n if (overlap(*it, bedRecords.front()))\n back(it->data)[0] = '*'; \/\/ Mark as overlapping with BED.\n return;\n }\n\n \/\/ Get range of ROI records overlapping with BED record.\n TRoiIter rangeBegin = roiRecords.begin();\n TRoiIter rangeEnd = rangeBegin;\n for (; rangeEnd != roiRecords.end() && overlap(*rangeEnd, bedRecords.front()); ++rangeEnd)\n {\n if (options.verbosity >= 2)\n {\n std::cerr << \"ROI RECORD\\t\";\n writeRecord(std::cerr, *rangeEnd, seqan::Roi());\n }\n continue;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Create a result ROI from that depending on the configuration.\n \/\/ ------------------------------------------------------------------------\n\n \/\/ Compute the smallest begin position and the largest end position of BED and all ROI objects.\n TBedRecord const & bedRecord = bedRecords.front();\n int beginPos = bedRecord.beginPos;\n int endPos = bedRecord.endPos;\n if (options.verbosity >= 2)\n std::cerr << \"beginPos, endPos == \" << beginPos << \", \" << endPos << \"\\n\";\n for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)\n {\n if (options.verbosity >= 2)\n std::cerr << \"it->beginPos, it->endPos == \" << it->beginPos << \", \" << it->endPos << \"\\n\";\n beginPos = std::min(it->beginPos, beginPos);\n endPos = std::max(it->endPos, endPos);\n if (options.verbosity >= 2)\n std::cerr << \"beginPos, endPos == \" << beginPos << \", \" << endPos << \"\\n\";\n }\n\n \/\/ Create bitmap marking positions as connected\/covered.\n seqan::String connected;\n resize(connected, endPos - beginPos, false);\n updateConnectivity(connected, beginPos, bedRecord, rangeBegin, rangeEnd);\n\n \/\/ Create array with counts.\n seqan::String counts;\n resize(counts, endPos - beginPos, 0);\n for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)\n for (unsigned j = it->beginPos - beginPos, i = 0; i < length(it->count); ++i, ++j)\n counts[j] += it->count[i]; \/\/ TODO(holtgrew): Increment or simply set?\n\n \/\/ Write resulting intervals to output file.\n writeRois(connected, counts, beginPos, bedRecord);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::cleanRoiRecords()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::cleanRoiRecords()\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"cleanRoiRecords()\\n\";\n }\n\n while (!roiRecords.empty() && (bedRecords.empty() || roiRecords.front().endPos <= bedRecords.front().beginPos))\n {\n \/\/ Remove data from front ROI, write it out, remove it.\n if (options.mode == IntersectBedOptions::DIFF && back(roiRecords.front().data)[0] == '.')\n {\n clear(roiRecords.front().data);\n writeRecord(roiFileOut, roiRecords.front());\n }\n roiRecords.pop_front();\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::pushRoi()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::pushRoi(TRoiRecord const & roiRecord)\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"pushRoi()\\n\"\n << \" \";\n writeRecord(std::cerr, roiRecord, seqan::Roi());\n }\n\n \/\/ Handle contig transition, we can unconditionally update ref.\n if (roiRecord.ref != ref)\n finishContig();\n ref = roiRecord.ref;\n\n \/\/ Complete processing all BED records that cannot overlap with roiRecord. After removing each BED record, remove\n \/\/ all ROI records that do not overlap with first BED record any more.\n while (!empty(bedRecords) && bedRecords.front().endPos <= roiRecord.beginPos)\n {\n processFirstBedRecord();\n bedRecords.pop_front();\n cleanRoiRecords();\n }\n\n \/\/ Finally, register ROI records.\n roiRecords.push_back(roiRecord);\n \/\/ Mark ROI record as not touched yet. We do this using the data entry.\n appendValue(roiRecords.back().data, \".\");\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::finishContig()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::finishContig()\n{\n if (options.verbosity >= 2)\n std::cerr << \"finishContig()\\n\";\n\n while (!empty(bedRecords))\n {\n processFirstBedRecord();\n bedRecords.pop_front();\n }\n\n cleanRoiRecords();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::updateConnectivity()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::updateConnectivity(seqan::String & bitmap,\n int beginPos, \/\/ position of bitmap[0]\n seqan::BedRecord const & bedRecord,\n std::list::const_iterator const & rangeBegin,\n std::list::const_iterator const & rangeEnd)\n{\n if (options.verbosity >= 2)\n std::cerr << \"updateConnectivity()\\n\";\n\n typedef std::list::const_iterator TRoiIter;\n\n switch (options.mode)\n {\n case IntersectBedOptions::PROJECTION:\n \/\/ Mark whole BED record range as covered.\n for (int pos = bedRecord.beginPos; pos != bedRecord.endPos; ++pos)\n bitmap[pos - beginPos] = true;\n break;\n case IntersectBedOptions::INTERSECTION:\n \/\/ Mark intersection of BED record and ROI records as covered.\n for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)\n {\n for (int pos = it->beginPos; pos != it->endPos; ++pos)\n if (pos >= bedRecord.beginPos && pos < bedRecord.endPos)\n bitmap[pos - beginPos] = true;\n }\n break;\n case IntersectBedOptions::UNION:\n \/\/ Mark union of BED and ROI intervals as being covered.\n for (unsigned i = 0; i < length(bitmap); ++i)\n bitmap[i] = true;\n break;\n case IntersectBedOptions::DIFF:\n default:\n SEQAN_FAIL(\"Cannot reach here!\");\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::writeRois()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::writeRois(seqan::String const & bitmap,\n seqan::String const & counts,\n int beginPos, \/\/ position of bitmap[0] and counts[0]\n seqan::BedRecord const & bedRecord)\n{\n \/\/ We will build a string of ranges in bitmap\/counts for writing out. The bitmap is used depending on the\n \/\/ combination mode.\n typedef seqan::Pair TIntPair;\n seqan::String pairs;\n \/\/ We also generate the names of the new regions.\n seqan::StringSet names;\n\n switch (options.mode)\n {\n case IntersectBedOptions::PROJECTION:\n \/\/ Use BED range only.\n appendValue(pairs, TIntPair(bedRecord.beginPos - beginPos, bedRecord.endPos - beginPos));\n break;\n case IntersectBedOptions::INTERSECTION:\n \/\/ Search for 0\/1 and 1\/0 flanks.\n {\n bool state = bitmap[0];\n int lastFlank = 0;\n for (unsigned i = 1; i < length(bitmap); ++i)\n {\n if (state)\n {\n if (!bitmap[i]) \/\/ Found a 1\/0 flank.\n {\n appendValue(pairs, TIntPair(lastFlank, i));\n state = false;\n lastFlank = i;\n }\n }\n else\n {\n if (bitmap[i]) \/\/ Found a 0\/1 flank.\n {\n state = true;\n lastFlank = i;\n }\n }\n }\n if (state)\n appendValue(pairs, TIntPair(lastFlank, length(bitmap)));\n }\n break;\n case IntersectBedOptions::UNION:\n \/\/ Use whole range, including overlaps to the left of right.\n appendValue(pairs, TIntPair(0, length(counts)));\n break;\n case IntersectBedOptions::DIFF:\n SEQAN_FAIL(\"Difference does not implemented yet!\");\n break;\n default:\n SEQAN_FAIL(\"Cannot reach here!\");\n }\n\n if (options.verbosity >= 2)\n std::cerr << \"Adding \" << length(pairs) << \" for BED \" << bedRecord.name << \"\\n\";\n\n for (unsigned i = 0; i < length(pairs); ++i)\n {\n std::stringstream ss;\n ss << bedRecord.name << \"_\" << i;\n appendValue(names, ss.str());\n }\n\n seqan::RoiRecord record;\n for (unsigned i = 0; i < length(pairs); ++i)\n {\n clear(record);\n\n record.ref = bedRecord.ref;\n record.beginPos = beginPos + pairs[i].i1;\n record.endPos = beginPos + pairs[i].i2;\n record.len = record.endPos - record.beginPos;\n record.name = names[i];\n record.strand = bedRecord.strand;\n record.countMax = 0;\n resize(record.count, pairs[i].i2 - pairs[i].i1, 0);\n for (int k = 0, j = pairs[i].i1; j != pairs[i].i2; ++j, ++k)\n {\n record.countMax = std::max(record.countMax, (unsigned)counts[j]);\n record.count[k] = counts[j];\n }\n\n writeRecord(roiFileOut, record);\n }\n}\n\n[FIX] Use list member function empty instead of global empty function.\/\/ ==========================================================================\n\/\/ NGS: Regions of Interest Analysis\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2012-2013, Bernd Jagla, Institut Pasteur\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\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 Knut Reinert or the FU Berlin nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"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 KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Bernd Jagla \n\/\/ Author: Manuel Holtgrewe \n\/\/ ==========================================================================\n\n#include \"project_interval.h\"\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::pushBed()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::pushBed(TBedRecord const & bedRecord)\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"pushBed()\\n\"\n << \" \";\n writeRecord(std::cerr, bedRecord, seqan::Bed());\n }\n\n \/\/ Handle contig transition, we can unconditionally update rId.\n if (bedRecord.ref != ref)\n finishContig();\n ref = bedRecord.ref;\n\n \/\/ Register new BED record.\n bedRecords.push_back(bedRecord);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Function IntersectBed::writeEmptyBed()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::writeEmptyBed(seqan::BedRecord const & bedRecord)\n{\n seqan::RoiRecord roiRecord;\n roiRecord.ref = bedRecord.ref;\n roiRecord.beginPos = bedRecord.beginPos;\n roiRecord.endPos = bedRecord.endPos;\n roiRecord.strand = bedRecord.strand;\n roiRecord.name = bedRecord.name;\n roiRecord.len = roiRecord.endPos - roiRecord.beginPos;\n roiRecord.countMax = 0;\n for (int i = 0; i < (int)roiRecord.len; ++i)\n appendValue(roiRecord.count, 0);\n\n writeRecord(roiFileOut, roiRecord);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::processFirstBedRecord()\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Return true iff lhs and rhs overlap (both are BED or ROI records).\ntemplate \nbool overlap(TLeft const & lhs, TRight const & rhs)\n{\n return (rhs.beginPos < lhs.endPos) && (lhs.beginPos < rhs.endPos);\n}\n\nvoid IntersectBed::processFirstBedRecord()\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"processFirstBedRecord()\\n\";\n if (!bedRecords.empty())\n {\n std::cerr << \" \";\n writeRecord(std::cerr, bedRecords.front(), seqan::Bed());\n }\n }\n\n \/\/ When computing symmetric difference, we write out the BED record as ROI if there is no overlapping ROI record.\n if (options.mode == IntersectBedOptions::DIFF)\n {\n if (roiRecords.empty() || roiRecords.front().beginPos >= bedRecords.front().endPos)\n {\n writeEmptyBed(bedRecords.front());\n return;\n }\n }\n\n if (roiRecords.empty())\n return;\n\n \/\/ When in DIFF mode: Mark all ROI records overlapping with current front BED record as such and stop.\n typedef std::list::\/*const_*\/iterator TRoiIter;\n if (options.mode == IntersectBedOptions::DIFF)\n {\n for (TRoiIter it = roiRecords.begin(); it != roiRecords.end(); ++it)\n if (overlap(*it, bedRecords.front()))\n back(it->data)[0] = '*'; \/\/ Mark as overlapping with BED.\n return;\n }\n\n \/\/ Get range of ROI records overlapping with BED record.\n TRoiIter rangeBegin = roiRecords.begin();\n TRoiIter rangeEnd = rangeBegin;\n for (; rangeEnd != roiRecords.end() && overlap(*rangeEnd, bedRecords.front()); ++rangeEnd)\n {\n if (options.verbosity >= 2)\n {\n std::cerr << \"ROI RECORD\\t\";\n writeRecord(std::cerr, *rangeEnd, seqan::Roi());\n }\n continue;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Create a result ROI from that depending on the configuration.\n \/\/ ------------------------------------------------------------------------\n\n \/\/ Compute the smallest begin position and the largest end position of BED and all ROI objects.\n TBedRecord const & bedRecord = bedRecords.front();\n int beginPos = bedRecord.beginPos;\n int endPos = bedRecord.endPos;\n if (options.verbosity >= 2)\n std::cerr << \"beginPos, endPos == \" << beginPos << \", \" << endPos << \"\\n\";\n for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)\n {\n if (options.verbosity >= 2)\n std::cerr << \"it->beginPos, it->endPos == \" << it->beginPos << \", \" << it->endPos << \"\\n\";\n beginPos = std::min(it->beginPos, beginPos);\n endPos = std::max(it->endPos, endPos);\n if (options.verbosity >= 2)\n std::cerr << \"beginPos, endPos == \" << beginPos << \", \" << endPos << \"\\n\";\n }\n\n \/\/ Create bitmap marking positions as connected\/covered.\n seqan::String connected;\n resize(connected, endPos - beginPos, false);\n updateConnectivity(connected, beginPos, bedRecord, rangeBegin, rangeEnd);\n\n \/\/ Create array with counts.\n seqan::String counts;\n resize(counts, endPos - beginPos, 0);\n for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)\n for (unsigned j = it->beginPos - beginPos, i = 0; i < length(it->count); ++i, ++j)\n counts[j] += it->count[i]; \/\/ TODO(holtgrew): Increment or simply set?\n\n \/\/ Write resulting intervals to output file.\n writeRois(connected, counts, beginPos, bedRecord);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::cleanRoiRecords()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::cleanRoiRecords()\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"cleanRoiRecords()\\n\";\n }\n\n while (!roiRecords.empty() && (bedRecords.empty() || roiRecords.front().endPos <= bedRecords.front().beginPos))\n {\n \/\/ Remove data from front ROI, write it out, remove it.\n if (options.mode == IntersectBedOptions::DIFF && back(roiRecords.front().data)[0] == '.')\n {\n clear(roiRecords.front().data);\n writeRecord(roiFileOut, roiRecords.front());\n }\n roiRecords.pop_front();\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::pushRoi()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::pushRoi(TRoiRecord const & roiRecord)\n{\n if (options.verbosity >= 2)\n {\n std::cerr << \"pushRoi()\\n\"\n << \" \";\n writeRecord(std::cerr, roiRecord, seqan::Roi());\n }\n\n \/\/ Handle contig transition, we can unconditionally update ref.\n if (roiRecord.ref != ref)\n finishContig();\n ref = roiRecord.ref;\n\n \/\/ Complete processing all BED records that cannot overlap with roiRecord. After removing each BED record, remove\n \/\/ all ROI records that do not overlap with first BED record any more.\n while (!bedRecords.empty() && bedRecords.front().endPos <= roiRecord.beginPos)\n {\n processFirstBedRecord();\n bedRecords.pop_front();\n cleanRoiRecords();\n }\n\n \/\/ Finally, register ROI records.\n roiRecords.push_back(roiRecord);\n \/\/ Mark ROI record as not touched yet. We do this using the data entry.\n appendValue(roiRecords.back().data, \".\");\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::finishContig()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::finishContig()\n{\n if (options.verbosity >= 2)\n std::cerr << \"finishContig()\\n\";\n\n while (!bedRecords.empty())\n {\n processFirstBedRecord();\n bedRecords.pop_front();\n }\n\n cleanRoiRecords();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::updateConnectivity()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::updateConnectivity(seqan::String & bitmap,\n int beginPos, \/\/ position of bitmap[0]\n seqan::BedRecord const & bedRecord,\n std::list::const_iterator const & rangeBegin,\n std::list::const_iterator const & rangeEnd)\n{\n if (options.verbosity >= 2)\n std::cerr << \"updateConnectivity()\\n\";\n\n typedef std::list::const_iterator TRoiIter;\n\n switch (options.mode)\n {\n case IntersectBedOptions::PROJECTION:\n \/\/ Mark whole BED record range as covered.\n for (int pos = bedRecord.beginPos; pos != bedRecord.endPos; ++pos)\n bitmap[pos - beginPos] = true;\n break;\n case IntersectBedOptions::INTERSECTION:\n \/\/ Mark intersection of BED record and ROI records as covered.\n for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)\n {\n for (int pos = it->beginPos; pos != it->endPos; ++pos)\n if (pos >= bedRecord.beginPos && pos < bedRecord.endPos)\n bitmap[pos - beginPos] = true;\n }\n break;\n case IntersectBedOptions::UNION:\n \/\/ Mark union of BED and ROI intervals as being covered.\n for (unsigned i = 0; i < length(bitmap); ++i)\n bitmap[i] = true;\n break;\n case IntersectBedOptions::DIFF:\n default:\n SEQAN_FAIL(\"Cannot reach here!\");\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Member Functions IntersectBed::writeRois()\n\/\/ ----------------------------------------------------------------------------\n\nvoid IntersectBed::writeRois(seqan::String const & bitmap,\n seqan::String const & counts,\n int beginPos, \/\/ position of bitmap[0] and counts[0]\n seqan::BedRecord const & bedRecord)\n{\n \/\/ We will build a string of ranges in bitmap\/counts for writing out. The bitmap is used depending on the\n \/\/ combination mode.\n typedef seqan::Pair TIntPair;\n seqan::String pairs;\n \/\/ We also generate the names of the new regions.\n seqan::StringSet names;\n\n switch (options.mode)\n {\n case IntersectBedOptions::PROJECTION:\n \/\/ Use BED range only.\n appendValue(pairs, TIntPair(bedRecord.beginPos - beginPos, bedRecord.endPos - beginPos));\n break;\n case IntersectBedOptions::INTERSECTION:\n \/\/ Search for 0\/1 and 1\/0 flanks.\n {\n bool state = bitmap[0];\n int lastFlank = 0;\n for (unsigned i = 1; i < length(bitmap); ++i)\n {\n if (state)\n {\n if (!bitmap[i]) \/\/ Found a 1\/0 flank.\n {\n appendValue(pairs, TIntPair(lastFlank, i));\n state = false;\n lastFlank = i;\n }\n }\n else\n {\n if (bitmap[i]) \/\/ Found a 0\/1 flank.\n {\n state = true;\n lastFlank = i;\n }\n }\n }\n if (state)\n appendValue(pairs, TIntPair(lastFlank, length(bitmap)));\n }\n break;\n case IntersectBedOptions::UNION:\n \/\/ Use whole range, including overlaps to the left of right.\n appendValue(pairs, TIntPair(0, length(counts)));\n break;\n case IntersectBedOptions::DIFF:\n SEQAN_FAIL(\"Difference does not implemented yet!\");\n break;\n default:\n SEQAN_FAIL(\"Cannot reach here!\");\n }\n\n if (options.verbosity >= 2)\n std::cerr << \"Adding \" << length(pairs) << \" for BED \" << bedRecord.name << \"\\n\";\n\n for (unsigned i = 0; i < length(pairs); ++i)\n {\n std::stringstream ss;\n ss << bedRecord.name << \"_\" << i;\n appendValue(names, ss.str());\n }\n\n seqan::RoiRecord record;\n for (unsigned i = 0; i < length(pairs); ++i)\n {\n clear(record);\n\n record.ref = bedRecord.ref;\n record.beginPos = beginPos + pairs[i].i1;\n record.endPos = beginPos + pairs[i].i2;\n record.len = record.endPos - record.beginPos;\n record.name = names[i];\n record.strand = bedRecord.strand;\n record.countMax = 0;\n resize(record.count, pairs[i].i2 - pairs[i].i1, 0);\n for (int k = 0, j = pairs[i].i1; j != pairs[i].i2; ++j, ++k)\n {\n record.countMax = std::max(record.countMax, (unsigned)counts[j]);\n record.count[k] = counts[j];\n }\n\n writeRecord(roiFileOut, record);\n }\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"di\/Injectable.h\"\n#include \"dao\/poco\/PocoSQLLocationDao.h\"\n#include \"dao\/poco\/PocoDaoManager.h\"\n#include \"transaction\/TransactionManager.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace Poco::Data;\nusing namespace Poco::Data::Keywords;\nusing namespace BeeeOn;\n\nBEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLLocationDao)\nBEEEON_OBJECT_CASTABLE(LocationDao)\nBEEEON_OBJECT_REF(\"daoManager\", &PocoSQLLocationDao::setDaoManager)\nBEEEON_OBJECT_REF(\"transactionManager\", &PocoSQLLocationDao::setTransactionManager)\nBEEEON_OBJECT_REF(\"sqlLoader\", &PocoSQLLocationDao::setSQLLoader)\nBEEEON_OBJECT_HOOK(\"done\", &PocoSQLLocationDao::loadQueries)\nBEEEON_OBJECT_END(BeeeOn, PocoSQLLocationDao)\n\nPocoSQLLocationDao::PocoSQLLocationDao()\n{\n\tregisterQuery(m_queryCreate);\n\tregisterQuery(m_queryUpdate);\n\tregisterQuery(m_queryRemove);\n\tregisterQuery(m_queryFetchById);\n\tregisterQuery(m_queryFetchByIdAndGatewayId);\n\tregisterQuery(m_queryFetchByGatewayId);\n}\n\nvoid PocoSQLLocationDao::create(Location &location)\n{\n\tlocation.setId(LocationID::random());\n\tstring id(location.id().toString());\n\tstring name(location.name());\n\tstring gatewayID(location.gateway().id().toString());\n\n\tStatement sql = (session() << m_queryCreate(),\n\t\tuse(id, \"id\"),\n\t\tuse(name, \"name\"),\n\t\tuse(gatewayID, \"gateway_id\")\n\t);\n\n\texecute(sql);\n}\n\nbool PocoSQLLocationDao::fetch(Location &location)\n{\n\tassureHasId(location);\n\tstring id(location.id().toString());\n\n\tStatement sql = (session() << m_queryFetchById(),\n\t\tuse(id, \"id\")\n\t);\n\n\tif (execute(sql) == 0)\n\t\treturn false;\n\n\tRecordSet result(sql);\n\treturn parseSingle(result, location);\n}\n\nbool PocoSQLLocationDao::fetchFrom(Location &location, const Gateway &gateway)\n{\n\tassureHasId(location);\n\tassureHasId(gateway);\n\n\tstring id(location.id().toString());\n\tstring gatewayID(gateway.id().toString());\n\n\tStatement sql = (session() << m_queryFetchByIdAndGatewayId(),\n\t\tuse(id, \"id\"),\n\t\tuse(gatewayID, \"gateway_id\")\n\t);\n\n\tif (execute(sql) == 0)\n\t\treturn false;\n\n\tRecordSet result(sql);\n\treturn parseSingle(result, location);\n}\n\nvoid PocoSQLLocationDao::fetchBy(std::vector &locations,\n\t\tconst Gateway &gateway)\n{\n\tassureHasId(gateway);\n\n\tstring gatewayID(gateway.id().toString());\n\n\tStatement sql = (session() << m_queryFetchByGatewayId(),\n\t\tuse(gatewayID, \"gateway_id\")\n\t);\n\n\texecute(sql);\n\tRecordSet result(sql);\n\tparseMany(result, locations);\n}\n\nbool PocoSQLLocationDao::update(Location &location)\n{\n\tassureHasId(location);\n\tassureHasId(location.gateway());\n\n\tstring id(location.id().toString());\n\tstring name(location.name());\n\n\tStatement sql = (session() << m_queryUpdate(),\n\t\tuse(name, \"name\"),\n\t\tuse(id, \"id\")\n\t);\n\n\treturn execute(sql) > 0;\n}\n\nbool PocoSQLLocationDao::remove(const Location &location)\n{\n\tassureHasId(location);\n\tstring id(location.id().toString());\n\n\tStatement sql = (session() << m_queryRemove(),\n\t\tuse(id, \"id\")\n\t);\n\n\treturn execute(sql) > 0;\n}\n\nbool PocoSQLLocationDao::parseSingle(RecordSet &result, Location &location,\n\t\tconst string &prefix)\n{\n\tif (result.begin() == result.end())\n\t\treturn false;\n\n\treturn parseSingle(*result.begin(), location, prefix);\n}\n\nbool PocoSQLLocationDao::parseSingle(Row &result, Location &location,\n\t\tconst string &prefix)\n{\n\tif (hasColumn(result, prefix + \"id\"))\n\t\tlocation.setId(LocationID::parse(result[prefix + \"id\"]));\n\n\tlocation.setName(result[prefix + \"name\"]);\n\n\tGateway gateway(GatewayID::parse(result[prefix + \"gateway_id\"]));\n\tlocation.setGateway(gateway);\n\n\tmarkLoaded(location);\n\treturn true;\n}\n\nbool PocoSQLLocationDao::parseIfIDNotNull(Row &result, Location &location,\n\t\tconst string &prefix)\n{\n\tconst string id = emptyWhenNull(result[prefix + \"id\"]);\n\tif (id.empty())\n\t\treturn false;\n\n\tlocation.setId(LocationID::parse(id));\n\n\tif (hasColumn(result, prefix + \"name\"))\n\t\tlocation.setName(result[prefix + \"name\"]);\n\n\tmarkLoaded(location);\n\treturn true;\n}\nPocoSQLLocationDao: fix order of arguments to locations.update#include \n#include \n#include \n#include \n#include \n\n#include \"di\/Injectable.h\"\n#include \"dao\/poco\/PocoSQLLocationDao.h\"\n#include \"dao\/poco\/PocoDaoManager.h\"\n#include \"transaction\/TransactionManager.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace Poco::Data;\nusing namespace Poco::Data::Keywords;\nusing namespace BeeeOn;\n\nBEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLLocationDao)\nBEEEON_OBJECT_CASTABLE(LocationDao)\nBEEEON_OBJECT_REF(\"daoManager\", &PocoSQLLocationDao::setDaoManager)\nBEEEON_OBJECT_REF(\"transactionManager\", &PocoSQLLocationDao::setTransactionManager)\nBEEEON_OBJECT_REF(\"sqlLoader\", &PocoSQLLocationDao::setSQLLoader)\nBEEEON_OBJECT_HOOK(\"done\", &PocoSQLLocationDao::loadQueries)\nBEEEON_OBJECT_END(BeeeOn, PocoSQLLocationDao)\n\nPocoSQLLocationDao::PocoSQLLocationDao()\n{\n\tregisterQuery(m_queryCreate);\n\tregisterQuery(m_queryUpdate);\n\tregisterQuery(m_queryRemove);\n\tregisterQuery(m_queryFetchById);\n\tregisterQuery(m_queryFetchByIdAndGatewayId);\n\tregisterQuery(m_queryFetchByGatewayId);\n}\n\nvoid PocoSQLLocationDao::create(Location &location)\n{\n\tlocation.setId(LocationID::random());\n\tstring id(location.id().toString());\n\tstring name(location.name());\n\tstring gatewayID(location.gateway().id().toString());\n\n\tStatement sql = (session() << m_queryCreate(),\n\t\tuse(id, \"id\"),\n\t\tuse(name, \"name\"),\n\t\tuse(gatewayID, \"gateway_id\")\n\t);\n\n\texecute(sql);\n}\n\nbool PocoSQLLocationDao::fetch(Location &location)\n{\n\tassureHasId(location);\n\tstring id(location.id().toString());\n\n\tStatement sql = (session() << m_queryFetchById(),\n\t\tuse(id, \"id\")\n\t);\n\n\tif (execute(sql) == 0)\n\t\treturn false;\n\n\tRecordSet result(sql);\n\treturn parseSingle(result, location);\n}\n\nbool PocoSQLLocationDao::fetchFrom(Location &location, const Gateway &gateway)\n{\n\tassureHasId(location);\n\tassureHasId(gateway);\n\n\tstring id(location.id().toString());\n\tstring gatewayID(gateway.id().toString());\n\n\tStatement sql = (session() << m_queryFetchByIdAndGatewayId(),\n\t\tuse(id, \"id\"),\n\t\tuse(gatewayID, \"gateway_id\")\n\t);\n\n\tif (execute(sql) == 0)\n\t\treturn false;\n\n\tRecordSet result(sql);\n\treturn parseSingle(result, location);\n}\n\nvoid PocoSQLLocationDao::fetchBy(std::vector &locations,\n\t\tconst Gateway &gateway)\n{\n\tassureHasId(gateway);\n\n\tstring gatewayID(gateway.id().toString());\n\n\tStatement sql = (session() << m_queryFetchByGatewayId(),\n\t\tuse(gatewayID, \"gateway_id\")\n\t);\n\n\texecute(sql);\n\tRecordSet result(sql);\n\tparseMany(result, locations);\n}\n\nbool PocoSQLLocationDao::update(Location &location)\n{\n\tassureHasId(location);\n\tassureHasId(location.gateway());\n\n\tstring id(location.id().toString());\n\tstring name(location.name());\n\n\tStatement sql = (session() << m_queryUpdate(),\n\t\tuse(id, \"id\"),\n\t\tuse(name, \"name\")\n\t);\n\n\treturn execute(sql) > 0;\n}\n\nbool PocoSQLLocationDao::remove(const Location &location)\n{\n\tassureHasId(location);\n\tstring id(location.id().toString());\n\n\tStatement sql = (session() << m_queryRemove(),\n\t\tuse(id, \"id\")\n\t);\n\n\treturn execute(sql) > 0;\n}\n\nbool PocoSQLLocationDao::parseSingle(RecordSet &result, Location &location,\n\t\tconst string &prefix)\n{\n\tif (result.begin() == result.end())\n\t\treturn false;\n\n\treturn parseSingle(*result.begin(), location, prefix);\n}\n\nbool PocoSQLLocationDao::parseSingle(Row &result, Location &location,\n\t\tconst string &prefix)\n{\n\tif (hasColumn(result, prefix + \"id\"))\n\t\tlocation.setId(LocationID::parse(result[prefix + \"id\"]));\n\n\tlocation.setName(result[prefix + \"name\"]);\n\n\tGateway gateway(GatewayID::parse(result[prefix + \"gateway_id\"]));\n\tlocation.setGateway(gateway);\n\n\tmarkLoaded(location);\n\treturn true;\n}\n\nbool PocoSQLLocationDao::parseIfIDNotNull(Row &result, Location &location,\n\t\tconst string &prefix)\n{\n\tconst string id = emptyWhenNull(result[prefix + \"id\"]);\n\tif (id.empty())\n\t\treturn false;\n\n\tlocation.setId(LocationID::parse(id));\n\n\tif (hasColumn(result, prefix + \"name\"))\n\t\tlocation.setName(result[prefix + \"name\"]);\n\n\tmarkLoaded(location);\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/* Copyright 2007-2015 QReal Research Group\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 \"trikKitInterpreterCommon\/robotModel\/real\/parts\/shell.h\"\n\n#include \n\nusing namespace trik::robotModel::real::parts;\nusing namespace kitBase::robotModel;\n\nShell::Shell(const DeviceInfo &info, const PortInfo &port\n\t\t, utils::robotCommunication::TcpRobotCommunicator &tcpRobotCommunicator)\n\t: robotModel::parts::TrikShell(info, port)\n\t, mRobotCommunicator(tcpRobotCommunicator)\n{\n\tconnect(&mRobotCommunicator, &utils::robotCommunication::TcpRobotCommunicator::printText\n\t\t\t, this, &Shell::textPrinted);\n}\n\nvoid Shell::say(const QString &text)\n{\n\tconst QString pathToCommand = \":\/trikQts\/templates\/say.t\";\n\tconst QString directCommand = utils::InFile::readAll(pathToCommand)\n\t\t\t.replace(\"@@TEXT@@\", \"\\\"\" + text + \"\\\"\") + \"script.run();\";\n\n\tmRobotCommunicator.runDirectCommand(directCommand);\n}\n\nvoid Shell::runCommand(const QString &command)\n{\n\tconst QString pathToCommand = \":\/trikQts\/templates\/system.t\";\n\tconst QString directCommand = utils::InFile::readAll(pathToCommand)\n\t\t\t.replace(\"@@COMMAND@@\", command) + \"script.run();\";\n\n\tmRobotCommunicator.runDirectCommand(directCommand);\n}\n\nvoid Shell::runCode(const QString &code)\n{\n\tmRobotCommunicator.runDirectCommand(code);\n}\n\nvoid Shell::writeToFile(const QString &filePath, const QString &text)\n{\n\tconst QString pathToCommand = \":\/trikQts\/templates\/files\/writeFile.t\";\n\tconst QString directCommand = utils::InFile::readAll(pathToCommand)\n\t\t\t.replace(\"@@FILE@@\", filePath).replace(\"@@TEXT@@\", \"\\\"\" + text + \"\\\"\") + \"script.run();\";\n\n\tmRobotCommunicator.runDirectCommand(directCommand);\n}\n\nvoid Shell::removeFile(const QString &filePath)\n{\n\tconst QString pathToCommand = \":\/trikQts\/templates\/files\/removeFile.t\";\n\tconst QString directCommand = utils::InFile::readAll(pathToCommand)\n\t\t\t.replace(\"@@FILE@@\", filePath) + \"script.run();\";\n\n\tmRobotCommunicator.runDirectCommand(directCommand);\n}\n\nvoid Shell::print(const QString &text)\n{\n\tconst QString pathToCommand = \":\/trikQts\/templates\/functions\/print.t\";\n\tconst QString directCommand = utils::InFile::readAll(pathToCommand)\n\t\t\t.replace(\"@@ARGUMENT@@\", \"\\\"\" + text + \"\\\"\") + \";script.run();\";\n\n\tmRobotCommunicator.runDirectCommand(directCommand);\n}\n\nvoid Shell::initVideoStreaming(QString qual, QString blackwhite)\n{\n\tconst QString shellToExecute = QString(\"\\\"\/etc\/init.d\/mjpg-encoder-ov7670 start --jpeg-qual \") + qual +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tQString(\" --white-black \") + blackwhite + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tQString(\" && \/etc\/init.d\/mjpg-streamer-ov7670.sh start\\\"\");\n\t runCommand(shellToExecute);\n}\nJpgEncoder: unnecessary duplicate file deleted<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief cap constraint\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"CapConstraint.h\"\n#include \"Utils\/transactions.h\"\n#include \"VocBase\/document-collection.h\"\n#include \"VocBase\/transaction.h\"\n\nusing namespace triagens::arango;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- class CapConstraint\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief minimum size\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint64_t const CapConstraint::MinSize = 16384;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\nCapConstraint::CapConstraint (TRI_idx_iid_t iid,\n TRI_document_collection_t* collection,\n size_t count,\n int64_t size)\n : Index(iid, std::vector()),\n _collection(collection),\n _count(count),\n _size(static_cast(size)) {\n\n initialize();\n}\n\nCapConstraint::~CapConstraint () {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n \nsize_t CapConstraint::memory () const {\n return 0;\n}\n\ntriagens::basics::Json CapConstraint::toJson (TRI_memory_zone_t* zone) const {\n auto json = Index::toJson(zone);\n\n json(\"size\", triagens::basics::Json(zone, static_cast(_count)))\n (\"byteSize\", triagens::basics::Json(zone, static_cast(_size)));\n\n return json;\n}\n \nint CapConstraint::insert (TRI_doc_mptr_t const*, \n bool) {\n return TRI_ERROR_NO_ERROR;\n}\n \nint CapConstraint::remove (TRI_doc_mptr_t const*, \n bool) {\n return TRI_ERROR_NO_ERROR;\n}\n \nint CapConstraint::postInsert (TRI_transaction_collection_t* trxCollection, \n TRI_doc_mptr_t const*) {\n TRI_ASSERT(_count > 0 || _size > 0);\n\n return apply(trxCollection->_collection->_collection, trxCollection);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief initialize the cap constraint\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint CapConstraint::initialize () {\n TRI_ASSERT(_count > 0 || _size > 0);\n\n TRI_headers_t* headers = _collection->_headersPtr; \/\/ ONLY IN INDEX (CAP)\n int64_t currentCount = static_cast(headers->count());\n int64_t currentSize = headers->size();\n\n if ((_count > 0 && currentCount <= _count) &&\n (_size > 0 && currentSize <= _size)) {\n \/\/ nothing to do\n return TRI_ERROR_NO_ERROR;\n }\n else {\n TRI_vocbase_t* vocbase = _collection->_vocbase;\n TRI_voc_cid_t cid = _collection->_info._cid;\n\n triagens::arango::SingleCollectionWriteTransaction trx(new triagens::arango::StandaloneTransactionContext(), vocbase, cid);\n trx.addHint(TRI_TRANSACTION_HINT_LOCK_NEVER, false);\n trx.addHint(TRI_TRANSACTION_HINT_NO_BEGIN_MARKER, false);\n trx.addHint(TRI_TRANSACTION_HINT_NO_ABORT_MARKER, false);\n trx.addHint(TRI_TRANSACTION_HINT_SINGLE_OPERATION, false); \/\/ this is actually not true, but necessary to create trx id 0\n\n int res = trx.begin();\n\n if (res != TRI_ERROR_NO_ERROR) {\n return res;\n }\n\n TRI_transaction_collection_t* trxCollection = trx.trxCollection();\n res = apply(_collection, trxCollection);\n\n res = trx.finish(res);\n\n return res;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief apply the cap constraint for the collection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint CapConstraint::apply (TRI_document_collection_t* document,\n TRI_transaction_collection_t* trxCollection) {\n TRI_headers_t* headers = document->_headersPtr; \/\/ PROTECTED by trx in trxCollection\n int64_t currentCount = static_cast(headers->count());\n int64_t currentSize = headers->size();\n\n int res = TRI_ERROR_NO_ERROR;\n\n \/\/ delete while at least one of the constraints is still violated\n while ((_count > 0 && currentCount > _count) ||\n (_size > 0 && currentSize > _size)) {\n TRI_doc_mptr_t* oldest = headers->front();\n\n if (oldest != nullptr) {\n TRI_ASSERT(oldest->getDataPtr() != nullptr); \/\/ ONLY IN INDEX, PROTECTED by RUNTIME\n size_t oldSize = ((TRI_df_marker_t*) (oldest->getDataPtr()))->_size; \/\/ ONLY IN INDEX, PROTECTED by RUNTIME\n\n TRI_ASSERT(oldSize > 0);\n\n if (trxCollection != nullptr) {\n res = TRI_DeleteDocumentDocumentCollection(trxCollection, nullptr, oldest);\n\n if (res != TRI_ERROR_NO_ERROR) {\n LOG_WARNING(\"cannot cap collection: %s\", TRI_errno_string(res));\n break;\n }\n }\n else {\n headers->unlink(oldest);\n }\n\n currentCount--;\n currentSize -= (int64_t) oldSize;\n }\n else {\n \/\/ we should not get here\n LOG_WARNING(\"logic error in %s\", __FUNCTION__);\n break;\n }\n }\n\n return res;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\nfixed cap constraints\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief cap constraint\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"CapConstraint.h\"\n#include \"Utils\/transactions.h\"\n#include \"VocBase\/document-collection.h\"\n#include \"VocBase\/transaction.h\"\n\nusing namespace triagens::arango;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- class CapConstraint\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief minimum size\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint64_t const CapConstraint::MinSize = 16384;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\nCapConstraint::CapConstraint (TRI_idx_iid_t iid,\n TRI_document_collection_t* collection,\n size_t count,\n int64_t size)\n : Index(iid, std::vector()),\n _collection(collection),\n _count(count),\n _size(static_cast(size)) {\n\n initialize();\n}\n\nCapConstraint::~CapConstraint () {\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n \nsize_t CapConstraint::memory () const {\n return 0;\n}\n\ntriagens::basics::Json CapConstraint::toJson (TRI_memory_zone_t* zone) const {\n auto json = Index::toJson(zone);\n\n json(\"size\", triagens::basics::Json(zone, static_cast(_count)))\n (\"byteSize\", triagens::basics::Json(zone, static_cast(_size)));\n\n return json;\n}\n \nint CapConstraint::insert (TRI_doc_mptr_t const* doc, \n bool) {\n if (_size > 0) {\n \/\/ there is a size restriction\n auto marker = static_cast(doc->getDataPtr()); \/\/ ONLY IN INDEX, PROTECTED by RUNTIME\n\n \/\/ check if the document would be too big\n if (static_cast(marker->_size) > _size) {\n return TRI_ERROR_ARANGO_DOCUMENT_TOO_LARGE;\n }\n }\n\n return TRI_ERROR_NO_ERROR;\n}\n \nint CapConstraint::remove (TRI_doc_mptr_t const*, \n bool) {\n return TRI_ERROR_NO_ERROR;\n}\n \nint CapConstraint::postInsert (TRI_transaction_collection_t* trxCollection, \n TRI_doc_mptr_t const*) {\n TRI_ASSERT(_count > 0 || _size > 0);\n\n return apply(trxCollection->_collection->_collection, trxCollection);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief initialize the cap constraint\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint CapConstraint::initialize () {\n TRI_ASSERT(_count > 0 || _size > 0);\n\n TRI_headers_t* headers = _collection->_headersPtr; \/\/ ONLY IN INDEX (CAP)\n int64_t currentCount = static_cast(headers->count());\n int64_t currentSize = headers->size();\n\n if ((_count > 0 && currentCount <= _count) &&\n (_size > 0 && currentSize <= _size)) {\n \/\/ nothing to do\n return TRI_ERROR_NO_ERROR;\n }\n else {\n TRI_vocbase_t* vocbase = _collection->_vocbase;\n TRI_voc_cid_t cid = _collection->_info._cid;\n\n triagens::arango::SingleCollectionWriteTransaction trx(new triagens::arango::StandaloneTransactionContext(), vocbase, cid);\n trx.addHint(TRI_TRANSACTION_HINT_LOCK_NEVER, false);\n trx.addHint(TRI_TRANSACTION_HINT_NO_BEGIN_MARKER, false);\n trx.addHint(TRI_TRANSACTION_HINT_NO_ABORT_MARKER, false);\n trx.addHint(TRI_TRANSACTION_HINT_SINGLE_OPERATION, false); \/\/ this is actually not true, but necessary to create trx id 0\n\n int res = trx.begin();\n\n if (res != TRI_ERROR_NO_ERROR) {\n return res;\n }\n\n TRI_transaction_collection_t* trxCollection = trx.trxCollection();\n res = apply(_collection, trxCollection);\n\n res = trx.finish(res);\n\n return res;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief apply the cap constraint for the collection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint CapConstraint::apply (TRI_document_collection_t* document,\n TRI_transaction_collection_t* trxCollection) {\n TRI_headers_t* headers = document->_headersPtr; \/\/ PROTECTED by trx in trxCollection\n int64_t currentCount = static_cast(headers->count());\n int64_t currentSize = headers->size();\n\n int res = TRI_ERROR_NO_ERROR;\n\n \/\/ delete while at least one of the constraints is still violated\n while ((_count > 0 && currentCount > _count) ||\n (_size > 0 && currentSize > _size)) {\n TRI_doc_mptr_t* oldest = headers->front();\n\n if (oldest != nullptr) {\n TRI_ASSERT(oldest->getDataPtr() != nullptr); \/\/ ONLY IN INDEX, PROTECTED by RUNTIME\n size_t oldSize = ((TRI_df_marker_t*) (oldest->getDataPtr()))->_size; \/\/ ONLY IN INDEX, PROTECTED by RUNTIME\n\n TRI_ASSERT(oldSize > 0);\n\n if (trxCollection != nullptr) {\n res = TRI_DeleteDocumentDocumentCollection(trxCollection, nullptr, oldest);\n\n if (res != TRI_ERROR_NO_ERROR) {\n LOG_WARNING(\"cannot cap collection: %s\", TRI_errno_string(res));\n break;\n }\n }\n else {\n headers->unlink(oldest);\n }\n\n currentCount--;\n currentSize -= (int64_t) oldSize;\n }\n else {\n \/\/ we should not get here\n LOG_WARNING(\"logic error in %s\", __FUNCTION__);\n break;\n }\n }\n\n return res;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: systemshell.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:56: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 _SYSTEMSHELL_HXX_\n#include \"systemshell.hxx\"\n#endif\n\n#include \"osl\/module.hxx\"\n\nconst rtl::OUString SYM_ADD_TO_RECENTLY_USED_FILE_LIST = rtl::OUString::createFromAscii(\"add_to_recently_used_file_list\");\nconst rtl::OUString LIB_RECENT_FILE = rtl::OUString::createFromAscii(\"librecentfile.so\");\n\nnamespace SystemShell {\n\n typedef void (*PFUNC_ADD_TO_RECENTLY_USED_LIST)(const rtl::OUString&, const rtl::OUString&);\n\n \/\/##############################\n rtl::OUString get_absolute_library_url(const rtl::OUString& lib_name)\n {\n rtl::OUString url;\n if (osl::Module::getUrlFromAddress(reinterpret_cast(AddToRecentDocumentList), url))\n {\n sal_Int32 index = url.lastIndexOf('\/');\n url = url.copy(0, index + 1);\n url += LIB_RECENT_FILE;\n }\n return url;\n }\n\n \/\/##############################\n void AddToRecentDocumentList(const rtl::OUString& aFileUrl, const rtl::OUString& aMimeType)\n {\n rtl::OUString librecentfile_url = get_absolute_library_url(LIB_RECENT_FILE);\n\n if (librecentfile_url.getLength())\n {\n osl::Module module(librecentfile_url);\n\n if (module.is())\n {\n \/\/ convert from reinterpret_cast\n \/\/ not allowed in gcc 3.3 without permissive.\n PFUNC_ADD_TO_RECENTLY_USED_LIST add_to_recently_used_file_list =\n reinterpret_cast(module.getFunctionSymbol(SYM_ADD_TO_RECENTLY_USED_FILE_LIST));\n\n if (add_to_recently_used_file_list)\n add_to_recently_used_file_list(aFileUrl, aMimeType);\n }\n }\n }\n\n} \/\/ namespace SystemShell\n\nINTEGRATION: CWS warnings01 (1.5.14); FILE MERGED 2005\/10\/26 15:08:25 pl 1.5.14.1: #i55991# remove warnings for solaris platform\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: systemshell.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 14:20:23 $\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 _SYSTEMSHELL_HXX_\n#include \"systemshell.hxx\"\n#endif\n\n#include \"osl\/module.hxx\"\n\nconst rtl::OUString SYM_ADD_TO_RECENTLY_USED_FILE_LIST = rtl::OUString::createFromAscii(\"add_to_recently_used_file_list\");\nconst rtl::OUString LIB_RECENT_FILE = rtl::OUString::createFromAscii(\"librecentfile.so\");\n\nnamespace SystemShell {\n\n typedef void (*PFUNC_ADD_TO_RECENTLY_USED_LIST)(const rtl::OUString&, const rtl::OUString&);\n\n \/\/##############################\n rtl::OUString get_absolute_library_url(const rtl::OUString& \/*lib_name*\/)\n {\n rtl::OUString url;\n if (osl::Module::getUrlFromAddress(reinterpret_cast(AddToRecentDocumentList), url))\n {\n sal_Int32 index = url.lastIndexOf('\/');\n url = url.copy(0, index + 1);\n url += LIB_RECENT_FILE;\n }\n return url;\n }\n\n \/\/##############################\n void AddToRecentDocumentList(const rtl::OUString& aFileUrl, const rtl::OUString& aMimeType)\n {\n rtl::OUString librecentfile_url = get_absolute_library_url(LIB_RECENT_FILE);\n\n if (librecentfile_url.getLength())\n {\n osl::Module module(librecentfile_url);\n\n if (module.is())\n {\n \/\/ convert from reinterpret_cast\n \/\/ not allowed in gcc 3.3 without permissive.\n PFUNC_ADD_TO_RECENTLY_USED_LIST add_to_recently_used_file_list =\n reinterpret_cast(module.getFunctionSymbol(SYM_ADD_TO_RECENTLY_USED_FILE_LIST));\n\n if (add_to_recently_used_file_list)\n add_to_recently_used_file_list(aFileUrl, aMimeType);\n }\n }\n }\n\n} \/\/ namespace SystemShell\n\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\n#include \n#include \n#include \n\nusing namespace Tp;\n\nclass TestContactSearchChan : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactSearchChan(QObject *parent = 0)\n : Test(parent),\n mConnService(0), mBaseConnService(0),\n mChan1Service(0)\n { }\n\nprotected Q_SLOTS:\n void onSearchStateChanged(Tp::ChannelContactSearchState state, const QString &errorName,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &details);\n void onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &result);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testContactSearch();\n void testContactSearchEmptyResult();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n ExampleEchoConnection *mConnService;\n TpBaseConnection *mBaseConnService;\n TpHandleRepoIface *mContactRepo;\n\n QString mConnName;\n QString mConnPath;\n ConnectionPtr mConn;\n ContactSearchChannelPtr mChan;\n ContactSearchChannelPtr mChan1;\n ContactSearchChannelPtr mChan2;\n\n QString mChan1Path;\n TpTestsContactSearchChannel *mChan1Service;\n QString mChan2Path;\n TpTestsContactSearchChannel *mChan2Service;\n\n ContactSearchChannel::SearchResult mSearchResult;\n\n struct SearchStateChangeInfo\n {\n SearchStateChangeInfo(ChannelContactSearchState state, const QString &errorName,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &details)\n : state(state), errorName(errorName), details(details)\n {\n }\n\n ChannelContactSearchState state;\n QString errorName;\n ContactSearchChannel::SearchStateChangeDetails details;\n };\n QList mSearchStateChangeInfoList;\n};\n\nvoid TestContactSearchChan::onSearchStateChanged(Tp::ChannelContactSearchState state,\n const QString &errorName,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &details)\n{\n mSearchStateChangeInfoList.append(SearchStateChangeInfo(state, errorName, details));\n mLoop->exit(0);\n}\n\nvoid TestContactSearchChan::onSearchResultReceived(\n const Tp::ContactSearchChannel::SearchResult &result)\n{\n QCOMPARE(mChan->searchState(), ChannelContactSearchStateInProgress);\n mSearchResult = result;\n mLoop->exit(0);\n}\n\nvoid TestContactSearchChan::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contact-search-chan\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n gchar *name;\n gchar *connPath;\n GError *error = 0;\n\n mConnService = EXAMPLE_ECHO_CONNECTION(g_object_new(\n EXAMPLE_TYPE_ECHO_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"example\",\n NULL));\n QVERIFY(mConnService != 0);\n mBaseConnService = TP_BASE_CONNECTION(mConnService);\n QVERIFY(mBaseConnService != 0);\n\n QVERIFY(tp_base_connection_register(mBaseConnService,\n \"example\", &name, &connPath, &error));\n QVERIFY(error == 0);\n\n QVERIFY(name != 0);\n QVERIFY(connPath != 0);\n\n mConnName = QLatin1String(name);\n mConnPath = QLatin1String(connPath);\n\n g_free(name);\n g_free(connPath);\n\n mConn = Connection::create(mConnName, mConnPath,\n ChannelFactory::create(QDBusConnection::sessionBus()),\n ContactFactory::create());\n QCOMPARE(mConn->isReady(), false);\n\n QVERIFY(connect(mConn->requestConnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mConn->isReady(), true);\n QCOMPARE(static_cast(mConn->status()),\n static_cast(Connection::StatusConnected));\n\n QByteArray chan1Path;\n mChan1Path = mConnPath + QLatin1String(\"\/ContactSearchChannel\/1\");\n chan1Path = mChan1Path.toAscii();\n mChan1Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new(\n TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL,\n \"connection\", mConnService,\n \"object-path\", chan1Path.data(),\n NULL));\n\n QByteArray chan2Path;\n mChan2Path = mConnPath + QLatin1String(\"\/ContactSearchChannel\/2\");\n chan2Path = mChan2Path.toAscii();\n mChan2Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new(\n TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL,\n \"connection\", mConnService,\n \"object-path\", chan2Path.data(),\n NULL));\n}\n\nvoid TestContactSearchChan::init()\n{\n initImpl();\n mSearchResult.clear();\n mSearchStateChangeInfoList.clear();\n}\n\nvoid TestContactSearchChan::testContactSearch()\n{\n mChan1 = ContactSearchChannel::create(mConn, mChan1Path, QVariantMap());\n mChan = mChan1;\n QVERIFY(connect(mChan1->becomeReady(ContactSearchChannel::FeatureCore),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mChan1->isReady(), true);\n\n QCOMPARE(mChan1->searchState(), ChannelContactSearchStateNotStarted);\n QCOMPARE(mChan1->limit(), static_cast(0));\n QCOMPARE(mChan1->availableSearchKeys().isEmpty(), false);\n QCOMPARE(mChan1->availableSearchKeys().count(), 1);\n QCOMPARE(mChan1->availableSearchKeys().first(), QLatin1String(\"employer\"));\n QCOMPARE(mChan1->server(), QLatin1String(\"characters.shakespeare.lit\"));\n\n QVERIFY(connect(mChan1.data(),\n SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &)),\n SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &))));\n QVERIFY(connect(mChan1.data(),\n SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)),\n SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &))));\n\n mChan1->search(QLatin1String(\"employer\"), QLatin1String(\"Collabora\"));\n while (mChan1->searchState() != ChannelContactSearchStateCompleted) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(mSearchStateChangeInfoList.count(), 2);\n SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0);\n QCOMPARE(info.state, ChannelContactSearchStateInProgress);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"in progress\"));\n\n info = mSearchStateChangeInfoList.at(1);\n QCOMPARE(info.state, ChannelContactSearchStateCompleted);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"completed\"));\n\n QCOMPARE(mSearchResult.isEmpty(), false);\n QCOMPARE(mSearchResult.size(), 3);\n\n QStringList expectedIds;\n expectedIds << QLatin1String(\"oggis\") << QLatin1String(\"andrunko\") <<\n QLatin1String(\"wjt\");\n expectedIds.sort();\n QStringList expectedFns;\n expectedFns << QLatin1String(\"Olli Salli\") << QLatin1String(\"Andre Moreira Magalhaes\") <<\n QLatin1String(\"Will Thompson\");\n expectedFns.sort();\n QStringList ids;\n QStringList fns;\n for (ContactSearchChannel::SearchResult::const_iterator it = mSearchResult.constBegin();\n it != mSearchResult.constEnd();\n ++it)\n {\n QCOMPARE(it.key().isNull(), false);\n ids << it.key()->id();\n QCOMPARE(it.value().isValid(), true);\n QCOMPARE(it.value().allFields().isEmpty(), false);\n Q_FOREACH (const ContactInfoField &contactInfo, it.value().allFields()) {\n QCOMPARE(contactInfo.fieldName, QLatin1String(\"fn\"));\n fns.append(contactInfo.fieldValue.first());\n }\n }\n ids.sort();\n QCOMPARE(ids, expectedIds);\n fns.sort();\n QCOMPARE(fns, expectedFns);\n\n mChan1.reset();\n}\n\nvoid TestContactSearchChan::testContactSearchEmptyResult()\n{\n mChan2 = ContactSearchChannel::create(mConn, mChan2Path, QVariantMap());\n mChan = mChan2;\n QVERIFY(connect(mChan2->becomeReady(ContactSearchChannel::FeatureCore),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mChan2->isReady(), true);\n\n QCOMPARE(mChan2->searchState(), ChannelContactSearchStateNotStarted);\n QCOMPARE(mChan2->limit(), static_cast(0));\n QCOMPARE(mChan2->availableSearchKeys().isEmpty(), false);\n QCOMPARE(mChan2->availableSearchKeys().count(), 1);\n QCOMPARE(mChan2->availableSearchKeys().first(), QLatin1String(\"employer\"));\n QCOMPARE(mChan2->server(), QLatin1String(\"characters.shakespeare.lit\"));\n\n QVERIFY(connect(mChan2.data(),\n SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &)),\n SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &))));\n QVERIFY(connect(mChan2.data(),\n SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)),\n SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &))));\n\n ContactSearchMap searchTerms;\n searchTerms.insert(QLatin1String(\"employer\"), QLatin1String(\"FooBar\"));\n mChan2->search(searchTerms);\n while (mChan2->searchState() != ChannelContactSearchStateCompleted) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(mSearchResult.isEmpty(), true);\n\n QCOMPARE(mSearchStateChangeInfoList.count(), 2);\n SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0);\n QCOMPARE(info.state, ChannelContactSearchStateInProgress);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"in progress\"));\n\n info = mSearchStateChangeInfoList.at(1);\n QCOMPARE(info.state, ChannelContactSearchStateCompleted);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"completed\"));\n\n mChan2.reset();\n}\n\nvoid TestContactSearchChan::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactSearchChan::cleanupTestCase()\n{\n if (mConn) {\n \/\/ Disconnect and wait for the readiness change\n QVERIFY(connect(mConn->requestDisconnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n\n if (mConn->isValid()) {\n QVERIFY(connect(mConn.data(),\n SIGNAL(invalidated(Tp::DBusProxy *,\n const QString &, const QString &)),\n mLoop,\n SLOT(quit())));\n QCOMPARE(mLoop->exec(), 0);\n }\n }\n\n if (mChan1Service != 0) {\n g_object_unref(mChan1Service);\n mChan1Service = 0;\n }\n\n if (mChan2Service != 0) {\n g_object_unref(mChan2Service);\n mChan2Service = 0;\n }\n\n if (mConnService != 0) {\n mBaseConnService = 0;\n g_object_unref(mConnService);\n mConnService = 0;\n }\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactSearchChan)\n#include \"_gen\/chan-contact-search.cpp.moc.hpp\"\nchan-contact-search test: Test that the pending operation returned from search only finishes when the state changes.#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\n#include \n#include \n#include \n\nusing namespace Tp;\n\nclass TestContactSearchChan : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactSearchChan(QObject *parent = 0)\n : Test(parent),\n mConnService(0), mBaseConnService(0),\n mChan1Service(0), mSearchReturned(false)\n { }\n\nprotected Q_SLOTS:\n void onSearchStateChanged(Tp::ChannelContactSearchState state, const QString &errorName,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &details);\n void onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &result);\n void onSearchReturned(Tp::PendingOperation *op);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testContactSearch();\n void testContactSearchEmptyResult();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n ExampleEchoConnection *mConnService;\n TpBaseConnection *mBaseConnService;\n TpHandleRepoIface *mContactRepo;\n\n QString mConnName;\n QString mConnPath;\n ConnectionPtr mConn;\n ContactSearchChannelPtr mChan;\n ContactSearchChannelPtr mChan1;\n ContactSearchChannelPtr mChan2;\n\n QString mChan1Path;\n TpTestsContactSearchChannel *mChan1Service;\n QString mChan2Path;\n TpTestsContactSearchChannel *mChan2Service;\n\n ContactSearchChannel::SearchResult mSearchResult;\n bool mSearchReturned;\n\n struct SearchStateChangeInfo\n {\n SearchStateChangeInfo(ChannelContactSearchState state, const QString &errorName,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &details)\n : state(state), errorName(errorName), details(details)\n {\n }\n\n ChannelContactSearchState state;\n QString errorName;\n ContactSearchChannel::SearchStateChangeDetails details;\n };\n QList mSearchStateChangeInfoList;\n};\n\nvoid TestContactSearchChan::onSearchStateChanged(Tp::ChannelContactSearchState state,\n const QString &errorName,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &details)\n{\n mSearchStateChangeInfoList.append(SearchStateChangeInfo(state, errorName, details));\n mLoop->exit(0);\n}\n\nvoid TestContactSearchChan::onSearchResultReceived(\n const Tp::ContactSearchChannel::SearchResult &result)\n{\n QCOMPARE(mChan->searchState(), ChannelContactSearchStateInProgress);\n mSearchResult = result;\n mLoop->exit(0);\n}\n\nvoid TestContactSearchChan::onSearchReturned(Tp::PendingOperation *op)\n{\n QCOMPARE(op->isError(), false);\n QVERIFY(mChan->searchState() != ChannelContactSearchStateNotStarted);\n mSearchReturned = true;\n mLoop->exit(0);\n}\n\nvoid TestContactSearchChan::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contact-search-chan\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n gchar *name;\n gchar *connPath;\n GError *error = 0;\n\n mConnService = EXAMPLE_ECHO_CONNECTION(g_object_new(\n EXAMPLE_TYPE_ECHO_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"example\",\n NULL));\n QVERIFY(mConnService != 0);\n mBaseConnService = TP_BASE_CONNECTION(mConnService);\n QVERIFY(mBaseConnService != 0);\n\n QVERIFY(tp_base_connection_register(mBaseConnService,\n \"example\", &name, &connPath, &error));\n QVERIFY(error == 0);\n\n QVERIFY(name != 0);\n QVERIFY(connPath != 0);\n\n mConnName = QLatin1String(name);\n mConnPath = QLatin1String(connPath);\n\n g_free(name);\n g_free(connPath);\n\n mConn = Connection::create(mConnName, mConnPath,\n ChannelFactory::create(QDBusConnection::sessionBus()),\n ContactFactory::create());\n QCOMPARE(mConn->isReady(), false);\n\n QVERIFY(connect(mConn->requestConnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mConn->isReady(), true);\n QCOMPARE(static_cast(mConn->status()),\n static_cast(Connection::StatusConnected));\n\n QByteArray chan1Path;\n mChan1Path = mConnPath + QLatin1String(\"\/ContactSearchChannel\/1\");\n chan1Path = mChan1Path.toAscii();\n mChan1Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new(\n TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL,\n \"connection\", mConnService,\n \"object-path\", chan1Path.data(),\n NULL));\n\n QByteArray chan2Path;\n mChan2Path = mConnPath + QLatin1String(\"\/ContactSearchChannel\/2\");\n chan2Path = mChan2Path.toAscii();\n mChan2Service = TP_TESTS_CONTACT_SEARCH_CHANNEL(g_object_new(\n TP_TESTS_TYPE_CONTACT_SEARCH_CHANNEL,\n \"connection\", mConnService,\n \"object-path\", chan2Path.data(),\n NULL));\n}\n\nvoid TestContactSearchChan::init()\n{\n initImpl();\n mSearchResult.clear();\n mSearchStateChangeInfoList.clear();\n mSearchReturned = false;\n}\n\nvoid TestContactSearchChan::testContactSearch()\n{\n mChan1 = ContactSearchChannel::create(mConn, mChan1Path, QVariantMap());\n mChan = mChan1;\n QVERIFY(connect(mChan1->becomeReady(ContactSearchChannel::FeatureCore),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mChan1->isReady(), true);\n\n QCOMPARE(mChan1->searchState(), ChannelContactSearchStateNotStarted);\n QCOMPARE(mChan1->limit(), static_cast(0));\n QCOMPARE(mChan1->availableSearchKeys().isEmpty(), false);\n QCOMPARE(mChan1->availableSearchKeys().count(), 1);\n QCOMPARE(mChan1->availableSearchKeys().first(), QLatin1String(\"employer\"));\n QCOMPARE(mChan1->server(), QLatin1String(\"characters.shakespeare.lit\"));\n\n QVERIFY(connect(mChan1.data(),\n SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &)),\n SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &))));\n QVERIFY(connect(mChan1.data(),\n SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)),\n SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &))));\n\n QVERIFY(connect(mChan1->search(QLatin1String(\"employer\"), QLatin1String(\"Collabora\")),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(onSearchReturned(Tp::PendingOperation *))));\n while (!mSearchReturned) {\n QCOMPARE(mLoop->exec(), 0);\n }\n while (mChan1->searchState() != ChannelContactSearchStateCompleted) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(mSearchReturned, true);\n\n QCOMPARE(mSearchStateChangeInfoList.count(), 2);\n SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0);\n QCOMPARE(info.state, ChannelContactSearchStateInProgress);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"in progress\"));\n\n info = mSearchStateChangeInfoList.at(1);\n QCOMPARE(info.state, ChannelContactSearchStateCompleted);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"completed\"));\n\n QCOMPARE(mSearchResult.isEmpty(), false);\n QCOMPARE(mSearchResult.size(), 3);\n\n QStringList expectedIds;\n expectedIds << QLatin1String(\"oggis\") << QLatin1String(\"andrunko\") <<\n QLatin1String(\"wjt\");\n expectedIds.sort();\n QStringList expectedFns;\n expectedFns << QLatin1String(\"Olli Salli\") << QLatin1String(\"Andre Moreira Magalhaes\") <<\n QLatin1String(\"Will Thompson\");\n expectedFns.sort();\n QStringList ids;\n QStringList fns;\n for (ContactSearchChannel::SearchResult::const_iterator it = mSearchResult.constBegin();\n it != mSearchResult.constEnd();\n ++it)\n {\n QCOMPARE(it.key().isNull(), false);\n ids << it.key()->id();\n QCOMPARE(it.value().isValid(), true);\n QCOMPARE(it.value().allFields().isEmpty(), false);\n Q_FOREACH (const ContactInfoField &contactInfo, it.value().allFields()) {\n QCOMPARE(contactInfo.fieldName, QLatin1String(\"fn\"));\n fns.append(contactInfo.fieldValue.first());\n }\n }\n ids.sort();\n QCOMPARE(ids, expectedIds);\n fns.sort();\n QCOMPARE(fns, expectedFns);\n\n mChan1.reset();\n}\n\nvoid TestContactSearchChan::testContactSearchEmptyResult()\n{\n mChan2 = ContactSearchChannel::create(mConn, mChan2Path, QVariantMap());\n mChan = mChan2;\n QVERIFY(connect(mChan2->becomeReady(ContactSearchChannel::FeatureCore),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n QCOMPARE(mChan2->isReady(), true);\n\n QCOMPARE(mChan2->searchState(), ChannelContactSearchStateNotStarted);\n QCOMPARE(mChan2->limit(), static_cast(0));\n QCOMPARE(mChan2->availableSearchKeys().isEmpty(), false);\n QCOMPARE(mChan2->availableSearchKeys().count(), 1);\n QCOMPARE(mChan2->availableSearchKeys().first(), QLatin1String(\"employer\"));\n QCOMPARE(mChan2->server(), QLatin1String(\"characters.shakespeare.lit\"));\n\n QVERIFY(connect(mChan2.data(),\n SIGNAL(searchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &)),\n SLOT(onSearchStateChanged(Tp::ChannelContactSearchState, const QString &,\n const Tp::ContactSearchChannel::SearchStateChangeDetails &))));\n QVERIFY(connect(mChan2.data(),\n SIGNAL(searchResultReceived(const Tp::ContactSearchChannel::SearchResult &)),\n SLOT(onSearchResultReceived(const Tp::ContactSearchChannel::SearchResult &))));\n\n ContactSearchMap searchTerms;\n searchTerms.insert(QLatin1String(\"employer\"), QLatin1String(\"FooBar\"));\n QVERIFY(connect(mChan2->search(searchTerms),\n SIGNAL(finished(Tp::PendingOperation *)),\n SLOT(onSearchReturned(Tp::PendingOperation *))));\n while (!mSearchReturned) {\n QCOMPARE(mLoop->exec(), 0);\n }\n while (mChan2->searchState() != ChannelContactSearchStateCompleted) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(mSearchReturned, true);\n\n QCOMPARE(mSearchResult.isEmpty(), true);\n\n QCOMPARE(mSearchStateChangeInfoList.count(), 2);\n SearchStateChangeInfo info = mSearchStateChangeInfoList.at(0);\n QCOMPARE(info.state, ChannelContactSearchStateInProgress);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"in progress\"));\n\n info = mSearchStateChangeInfoList.at(1);\n QCOMPARE(info.state, ChannelContactSearchStateCompleted);\n QCOMPARE(info.errorName, QLatin1String(\"\"));\n QCOMPARE(info.details.hasDebugMessage(), true);\n QCOMPARE(info.details.debugMessage(), QLatin1String(\"completed\"));\n\n mChan2.reset();\n}\n\nvoid TestContactSearchChan::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactSearchChan::cleanupTestCase()\n{\n if (mConn) {\n \/\/ Disconnect and wait for the readiness change\n QVERIFY(connect(mConn->requestDisconnect(),\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n\n if (mConn->isValid()) {\n QVERIFY(connect(mConn.data(),\n SIGNAL(invalidated(Tp::DBusProxy *,\n const QString &, const QString &)),\n mLoop,\n SLOT(quit())));\n QCOMPARE(mLoop->exec(), 0);\n }\n }\n\n if (mChan1Service != 0) {\n g_object_unref(mChan1Service);\n mChan1Service = 0;\n }\n\n if (mChan2Service != 0) {\n g_object_unref(mChan2Service);\n mChan2Service = 0;\n }\n\n if (mConnService != 0) {\n mBaseConnService = 0;\n g_object_unref(mConnService);\n mConnService = 0;\n }\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactSearchChan)\n#include \"_gen\/chan-contact-search.cpp.moc.hpp\"\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2003 [NAMES_GO_HERE]\n * Massachusetts Institute of Technology\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 \"p2psim\/network.h\"\n#include \"p2psim\/topology.h\"\n#include \"protocols\/protocolfactory.h\"\n#include \"euclidean.h\"\n#include \n#include \nusing namespace std;\n\nEuclidean::Euclidean(vector*)\n{\n}\n\nEuclidean::~Euclidean()\n{\n}\n\nTime\nEuclidean::latency(IPAddress ip1x, IPAddress ip2x, bool reply)\n{\n IPAddress ip1 = Network::Instance()->first_ip(ip1x);\n IPAddress ip2 = Network::Instance()->first_ip(ip2x);\n assert(ip1 > 0 && ip2 > 0);\n Coord c1 = _nodes[ip1];\n Coord c2 = _nodes[ip2];\n\n if (ip1==ip2)\n return 0;\n else {\n Time t= (Time) hypot(labs(c2.first - c1.first), labs(c2.second - c1.second));\n if (t > 1000) \n fprintf(stderr,\"warning! %u,%u -> %u,%u\\n\",c1.first,c1.second,c2.first,c2.second);\n return t;\n }\n}\n\n\nvoid\nEuclidean::parse(ifstream &ifs)\n{\n string line;\n Time max_first, max_second;\n\n max_first = max_second = 0;\n while(getline(ifs,line)) {\n vector words = split(line);\n\n \/\/ skip empty lines and commented lines\n if(words.empty() || words[0][0] == '#')\n continue;\n\n \/\/ nodeid, coordinates and at least one protocol\n if(words.size() < 2) {\n cerr << \"provide nodeid and coordinates per line\" << endl;\n continue;\n }\n\n \/\/ node-id\n IPAddress ipaddr = (IPAddress) strtoull(words[0].c_str(), NULL, 10);\n if(!ipaddr)\n cerr << \"found node-id 0. you're asking for trouble.\" << endl;\n\n \/\/ x,y coordinates\n vector coords = split(words[1], \",\");\n Coord c;\n if (coords.size () < 2) {\n cerr << \"malformed coordinates \" << endl;\n exit (-1);\n }\n c.first = atoi(coords[0].c_str());\n c.second = atoi(coords[1].c_str());\n if ((Time) c.first > max_first) \n max_first = c.first;\n else if ((Time) c.second > max_second)\n max_second = c.second;\n\n \/\/ what kind of node?\n Node *p = ProtocolFactory::Instance()->create(ipaddr);\n\n \/\/ add the new node it to the topology\n if(_nodes.find(p->ip()) != _nodes.end())\n cerr << \"warning: node \" << ipaddr << \" already added! (\" <ip()] = c;\n\n \/\/ add the node to the network\n send(Network::Instance()->nodechan(), &p);\n }\n\n _med_lat = (Time) sqrt((double) (max_first * max_first + max_second * max_second))\/3;\n}\nget rid of annoying warning message\/*\n * Copyright (c) 2003 [NAMES_GO_HERE]\n * Massachusetts Institute of Technology\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 \"p2psim\/network.h\"\n#include \"p2psim\/topology.h\"\n#include \"protocols\/protocolfactory.h\"\n#include \"euclidean.h\"\n#include \n#include \nusing namespace std;\n\nEuclidean::Euclidean(vector*)\n{\n}\n\nEuclidean::~Euclidean()\n{\n}\n\nTime\nEuclidean::latency(IPAddress ip1x, IPAddress ip2x, bool reply)\n{\n IPAddress ip1 = Network::Instance()->first_ip(ip1x);\n IPAddress ip2 = Network::Instance()->first_ip(ip2x);\n assert(ip1 > 0 && ip2 > 0);\n Coord c1 = _nodes[ip1];\n Coord c2 = _nodes[ip2];\n\n if (ip1==ip2)\n return 0;\n else {\n Time t= (Time) hypot(labs(c2.first - c1.first), labs(c2.second - c1.second));\n return t;\n }\n}\n\n\nvoid\nEuclidean::parse(ifstream &ifs)\n{\n string line;\n Time max_first, max_second;\n\n max_first = max_second = 0;\n while(getline(ifs,line)) {\n vector words = split(line);\n\n \/\/ skip empty lines and commented lines\n if(words.empty() || words[0][0] == '#')\n continue;\n\n \/\/ nodeid, coordinates and at least one protocol\n if(words.size() < 2) {\n cerr << \"provide nodeid and coordinates per line\" << endl;\n continue;\n }\n\n \/\/ node-id\n IPAddress ipaddr = (IPAddress) strtoull(words[0].c_str(), NULL, 10);\n if(!ipaddr)\n cerr << \"found node-id 0. you're asking for trouble.\" << endl;\n\n \/\/ x,y coordinates\n vector coords = split(words[1], \",\");\n Coord c;\n if (coords.size () < 2) {\n cerr << \"malformed coordinates \" << endl;\n exit (-1);\n }\n c.first = atoi(coords[0].c_str());\n c.second = atoi(coords[1].c_str());\n if ((Time) c.first > max_first) \n max_first = c.first;\n else if ((Time) c.second > max_second)\n max_second = c.second;\n\n \/\/ what kind of node?\n Node *p = ProtocolFactory::Instance()->create(ipaddr);\n\n \/\/ add the new node it to the topology\n if(_nodes.find(p->ip()) != _nodes.end())\n cerr << \"warning: node \" << ipaddr << \" already added! (\" <ip()] = c;\n\n \/\/ add the node to the network\n send(Network::Instance()->nodechan(), &p);\n }\n\n _med_lat = (Time) sqrt((double) (max_first * max_first + max_second * max_second))\/3;\n}\n<|endoftext|>"} {"text":"Unused return value warning fix<|endoftext|>"} {"text":"Allows receivers of nullptr from begin_data to output any quantity of data.<|endoftext|>"} {"text":"#include \"WhistleControl.h\"\n\nusing namespace naoth;\n\nWhistleControl::WhistleControl():\n onOffSwitch(0),\n whistleListFile(\"whistles.lst\"),\n activeChannels(\"1010\")\n\n{}\n\nvoid WhistleControl::print(std::ostream& stream) const\n{\n stream << \"switch: \" << (onOffSwitch == 1 ? \"on\" : \"off\") << std::endl;\n stream << \"whistle list file: \" << whistleListFile << std::endl;\n stream << \"active channels(Left|Front|Right|Rear): \" << activeChannels << std::endl;\n}\n\nWhistleControl::~WhistleControl()\n{}\n\ninitialize whistlecontrol variables#include \"WhistleControl.h\"\n\nusing namespace naoth;\n\nWhistleControl::WhistleControl():\n onOffSwitch(0),\n whistleListFile(\"whistles.lst\"),\n activeChannels(\"1010\"),\n threshold(0.4),\n checkAllWhistles(true),\n saveRawAudio(false)\n{}\n\nvoid WhistleControl::print(std::ostream& stream) const\n{\n stream << \"switch: \" << (onOffSwitch == 1 ? \"on\" : \"off\") << std::endl;\n stream << \"whistle list file: \" << whistleListFile << std::endl;\n stream << \"active channels(Left|Front|Right|Rear): \" << activeChannels << std::endl;\n}\n\nWhistleControl::~WhistleControl()\n{}\n\n<|endoftext|>"} {"text":"#include \n\n#include \"..\/include\/Account.h\"\n\nusing namespace std;\n\nstatic const string Account::admin = \"AA\";\nstatic const string Account::sell = \"SS\";\nstatic const string Account::buy = \"BS\";\nstatic const string Account::full = \"FS\";\nstatic const double Account::maxPrice = 999999.99;\n\nstring Account::getType() {\n return this->type;\n}\n\nvoid Account::setType(string type) {\n this->type = type;\n}\n\ndouble Account::getBalance() {\n return this->balance;\n}\n\nvoid Account::setBalance(double balance) {\n this->balance = balance;\n}\n\nstring Account::getUsername() {\n return this->username;\n}\n\nvoid Account::setUsername(string username) {\n this->username = username;\n}\nFIXED: 'static' may not be used when defining (as opposed to declaring) a static data member#include \n\n#include \"..\/include\/Account.h\"\n\nusing namespace std;\n\n\/\/ ‘static’ may not be used when defining (as opposed to declaring) a static data member [-fpermissive]\nconst string Account::admin = \"AA\";\nconst string Account::sell = \"SS\";\nconst string Account::buy = \"BS\";\nconst string Account::full = \"FS\";\nconst double Account::maxPrice = 999999.99;\n\nstring Account::getType() {\n return this->type;\n}\n\nvoid Account::setType(string type) {\n this->type = type;\n}\n\ndouble Account::getBalance() {\n return this->balance;\n}\n\nvoid Account::setBalance(double balance) {\n this->balance = balance;\n}\n\nstring Account::getUsername() {\n return this->username;\n}\n\nvoid Account::setUsername(string username) {\n this->username = username;\n}\n<|endoftext|>"} {"text":"#include \"LogicController.h\"\n\nLogicController::LogicController() {\n logicState = LOGIC_STATE_INTERRUPT;\n processState = PROCCESS_STATE_SEARCHING;\n\n prioritizedControllers = {\n PrioritizedController{0, (Controller*)(&searchController)},\n PrioritizedController{1, (Controller*)(&obstacleController)},\n PrioritizedController{2, (Controller*)(&pickUpController)}\n };\n\n control_queue = priority_queue();\n\n}\n\nLogicController::~LogicController() {}\n\nvoid LogicController::Reset() {\n\n logicState = LOGIC_STATE_INTERRUPT;\n processState = PROCCESS_STATE_SEARCHING;\n\n prioritizedControllers = {\n PrioritizedController{0, (Controller*)(&searchController)},\n PrioritizedController{1, (Controller*)(&obstacleController)},\n PrioritizedController{2, (Controller*)(&pickUpController)}\n };\n\n control_queue = priority_queue();\n}\n\nResult LogicController::DoWork() {\n Result result;\n\n\n if (processState == PROCCESS_STATE_SEARCHING) {\n\n }\n else if (processState == PROCCESS_COLLECTING_TARGET) {\n\n }\n else if (processState == PROCCESS_STATE_TARGET_PICKEDUP) {\n\n }\n\n\n switch(logicState) {\n case LOGIC_STATE_INTERRUPT: {\n\n \/\/Reset the control queue\n control_queue = priority_queue();\n\n for(PrioritizedController cntrlr : prioritizedControllers) {\n if(cntrlr.controller->ShouldInterrupt()) {\n control_queue.push(cntrlr);\n }\n }\n\n if(control_queue.empty()) {\n result.type = behavior;\n result.b = wait;\n\n return result;\n }\n\n result = control_queue.top().controller->DoWork();\n\n if(result.type == behavior) {\n if(result.b == nextProcess) {\n if (processState == _LAST) {\n processState = _FIRST;\n }\n else {\n processState = (ProcessState)((int)processState + 1);\n }\n } else if(result.b == prevProcess) {\n if (processState == _FIRST) {\n processState = (ProcessState)((int)_LAST - 1);\n }\n else {\n processState = (ProcessState)((int)processState - 1);\n }\n }\n } else if(result.type == precisionDriving) {\n\n logicState = LOGIC_STATE_PRECISION_COMMAND;\n\n } else if(result.type == waypoint) {\n\n logicState = LOGIC_STATE_WAITING;\n result = control_queue.top().controller->DoWork();\n\n }\n\n break;\n }\n\n case LOGIC_STATE_WAITING: {\n\n result = driveController.DoWork();\n if (result.type = behavior) {\n if(driveController.ShouldInterrupt()) {\n logicState = LOGIC_STATE_INTERRUPT;\n }\n else {\n return result;\n }\n }\n else {\n return result;\n }\n\n break;\n }\n\n case LOGIC_STATE_PRECISION_COMMAND: {\n\n result = control_queue.top().controller->DoWork();\n driveController.setResultData(result);\n result = driveController.DoWork();\n break;\n }\n }\n\n return result;\n}\n\nvoid LogicController::UpdateData() {\n\n\n}\n\nvoid LogicController::ProcessData() {\n\n}\n\nbool LogicController::ShouldInterrupt() {\n ProcessData();\n\n return false;\n}\n\nbool LogicController::HasWork() {\n return false;\n}\n\n\nvoid LogicController::controllerInterconnect() {\n\n\n if(pickUpController.GetIgnoreCenter()) {\n obstacleController.SetIgnoreCenter();\n }\n}\n\n\nvoid LogicController::setPositionData(Point currentLocation) {\n searchController.setCurrentLocation(currentLocation);\n dropOffController.SetCurrentLocation(currentLocation);\n obstacleController.SetCurrentLocation(currentLocation);\n}\n\nvoid LogicController::setMapPositionData(Point currentLocationMap) {\n\n}\n\nvoid LogicController::setVelocityData(float linearVelocity, float angularVelocity) {\n driveController.SetVelocityData(linearVelocity,angularVelocity);\n}\n\nvoid LogicController::setMapVelocityData(float linearVelocity, float angularVelocity) {\n\n}\n\nvoid LogicController::setAprilTags(vector tags) {\n pickUpController.SetTagData(tags);\n obstacleController.SetTagData(tags);\n dropOffController.setTargetData(tags);\n}\n\nvoid LogicController::setSonarData(float left, float center, float right) {\n pickUpController.SetSonarData(center);\n obstacleController.SetSonarData(left,center,right);\n}\n\nvoid LogicController::setCenterLocationOdom(Point centerLocationOdom) {\n searchController.setCenterLocation(centerLocationOdom);\n dropOffController.SetCenterLocation(centerLocationOdom);\n}\n\nvoid LogicController::setCenterLocationMap(Point centerLocationMap) {\n\n}\nAdded alternet priorites based upon process loop state#include \"LogicController.h\"\n\nLogicController::LogicController() {\n logicState = LOGIC_STATE_INTERRUPT;\n processState = PROCCESS_STATE_SEARCHING;\n\n prioritizedControllers = {\n PrioritizedController{0, (Controller*)(&searchController)},\n PrioritizedController{1, (Controller*)(&obstacleController)},\n PrioritizedController{2, (Controller*)(&pickUpController)},\n PrioritizedController{-1, (Controller*)(&dropOffController)}\n };\n\n control_queue = priority_queue();\n\n}\n\nLogicController::~LogicController() {}\n\nvoid LogicController::Reset() {\n\n logicState = LOGIC_STATE_INTERRUPT;\n processState = PROCCESS_STATE_SEARCHING;\n\n prioritizedControllers = {\n PrioritizedController{0, (Controller*)(&searchController)},\n PrioritizedController{1, (Controller*)(&obstacleController)},\n PrioritizedController{2, (Controller*)(&pickUpController)}\n };\n\n control_queue = priority_queue();\n}\n\nResult LogicController::DoWork() {\n Result result;\n\n\n if (processState == PROCCESS_STATE_SEARCHING) {\n prioritizedControllers = {\n PrioritizedController{0, (Controller*)(&searchController)},\n PrioritizedController{1, (Controller*)(&obstacleController)},\n PrioritizedController{2, (Controller*)(&pickUpController)},\n PrioritizedController{-1, (Controller*)(&dropOffController)}\n };\n }\n else if (processState == PROCCESS_COLLECTING_TARGET) {\n prioritizedControllers = {\n PrioritizedController{-1, (Controller*)(&searchController)},\n PrioritizedController{1, (Controller*)(&obstacleController)},\n PrioritizedController{2, (Controller*)(&pickUpController)},\n PrioritizedController{-1, (Controller*)(&dropOffController)}\n };\n }\n else if (processState == PROCCESS_STATE_TARGET_PICKEDUP) {\n prioritizedControllers = {\n PrioritizedController{-1, (Controller*)(&searchController)},\n PrioritizedController{2, (Controller*)(&obstacleController)},\n PrioritizedController{-1, (Controller*)(&pickUpController)},\n PrioritizedController{1, (Controller*)(&dropOffController)}\n };\n }\n\n\n switch(logicState) {\n case LOGIC_STATE_INTERRUPT: {\n\n \/\/Reset the control queue\n control_queue = priority_queue();\n\n for(PrioritizedController cntrlr : prioritizedControllers) {\n if(cntrlr.controller->ShouldInterrupt()) {\n if (cntrlr.priority < 0) {\n continue;\n }\n else {\n control_queue.push(cntrlr);\n }\n }\n }\n\n if(control_queue.empty()) {\n result.type = behavior;\n result.b = wait;\n\n return result;\n }\n\n result = control_queue.top().controller->DoWork();\n\n if(result.type == behavior) {\n if(result.b == nextProcess) {\n if (processState == _LAST) {\n processState = _FIRST;\n }\n else {\n processState = (ProcessState)((int)processState + 1);\n }\n } else if(result.b == prevProcess) {\n if (processState == _FIRST) {\n processState = (ProcessState)((int)_LAST - 1);\n }\n else {\n processState = (ProcessState)((int)processState - 1);\n }\n }\n } else if(result.type == precisionDriving) {\n\n logicState = LOGIC_STATE_PRECISION_COMMAND;\n\n } else if(result.type == waypoint) {\n\n logicState = LOGIC_STATE_WAITING;\n result = control_queue.top().controller->DoWork();\n\n }\n\n break;\n }\n\n case LOGIC_STATE_WAITING: {\n\n result = driveController.DoWork();\n if (result.type = behavior) {\n if(driveController.ShouldInterrupt()) {\n logicState = LOGIC_STATE_INTERRUPT;\n }\n else {\n return result;\n }\n }\n else {\n return result;\n }\n\n break;\n }\n\n case LOGIC_STATE_PRECISION_COMMAND: {\n\n result = control_queue.top().controller->DoWork();\n driveController.setResultData(result);\n result = driveController.DoWork();\n break;\n }\n }\n\n return result;\n}\n\nvoid LogicController::UpdateData() {\n\n\n}\n\nvoid LogicController::ProcessData() {\n\n}\n\nbool LogicController::ShouldInterrupt() {\n ProcessData();\n\n return false;\n}\n\nbool LogicController::HasWork() {\n return false;\n}\n\n\nvoid LogicController::controllerInterconnect() {\n\n\n if(pickUpController.GetIgnoreCenter()) {\n obstacleController.SetIgnoreCenter();\n }\n}\n\n\nvoid LogicController::setPositionData(Point currentLocation) {\n searchController.setCurrentLocation(currentLocation);\n dropOffController.SetCurrentLocation(currentLocation);\n obstacleController.SetCurrentLocation(currentLocation);\n}\n\nvoid LogicController::setMapPositionData(Point currentLocationMap) {\n\n}\n\nvoid LogicController::setVelocityData(float linearVelocity, float angularVelocity) {\n driveController.SetVelocityData(linearVelocity,angularVelocity);\n}\n\nvoid LogicController::setMapVelocityData(float linearVelocity, float angularVelocity) {\n\n}\n\nvoid LogicController::setAprilTags(vector tags) {\n pickUpController.SetTagData(tags);\n obstacleController.SetTagData(tags);\n dropOffController.setTargetData(tags);\n}\n\nvoid LogicController::setSonarData(float left, float center, float right) {\n pickUpController.SetSonarData(center);\n obstacleController.SetSonarData(left,center,right);\n}\n\nvoid LogicController::setCenterLocationOdom(Point centerLocationOdom) {\n searchController.setCenterLocation(centerLocationOdom);\n dropOffController.SetCenterLocation(centerLocationOdom);\n}\n\nvoid LogicController::setCenterLocationMap(Point centerLocationMap) {\n\n}\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library 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 Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see .\n*\/\n\n#include \"iodevicereader.h\"\n#include \"qasyncreader.h\"\n\n#include \"mediagraph.h\"\n\n#include \n\n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nnamespace Phonon\n{\n namespace DS9\n {\n \/\/these mediatypes define a stream, its type will be autodetected by DirectShow\n static QVector getMediaTypes()\n {\n AM_MEDIA_TYPE mt = { MEDIATYPE_Stream, MEDIASUBTYPE_NULL, TRUE, FALSE, 1, GUID_NULL, 0, 0, 0};\n\n QVector ret;\n \/\/normal auto-detect stream\n ret << mt;\n \/\/AVI stream\n mt.subtype = MEDIASUBTYPE_Avi;\n ret << mt;\n \/\/WAVE stream\n mt.subtype = MEDIASUBTYPE_WAVE;\n ret << mt;\n return ret;\n }\n\n class StreamReader : public QAsyncReader, public Phonon::StreamInterface\n {\n public:\n StreamReader(QBaseFilter *parent, const Phonon::MediaSource &source, const MediaGraph *mg) : \n QAsyncReader(parent, getMediaTypes()),\n m_seekable(false), m_pos(0), m_size(-1), m_mediaGraph(mg)\n {\n connectToSource(source);\n }\n\n \/\/for Phonon::StreamInterface\n void writeData(const QByteArray &data)\n {\n m_pos += data.size();\n m_buffer += data;\n }\n\n void endOfData()\n {\n }\n\n void setStreamSize(qint64 newSize)\n {\n QMutexLocker locker(&m_mutex);\n m_size = newSize;\n }\n\n void setStreamSeekable(bool s)\n {\n QMutexLocker locker(&m_mutex);\n m_seekable = s;\n }\n\n \/\/virtual pure members\n\n \/\/implementation from IAsyncReader\n STDMETHODIMP Length(LONGLONG *total, LONGLONG *available)\n {\n QMutexLocker locker(&m_mutex);\n if (total) {\n *total = m_size;\n }\n\n if (available) {\n *available = m_size;\n }\n\n return S_OK;\n }\n\n\n HRESULT read(LONGLONG pos, LONG length, BYTE *buffer, LONG *actual)\n {\n Q_ASSERT(!m_mutex.tryLock());\n if (m_mediaGraph->isStopping()) {\n return VFW_E_WRONG_STATE;\n }\n\n if(m_size != 1 && pos + length > m_size) {\n \/\/it tries to read outside of the boundaries\n return E_FAIL;\n }\n\n if (m_pos - m_buffer.size() != pos) {\n if (!m_seekable) {\n return S_FALSE;\n }\n m_pos = pos;\n seekStream(pos);\n m_buffer.clear();\n }\n\n int oldSize = m_buffer.size();\n while (m_buffer.size() < int(length)) {\n needData();\n if (m_mediaGraph->isStopping()) {\n return VFW_E_WRONG_STATE;\n }\n\n if (oldSize == m_buffer.size()) {\n break; \/\/we didn't get any data\n }\n oldSize = m_buffer.size();\n }\n\n int bytesRead = qMin(m_buffer.size(), int(length));\n qMemCopy(buffer, m_buffer.data(), bytesRead);\n \/\/truncate the buffer\n m_buffer = m_buffer.mid(bytesRead);\n\n if (actual) {\n *actual = bytesRead; \/\/initialization\n }\n\n return bytesRead == length ? S_OK : S_FALSE;\n }\n\n public:\n \/\/for Phonon::StreamInterface\n QByteArray m_buffer;\n bool m_seekable;\n qint64 m_pos;\n qint64 m_size;\n\n const MediaGraph *m_mediaGraph;\n };\n\n IODeviceReader::IODeviceReader(const Phonon::MediaSource &source, const MediaGraph *mg) :\n QBaseFilter(CLSID_NULL)\n {\n \/\/create the output pin\n m_streamReader = new StreamReader(this, source, mg);\n }\n\n IODeviceReader::~IODeviceReader()\n {\n }\n }\n}\n\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nQT_END_NAMESPACE\nPhonon: allows to stream wave files from QIODevice\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library 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 Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see .\n*\/\n\n#include \"iodevicereader.h\"\n#include \"qasyncreader.h\"\n\n#include \"mediagraph.h\"\n\n#include \n\n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\n#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nnamespace Phonon\n{\n namespace DS9\n {\n \/\/these mediatypes define a stream, its type will be autodetected by DirectShow\n static QVector getMediaTypes()\n {\n \/\/the order here is important because otherwise,\n \/\/directshow might not be able to detect the stream type correctly\n\n AM_MEDIA_TYPE mt = { MEDIATYPE_Stream, MEDIASUBTYPE_Avi, TRUE, FALSE, 1, GUID_NULL, 0, 0, 0};\n\n QVector ret;\n \/\/AVI stream\n ret << mt;\n \/\/WAVE stream\n mt.subtype = MEDIASUBTYPE_WAVE;\n ret << mt;\n \/\/normal auto-detect stream (must be at the end!)\n mt.subtype = MEDIASUBTYPE_NULL;\n ret << mt;\n return ret;\n }\n\n class StreamReader : public QAsyncReader, public Phonon::StreamInterface\n {\n public:\n StreamReader(QBaseFilter *parent, const Phonon::MediaSource &source, const MediaGraph *mg) : \n QAsyncReader(parent, getMediaTypes()),\n m_seekable(false), m_pos(0), m_size(-1), m_mediaGraph(mg)\n {\n connectToSource(source);\n }\n\n \/\/for Phonon::StreamInterface\n void writeData(const QByteArray &data)\n {\n m_pos += data.size();\n m_buffer += data;\n }\n\n void endOfData()\n {\n }\n\n void setStreamSize(qint64 newSize)\n {\n QMutexLocker locker(&m_mutex);\n m_size = newSize;\n }\n\n void setStreamSeekable(bool s)\n {\n QMutexLocker locker(&m_mutex);\n m_seekable = s;\n }\n\n \/\/virtual pure members\n\n \/\/implementation from IAsyncReader\n STDMETHODIMP Length(LONGLONG *total, LONGLONG *available)\n {\n QMutexLocker locker(&m_mutex);\n if (total) {\n *total = m_size;\n }\n\n if (available) {\n *available = m_size;\n }\n\n return S_OK;\n }\n\n\n HRESULT read(LONGLONG pos, LONG length, BYTE *buffer, LONG *actual)\n {\n Q_ASSERT(!m_mutex.tryLock());\n if (m_mediaGraph->isStopping()) {\n return VFW_E_WRONG_STATE;\n }\n\n if(m_size != 1 && pos + length > m_size) {\n \/\/it tries to read outside of the boundaries\n return E_FAIL;\n }\n\n if (m_pos - m_buffer.size() != pos) {\n if (!m_seekable) {\n return S_FALSE;\n }\n m_pos = pos;\n seekStream(pos);\n m_buffer.clear();\n }\n\n int oldSize = m_buffer.size();\n while (m_buffer.size() < int(length)) {\n needData();\n if (m_mediaGraph->isStopping()) {\n return VFW_E_WRONG_STATE;\n }\n\n if (oldSize == m_buffer.size()) {\n break; \/\/we didn't get any data\n }\n oldSize = m_buffer.size();\n }\n\n int bytesRead = qMin(m_buffer.size(), int(length));\n qMemCopy(buffer, m_buffer.data(), bytesRead);\n \/\/truncate the buffer\n m_buffer = m_buffer.mid(bytesRead);\n\n if (actual) {\n *actual = bytesRead; \/\/initialization\n }\n\n return bytesRead == length ? S_OK : S_FALSE;\n }\n\n public:\n \/\/for Phonon::StreamInterface\n QByteArray m_buffer;\n bool m_seekable;\n qint64 m_pos;\n qint64 m_size;\n\n const MediaGraph *m_mediaGraph;\n };\n\n IODeviceReader::IODeviceReader(const Phonon::MediaSource &source, const MediaGraph *mg) :\n QBaseFilter(CLSID_NULL)\n {\n \/\/create the output pin\n m_streamReader = new StreamReader(this, source, mg);\n }\n\n IODeviceReader::~IODeviceReader()\n {\n }\n }\n}\n\n#endif \/\/QT_NO_PHONON_ABSTRACTMEDIASTREAM\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"#include \"opencv.hpp\"\n#include \"utilities.hpp\"\n#include \"AspectError.hpp\"\n#include \n#include \n\nstruct HeaderData\n{\n timespec captureTime, captureTimeMono;\n int cameraID;\n float cameraTemperature;\n int cpuTemperature;\n int i2c_temperatures[8];\n long frameCount;\n int exposure;\n timespec imageWriteTime;\n int preampGain;\n int analogGain;\n float sunCenter[2];\n float sunCenterError[2];\n int imageMinMax[2];\n float XYinterceptslope[4];\n double CTLsolution[2];\n float screenCenter[2];\n float screenCenterError[2];\n int fiducialCount;\n float fiducialX[10];\n float fiducialY[10];\n int limbCount;\n float limbX[10];\n float limbY[10];\n \/\/float limbXerror[10];\n \/\/float limbYerror[10];\n int fiducialIDX[10];\n int fiducialIDY[10];\n float cpuVoltage[5];\n bool isTracking;\n bool isOutputting;\n\n AspectCode runResult;\n\n float latitude;\n float longitude;\n float solarTarget[2];\n double northAngle;\n float clockingAngle;\n};\n\nint writePNGImage(cv::InputArray _image, const std::string fileName);\nint writeFITSImage(cv::InputArray, HeaderData keys, const std::string fileName);\nint readFITSImage(const std::string fileName, cv::OutputArray image);\nint readFITSHeader(const std::string fileName, HeaderData &keys);\nremoving utilities.hpp#include \"opencv.hpp\"\n#include \n#include \n\nstruct HeaderData\n{\n timespec captureTime, captureTimeMono;\n int cameraID;\n float cameraTemperature;\n int cpuTemperature;\n int i2c_temperatures[8];\n long frameCount;\n int exposure;\n timespec imageWriteTime;\n int preampGain;\n int analogGain;\n float sunCenter[2];\n float sunCenterError[2];\n int imageMinMax[2];\n float XYinterceptslope[4];\n double CTLsolution[2];\n float screenCenter[2];\n float screenCenterError[2];\n int fiducialCount;\n float fiducialX[10];\n float fiducialY[10];\n int limbCount;\n float limbX[10];\n float limbY[10];\n \/\/float limbXerror[10];\n \/\/float limbYerror[10];\n int fiducialIDX[10];\n int fiducialIDY[10];\n float cpuVoltage[5];\n bool isTracking;\n bool isOutputting;\n\n float latitude;\n float longitude;\n float solarTarget[2];\n double northAngle;\n float clockingAngle;\n};\n\nint writePNGImage(cv::InputArray _image, const std::string fileName);\nint writeFITSImage(cv::InputArray, HeaderData keys, const std::string fileName);\nint readFITSImage(const std::string fileName, cv::OutputArray image);\nint readFITSHeader(const std::string fileName, HeaderData &keys);\n<|endoftext|>"} {"text":"\/\/=============================================================================================================\n\/**\n* @file realtimemultisamplearraydelegate.cpp\n* @author Christoph Dinh ;\n* Matti Hamalainen \n* @version 1.0\n* @date May, 2014\n*\n* @section LICENSE\n*\n* Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Implementation of the RealTimeMultiSampleArrayDelegate Class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"realtimemultisamplearraydelegate.h\"\n\n#include \"realtimemultisamplearraymodel.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace XDISPLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nRealTimeMultiSampleArrayDelegate::RealTimeMultiSampleArrayDelegate(QObject *parent)\n: QAbstractItemDelegate(parent)\n{\n\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RealTimeMultiSampleArrayDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n float t_fPlotHeight = option.rect.height();\n switch(index.column()) {\n case 0: { \/\/chnames\n painter->save();\n\n painter->rotate(-90);\n painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString());\n\n painter->restore();\n break;\n }\n case 1: { \/\/data plot\n painter->save();\n\n \/\/draw special background when channel is marked as bad\n\/\/ QVariant v = index.model()->data(index,Qt::BackgroundRole);\n\/\/ if(v.canConvert() && !(option.state & QStyle::State_Selected)) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, qvariant_cast(v));\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n\/\/ \/\/Highlight selected channels\n\/\/ if(option.state & QStyle::State_Selected) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, option.palette.highlight());\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n \/\/Get data\n QVariant variant = index.model()->data(index,Qt::DisplayRole);\n QList< QVector > data = variant.value< QList< QVector > >();\n\n\n const RealTimeMultiSampleArrayModel* t_pModel = static_cast(index.model());\n\n if(data.size() > 0)\n {\n \/\/ const RealTimeMultiSampleArrayModel* t_rtmsaModel = (static_cast(index.model()));\n\n QPainterPath path(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y()));\n\n \/\/Plot grid\n painter->setRenderHint(QPainter::Antialiasing, false);\n createGridPath(index, option, path, data);\n\n painter->save();\n QPen pen;\n pen.setStyle(Qt::DotLine);\n pen.setWidthF(0.5);\n painter->setPen(pen);\n painter->drawPath(path);\n painter->restore();\n\n \/\/Plot data path\n path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y()));\n QPainterPath lastPath(QPointF(option.rect.x(),option.rect.y()));\n\n createPlotPath(index, option, path, lastPath, data[0], data[1]);\n\n painter->save();\n painter->translate(0,t_fPlotHeight\/2);\n painter->setRenderHint(QPainter::Antialiasing, true);\n\n if(option.state & QStyle::State_Selected)\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine));\n else\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine));\n\n painter->drawPath(path);\n painter->restore();\n\n \/\/Plot last data path\n painter->translate(0,t_fPlotHeight\/2);\n painter->setRenderHint(QPainter::Antialiasing, true);\n if(option.state & QStyle::State_Selected)\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine));\n else\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine));\n painter->drawPath(lastPath);\n\n painter->restore();\n }\n break;\n }\n }\n\n}\n\n\n\/\/*************************************************************************************************************\n\nQSize RealTimeMultiSampleArrayDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n QSize size;\n\n switch(index.column()) {\n case 0:\n size = QSize(20,option.rect.height());\n break;\n case 1:\n QList< QVector > data = index.model()->data(index).value< QList > >();\n\/\/ qint32 nsamples = (static_cast(index.model()))->lastSample()-(static_cast(index.model()))->firstSample();\n\n\/\/ size = QSize(nsamples*m_dDx,m_dPlotHeight);\n Q_UNUSED(option);\n break;\n }\n\n\n return size;\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RealTimeMultiSampleArrayDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QPainterPath& lastPath, QVector& data, QVector& lastData) const\n{\n const RealTimeMultiSampleArrayModel* t_pModel = static_cast(index.model());\n\n \/\/get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value)\n qint32 kind = t_pModel->getKind(index.row());\n float fMaxValue = 1e-9f;\n\n float Amp = 1e-9f;\n\n switch(kind) {\n case FIFFV_MEG_CH: {\n qint32 unit =t_pModel->getUnit(index.row());\n if(unit == FIFF_UNIT_T_M) {\n fMaxValue = 1e-10f;\n if(t_pModel->getScaling().contains(FIFF_UNIT_T_M))\n fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T_M];\n }\n else if(unit == FIFF_UNIT_T)\n {\n if(t_pModel->getCoil(index.row()) == FIFFV_COIL_BABY_MAG)\n fMaxValue = 1e-11f;\n else\n fMaxValue = 1e-11f;\n\n if(t_pModel->getScaling().contains(FIFF_UNIT_T))\n fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T];\n } \n Amp = 1e-10f;\n\n break;\n }\n\n case FIFFV_REF_MEG_CH: { \/*11\/04\/14 Added by Limin: MEG reference channel *\/\n fMaxValue = 1e-11f;\n\n if(t_pModel->getScaling().contains(FIFF_UNIT_T))\n fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T];\n\n Amp = 1e-10f;\n\n break;\n }\n case FIFFV_EEG_CH: {\n fMaxValue = 1e-4f;\n if(t_pModel->getScaling().contains(FIFFV_EEG_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_EEG_CH];\n Amp = 1e-4f;\n break;\n }\n case FIFFV_EOG_CH: {\n fMaxValue = 1e-3f;\n if(t_pModel->getScaling().contains(FIFFV_EOG_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_EOG_CH];\n Amp = 1e-3f;\n break;\n }\n case FIFFV_STIM_CH: {\n fMaxValue = 5;\n if(t_pModel->getScaling().contains(FIFFV_STIM_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_STIM_CH];\n Amp = 1.0f;\n break;\n }\n case FIFFV_MISC_CH: {\n fMaxValue = 1e-3f;\n if(t_pModel->getScaling().contains(FIFFV_MISC_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_MISC_CH];\n Amp = 1e-3f;\n break;\n }\n }\n\n float fValue;\n \/\/float fScaleY = option.rect.height()\/(2*fMaxValue);\n float fScaleY = Amp \/ fMaxValue;\n\n float y_base = path.currentPosition().y();\n QPointF qSamplePosition;\n\n float fDx = ((float)option.rect.width()) \/ t_pModel->getMaxSamples();\n\n \/\/Move to initial starting point\n if(data.size() > 0)\n {\n\/\/ float val = data[0];\n fValue = 0;\/\/(val-data[0])*fScaleY;\n\n float newY = y_base-fValue;\/\/Reverse direction -> plot the right way\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX(path.currentPosition().x());\n\n path.moveTo(qSamplePosition);\n }\n\n \/\/create lines from one to the next sample\n qint32 i;\n for(i = 1; i < data.size(); ++i) {\n float val = data[i] - data[0]; \/\/remove first sample data[0] as offset\n fValue = val*fScaleY;\n \/\/qDebug()<<\"val\"< plot the right way\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX(path.currentPosition().x()+fDx);\n\n path.lineTo(qSamplePosition);\n }\n\n \/\/create lines from one to the next sample for last path\n qint32 sample_offset = t_pModel->numVLines() + 1;\n qSamplePosition.setX(qSamplePosition.x() + fDx*sample_offset);\n lastPath.moveTo(qSamplePosition);\n\n for(i += sample_offset; i < lastData.size(); ++i) {\n float val = lastData[i] - lastData[0]; \/\/remove first sample lastData[0] as offset\n fValue = val*fScaleY;\n\n float newY = y_base-fValue;\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX(lastPath.currentPosition().x()+fDx);\n\n lastPath.lineTo(qSamplePosition);\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RealTimeMultiSampleArrayDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QList< QVector >& data) const\n{\n Q_UNUSED(data)\n\n const RealTimeMultiSampleArrayModel* t_pModel = static_cast(index.model());\n\n if(t_pModel->numVLines() > 0)\n {\n \/\/horizontal lines\n float distance = option.rect.width()\/(t_pModel->numVLines()+1);\n\n float yStart = option.rect.topLeft().y();\n\n float yEnd = option.rect.bottomRight().y();\n\n for(qint8 i = 0; i < t_pModel->numVLines(); ++i) {\n float x = distance*(i+1);\n path.moveTo(x,yStart);\n path.lineTo(x,yEnd);\n }\n }\n}\ncorrected scaling\/\/=============================================================================================================\n\/**\n* @file realtimemultisamplearraydelegate.cpp\n* @author Christoph Dinh ;\n* Matti Hamalainen \n* @version 1.0\n* @date May, 2014\n*\n* @section LICENSE\n*\n* Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Implementation of the RealTimeMultiSampleArrayDelegate Class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"realtimemultisamplearraydelegate.h\"\n\n#include \"realtimemultisamplearraymodel.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace XDISPLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nRealTimeMultiSampleArrayDelegate::RealTimeMultiSampleArrayDelegate(QObject *parent)\n: QAbstractItemDelegate(parent)\n{\n\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RealTimeMultiSampleArrayDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n float t_fPlotHeight = option.rect.height();\n switch(index.column()) {\n case 0: { \/\/chnames\n painter->save();\n\n painter->rotate(-90);\n painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString());\n\n painter->restore();\n break;\n }\n case 1: { \/\/data plot\n painter->save();\n\n \/\/draw special background when channel is marked as bad\n\/\/ QVariant v = index.model()->data(index,Qt::BackgroundRole);\n\/\/ if(v.canConvert() && !(option.state & QStyle::State_Selected)) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, qvariant_cast(v));\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n\/\/ \/\/Highlight selected channels\n\/\/ if(option.state & QStyle::State_Selected) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, option.palette.highlight());\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n \/\/Get data\n QVariant variant = index.model()->data(index,Qt::DisplayRole);\n QList< QVector > data = variant.value< QList< QVector > >();\n\n\n const RealTimeMultiSampleArrayModel* t_pModel = static_cast(index.model());\n\n if(data.size() > 0)\n {\n \/\/ const RealTimeMultiSampleArrayModel* t_rtmsaModel = (static_cast(index.model()));\n\n QPainterPath path(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y()));\n\n \/\/Plot grid\n painter->setRenderHint(QPainter::Antialiasing, false);\n createGridPath(index, option, path, data);\n\n painter->save();\n QPen pen;\n pen.setStyle(Qt::DotLine);\n pen.setWidthF(0.5);\n painter->setPen(pen);\n painter->drawPath(path);\n painter->restore();\n\n \/\/Plot data path\n path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y()));\n QPainterPath lastPath(QPointF(option.rect.x(),option.rect.y()));\n\n createPlotPath(index, option, path, lastPath, data[0], data[1]);\n\n painter->save();\n painter->translate(0,t_fPlotHeight\/2);\n painter->setRenderHint(QPainter::Antialiasing, true);\n\n if(option.state & QStyle::State_Selected)\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine));\n else\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine));\n\n painter->drawPath(path);\n painter->restore();\n\n \/\/Plot last data path\n painter->translate(0,t_fPlotHeight\/2);\n painter->setRenderHint(QPainter::Antialiasing, true);\n if(option.state & QStyle::State_Selected)\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine));\n else\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine));\n painter->drawPath(lastPath);\n\n painter->restore();\n }\n break;\n }\n }\n\n}\n\n\n\/\/*************************************************************************************************************\n\nQSize RealTimeMultiSampleArrayDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n QSize size;\n\n switch(index.column()) {\n case 0:\n size = QSize(20,option.rect.height());\n break;\n case 1:\n QList< QVector > data = index.model()->data(index).value< QList > >();\n\/\/ qint32 nsamples = (static_cast(index.model()))->lastSample()-(static_cast(index.model()))->firstSample();\n\n\/\/ size = QSize(nsamples*m_dDx,m_dPlotHeight);\n Q_UNUSED(option);\n break;\n }\n\n\n return size;\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RealTimeMultiSampleArrayDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QPainterPath& lastPath, QVector& data, QVector& lastData) const\n{\n const RealTimeMultiSampleArrayModel* t_pModel = static_cast(index.model());\n\n \/\/get maximum range of respective channel type (range value in FiffChInfo does not seem to contain a reasonable value)\n qint32 kind = t_pModel->getKind(index.row());\n float fMaxValue = 1e-9f;\n\/\/ float Amp = 1e-9f;\n\n switch(kind) {\n case FIFFV_MEG_CH: {\n qint32 unit =t_pModel->getUnit(index.row());\n if(unit == FIFF_UNIT_T_M) {\n fMaxValue = 1e-10f;\n if(t_pModel->getScaling().contains(FIFF_UNIT_T_M))\n fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T_M];\n }\n else if(unit == FIFF_UNIT_T)\n {\n if(t_pModel->getCoil(index.row()) == FIFFV_COIL_BABY_MAG)\n fMaxValue = 1e-11f;\n else\n fMaxValue = 1e-11f;\n\n if(t_pModel->getScaling().contains(FIFF_UNIT_T))\n fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T];\n } \n\/\/ Amp = 1e-10f;\n break;\n }\n\n case FIFFV_REF_MEG_CH: { \/*11\/04\/14 Added by Limin: MEG reference channel *\/\n fMaxValue = 1e-11f;\n\n if(t_pModel->getScaling().contains(FIFF_UNIT_T))\n fMaxValue = t_pModel->getScaling()[FIFF_UNIT_T];\n\/\/ Amp = 1e-10f;\n break;\n }\n case FIFFV_EEG_CH: {\n fMaxValue = 1e-4f;\n if(t_pModel->getScaling().contains(FIFFV_EEG_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_EEG_CH];\n\/\/ Amp = 1e-4f;\n break;\n }\n case FIFFV_EOG_CH: {\n fMaxValue = 1e-3f;\n if(t_pModel->getScaling().contains(FIFFV_EOG_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_EOG_CH];\n\/\/ Amp = 1e-3f;\n break;\n }\n case FIFFV_STIM_CH: {\n fMaxValue = 5;\n if(t_pModel->getScaling().contains(FIFFV_STIM_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_STIM_CH];\n\/\/ Amp = 1.0f;\n break;\n }\n case FIFFV_MISC_CH: {\n fMaxValue = 1e-3f;\n if(t_pModel->getScaling().contains(FIFFV_MISC_CH))\n fMaxValue = t_pModel->getScaling()[FIFFV_MISC_CH];\n\/\/ Amp = 1e-3f;\n break;\n }\n }\n\n float fValue;\n float fScaleY = option.rect.height()\/(2*fMaxValue);\n\/\/ float fScaleY = Amp \/ fMaxValue;\n\n float y_base = path.currentPosition().y();\n QPointF qSamplePosition;\n\n float fDx = ((float)option.rect.width()) \/ t_pModel->getMaxSamples();\n\n \/\/Move to initial starting point\n if(data.size() > 0)\n {\n\/\/ float val = data[0];\n fValue = 0;\/\/(val-data[0])*fScaleY;\n\n float newY = y_base-fValue;\/\/Reverse direction -> plot the right way\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX(path.currentPosition().x());\n\n path.moveTo(qSamplePosition);\n }\n\n \/\/create lines from one to the next sample\n qint32 i;\n for(i = 1; i < data.size(); ++i) {\n float val = data[i] - data[0]; \/\/remove first sample data[0] as offset\n fValue = val*fScaleY;\n \/\/qDebug()<<\"val\"< plot the right way\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX(path.currentPosition().x()+fDx);\n\n path.lineTo(qSamplePosition);\n }\n\n \/\/create lines from one to the next sample for last path\n qint32 sample_offset = t_pModel->numVLines() + 1;\n qSamplePosition.setX(qSamplePosition.x() + fDx*sample_offset);\n lastPath.moveTo(qSamplePosition);\n\n for(i += sample_offset; i < lastData.size(); ++i) {\n float val = lastData[i] - lastData[0]; \/\/remove first sample lastData[0] as offset\n fValue = val*fScaleY;\n\n float newY = y_base-fValue;\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX(lastPath.currentPosition().x()+fDx);\n\n lastPath.lineTo(qSamplePosition);\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid RealTimeMultiSampleArrayDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, QList< QVector >& data) const\n{\n Q_UNUSED(data)\n\n const RealTimeMultiSampleArrayModel* t_pModel = static_cast(index.model());\n\n if(t_pModel->numVLines() > 0)\n {\n \/\/horizontal lines\n float distance = option.rect.width()\/(t_pModel->numVLines()+1);\n\n float yStart = option.rect.topLeft().y();\n\n float yEnd = option.rect.bottomRight().y();\n\n for(qint8 i = 0; i < t_pModel->numVLines(); ++i) {\n float x = distance*(i+1);\n path.moveTo(x,yStart);\n path.lineTo(x,yEnd);\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/\/ This file was copied from apache::thrift::server::TThreadedServer.cpp v0.9.0, with the\n\/\/ significant changes noted inline below.\n\n#include \"rpc\/TAcceptQueueServer.h\"\n\n#include \n\n#include \"util\/thread-pool.h\"\n\nDEFINE_int32(accepted_cnxn_queue_depth, 10000,\n \"(Advanced) The size of the post-accept, pre-setup connection queue for Impala \"\n \"internal connections\");\n\nnamespace apache {\nnamespace thrift {\nnamespace server {\n\nusing boost::shared_ptr;\nusing namespace std;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\nusing namespace apache::thrift::concurrency;\nusing namespace impala;\n\nclass TAcceptQueueServer::Task : public Runnable {\n public:\n Task(TAcceptQueueServer& server, shared_ptr processor,\n shared_ptr input, shared_ptr output,\n shared_ptr transport)\n : server_(server),\n processor_(std::move(processor)),\n input_(std::move(input)),\n output_(std::move(output)),\n transport_(std::move(transport)) {}\n\n ~Task() override = default;\n\n void run() override {\n boost::shared_ptr eventHandler = server_.getEventHandler();\n void* connectionContext = nullptr;\n if (eventHandler != nullptr) {\n connectionContext = eventHandler->createContext(input_, output_);\n }\n try {\n for (;;) {\n if (eventHandler != nullptr) {\n eventHandler->processContext(connectionContext, transport_);\n }\n if (!processor_->process(input_, output_, connectionContext)\n || !input_->getTransport()->peek()) {\n break;\n }\n }\n } catch (const TTransportException& ttx) {\n if (ttx.getType() != TTransportException::END_OF_FILE) {\n string errStr = string(\"TAcceptQueueServer client died: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n } catch (const std::exception& x) {\n GlobalOutput.printf(\n \"TAcceptQueueServer exception: %s: %s\", typeid(x).name(), x.what());\n } catch (...) {\n GlobalOutput(\"TAcceptQueueServer uncaught exception.\");\n }\n if (eventHandler != nullptr) {\n eventHandler->deleteContext(connectionContext, input_, output_);\n }\n\n try {\n input_->getTransport()->close();\n } catch (TTransportException& ttx) {\n string errStr = string(\"TAcceptQueueServer input close failed: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n output_->getTransport()->close();\n } catch (TTransportException& ttx) {\n string errStr = string(\"TAcceptQueueServer output close failed: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n\n \/\/ Remove this task from parent bookkeeping\n {\n Synchronized s(server_.tasksMonitor_);\n server_.tasks_.erase(this);\n server_.tasksMonitor_.notify();\n }\n }\n\n private:\n TAcceptQueueServer& server_;\n friend class TAcceptQueueServer;\n\n shared_ptr processor_;\n shared_ptr input_;\n shared_ptr output_;\n shared_ptr transport_;\n};\n\nTAcceptQueueServer::TAcceptQueueServer(const boost::shared_ptr& processor,\n const boost::shared_ptr& serverTransport,\n const boost::shared_ptr& transportFactory,\n const boost::shared_ptr& protocolFactory,\n const boost::shared_ptr& threadFactory,\n int32_t maxTasks)\n : TServer(processor, serverTransport, transportFactory, protocolFactory),\n threadFactory_(threadFactory), maxTasks_(maxTasks) {\n init();\n}\n\nvoid TAcceptQueueServer::init() {\n stop_ = false;\n metrics_enabled_ = false;\n queue_size_metric_ = nullptr;\n\n if (!threadFactory_) {\n threadFactory_.reset(new PlatformThreadFactory);\n }\n}\n\n\/\/ New.\nvoid TAcceptQueueServer::SetupConnection(boost::shared_ptr client) {\n if (metrics_enabled_) queue_size_metric_->Increment(-1);\n shared_ptr inputTransport;\n shared_ptr outputTransport;\n try {\n inputTransport = inputTransportFactory_->getTransport(client);\n outputTransport = outputTransportFactory_->getTransport(client);\n shared_ptr inputProtocol =\n inputProtocolFactory_->getProtocol(inputTransport);\n shared_ptr outputProtocol =\n outputProtocolFactory_->getProtocol(outputTransport);\n\n shared_ptr processor =\n getProcessor(inputProtocol, outputProtocol, client);\n\n TAcceptQueueServer::Task* task = new TAcceptQueueServer::Task(\n *this, processor, inputProtocol, outputProtocol, client);\n\n \/\/ Create a task\n shared_ptr runnable = shared_ptr(task);\n\n \/\/ Create a thread for this task\n shared_ptr thread = shared_ptr(threadFactory_->newThread(runnable));\n\n \/\/ Insert thread into the set of threads\n {\n Synchronized s(tasksMonitor_);\n while (maxTasks_ > 0 && tasks_.size() >= maxTasks_) {\n tasksMonitor_.wait();\n }\n tasks_.insert(task);\n }\n\n \/\/ Start the thread!\n thread->start();\n } catch (TException& tx) {\n if (inputTransport != nullptr) {\n inputTransport->close();\n }\n if (outputTransport != nullptr) {\n outputTransport->close();\n }\n if (client != nullptr) {\n client->close();\n }\n string errStr = string(\"TAcceptQueueServer: Caught TException: \") + tx.what();\n GlobalOutput(errStr.c_str());\n } catch (string s) {\n if (inputTransport != nullptr) {\n inputTransport->close();\n }\n if (outputTransport != nullptr) {\n outputTransport->close();\n }\n if (client != nullptr) {\n client->close();\n }\n string errStr = \"TAcceptQueueServer: Unknown exception: \" + s;\n GlobalOutput(errStr.c_str());\n }\n}\n\nvoid TAcceptQueueServer::serve() {\n \/\/ Start the server listening\n serverTransport_->listen();\n\n \/\/ Run the preServe event\n if (eventHandler_ != nullptr) {\n eventHandler_->preServe();\n }\n\n \/\/ Only using one thread here is sufficient for performance, and it avoids potential\n \/\/ thread safety issues with the thrift code called in SetupConnection.\n constexpr int CONNECTION_SETUP_POOL_SIZE = 1;\n\n \/\/ New - this is the thread pool used to process the internal accept queue.\n ThreadPool> connection_setup_pool(\"setup-server\", \"setup-worker\",\n CONNECTION_SETUP_POOL_SIZE, FLAGS_accepted_cnxn_queue_depth,\n [this](int tid, const shared_ptr& item) {\n this->SetupConnection(item);\n });\n \/\/ Initialize the thread pool\n Status status = connection_setup_pool.Init();\n if (!status.ok()) {\n status.AddDetail(\"TAcceptQueueServer: thread pool could not start.\");\n string errStr = status.GetDetail();\n GlobalOutput(errStr.c_str());\n stop_ = true;\n }\n\n while (!stop_) {\n try {\n \/\/ Fetch client from server\n shared_ptr client = serverTransport_->accept();\n\n \/\/ New - the work done to setup the connection has been moved to SetupConnection.\n if (!connection_setup_pool.Offer(std::move(client))) {\n string errStr = string(\"TAcceptQueueServer: thread pool unexpectedly shut down.\");\n GlobalOutput(errStr.c_str());\n stop_ = true;\n break;\n }\n if (metrics_enabled_) queue_size_metric_->Increment(1);\n } catch (TTransportException& ttx) {\n if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) {\n string errStr =\n string(\"TAcceptQueueServer: TServerTransport died on accept: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n continue;\n } catch (TException& tx) {\n string errStr = string(\"TAcceptQueueServer: Caught TException: \") + tx.what();\n GlobalOutput(errStr.c_str());\n continue;\n } catch (string s) {\n string errStr = \"TAcceptQueueServer: Unknown exception: \" + s;\n GlobalOutput(errStr.c_str());\n break;\n }\n }\n\n \/\/ If stopped manually, make sure to close server transport\n if (stop_) {\n try {\n serverTransport_->close();\n connection_setup_pool.Shutdown();\n } catch (TException& tx) {\n string errStr = string(\"TAcceptQueueServer: Exception shutting down: \") + tx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n Synchronized s(tasksMonitor_);\n while (!tasks_.empty()) {\n tasksMonitor_.wait();\n }\n } catch (TException& tx) {\n string errStr =\n string(\"TAcceptQueueServer: Exception joining workers: \") + tx.what();\n GlobalOutput(errStr.c_str());\n }\n stop_ = false;\n }\n}\n\nvoid TAcceptQueueServer::InitMetrics(MetricGroup* metrics, const string& key_prefix) {\n DCHECK(metrics != nullptr);\n stringstream queue_size_ss;\n queue_size_ss << key_prefix << \".connection-setup-queue-size\";\n queue_size_metric_ = metrics->AddGauge(queue_size_ss.str(), 0);\n metrics_enabled_ = true;\n}\n\n} \/\/ namespace server\n} \/\/ namespace thrift\n} \/\/ namespace apache\nIMPALA-7565: Add startup flag to set thrift connection setup thread pool size\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/\/ This file was copied from apache::thrift::server::TThreadedServer.cpp v0.9.0, with the\n\/\/ significant changes noted inline below.\n\n#include \"rpc\/TAcceptQueueServer.h\"\n\n#include \n\n#include \"util\/thread-pool.h\"\n\nDEFINE_int32(accepted_cnxn_queue_depth, 10000,\n \"(Advanced) The size of the post-accept, pre-setup connection queue in each thrift \"\n \"server set up to service Impala internal and external connections.\");\n\nDEFINE_int32_hidden(accepted_cnxn_setup_thread_pool_size, 1,\n \"(Advanced) The size of the thread pool that is used to process the \"\n \"post-accept, pre-setup connection queue in each thrift server set up to service \"\n \"Impala internal and external connections. Warning: This is untested for values \"\n \"greater than 1 which might exhibit unpredictable behavior and\/or cause crashes.\");\n\nnamespace apache {\nnamespace thrift {\nnamespace server {\n\nusing boost::shared_ptr;\nusing namespace std;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\nusing namespace apache::thrift::concurrency;\nusing namespace impala;\n\nclass TAcceptQueueServer::Task : public Runnable {\n public:\n Task(TAcceptQueueServer& server, shared_ptr processor,\n shared_ptr input, shared_ptr output,\n shared_ptr transport)\n : server_(server),\n processor_(std::move(processor)),\n input_(std::move(input)),\n output_(std::move(output)),\n transport_(std::move(transport)) {}\n\n ~Task() override = default;\n\n void run() override {\n boost::shared_ptr eventHandler = server_.getEventHandler();\n void* connectionContext = nullptr;\n if (eventHandler != nullptr) {\n connectionContext = eventHandler->createContext(input_, output_);\n }\n try {\n for (;;) {\n if (eventHandler != nullptr) {\n eventHandler->processContext(connectionContext, transport_);\n }\n if (!processor_->process(input_, output_, connectionContext)\n || !input_->getTransport()->peek()) {\n break;\n }\n }\n } catch (const TTransportException& ttx) {\n if (ttx.getType() != TTransportException::END_OF_FILE) {\n string errStr = string(\"TAcceptQueueServer client died: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n } catch (const std::exception& x) {\n GlobalOutput.printf(\n \"TAcceptQueueServer exception: %s: %s\", typeid(x).name(), x.what());\n } catch (...) {\n GlobalOutput(\"TAcceptQueueServer uncaught exception.\");\n }\n if (eventHandler != nullptr) {\n eventHandler->deleteContext(connectionContext, input_, output_);\n }\n\n try {\n input_->getTransport()->close();\n } catch (TTransportException& ttx) {\n string errStr = string(\"TAcceptQueueServer input close failed: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n output_->getTransport()->close();\n } catch (TTransportException& ttx) {\n string errStr = string(\"TAcceptQueueServer output close failed: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n\n \/\/ Remove this task from parent bookkeeping\n {\n Synchronized s(server_.tasksMonitor_);\n server_.tasks_.erase(this);\n server_.tasksMonitor_.notify();\n }\n }\n\n private:\n TAcceptQueueServer& server_;\n friend class TAcceptQueueServer;\n\n shared_ptr processor_;\n shared_ptr input_;\n shared_ptr output_;\n shared_ptr transport_;\n};\n\nTAcceptQueueServer::TAcceptQueueServer(const boost::shared_ptr& processor,\n const boost::shared_ptr& serverTransport,\n const boost::shared_ptr& transportFactory,\n const boost::shared_ptr& protocolFactory,\n const boost::shared_ptr& threadFactory,\n int32_t maxTasks)\n : TServer(processor, serverTransport, transportFactory, protocolFactory),\n threadFactory_(threadFactory), maxTasks_(maxTasks) {\n init();\n}\n\nvoid TAcceptQueueServer::init() {\n stop_ = false;\n metrics_enabled_ = false;\n queue_size_metric_ = nullptr;\n\n if (!threadFactory_) {\n threadFactory_.reset(new PlatformThreadFactory);\n }\n}\n\n\/\/ New.\nvoid TAcceptQueueServer::SetupConnection(boost::shared_ptr client) {\n if (metrics_enabled_) queue_size_metric_->Increment(-1);\n shared_ptr inputTransport;\n shared_ptr outputTransport;\n try {\n inputTransport = inputTransportFactory_->getTransport(client);\n outputTransport = outputTransportFactory_->getTransport(client);\n shared_ptr inputProtocol =\n inputProtocolFactory_->getProtocol(inputTransport);\n shared_ptr outputProtocol =\n outputProtocolFactory_->getProtocol(outputTransport);\n\n shared_ptr processor =\n getProcessor(inputProtocol, outputProtocol, client);\n\n TAcceptQueueServer::Task* task = new TAcceptQueueServer::Task(\n *this, processor, inputProtocol, outputProtocol, client);\n\n \/\/ Create a task\n shared_ptr runnable = shared_ptr(task);\n\n \/\/ Create a thread for this task\n shared_ptr thread = shared_ptr(threadFactory_->newThread(runnable));\n\n \/\/ Insert thread into the set of threads\n {\n Synchronized s(tasksMonitor_);\n while (maxTasks_ > 0 && tasks_.size() >= maxTasks_) {\n tasksMonitor_.wait();\n }\n tasks_.insert(task);\n }\n\n \/\/ Start the thread!\n thread->start();\n } catch (TException& tx) {\n if (inputTransport != nullptr) {\n inputTransport->close();\n }\n if (outputTransport != nullptr) {\n outputTransport->close();\n }\n if (client != nullptr) {\n client->close();\n }\n string errStr = string(\"TAcceptQueueServer: Caught TException: \") + tx.what();\n GlobalOutput(errStr.c_str());\n } catch (string s) {\n if (inputTransport != nullptr) {\n inputTransport->close();\n }\n if (outputTransport != nullptr) {\n outputTransport->close();\n }\n if (client != nullptr) {\n client->close();\n }\n string errStr = \"TAcceptQueueServer: Unknown exception: \" + s;\n GlobalOutput(errStr.c_str());\n }\n}\n\nvoid TAcceptQueueServer::serve() {\n \/\/ Start the server listening\n serverTransport_->listen();\n\n \/\/ Run the preServe event\n if (eventHandler_ != nullptr) {\n eventHandler_->preServe();\n }\n\n if (FLAGS_accepted_cnxn_setup_thread_pool_size > 1) {\n LOG(WARNING) << \"connection_setup_thread_pool_size is set to \"\n << FLAGS_accepted_cnxn_setup_thread_pool_size\n << \". Values greater than 1 are untested and might exhibit \"\n \"unpredictable behavior and\/or cause crashes.\";\n }\n \/\/ New - this is the thread pool used to process the internal accept queue.\n \/\/ TODO: IMPALA-7565: Make sure the related thrift code is thread safe and subsequently\n \/\/ enable multi-threading by default.\n ThreadPool> connection_setup_pool(\"setup-server\", \"setup-worker\",\n FLAGS_accepted_cnxn_setup_thread_pool_size, FLAGS_accepted_cnxn_queue_depth,\n [this](int tid, const shared_ptr& item) {\n this->SetupConnection(item);\n });\n \/\/ Initialize the thread pool\n Status status = connection_setup_pool.Init();\n if (!status.ok()) {\n status.AddDetail(\"TAcceptQueueServer: thread pool could not start.\");\n string errStr = status.GetDetail();\n GlobalOutput(errStr.c_str());\n stop_ = true;\n }\n\n while (!stop_) {\n try {\n \/\/ Fetch client from server\n shared_ptr client = serverTransport_->accept();\n\n \/\/ New - the work done to setup the connection has been moved to SetupConnection.\n if (!connection_setup_pool.Offer(std::move(client))) {\n string errStr = string(\"TAcceptQueueServer: thread pool unexpectedly shut down.\");\n GlobalOutput(errStr.c_str());\n stop_ = true;\n break;\n }\n if (metrics_enabled_) queue_size_metric_->Increment(1);\n } catch (TTransportException& ttx) {\n if (!stop_ || ttx.getType() != TTransportException::INTERRUPTED) {\n string errStr =\n string(\"TAcceptQueueServer: TServerTransport died on accept: \") + ttx.what();\n GlobalOutput(errStr.c_str());\n }\n continue;\n } catch (TException& tx) {\n string errStr = string(\"TAcceptQueueServer: Caught TException: \") + tx.what();\n GlobalOutput(errStr.c_str());\n continue;\n } catch (string s) {\n string errStr = \"TAcceptQueueServer: Unknown exception: \" + s;\n GlobalOutput(errStr.c_str());\n break;\n }\n }\n\n \/\/ If stopped manually, make sure to close server transport\n if (stop_) {\n try {\n serverTransport_->close();\n connection_setup_pool.Shutdown();\n } catch (TException& tx) {\n string errStr = string(\"TAcceptQueueServer: Exception shutting down: \") + tx.what();\n GlobalOutput(errStr.c_str());\n }\n try {\n Synchronized s(tasksMonitor_);\n while (!tasks_.empty()) {\n tasksMonitor_.wait();\n }\n } catch (TException& tx) {\n string errStr =\n string(\"TAcceptQueueServer: Exception joining workers: \") + tx.what();\n GlobalOutput(errStr.c_str());\n }\n stop_ = false;\n }\n}\n\nvoid TAcceptQueueServer::InitMetrics(MetricGroup* metrics, const string& key_prefix) {\n DCHECK(metrics != nullptr);\n stringstream queue_size_ss;\n queue_size_ss << key_prefix << \".connection-setup-queue-size\";\n queue_size_metric_ = metrics->AddGauge(queue_size_ss.str(), 0);\n metrics_enabled_ = true;\n}\n\n} \/\/ namespace server\n} \/\/ namespace thrift\n} \/\/ namespace apache\n<|endoftext|>"} {"text":"\/***************************************************************************\r\n * Copyright (c) 2008 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n\r\n# include \r\n#endif\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"DrawUtil.h\"\r\n#include \"Geometry.h\"\r\n#include \"Cosmetic.h\"\r\n#include \"CosmeticEdgePy.h\"\r\n#include \"CosmeticEdgePy.cpp\"\r\n\r\nusing namespace TechDraw;\r\n\r\n\/\/ returns a string which represents the object e.g. when printed in python\r\nstd::string CosmeticEdgePy::representation(void) const\r\n{\r\n std::stringstream ss;\r\n ss << \" at \" << std::hex << this;\r\n return ss.str();\r\n\/\/ return \"\";\r\n}\r\n\r\nPyObject *CosmeticEdgePy::PyMake(struct _typeobject *, PyObject *, PyObject *) \/\/ Python wrapper\r\n{\r\n \/\/ never create such objects with the constructor\r\n PyErr_SetString(PyExc_RuntimeError,\r\n \"You cannot create an instance of the abstract class 'CosmeticEdge'.\");\r\n return 0;\r\n}\r\n\r\n\/\/ constructor method\r\nint CosmeticEdgePy::PyInit(PyObject* \/*args*\/, PyObject* \/*kwd*\/)\r\n{\r\n return 0;\r\n}\r\n\r\n\/\/From Part::GeometryPy.cpp\r\nPyObject* CosmeticEdgePy::clone(PyObject *args)\r\n{\r\n if (!PyArg_ParseTuple(args, \"\"))\r\n return NULL;\r\n\r\n TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr();\r\n PyTypeObject* type = this->GetType();\r\n PyObject* cpy = 0;\r\n \/\/ let the type object decide\r\n if (type->tp_new)\r\n cpy = type->tp_new(type, this, 0);\r\n if (!cpy) {\r\n PyErr_SetString(PyExc_TypeError, \"failed to create clone of CosmeticEdge\");\r\n return 0;\r\n }\r\n\r\n TechDraw::CosmeticEdgePy* geompy = static_cast(cpy);\r\n \/\/ the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass\r\n \/\/ so delete it now to avoid a memory leak\r\n if (geompy->_pcTwinPointer) {\r\n TechDraw::CosmeticEdge* clone = static_cast(geompy->_pcTwinPointer);\r\n delete clone;\r\n }\r\n geompy->_pcTwinPointer = geom->clone();\r\n return cpy;\r\n}\r\n\r\nPyObject* CosmeticEdgePy::copy(PyObject *args)\r\n{\r\n if (!PyArg_ParseTuple(args, \"\"))\r\n return NULL;\r\n\r\n TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr();\r\n PyTypeObject* type = this->GetType();\r\n PyObject* cpy = 0;\r\n \/\/ let the type object decide\r\n if (type->tp_new)\r\n cpy = type->tp_new(type, this, 0);\r\n if (!cpy) {\r\n PyErr_SetString(PyExc_TypeError, \"failed to create copy of CosmeticEdge\");\r\n return 0;\r\n }\r\n\r\n TechDraw::CosmeticEdgePy* geompy = static_cast(cpy);\r\n \/\/ the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass\r\n \/\/ so delete it now to avoid a memory leak\r\n if (geompy->_pcTwinPointer) {\r\n TechDraw::CosmeticEdge* copy = static_cast(geompy->_pcTwinPointer);\r\n delete copy;\r\n }\r\n geompy->_pcTwinPointer = geom->copy();\r\n return cpy;\r\n}\r\n\r\nvoid CosmeticEdgePy::setFormat(Py::Object arg)\r\n{\r\n PyObject* pTuple = arg.ptr();\r\n int style = 1;\r\n double weight = 0.50;\r\n double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;\r\n App::Color c(red, blue, green, alpha);\r\n bool visible = 1; \r\n \r\n TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr();\r\n if (PyTuple_Check(pTuple)) {\r\n int tSize = (int) PyTuple_Size(pTuple);\r\n if (tSize > 3) {\r\n PyObject* pStyle = PyTuple_GetItem(pTuple,0);\r\n style = (int) PyLong_AsLong(pStyle);\r\n PyObject* pWeight = PyTuple_GetItem(pTuple,1);\r\n weight = PyFloat_AsDouble(pWeight);\r\n PyObject* pColor = PyTuple_GetItem(pTuple,2);\r\n c = DrawUtil::pyTupleToColor(pColor);\r\n PyObject* pVisible = PyTuple_GetItem(pTuple,3);\r\n visible = (bool) PyLong_AsLong(pVisible);\r\n\r\n ce->m_format.m_style = style;\r\n ce->m_format.m_weight = weight;\r\n ce->m_format.m_color = c;\r\n ce->m_format.m_visible = visible;\r\n }\r\n } else {\r\n Base::Console().Error(\"CEPI::setFormat - not a tuple!\\n\");\r\n }\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getFormat(void) const\r\n{\r\n TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr();\r\n\r\n PyObject* pStyle = PyLong_FromLong((long) ce->m_format.m_style);\r\n PyObject* pWeight = PyFloat_FromDouble(ce->m_format.m_weight);\r\n PyObject* pColor = DrawUtil::colorToPyTuple(ce->m_format.m_color);\r\n PyObject* pVisible = PyBool_FromLong((long) ce->m_format.m_visible);\r\n\r\n PyObject* result = PyTuple_New(4);\r\n\r\n PyTuple_SET_ITEM(result, 0, pStyle);\r\n PyTuple_SET_ITEM(result, 1, pWeight);\r\n PyTuple_SET_ITEM(result, 2, pColor);\r\n PyTuple_SET_ITEM(result, 3, pVisible);\r\n\r\n return Py::asObject(result);\r\n}\r\n\r\nPy::String CosmeticEdgePy::getTag(void) const\r\n{\r\n std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getTag());\r\n return Py::String(tmp);\r\n}\r\n\r\n\/\/Py::String CosmeticEdgePy::getOwner(void) const\r\n\/\/{\r\n\/\/\/\/ std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getOwner());\r\n\/\/ std::string tmp = \"not implemented yet\";\r\n\/\/ return Py::String(tmp);\r\n\/\/}\r\n\r\n\/\/TODO: make BaseGeom py-aware or convert TD geometry to ??Part::Geometry2d?? or other\r\n\/\/ py-aware class.\r\n\/\/Py::Object CosmeticEdgePy::getGeometry(void) const\r\n\/\/{\r\n\/\/\/\/ TechDraw::BaseGeom* bg = getCosmeticEdgePtr()->m_geometry;\r\n\/\/ Base::Console().Message(\"Not implemented yet\");\r\n\/\/ return Py::asObject(Py_None);\r\n\/\/}\r\n\r\n\/\/void CosmeticEdgePy::setGeometry(Py::Object arg)\r\n\/\/{\r\n\/\/ Base::Console().Message(\"Not implemented yet\");\r\n\/\/ PyObject* p = arg.ptr();\r\n\/\/ if (PyObject_TypeCheck(p, &(TechDraw::BaseGeomPy::Type))) {\r\n\/\/ \/\/TODO\r\n\/\/ } else {\r\n\/\/ std::string error = std::string(\"type must be 'BaseGeom', not \");\r\n\/\/ error += p->ob_type->tp_name;\r\n\/\/ throw Py::TypeError(error);\r\n\/\/ }\r\n\/\/}\r\n\r\nPy::Object CosmeticEdgePy::getStart(void) const\r\n{\r\n Base::Vector3d point = getCosmeticEdgePtr()->permaStart;\r\n return Py::asObject(new Base::VectorPy(point));\r\n}\r\n\r\nvoid CosmeticEdgePy::setStart(Py::Object arg)\r\n{\r\n PyObject* p = arg.ptr();\r\n Base::Vector3d pNew;\r\n if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) {\r\n pNew = static_cast(p)->value();\r\n }\r\n else if (PyObject_TypeCheck(p, &PyTuple_Type)) {\r\n pNew = Base::getVectorFromTuple(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Vector', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n pNew = DrawUtil::invertY(pNew);\r\n Base::Vector3d pEnd = getCosmeticEdgePtr()->permaEnd;\r\n pEnd = DrawUtil::invertY(pEnd);\r\n gp_Pnt gp1(pNew.x,pNew.y,pNew.z);\r\n gp_Pnt gp2(pEnd.x,pEnd.y,pEnd.z);\r\n TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2);\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e);\r\n getCosmeticEdgePtr()->permaStart = pNew;\r\n delete oldGeom;\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getEnd(void) const\r\n{\r\n Base::Vector3d point = getCosmeticEdgePtr()->permaEnd;\r\n return Py::asObject(new Base::VectorPy(point));\r\n}\r\n\r\nvoid CosmeticEdgePy::setEnd(Py::Object arg)\r\n{\r\n PyObject* p = arg.ptr();\r\n Base::Vector3d pNew;\r\n if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) {\r\n pNew = static_cast(p)->value();\r\n }\r\n else if (PyObject_TypeCheck(p, &PyTuple_Type)) {\r\n pNew = Base::getVectorFromTuple(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Vector', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n pNew = DrawUtil::invertY(pNew);\r\n Base::Vector3d pStart = getCosmeticEdgePtr()->permaStart;\r\n pStart = DrawUtil::invertY(pStart);\r\n gp_Pnt gp1(pNew.x,pNew.y,pNew.z);\r\n gp_Pnt gp2(pStart.x,pStart.y,pStart.z);\r\n TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp2, gp1);\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e);\r\n getCosmeticEdgePtr()->permaEnd = pNew;\r\n delete oldGeom;\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getRadius(void) const\r\n{\r\n double r = getCosmeticEdgePtr()->permaRadius;\r\n return Py::asObject(PyFloat_FromDouble(r));\r\n}\r\n\r\nvoid CosmeticEdgePy::setRadius(Py::Object arg)\r\n{\r\n \/\/TODO: check if the edge has a radius attrib\r\n PyObject* p = arg.ptr();\r\n double r;\r\n if (PyObject_TypeCheck(p, &PyFloat_Type)) {\r\n r = PyFloat_AsDouble(p);\r\n }\r\n else if (PyObject_TypeCheck(p, &PyLong_Type)) {\r\n r = (double) PyLong_AsLong(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Float' or 'Int', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n getCosmeticEdgePtr()->permaRadius = r;\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, r);\r\n delete oldGeom;\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getCenter(void) const\r\n{\r\n Base::Vector3d point = getCosmeticEdgePtr()->permaStart;\r\n return Py::asObject(new Base::VectorPy(point));\r\n}\r\n\r\nvoid CosmeticEdgePy::setCenter(Py::Object arg)\r\n{\r\n PyObject* p = arg.ptr();\r\n Base::Vector3d pNew;\r\n if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) {\r\n pNew = static_cast(p)->value();\r\n }\r\n else if (PyObject_TypeCheck(p, &PyTuple_Type)) {\r\n pNew = Base::getVectorFromTuple(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Vector', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n pNew = DrawUtil::invertY(pNew);\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n TechDraw::Circle* oldCircle = dynamic_cast(oldGeom);\r\n\r\n getCosmeticEdgePtr()->permaStart = pNew;\r\n getCosmeticEdgePtr()->permaEnd = pNew;\r\n getCosmeticEdgePtr()->permaRadius = oldCircle->radius;\r\n getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, oldCircle->radius);\r\n delete oldGeom;\r\n}\r\n\r\nPyObject *CosmeticEdgePy::getCustomAttributes(const char* \/*attr*\/) const\r\n{\r\n return 0;\r\n}\r\n\r\nint CosmeticEdgePy::setCustomAttributes(const char* \/*attr*\/, PyObject* \/*obj*\/)\r\n{\r\n return 0;\r\n}\r\n\r\n[TD]CosmeticEdge type guards\/***************************************************************************\r\n * Copyright (c) 2008 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n\r\n# include \r\n#endif\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"DrawUtil.h\"\r\n#include \"Geometry.h\"\r\n#include \"Cosmetic.h\"\r\n#include \"CosmeticEdgePy.h\"\r\n#include \"CosmeticEdgePy.cpp\"\r\n\r\nusing namespace TechDraw;\r\n\r\n\/\/ returns a string which represents the object e.g. when printed in python\r\nstd::string CosmeticEdgePy::representation(void) const\r\n{\r\n std::stringstream ss;\r\n ss << \" at \" << std::hex << this;\r\n return ss.str();\r\n\/\/ return \"\";\r\n}\r\n\r\nPyObject *CosmeticEdgePy::PyMake(struct _typeobject *, PyObject *, PyObject *) \/\/ Python wrapper\r\n{\r\n \/\/ never create such objects with the constructor\r\n PyErr_SetString(PyExc_RuntimeError,\r\n \"You cannot create an instance of the abstract class 'CosmeticEdge'.\");\r\n return 0;\r\n}\r\n\r\n\/\/ constructor method\r\nint CosmeticEdgePy::PyInit(PyObject* \/*args*\/, PyObject* \/*kwd*\/)\r\n{\r\n return 0;\r\n}\r\n\r\n\/\/From Part::GeometryPy.cpp\r\nPyObject* CosmeticEdgePy::clone(PyObject *args)\r\n{\r\n if (!PyArg_ParseTuple(args, \"\"))\r\n return NULL;\r\n\r\n TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr();\r\n PyTypeObject* type = this->GetType();\r\n PyObject* cpy = 0;\r\n \/\/ let the type object decide\r\n if (type->tp_new)\r\n cpy = type->tp_new(type, this, 0);\r\n if (!cpy) {\r\n PyErr_SetString(PyExc_TypeError, \"failed to create clone of CosmeticEdge\");\r\n return 0;\r\n }\r\n\r\n TechDraw::CosmeticEdgePy* geompy = static_cast(cpy);\r\n \/\/ the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass\r\n \/\/ so delete it now to avoid a memory leak\r\n if (geompy->_pcTwinPointer) {\r\n TechDraw::CosmeticEdge* clone = static_cast(geompy->_pcTwinPointer);\r\n delete clone;\r\n }\r\n geompy->_pcTwinPointer = geom->clone();\r\n return cpy;\r\n}\r\n\r\nPyObject* CosmeticEdgePy::copy(PyObject *args)\r\n{\r\n if (!PyArg_ParseTuple(args, \"\"))\r\n return NULL;\r\n\r\n TechDraw::CosmeticEdge* geom = this->getCosmeticEdgePtr();\r\n PyTypeObject* type = this->GetType();\r\n PyObject* cpy = 0;\r\n \/\/ let the type object decide\r\n if (type->tp_new)\r\n cpy = type->tp_new(type, this, 0);\r\n if (!cpy) {\r\n PyErr_SetString(PyExc_TypeError, \"failed to create copy of CosmeticEdge\");\r\n return 0;\r\n }\r\n\r\n TechDraw::CosmeticEdgePy* geompy = static_cast(cpy);\r\n \/\/ the PyMake function must have created the corresponding instance of the 'CosmeticEdge' subclass\r\n \/\/ so delete it now to avoid a memory leak\r\n if (geompy->_pcTwinPointer) {\r\n TechDraw::CosmeticEdge* copy = static_cast(geompy->_pcTwinPointer);\r\n delete copy;\r\n }\r\n geompy->_pcTwinPointer = geom->copy();\r\n return cpy;\r\n}\r\n\r\nvoid CosmeticEdgePy::setFormat(Py::Object arg)\r\n{\r\n PyObject* pTuple = arg.ptr();\r\n int style = 1;\r\n double weight = 0.50;\r\n double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0;\r\n App::Color c(red, blue, green, alpha);\r\n bool visible = 1; \r\n \r\n TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr();\r\n if (PyTuple_Check(pTuple)) {\r\n int tSize = (int) PyTuple_Size(pTuple);\r\n if (tSize > 3) {\r\n PyObject* pStyle = PyTuple_GetItem(pTuple,0);\r\n style = (int) PyLong_AsLong(pStyle);\r\n PyObject* pWeight = PyTuple_GetItem(pTuple,1);\r\n weight = PyFloat_AsDouble(pWeight);\r\n PyObject* pColor = PyTuple_GetItem(pTuple,2);\r\n c = DrawUtil::pyTupleToColor(pColor);\r\n PyObject* pVisible = PyTuple_GetItem(pTuple,3);\r\n visible = (bool) PyLong_AsLong(pVisible);\r\n\r\n ce->m_format.m_style = style;\r\n ce->m_format.m_weight = weight;\r\n ce->m_format.m_color = c;\r\n ce->m_format.m_visible = visible;\r\n }\r\n } else {\r\n Base::Console().Error(\"CEPI::setFormat - not a tuple!\\n\");\r\n }\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getFormat(void) const\r\n{\r\n TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr();\r\n\r\n PyObject* pStyle = PyLong_FromLong((long) ce->m_format.m_style);\r\n PyObject* pWeight = PyFloat_FromDouble(ce->m_format.m_weight);\r\n PyObject* pColor = DrawUtil::colorToPyTuple(ce->m_format.m_color);\r\n PyObject* pVisible = PyBool_FromLong((long) ce->m_format.m_visible);\r\n\r\n PyObject* result = PyTuple_New(4);\r\n\r\n PyTuple_SET_ITEM(result, 0, pStyle);\r\n PyTuple_SET_ITEM(result, 1, pWeight);\r\n PyTuple_SET_ITEM(result, 2, pColor);\r\n PyTuple_SET_ITEM(result, 3, pVisible);\r\n\r\n return Py::asObject(result);\r\n}\r\n\r\nPy::String CosmeticEdgePy::getTag(void) const\r\n{\r\n std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getTag());\r\n return Py::String(tmp);\r\n}\r\n\r\n\/\/Py::String CosmeticEdgePy::getOwner(void) const\r\n\/\/{\r\n\/\/\/\/ std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getOwner());\r\n\/\/ std::string tmp = \"not implemented yet\";\r\n\/\/ return Py::String(tmp);\r\n\/\/}\r\n\r\n\/\/TODO: make BaseGeom py-aware or convert TD geometry to ??Part::Geometry2d?? or other\r\n\/\/ py-aware class.\r\n\/\/Py::Object CosmeticEdgePy::getGeometry(void) const\r\n\/\/{\r\n\/\/\/\/ TechDraw::BaseGeom* bg = getCosmeticEdgePtr()->m_geometry;\r\n\/\/ Base::Console().Message(\"Not implemented yet\");\r\n\/\/ return Py::asObject(Py_None);\r\n\/\/}\r\n\r\n\/\/void CosmeticEdgePy::setGeometry(Py::Object arg)\r\n\/\/{\r\n\/\/ Base::Console().Message(\"Not implemented yet\");\r\n\/\/ PyObject* p = arg.ptr();\r\n\/\/ if (PyObject_TypeCheck(p, &(TechDraw::BaseGeomPy::Type))) {\r\n\/\/ \/\/TODO\r\n\/\/ } else {\r\n\/\/ std::string error = std::string(\"type must be 'BaseGeom', not \");\r\n\/\/ error += p->ob_type->tp_name;\r\n\/\/ throw Py::TypeError(error);\r\n\/\/ }\r\n\/\/}\r\n\r\nPy::Object CosmeticEdgePy::getStart(void) const\r\n{\r\n Base::Vector3d point = getCosmeticEdgePtr()->permaStart;\r\n return Py::asObject(new Base::VectorPy(point));\r\n}\r\n\r\nvoid CosmeticEdgePy::setStart(Py::Object arg)\r\n{\r\n PyObject* p = arg.ptr();\r\n Base::Vector3d pNew;\r\n if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) {\r\n pNew = static_cast(p)->value();\r\n }\r\n else if (PyObject_TypeCheck(p, &PyTuple_Type)) {\r\n pNew = Base::getVectorFromTuple(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Vector', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n pNew = DrawUtil::invertY(pNew);\r\n Base::Vector3d pEnd = getCosmeticEdgePtr()->permaEnd;\r\n pEnd = DrawUtil::invertY(pEnd);\r\n gp_Pnt gp1(pNew.x,pNew.y,pNew.z);\r\n gp_Pnt gp2(pEnd.x,pEnd.y,pEnd.z);\r\n TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2);\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e);\r\n getCosmeticEdgePtr()->permaStart = pNew;\r\n delete oldGeom;\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getEnd(void) const\r\n{\r\n Base::Vector3d point = getCosmeticEdgePtr()->permaEnd;\r\n return Py::asObject(new Base::VectorPy(point));\r\n}\r\n\r\nvoid CosmeticEdgePy::setEnd(Py::Object arg)\r\n{\r\n PyObject* p = arg.ptr();\r\n Base::Vector3d pNew;\r\n if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) {\r\n pNew = static_cast(p)->value();\r\n }\r\n else if (PyObject_TypeCheck(p, &PyTuple_Type)) {\r\n pNew = Base::getVectorFromTuple(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Vector', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n pNew = DrawUtil::invertY(pNew);\r\n Base::Vector3d pStart = getCosmeticEdgePtr()->permaStart;\r\n pStart = DrawUtil::invertY(pStart);\r\n gp_Pnt gp1(pNew.x,pNew.y,pNew.z);\r\n gp_Pnt gp2(pStart.x,pStart.y,pStart.z);\r\n TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp2, gp1);\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n getCosmeticEdgePtr()->m_geometry = TechDraw::BaseGeom::baseFactory(e);\r\n getCosmeticEdgePtr()->permaEnd = pNew;\r\n delete oldGeom;\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getRadius(void) const\r\n{\r\n TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType;\r\n if ( (gt != TechDraw::GeomType::CIRCLE) &&\r\n (gt != TechDraw::GeomType::ARCOFCIRCLE) ) {\r\n std::string error = \"not a cirle. Can not set radius\";\r\n throw Py::TypeError(error);\r\n }\r\n double r = getCosmeticEdgePtr()->permaRadius;\r\n return Py::asObject(PyFloat_FromDouble(r));\r\n}\r\n\r\nvoid CosmeticEdgePy::setRadius(Py::Object arg)\r\n{\r\n TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType;\r\n PyObject* p = arg.ptr();\r\n if ( (gt != TechDraw::GeomType::CIRCLE) &&\r\n (gt != TechDraw::GeomType::ARCOFCIRCLE) ) {\r\n std::string error = std::string(p->ob_type->tp_name);\r\n error += \" is not a cirle. Can not set radius\";\r\n throw Py::TypeError(error);\r\n }\r\n\r\n double r;\r\n if (PyObject_TypeCheck(p, &PyFloat_Type)) {\r\n r = PyFloat_AsDouble(p);\r\n }\r\n else if (PyObject_TypeCheck(p, &PyLong_Type)) {\r\n r = (double) PyLong_AsLong(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Float' or 'Int', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n getCosmeticEdgePtr()->permaRadius = r;\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, r);\r\n delete oldGeom;\r\n}\r\n\r\nPy::Object CosmeticEdgePy::getCenter(void) const\r\n{\r\n TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType;\r\n if ( (gt != TechDraw::GeomType::CIRCLE) &&\r\n (gt != TechDraw::GeomType::ARCOFCIRCLE) ) {\r\n std::string error = \"not a cirle. Can not get center\";\r\n throw Py::TypeError(error);\r\n }\r\n Base::Vector3d point = getCosmeticEdgePtr()->permaStart;\r\n return Py::asObject(new Base::VectorPy(point));\r\n}\r\n\r\nvoid CosmeticEdgePy::setCenter(Py::Object arg)\r\n{\r\n TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType;\r\n PyObject* p = arg.ptr();\r\n if ( (gt != TechDraw::GeomType::CIRCLE) &&\r\n (gt != TechDraw::GeomType::ARCOFCIRCLE) ) {\r\n std::string error = std::string(p->ob_type->tp_name);\r\n error += \" is not a cirle. Can not set center\";\r\n throw Py::TypeError(error);\r\n }\r\n\r\n\/\/ PyObject* p = arg.ptr();\r\n Base::Vector3d pNew;\r\n if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) {\r\n pNew = static_cast(p)->value();\r\n }\r\n else if (PyObject_TypeCheck(p, &PyTuple_Type)) {\r\n pNew = Base::getVectorFromTuple(p);\r\n }\r\n else {\r\n std::string error = std::string(\"type must be 'Vector', not \");\r\n error += p->ob_type->tp_name;\r\n throw Py::TypeError(error);\r\n }\r\n\r\n pNew = DrawUtil::invertY(pNew);\r\n auto oldGeom = getCosmeticEdgePtr()->m_geometry;\r\n TechDraw::Circle* oldCircle = dynamic_cast(oldGeom);\r\n\r\n getCosmeticEdgePtr()->permaStart = pNew;\r\n getCosmeticEdgePtr()->permaEnd = pNew;\r\n getCosmeticEdgePtr()->permaRadius = oldCircle->radius;\r\n getCosmeticEdgePtr()->m_geometry = new TechDraw::Circle(getCosmeticEdgePtr()->permaStart, oldCircle->radius);\r\n delete oldGeom;\r\n}\r\n\r\nPyObject *CosmeticEdgePy::getCustomAttributes(const char* \/*attr*\/) const\r\n{\r\n return 0;\r\n}\r\n\r\nint CosmeticEdgePy::setCustomAttributes(const char* \/*attr*\/, PyObject* \/*obj*\/)\r\n{\r\n return 0;\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tnamespace\n\t{\n\t\tvoid LoadMaterials(Model* model, const ModelParameters& parameters)\n\t\t{\n\t\t\tunsigned int matCount = model->GetMaterialCount();\n\n\t\t\tfor (unsigned int i = 0; i < matCount; ++i)\n\t\t\t{\n\t\t\t\tconst ParameterList& matData = model->GetMesh()->GetMaterialData(i);\n\n\t\t\t\tString filePath;\n\t\t\t\tif (matData.GetStringParameter(MaterialData::FilePath, &filePath))\n\t\t\t\t{\n\t\t\t\t\tMaterialRef material = Material::New();\n\t\t\t\t\tif (material->LoadFromFile(filePath, parameters.material))\n\t\t\t\t\t\tmodel->SetMaterial(i, std::move(material));\n\t\t\t\t\telse\n\t\t\t\t\t\tNazaraWarning(\"Failed to load material from file \" + String::Number(i));\n\t\t\t\t}\n\t\t\t\telse if (matData.HasParameter(MaterialData::CustomDefined))\n\t\t\t\t{\n\t\t\t\t\tMaterialRef material = Material::New();\n\t\t\t\t\tmaterial->BuildFromParameters(matData, parameters.material);\n\n\t\t\t\t\tmodel->SetMaterial(i, std::move(material));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTernary CheckStatic(Stream& stream, const ModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(stream);\n\n\t\t\tbool skip;\n\t\t\tif (parameters.custom.GetBooleanParameter(\"SkipNativeMeshLoader\", &skip) && skip)\n\t\t\t\treturn Ternary_False;\n\n\t\t\treturn Ternary_Unknown;\n\t\t}\n\n\t\tbool LoadStatic(Model* model, Stream& stream, const ModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(parameters);\n\n\t\t\tMeshRef mesh = Mesh::New();\n\t\t\tif (!mesh->LoadFromStream(stream, parameters.mesh))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load model mesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (mesh->IsAnimable())\n\t\t\t{\n\t\t\t\tNazaraError(\"Can't load animated mesh into static model\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tmodel->Reset();\n\t\t\tmodel->SetMesh(mesh);\n\n\t\t\tif (parameters.loadMaterials)\n\t\t\t\tLoadMaterials(model, parameters);\n\n\t\t\treturn true;\n\t\t}\n\n\t\tTernary CheckAnimated(Stream& stream, const SkeletalModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(stream);\n\n\t\t\tbool skip;\n\t\t\tif (parameters.custom.GetBooleanParameter(\"SkipNativeAnimatedMeshLoader\", &skip) && skip)\n\t\t\t\treturn Ternary_False;\n\n\t\t\treturn Ternary_Unknown;\n\t\t}\n\n\t\tbool LoadAnimated(SkeletalModel* model, Stream& stream, const SkeletalModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(parameters);\n\n\t\t\tMeshRef mesh = Mesh::New();\n\t\t\tif (!mesh->LoadFromStream(stream, parameters.mesh))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load model mesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!mesh->IsAnimable())\n\t\t\t{\n\t\t\t\tNazaraError(\"Can't load static mesh into animated model\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tmodel->Reset();\n\t\t\tmodel->SetMesh(mesh);\n\n\t\t\tif (parameters.loadMaterials)\n\t\t\t\tLoadMaterials(model, parameters);\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tnamespace Loaders\n\t{\n\t\tvoid RegisterMesh()\n\t\t{\n\t\t\tModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic);\n\t\t\tSkeletalModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated);\n\t\t}\n\n\t\tvoid UnregisterMesh()\n\t\t{\n\t\t\tModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic);\n\t\t\tSkeletalModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated);\n\t\t}\n\t}\n}\n\nDefault behaviour without precision on name\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Graphics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tnamespace\n\t{\n\t\tvoid LoadMaterials(Model* model, const ModelParameters& parameters)\n\t\t{\n\t\t\tunsigned int matCount = model->GetMaterialCount();\n\n\t\t\tfor (unsigned int i = 0; i < matCount; ++i)\n\t\t\t{\n\t\t\t\tconst ParameterList& matData = model->GetMesh()->GetMaterialData(i);\n\n\t\t\t\tString filePath;\n\t\t\t\tif (matData.GetStringParameter(MaterialData::FilePath, &filePath))\n\t\t\t\t{\n\t\t\t\t\tif (!File::Exists(filePath))\n\t\t\t\t\t{\n\t\t\t\t\t\tNazaraWarning(\"Shader name does not refer to an existing file, \\\".tga\\\" is used by default\");\n\t\t\t\t\t\tfilePath += \".tga\";\n\t\t\t\t\t}\n\n\t\t\t\t\tMaterialRef material = Material::New();\n\t\t\t\t\tif (material->LoadFromFile(filePath, parameters.material))\n\t\t\t\t\t\tmodel->SetMaterial(i, std::move(material));\n\t\t\t\t\telse\n\t\t\t\t\t\tNazaraWarning(\"Failed to load material from file \" + String::Number(i));\n\t\t\t\t}\n\t\t\t\telse if (matData.HasParameter(MaterialData::CustomDefined))\n\t\t\t\t{\n\t\t\t\t\tMaterialRef material = Material::New();\n\t\t\t\t\tmaterial->BuildFromParameters(matData, parameters.material);\n\n\t\t\t\t\tmodel->SetMaterial(i, std::move(material));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tTernary CheckStatic(Stream& stream, const ModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(stream);\n\n\t\t\tbool skip;\n\t\t\tif (parameters.custom.GetBooleanParameter(\"SkipNativeMeshLoader\", &skip) && skip)\n\t\t\t\treturn Ternary_False;\n\n\t\t\treturn Ternary_Unknown;\n\t\t}\n\n\t\tbool LoadStatic(Model* model, Stream& stream, const ModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(parameters);\n\n\t\t\tMeshRef mesh = Mesh::New();\n\t\t\tif (!mesh->LoadFromStream(stream, parameters.mesh))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load model mesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (mesh->IsAnimable())\n\t\t\t{\n\t\t\t\tNazaraError(\"Can't load animated mesh into static model\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tmodel->Reset();\n\t\t\tmodel->SetMesh(mesh);\n\n\t\t\tif (parameters.loadMaterials)\n\t\t\t\tLoadMaterials(model, parameters);\n\n\t\t\treturn true;\n\t\t}\n\n\t\tTernary CheckAnimated(Stream& stream, const SkeletalModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(stream);\n\n\t\t\tbool skip;\n\t\t\tif (parameters.custom.GetBooleanParameter(\"SkipNativeAnimatedMeshLoader\", &skip) && skip)\n\t\t\t\treturn Ternary_False;\n\n\t\t\treturn Ternary_Unknown;\n\t\t}\n\n\t\tbool LoadAnimated(SkeletalModel* model, Stream& stream, const SkeletalModelParameters& parameters)\n\t\t{\n\t\t\tNazaraUnused(parameters);\n\n\t\t\tMeshRef mesh = Mesh::New();\n\t\t\tif (!mesh->LoadFromStream(stream, parameters.mesh))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load model mesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!mesh->IsAnimable())\n\t\t\t{\n\t\t\t\tNazaraError(\"Can't load static mesh into animated model\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tmodel->Reset();\n\t\t\tmodel->SetMesh(mesh);\n\n\t\t\tif (parameters.loadMaterials)\n\t\t\t\tLoadMaterials(model, parameters);\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tnamespace Loaders\n\t{\n\t\tvoid RegisterMesh()\n\t\t{\n\t\t\tModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic);\n\t\t\tSkeletalModelLoader::RegisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated);\n\t\t}\n\n\t\tvoid UnregisterMesh()\n\t\t{\n\t\t\tModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckStatic, LoadStatic);\n\t\t\tSkeletalModelLoader::UnregisterLoader(MeshLoader::IsExtensionSupported, CheckAnimated, LoadAnimated);\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"list.h\"\n#include \"simplelist.h\"\n#include \"extArray.h\"\n#include \"stringSpace.h\"\n#include \"HashTable.h\"\n#include \"condor_classad.h\"\n#include \"classad_collection_types.h\"\n#include \"MyString.h\"\n#include \"Set.h\"\n#include \"condor_distribution.h\"\n#include \"file_transfer.h\"\n#include \"extra_param_info.h\"\n#include \"daemon.h\"\n#include \"condor_cred_base.h\"\n#include \"condor_credential.h\"\n#include \"condor_config.h\"\n#include \"condor_transfer_request.h\"\n#include \"log_transaction.h\"\n#include \"killfamily.h\"\n#include \"passwd_cache.h\"\n#include \"proc_family_direct.h\"\n#include \"credential.h\"\n\ntemplate class ExtArray;\ntemplate class SimpleList;\ntemplate class List; \t\ttemplate class Item;\ntemplate class List; \t\ttemplate class Item;\ntemplate class SimpleList; \ntemplate class SimpleList;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class HashTable;\ntemplate class HashBucket;\ntemplate class Set;\ntemplate class SetElem;\ntemplate class Set;\ntemplate class SetElem;\ntemplate class Set;\ntemplate class SetElem;\ntemplate class HashTable;\ntemplate class HashBucket;\ntemplate class HashTable;\ntemplate class HashBucket;\ntemplate class HashTable;\ntemplate class Queue;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class SimpleList;\ntemplate class HashTable;\ntemplate class SimpleList;\ntemplate class SimpleListIterator;\ntemplate class List;\ntemplate class Item;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class SimpleList ;\n\n#if defined(Solaris)\ntemplate class ExtArray;\n#endif\nFix for platforms lacking classad external.\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"list.h\"\n#include \"simplelist.h\"\n#include \"extArray.h\"\n#include \"stringSpace.h\"\n#include \"HashTable.h\"\n#include \"condor_classad.h\"\n#include \"classad_collection_types.h\"\n#include \"MyString.h\"\n#include \"Set.h\"\n#include \"condor_distribution.h\"\n#include \"file_transfer.h\"\n#include \"extra_param_info.h\"\n#include \"daemon.h\"\n#include \"condor_cred_base.h\"\n#include \"condor_credential.h\"\n#include \"condor_config.h\"\n#include \"condor_transfer_request.h\"\n#include \"log_transaction.h\"\n#include \"killfamily.h\"\n#include \"passwd_cache.h\"\n#include \"proc_family_direct.h\"\n#if HAVE_EXT_CLASSADS \n#include \"credential.h\"\n#endif\n\ntemplate class ExtArray;\ntemplate class SimpleList;\ntemplate class List; \t\ttemplate class Item;\ntemplate class List; \t\ttemplate class Item;\ntemplate class SimpleList; \ntemplate class SimpleList;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class ExtArray;\ntemplate class HashTable;\ntemplate class HashBucket;\ntemplate class Set;\ntemplate class SetElem;\ntemplate class Set;\ntemplate class SetElem;\ntemplate class Set;\ntemplate class SetElem;\ntemplate class HashTable;\ntemplate class HashBucket;\ntemplate class HashTable;\ntemplate class HashBucket;\ntemplate class HashTable;\ntemplate class Queue;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class HashTable;\ntemplate class SimpleList;\ntemplate class HashTable;\ntemplate class SimpleList;\ntemplate class SimpleListIterator;\ntemplate class List;\ntemplate class Item;\ntemplate class HashTable;\ntemplate class HashTable;\n\n#if HAVE_EXT_CLASSADS \ntemplate class SimpleList ;\n#endif\n\n#if defined(Solaris)\ntemplate class ExtArray;\n#endif\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 \"mthemedaemonprotocol.h\"\n#include \n#include \n\nusing namespace M::MThemeDaemonProtocol;\n\nconst QString M::MThemeDaemonProtocol::ServerAddress = \"m.mthemedaemon\";\nstatic const int SOCKET_DELAY_MS = 15000;\n\nPacketData::~PacketData()\n{}\n\nPixmapIdentifier::~PixmapIdentifier()\n{}\n\nNumber::~Number()\n{}\n\nString::~String()\n{}\n\nStringBool::~StringBool()\n{}\n\nPixmapHandle::~PixmapHandle()\n{}\n\nClientList::~ClientList()\n{}\n\nThemeChangeInfo::~ThemeChangeInfo()\n{}\n\nMostUsedPixmaps::~MostUsedPixmaps()\n{}\n\nRequestedPixmap::~RequestedPixmap()\n{}\n\nPacket::Packet(PacketType type, quint64 seq, PacketData *data)\n:\n m_seq (seq),\n m_data (data),\n m_type (type)\n{}\n\nPacket::~Packet()\n{}\n\nvoid Packet::setData(PacketData *data)\n{\n m_data = QSharedPointer(data);\n}\n\nQDataStream &operator<<(QDataStream &stream, const Packet &packet)\n{\n Q_ASSERT(packet.type() != Packet::Unknown);\n\n QByteArray serializedPackageData;\n QDataStream serializedPackageDataStream(&serializedPackageData, QIODevice::WriteOnly);\n writePacketData(serializedPackageDataStream, packet);\n stream.writeBytes(serializedPackageData.constData(), serializedPackageData.length());\n\n return stream;\n}\n\nvoid writePacketData(QDataStream &stream, const M::MThemeDaemonProtocol::Packet &packet)\n{\n stream << quint32(packet.type());\n stream << packet.sequenceNumber();\n\n switch (packet.type()) {\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n stream << static_cast(packet.data())->string;\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n const ThemeChangeInfo* info = static_cast(packet.data());\n stream << info->themeInheritance << info->themeLibraryNames;\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n stream << static_cast(packet.data())->value;\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n const StringBool *sb = static_cast(packet.data());\n stream << sb->string << sb->b;\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n const PixmapIdentifier *id = static_cast(packet.data());\n stream << *id;\n } break;\n\n case Packet::RequestPixmapPacket: {\n const RequestedPixmap *pixmap = static_cast(packet.data());\n stream << pixmap->priority;\n stream << pixmap->id;\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n const PixmapHandle *h = static_cast(packet.data());\n stream << *h;\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n const MostUsedPixmaps *mostUsedPixmaps = static_cast(packet.data());\n\n stream << mostUsedPixmaps->addedHandles;\n stream << mostUsedPixmaps->removedIdentifiers;\n } break;\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n const ClientList *cl = static_cast(packet.data());\n quint32 clientCount = cl->clients.count();\n stream << clientCount;\n for (uint i = 0; i < clientCount; ++i)\n {\n const ClientInfo &info = cl->clients.at(i);\n stream << info.name;\n quint32 pixmapCount = info.pixmaps.count();\n stream << pixmapCount;\n for (quint32 j = 0; j < pixmapCount; ++j) {\n stream << info.pixmaps.at(j);\n }\n quint32 requestedPixmapCount = info.requestedPixmaps.count();\n stream << requestedPixmapCount;\n for (quint32 j = 0; j < requestedPixmapCount; ++j) {\n stream << info.requestedPixmaps.at(j);\n }\n quint32 releasedPixmapCount = info.releasedPixmaps.count();\n stream << releasedPixmapCount;\n for (quint32 j = 0; j < releasedPixmapCount; ++j) {\n stream << info.releasedPixmaps.at(j);\n }\n }\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nstatic bool waitForAvailableBytes(QDataStream &stream, quint32 count)\n{\n while (stream.device()->bytesAvailable() < count) {\n if (!stream.device()->waitForReadyRead(SOCKET_DELAY_MS)) {\n return false;\n }\n }\n return true;\n}\n\nQDataStream &operator>>(QDataStream &stream, Packet &packet)\n{\n if (!waitForAvailableBytes(stream, sizeof(quint32))) {\n return stream;\n }\n quint32 length;\n stream >> length;\n if (!waitForAvailableBytes(stream, length)) {\n return stream;\n }\n\n char *raw = new char[length];\n stream.readRawData(raw, length);\n QByteArray serializedPackageData = QByteArray::fromRawData(raw, length);\n QDataStream serializedPackageDataStream(serializedPackageData);\n readPacketData(serializedPackageDataStream, packet);\n\n delete[] raw;\n\n return stream;\n}\n\nvoid readPacketData(QDataStream &stream, M::MThemeDaemonProtocol::Packet &packet)\n{\n quint32 type = 0;\n quint64 seq = 0;\n\n stream >> type >> seq;\n\n packet.setType(Packet::PacketType(type));\n packet.setSequenceNumber(seq);\n\n switch (packet.type()) {\n\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n QString string;\n stream >> string;\n packet.setData(new String(string));\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n QStringList themeInheritance, themeLibraryNames;\n stream >> themeInheritance >> themeLibraryNames;\n packet.setData(new ThemeChangeInfo(themeInheritance, themeLibraryNames));\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n qint32 priority;\n stream >> priority;\n packet.setData(new Number(priority));\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n QString string;\n stream >> string;\n bool b = false;\n stream >> b;\n packet.setData(new StringBool(string, b));\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new PixmapIdentifier(id));\n } break;\n\n case Packet::RequestPixmapPacket: {\n qint32 priority;\n stream >> priority;\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new RequestedPixmap(id, priority));\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n PixmapHandle h;\n stream >> h;\n packet.setData(new PixmapHandle(h));\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n QList addedHandles;\n stream >> addedHandles;\n\n QList removedIdentifiers;\n stream >> removedIdentifiers;\n\n packet.setData(new MostUsedPixmaps(addedHandles, removedIdentifiers));\n } break;\n\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n QList clients;\n quint32 clientCount = 0;\n stream >> clientCount;\n while (clientCount) {\n ClientInfo info;\n stream >> info.name;\n quint32 pixmapCount = 0;\n stream >> pixmapCount;\n while (pixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.pixmaps.append(id);\n --pixmapCount;\n }\n quint32 requestedPixmapCount = 0;\n stream >> requestedPixmapCount;\n while (requestedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.requestedPixmaps.append(id);\n --requestedPixmapCount;\n }\n quint32 releasedPixmapCount = 0;\n stream >> releasedPixmapCount;\n while (releasedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.releasedPixmaps.append(id);\n --releasedPixmapCount;\n }\n\n clients.append(info);\n --clientCount;\n }\n packet.setData(new ClientList(clients));\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream << handle.identifier;\n stream << quint64(quintptr(handle.pixmapHandle.xHandle));\n stream << quint64(quintptr(handle.pixmapHandle.eglHandle));\n stream << handle.pixmapHandle.shmHandle;\n stream << handle.pixmapHandle.size;\n stream << (quint64)handle.pixmapHandle.format;\n stream << handle.pixmapHandle.numBytes;\n stream << (bool)handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream >> handle.identifier;\n\n quint64 h;\n stream >> h;\n handle.pixmapHandle.xHandle = (Qt::HANDLE) quintptr(h);\n stream >> h;\n handle.pixmapHandle.eglHandle = (Qt::HANDLE) quintptr(h);\n stream >> handle.pixmapHandle.shmHandle;\n stream >> handle.pixmapHandle.size;\n stream >> h;\n handle.pixmapHandle.format = QImage::Format(h);\n stream >> handle.pixmapHandle.numBytes;\n stream >> handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n stream << id.imageId;\n stream << id.size;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n QString imageId;\n stream >> imageId;\n QSize size;\n stream >> size;\n id.imageId = imageId;\n id.size = size;\n return stream;\n}\n\nuint M::MThemeDaemonProtocol::qHash(const PixmapIdentifier &id)\n{\n using ::qHash;\n\n const uint idHash = qHash(id.imageId);\n const uint widthHash = qHash(id.size.width());\n const uint heightHash = qHash(id.size.height());\n\n \/\/ Twiddle the bits a little, taking a cue from Qt's own qHash() overloads\n return idHash ^ (widthHash << 8) ^ (widthHash >> 24) ^ (heightHash << 24) ^ (heightHash >> 8);\n}\nRevert \"Changes: fix mismatched free() \/ delete \/ delete []\"\/***************************************************************************\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 \"mthemedaemonprotocol.h\"\n#include \n#include \n\nusing namespace M::MThemeDaemonProtocol;\n\nconst QString M::MThemeDaemonProtocol::ServerAddress = \"m.mthemedaemon\";\nstatic const int SOCKET_DELAY_MS = 15000;\n\nPacketData::~PacketData()\n{}\n\nPixmapIdentifier::~PixmapIdentifier()\n{}\n\nNumber::~Number()\n{}\n\nString::~String()\n{}\n\nStringBool::~StringBool()\n{}\n\nPixmapHandle::~PixmapHandle()\n{}\n\nClientList::~ClientList()\n{}\n\nThemeChangeInfo::~ThemeChangeInfo()\n{}\n\nMostUsedPixmaps::~MostUsedPixmaps()\n{}\n\nRequestedPixmap::~RequestedPixmap()\n{}\n\nPacket::Packet(PacketType type, quint64 seq, PacketData *data)\n:\n m_seq (seq),\n m_data (data),\n m_type (type)\n{}\n\nPacket::~Packet()\n{}\n\nvoid Packet::setData(PacketData *data)\n{\n m_data = QSharedPointer(data);\n}\n\nQDataStream &operator<<(QDataStream &stream, const Packet &packet)\n{\n Q_ASSERT(packet.type() != Packet::Unknown);\n\n QByteArray serializedPackageData;\n QDataStream serializedPackageDataStream(&serializedPackageData, QIODevice::WriteOnly);\n writePacketData(serializedPackageDataStream, packet);\n stream.writeBytes(serializedPackageData.constData(), serializedPackageData.length());\n\n return stream;\n}\n\nvoid writePacketData(QDataStream &stream, const M::MThemeDaemonProtocol::Packet &packet)\n{\n stream << quint32(packet.type());\n stream << packet.sequenceNumber();\n\n switch (packet.type()) {\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n stream << static_cast(packet.data())->string;\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n const ThemeChangeInfo* info = static_cast(packet.data());\n stream << info->themeInheritance << info->themeLibraryNames;\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n stream << static_cast(packet.data())->value;\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n const StringBool *sb = static_cast(packet.data());\n stream << sb->string << sb->b;\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n const PixmapIdentifier *id = static_cast(packet.data());\n stream << *id;\n } break;\n\n case Packet::RequestPixmapPacket: {\n const RequestedPixmap *pixmap = static_cast(packet.data());\n stream << pixmap->priority;\n stream << pixmap->id;\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n const PixmapHandle *h = static_cast(packet.data());\n stream << *h;\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n const MostUsedPixmaps *mostUsedPixmaps = static_cast(packet.data());\n\n stream << mostUsedPixmaps->addedHandles;\n stream << mostUsedPixmaps->removedIdentifiers;\n } break;\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n const ClientList *cl = static_cast(packet.data());\n quint32 clientCount = cl->clients.count();\n stream << clientCount;\n for (uint i = 0; i < clientCount; ++i)\n {\n const ClientInfo &info = cl->clients.at(i);\n stream << info.name;\n quint32 pixmapCount = info.pixmaps.count();\n stream << pixmapCount;\n for (quint32 j = 0; j < pixmapCount; ++j) {\n stream << info.pixmaps.at(j);\n }\n quint32 requestedPixmapCount = info.requestedPixmaps.count();\n stream << requestedPixmapCount;\n for (quint32 j = 0; j < requestedPixmapCount; ++j) {\n stream << info.requestedPixmaps.at(j);\n }\n quint32 releasedPixmapCount = info.releasedPixmaps.count();\n stream << releasedPixmapCount;\n for (quint32 j = 0; j < releasedPixmapCount; ++j) {\n stream << info.releasedPixmaps.at(j);\n }\n }\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nstatic bool waitForAvailableBytes(QDataStream &stream, quint32 count)\n{\n while (stream.device()->bytesAvailable() < count) {\n if (!stream.device()->waitForReadyRead(SOCKET_DELAY_MS)) {\n return false;\n }\n }\n return true;\n}\n\nQDataStream &operator>>(QDataStream &stream, Packet &packet)\n{\n if (!waitForAvailableBytes(stream, sizeof(quint32))) {\n return stream;\n }\n quint32 length;\n stream >> length;\n if (!waitForAvailableBytes(stream, length)) {\n return stream;\n }\n\n char *raw = new char[length];\n stream.readRawData(raw, length);\n QByteArray serializedPackageData = QByteArray::fromRawData(raw, length);\n QDataStream serializedPackageDataStream(serializedPackageData);\n readPacketData(serializedPackageDataStream, packet);\n\n delete raw;\n\n return stream;\n}\n\nvoid readPacketData(QDataStream &stream, M::MThemeDaemonProtocol::Packet &packet)\n{\n quint32 type = 0;\n quint64 seq = 0;\n\n stream >> type >> seq;\n\n packet.setType(Packet::PacketType(type));\n packet.setSequenceNumber(seq);\n\n switch (packet.type()) {\n\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n QString string;\n stream >> string;\n packet.setData(new String(string));\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n QStringList themeInheritance, themeLibraryNames;\n stream >> themeInheritance >> themeLibraryNames;\n packet.setData(new ThemeChangeInfo(themeInheritance, themeLibraryNames));\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n qint32 priority;\n stream >> priority;\n packet.setData(new Number(priority));\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n QString string;\n stream >> string;\n bool b = false;\n stream >> b;\n packet.setData(new StringBool(string, b));\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new PixmapIdentifier(id));\n } break;\n\n case Packet::RequestPixmapPacket: {\n qint32 priority;\n stream >> priority;\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new RequestedPixmap(id, priority));\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n PixmapHandle h;\n stream >> h;\n packet.setData(new PixmapHandle(h));\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n QList addedHandles;\n stream >> addedHandles;\n\n QList removedIdentifiers;\n stream >> removedIdentifiers;\n\n packet.setData(new MostUsedPixmaps(addedHandles, removedIdentifiers));\n } break;\n\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n QList clients;\n quint32 clientCount = 0;\n stream >> clientCount;\n while (clientCount) {\n ClientInfo info;\n stream >> info.name;\n quint32 pixmapCount = 0;\n stream >> pixmapCount;\n while (pixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.pixmaps.append(id);\n --pixmapCount;\n }\n quint32 requestedPixmapCount = 0;\n stream >> requestedPixmapCount;\n while (requestedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.requestedPixmaps.append(id);\n --requestedPixmapCount;\n }\n quint32 releasedPixmapCount = 0;\n stream >> releasedPixmapCount;\n while (releasedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.releasedPixmaps.append(id);\n --releasedPixmapCount;\n }\n\n clients.append(info);\n --clientCount;\n }\n packet.setData(new ClientList(clients));\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream << handle.identifier;\n stream << quint64(quintptr(handle.pixmapHandle.xHandle));\n stream << quint64(quintptr(handle.pixmapHandle.eglHandle));\n stream << handle.pixmapHandle.shmHandle;\n stream << handle.pixmapHandle.size;\n stream << (quint64)handle.pixmapHandle.format;\n stream << handle.pixmapHandle.numBytes;\n stream << (bool)handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream >> handle.identifier;\n\n quint64 h;\n stream >> h;\n handle.pixmapHandle.xHandle = (Qt::HANDLE) quintptr(h);\n stream >> h;\n handle.pixmapHandle.eglHandle = (Qt::HANDLE) quintptr(h);\n stream >> handle.pixmapHandle.shmHandle;\n stream >> handle.pixmapHandle.size;\n stream >> h;\n handle.pixmapHandle.format = QImage::Format(h);\n stream >> handle.pixmapHandle.numBytes;\n stream >> handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n stream << id.imageId;\n stream << id.size;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n QString imageId;\n stream >> imageId;\n QSize size;\n stream >> size;\n id.imageId = imageId;\n id.size = size;\n return stream;\n}\n\nuint M::MThemeDaemonProtocol::qHash(const PixmapIdentifier &id)\n{\n using ::qHash;\n\n const uint idHash = qHash(id.imageId);\n const uint widthHash = qHash(id.size.width());\n const uint heightHash = qHash(id.size.height());\n\n \/\/ Twiddle the bits a little, taking a cue from Qt's own qHash() overloads\n return idHash ^ (widthHash << 8) ^ (widthHash >> 24) ^ (heightHash << 24) ^ (heightHash >> 8);\n}\n<|endoftext|>"} {"text":"\/*\n * FileLogDestination.cpp\n * \n * Copyright (C) 2020 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement\n * with RStudio, then this program is licensed to you under the following terms:\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, 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 the following conditions:\n *\n * The above copyright notice and this permission notice 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 IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS 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 IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\nnamespace rstudio {\nnamespace core {\nnamespace log {\n\n\/\/ FileLogOptions ======================================================================================================\nFileLogOptions::FileLogOptions(FilePath in_directory) :\n m_directory(std::move(in_directory)),\n m_fileMode(s_defaultFileMode),\n m_maxSizeMb(s_defaultMaxSizeMb),\n m_doRotation(s_defaultDoRotation),\n m_includePid(s_defaultIncludePid)\n{\n}\n\nFileLogOptions::FileLogOptions(\n FilePath in_directory,\n std::string in_fileMode,\n double in_maxSizeMb,\n bool in_doRotation,\n bool in_includePid) :\n m_directory(std::move(in_directory)),\n m_fileMode(std::move(in_fileMode)),\n m_maxSizeMb(in_maxSizeMb),\n m_doRotation(in_doRotation),\n m_includePid(in_includePid)\n{\n}\n\nconst FilePath& FileLogOptions::getDirectory() const\n{\n return m_directory;\n}\n\nconst std::string& FileLogOptions::getFileMode() const\n{\n return m_fileMode;\n}\n\ndouble FileLogOptions::getMaxSizeMb() const\n{\n return m_maxSizeMb;\n}\n\nbool FileLogOptions::doRotation() const\n{\n return m_doRotation;\n}\n\nbool FileLogOptions::includePid() const\n{\n return m_includePid;\n}\n\n\/\/ FileLogDestination ==================================================================================================\nstruct FileLogDestination::Impl\n{\n Impl(unsigned int in_id, const std::string& in_name, FileLogOptions in_options) :\n LogOptions(std::move(in_options)),\n LogName(in_name + \".log\"),\n RotatedLogName(in_name + \".old.log\"),\n Id(in_id)\n {\n LogOptions.getDirectory().ensureDirectory();\n };\n\n ~Impl()\n {\n closeLogFile();\n }\n\n void closeLogFile()\n {\n if (LogOutputStream)\n {\n LogOutputStream->flush();\n LogOutputStream.reset();\n }\n }\n\n \/\/ Returns true if the log file was opened, false otherwise.\n bool openLogFile()\n {\n \/\/ We can't safely log in this function.\n Error error = LogOptions.getDirectory().completeChildPath(LogName, LogFile);\n if (error)\n return false;\n\n error = LogFile.ensureFile();\n if (error)\n return false;\n\n error = LogFile.openForWrite(LogOutputStream, false);\n if (error)\n return false;\n\n return true;\n }\n\n \/\/ Returns true if it is safe to log; false otherwise.\n bool rotateLogFile()\n {\n \/\/ Calculate the maximum size in bytes.\n const uintmax_t maxSize = 1048576.0 * LogOptions.getMaxSizeMb();\n\n \/\/ Only rotate if we're configured to rotate.\n if (LogOptions.doRotation())\n {\n \/\/ Convert MB to B for comparison.\n if (LogFile.getSize() >= maxSize)\n {\n FilePath rotatedLogFile = FilePath(LogOptions.getDirectory()).completeChildPath(RotatedLogName);\n\n \/\/ We can't safely log errors in this function because we'll end up in an infinitely recursive\n \/\/ rotateLogFile() call.\n Error error = rotatedLogFile.remove();\n if (error)\n return false;\n\n \/\/ Close the existing log file and then move it.\n closeLogFile();\n error = LogFile.move(rotatedLogFile);\n if (error)\n return false;\n\n \/\/ Now re-open the log file.\n openLogFile();\n }\n }\n\n return LogFile.getSize() < maxSize;\n }\n\n FileLogOptions LogOptions;\n FilePath LogFile;\n std::string LogName;\n std::string RotatedLogName;\n boost::mutex Mutex;\n unsigned int Id;\n std::shared_ptr LogOutputStream;\n};\n\nFileLogDestination::FileLogDestination(\n unsigned int in_id,\n LogLevel in_logLevel,\n const std::string& in_programId,\n FileLogOptions in_logOptions) :\n ILogDestination(in_logLevel),\n m_impl(new Impl(in_id, in_programId, std::move(in_logOptions)))\n{\n}\n\nFileLogDestination::~FileLogDestination()\n{\n if (m_impl->LogOutputStream.get())\n m_impl->LogOutputStream->flush();\n}\n\nunsigned int FileLogDestination::getId() const\n{\n return m_impl->Id;\n}\n\nvoid FileLogDestination::writeLog(LogLevel in_logLevel, const std::string& in_message)\n{\n \/\/ Don't write logs that are more detailed than the configured maximum.\n if (in_logLevel > m_logLevel)\n return;\n\n \/\/ Lock the mutex before attempting to write.\n boost::unique_lock lock(m_impl->Mutex);\n\n \/\/ Open the log file if it's not open. If it fails to open, log nothing.\n if (!m_impl->LogOutputStream && !m_impl->openLogFile())\n return;\n\n \/\/ Rotate the log file if necessary.\n m_impl->rotateLogFile();\n (*m_impl->LogOutputStream) << in_message;\n m_impl->LogOutputStream->flush();\n}\n\n} \/\/ namespace log\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\nFix bug where failure to rotate a log file could cause a segfault. Fixes https:\/\/github.com\/rstudio\/rstudio-pro\/issues\/1779\/*\n * FileLogDestination.cpp\n * \n * Copyright (C) 2020 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement\n * with RStudio, then this program is licensed to you under the following terms:\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, 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 the following conditions:\n *\n * The above copyright notice and this permission notice 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 IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS 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 IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\nnamespace rstudio {\nnamespace core {\nnamespace log {\n\n\/\/ FileLogOptions ======================================================================================================\nFileLogOptions::FileLogOptions(FilePath in_directory) :\n m_directory(std::move(in_directory)),\n m_fileMode(s_defaultFileMode),\n m_maxSizeMb(s_defaultMaxSizeMb),\n m_doRotation(s_defaultDoRotation),\n m_includePid(s_defaultIncludePid)\n{\n}\n\nFileLogOptions::FileLogOptions(\n FilePath in_directory,\n std::string in_fileMode,\n double in_maxSizeMb,\n bool in_doRotation,\n bool in_includePid) :\n m_directory(std::move(in_directory)),\n m_fileMode(std::move(in_fileMode)),\n m_maxSizeMb(in_maxSizeMb),\n m_doRotation(in_doRotation),\n m_includePid(in_includePid)\n{\n}\n\nconst FilePath& FileLogOptions::getDirectory() const\n{\n return m_directory;\n}\n\nconst std::string& FileLogOptions::getFileMode() const\n{\n return m_fileMode;\n}\n\ndouble FileLogOptions::getMaxSizeMb() const\n{\n return m_maxSizeMb;\n}\n\nbool FileLogOptions::doRotation() const\n{\n return m_doRotation;\n}\n\nbool FileLogOptions::includePid() const\n{\n return m_includePid;\n}\n\n\/\/ FileLogDestination ==================================================================================================\nstruct FileLogDestination::Impl\n{\n Impl(unsigned int in_id, const std::string& in_name, FileLogOptions in_options) :\n LogOptions(std::move(in_options)),\n LogName(in_name + \".log\"),\n RotatedLogName(in_name + \".old.log\"),\n Id(in_id)\n {\n LogOptions.getDirectory().ensureDirectory();\n };\n\n ~Impl()\n {\n closeLogFile();\n }\n\n void closeLogFile()\n {\n if (LogOutputStream)\n {\n LogOutputStream->flush();\n LogOutputStream.reset();\n }\n }\n\n \/\/ Returns true if the log file was opened, false otherwise.\n bool openLogFile()\n {\n \/\/ We can't safely log in this function.\n Error error = LogOptions.getDirectory().completeChildPath(LogName, LogFile);\n if (error)\n return false;\n\n error = LogFile.ensureFile();\n if (error)\n return false;\n\n error = LogFile.openForWrite(LogOutputStream, false);\n if (error)\n return false;\n\n return true;\n }\n\n \/\/ Returns true if it is safe to log; false otherwise.\n bool rotateLogFile()\n {\n \/\/ Calculate the maximum size in bytes.\n const uintmax_t maxSize = 1048576.0 * LogOptions.getMaxSizeMb();\n\n \/\/ Only rotate if we're configured to rotate.\n if (LogOptions.doRotation())\n {\n \/\/ Convert MB to B for comparison.\n if (LogFile.getSize() >= maxSize)\n {\n FilePath rotatedLogFile = FilePath(LogOptions.getDirectory()).completeChildPath(RotatedLogName);\n\n \/\/ We can't safely log errors in this function because we'll end up in an infinitely recursive\n \/\/ rotateLogFile() call.\n Error error = rotatedLogFile.remove();\n if (error)\n return false;\n\n \/\/ Close the existing log file and then move it.\n closeLogFile();\n error = LogFile.move(rotatedLogFile);\n if (error)\n return false;\n\n \/\/ Now re-open the log file.\n if (!openLogFile())\n return false;\n }\n\n \/\/ we only sucessfully rotated (and thus are safe to log) if the\n \/\/ file size is now lower than the limit\n return LogFile.getSize() < maxSize;\n }\n else\n {\n \/\/ we are configured not to rotate logs, which means the log file can grow unboundedly large\n \/\/ thus, we are safe to log\n return true;\n }\n }\n\n FileLogOptions LogOptions;\n FilePath LogFile;\n std::string LogName;\n std::string RotatedLogName;\n boost::mutex Mutex;\n unsigned int Id;\n std::shared_ptr LogOutputStream;\n};\n\nFileLogDestination::FileLogDestination(\n unsigned int in_id,\n LogLevel in_logLevel,\n const std::string& in_programId,\n FileLogOptions in_logOptions) :\n ILogDestination(in_logLevel),\n m_impl(new Impl(in_id, in_programId, std::move(in_logOptions)))\n{\n}\n\nFileLogDestination::~FileLogDestination()\n{\n if (m_impl->LogOutputStream.get())\n m_impl->LogOutputStream->flush();\n}\n\nunsigned int FileLogDestination::getId() const\n{\n return m_impl->Id;\n}\n\nvoid FileLogDestination::writeLog(LogLevel in_logLevel, const std::string& in_message)\n{\n \/\/ Don't write logs that are more detailed than the configured maximum.\n if (in_logLevel > m_logLevel)\n return;\n\n \/\/ Lock the mutex before attempting to write.\n boost::unique_lock lock(m_impl->Mutex);\n\n \/\/ Open the log file if it's not open. If it fails to open, log nothing.\n if (!m_impl->LogOutputStream && !m_impl->openLogFile())\n return;\n\n \/\/ Rotate the log file if necessary. If it fails to rotate, log nothing.\n if (!m_impl->rotateLogFile())\n return;\n\n (*m_impl->LogOutputStream) << in_message;\n m_impl->LogOutputStream->flush();\n}\n\n} \/\/ namespace log\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n<|endoftext|>"} {"text":"#include \n#include \"RelativeDetector.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\n\nRelativeDetector::RelativeDetector()\n{\n cout << \"RelativeDetector Constructor\" << endl;\n thresh_value_ = 255;\n grad_thresh_value_ = 255;\n\n cluster_process_.set_threshold(0);\n cluster_process_.set_gate(25); \/\/ 15, 50, 100\n cluster_process_.set_min_cluster_size(30); \n\n int erosionElem = cv::MORPH_ELLIPSE;\n int erosionSize = 1;\n int dilationElem = cv::MORPH_ELLIPSE; \/\/ MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE\n int dilationSize = 1; \n\n erosionConfig_ = cv::getStructuringElement( erosionElem,\n cv::Size(2*erosionSize+1, 2*erosionSize+1),\n cv::Point(erosionSize, erosionSize) );\n \n dilationConfig_ = cv::getStructuringElement( dilationElem,\n cv::Size(2*dilationSize+1, 2*dilationSize+1),\n cv::Point(dilationSize, dilationSize) );\n}\n\nRelativeDetector::~RelativeDetector()\n{\n cout << \"RelativeDetector Destructor\" << endl;\n}\n\nvoid RelativeDetector::print()\n{\n cout << \"I am the Relative Detector\" << endl;\n}\n\nvoid RelativeDetector::set_stream(syllo::Stream *stream)\n{\n stream_ = stream;\n}\n\ndouble RelativeDetector::trajectory_diff(std::list &t1,\n std::list &t2)\n{\n \/\/ Calculate differences in trajectories\n double total_diff = 0;\n std::vector diffs;\n int frame = 0;\n std::list::iterator it1 = t1.begin();\n std::list::iterator it2 = t2.begin();\n for(; it1 != t1.end() && it2 != t2.end(); \n it1++, it2++) { \n \n double diff = pow(it1->x - it2->x, 2) + pow(it1->y - it2->y, 2);\n diffs.push_back(cv::Point2d(frame,diff)); \n total_diff += diff;\n frame++; \n }\n \/\/vectors.push_back(diffs);\n \/\/labels.push_back(\"Diff\");\n \/\/styles.push_back(\"linespoints\");\n\n \/\/vectors.push_back(costs);\n \/\/labels.push_back(\"Cost\");\n \/\/styles.push_back(\"linespoints\");\n \/\/plot.plot(vectors, title2, labels, styles);\n \n double mean = total_diff \/ (double)diffs.size();\n double RMSE = sqrt(mean);\n return RMSE;\n}\n\nvoid RelativeDetector::trajectory_polar_diff(std::list &traj,\n std::list &diffs)\n{\n std::list::reverse_iterator it = traj.rbegin();\n cv::Point2d prev;\n for(; it != traj.rend(); it++) {\n if (it == traj.rbegin()) {\n prev = it->undistorted_centroid();\n continue;\n }\n \n cv::Point2d p = it->undistorted_centroid();\n \n \/\/ Convert to polar\n double range = sqrt( pow(p.x,2) + pow(p.y,2) );\n double range_prev = sqrt( pow(prev.x,2) + pow(prev.y,2) ); \n double theta = atan(p.y \/ p.x);\n double theta_prev = atan(prev.y \/ prev.x);\n \/\/\n cv::Point2d polar(range,theta);\n cv::Point2d polar_prev(range_prev, theta_prev);\n \n double range_diff = range - range_prev;\n double theta_diff = theta - theta_prev;\n \n cv::Point2d temp;\n temp.x = range_diff;\n temp.y = theta_diff; \n \n diffs.push_back(temp); \n \n prev = it->undistorted_centroid();\n }\n}\n\nstruct TrajRMSE {\n int ID1;\n int ID2;\n double RMSE;\n};\n\nvoid RelativeDetector::trajectory_similarity(int frame_number, cv::Mat &img)\n{\n \/\/cout << \"==========================================\" << endl;\n std::map > trajectories;\n for (std::map >::iterator \n it = tracks_history_.begin(); it != tracks_history_.end(); ) {\n if (it->second.back().frame() < frame_number) {\n \/\/ Clear out track IDs that are dead\n tracks_history_.erase(it++);\n } else {\n if (it->second.back().is_tracked()) {\n \/\/cout << \"Tracked: \" << it->first << endl;\n \/\/ Compute derivative of each current track's trajectory\n trajectory_polar_diff(it->second, trajectories[it->first]); \n }\n it++;\n }\n }\n\n std::map RMSEs;\n \/\/ Store RMSE between each trajectory in a map\/hash. A string will be used\n \/\/ to hash the values. The string is of the form \"n:m\", where n and m are\n \/\/ the trajectory IDs and n is less than m.\n\n \/\/ Calculate differences between trajectory derivatives\n std::map >::iterator it_1 = trajectories.begin();\n for(; it_1 != trajectories.end(); it_1++) {\n std::map >::iterator it_2 = trajectories.begin();\n for(; it_2 != trajectories.end(); it_2++) {\n \/\/ Determine if this trajectory difference has already been\n \/\/ calculated\n std::string key;\n struct TrajRMSE traj;\n if (it_1->first == it_2->first) {\n \/\/ Don't calculate trajectory diff between two trajectories\n \/\/ with the same ID. This is the same trajectory.\n continue;\n } else if (it_1->first < it_2->first) {\n key = syllo::int2str(it_1->first) + \":\" + syllo::int2str(it_2->first);\n traj.ID1 = it_1->first;\n traj.ID2 = it_2->first;\n } else {\n key = syllo::int2str(it_2->first) + \":\" + syllo::int2str(it_1->first);\n traj.ID1 = it_2->first;\n traj.ID2 = it_1->first;\n }\n\n if (RMSEs.count(key) == 0) { \n double RMSE = trajectory_diff(it_1->second, it_2->second);\n traj.RMSE = RMSE;\n RMSEs[key] = traj;\n \/\/cout << \"--------------\" << endl;\n \/\/cout << it_1->first << \" - \" << it_2->first << \" : \" << RMSE << endl;\n }\n }\n }\n\n \/\/ Print out the RMSEs for this frame:\n \/\/cout << \"-----------------\" << endl;\n for(std::map::iterator it = RMSEs.begin();\n it != RMSEs.end(); it++) {\n \/\/cout << it->first << \": \" << it->second.RMSE << endl;\n \n \/\/ If the RMSE between two trajectories is less than a threshold,\n \/\/ circle the trajectories\n if (it->second.RMSE < 0.017) {\n \/\/ Get the two IDs in the track history and circle them\n cv::Point p1 = tracks_history_[it->second.ID1].back().centroid();\n cv::Point p2 = tracks_history_[it->second.ID2].back().centroid();\n \n \/\/cv::circle(img, p1, 10, cv::Scalar(0,255,255), 1, 8, 0);\n \/\/cv::circle(img, p2, 10, cv::Scalar(0,255,255), 1, 8, 0);\n cv::line(img, p1, p2, cv::Scalar(0,255,255), 1, 8, 0);\n } \n }\n\n cv::imshow(\"SimTraj\", img);\n}\n\nint RelativeDetector::set_frame(int frame_number, const cv::Mat &original)\n{ \n cv::Mat original_w_tracks, original_copy; \n original_w_tracks = original;\n original_copy = original;\n \n \/\/cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR);\n \/\/wb::show_nonzero(original_copy);\n \n \/\/cv::Mat bad_gray;\n \/\/cv::applyColorMap(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::cvtColor(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::imshow(\"bad\", bad_gray);\n \n cv::Mat gray;\n if (original.channels() != 1) { \n Jet2Gray_matlab(original,gray); \n } else {\n gray = original.clone();\n }\n cv::imshow(\"Gray\", gray);\n \n \/\/cv::Mat ndt_img;\n \/\/ndt_.set_frame(gray, ndt_img);\n \/\/cv::imshow(\"ndt\", ndt_img);\n \n \/\/ Compute median\n cv::Mat median;\n cv::medianBlur(gray, median,5);\n cv::imshow(\"median\", median); \n \n \/\/\/ \/\/ Compute estimated gradient\n \/\/\/ cv::Mat grad; \n \/\/\/ wb::gradient_sobel(median, grad);\n \/\/\/ cv::imshow(\"gradient\", grad);\n \/\/\/ \n \/\/\/cv::Mat thresh_grad;\n \/\/\/wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5);\n \/\/\/ cv::imshow(\"grad thresh\", thresh_grad);\n\n cv::Mat thresh_amp; \n#if 1 \n wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5);\n \n#else\n \/\/ TODO: For some reason, using this static threshold kills regular sonar\n \/\/ images, (vs. simulated sonar images), it might have to do with the\n \/\/ number of detected blobs Used for thresholding simulated sonar data\n \/\/ from Gazebo\n cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO);\n#endif\n cv::imshow(\"thresh amp\", thresh_amp);\n \n \/\/\/ cv::Mat thresh_and_grad = thresh_amp + thresh_grad;\n \/\/\/ cv::imshow(\"thresh and grad\", thresh_and_grad); \n cv::Mat erode;\n cv::erode(thresh_amp, erode, erosionConfig_);\n \/\/cv::imshow(\"erode\", erode);\n \n cv::Mat dilate;\n cv::dilate(erode, dilate, dilationConfig_);\n cv::imshow(\"Erode\/Dilate\", dilate);\n \/\/dilate = thresh_amp; \n \n cv::Mat blob_consolidate;\n blob_process_.consolidate_tracks(gray, blob_consolidate);\n cv::imshow(\"Consolidate\", blob_consolidate);\n \/\/if (found_overlap) {\n \/\/ cv::waitKey(0);\n \/\/}\n \n blob_process_.process_frame(dilate, median, thresh_value_);\n \n cv::Mat blob_img;\n blob_process_.overlay_blobs(gray, blob_img); \n \n blob_process_.overlay_tracks(blob_img, blob_img);\n cv::imshow(\"Blobs\", blob_img); \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Tracking \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n tracks_.clear(); \/\/ clear out the tracks from previous loop\n \n std::vector blobs = blob_process_.blobs();\n std::vector::iterator it = blobs.begin();\n for (; it != blobs.end(); it++) {\n\n \/\/ Have to transform tracks from distorted cartesian\n \/\/ to polar, then to undistorted cartesian\n cv::Point p = it->estimated_centroid();\n\n double x, y;\n if (stream_->type() == syllo::SonarType) { \n double range = stream_->pixel_range(p.y, p.x); \/\/row, col\n double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; \/\/ pi\/180\n y = -range*cos(bearing);\n x = range*sin(bearing);\n } else {\n x = p.x;\n y = p.y;\n }\n \n \/\/it->set_undistorted_centroid(cv::Point2f(p.x,p.y));\n it->set_undistorted_centroid(cv::Point2f(x,y));\n it->set_frame(frame_number);\n \n tracks_history_[it->id()].push_back((wb::Entity)*it);\n \n tracks_.push_back((wb::Entity)*it);\n }\n\n \/\/ Calculate Similarity between current tracks\n this->trajectory_similarity(frame_number, blob_img);\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Display images\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (!hide_windows_) { \n }\n \n return 0;\n}\n\nextern \"C\" {\n Detector *maker(){\n return new RelativeDetector;\n }\n\n class proxy {\n public:\n proxy(){\n \/\/ register the maker with the factory\n \/\/ causes static initialization error plugin_manager_.factory[\"blank_detector\"] = maker;\n plugin_manager_.factory[\"relative_detector\"] = maker;\n }\n };\n \/\/ our one instance of the proxy\n proxy p;\n}\n\n\n\/\/\/ Color map tests\n\/\/\/cv::Mat grad;\n\/\/\/create_gradient(grad, 100, 255);\n\/\/\/cv::imshow(\"gradient\", grad);\n\/\/\/\n\/\/\/cv::Mat jet_matlab;\n\/\/\/Gray2Jet_matlab(grad,jet_matlab);\n\/\/\/cv::imshow(\"jet matlab\", jet_matlab);\n\/\/\/\n\/\/\/cv::Mat gray_2;\n\/\/\/Jet2Gray_matlab(jet_matlab,gray_2);\n\/\/\/cv::imshow(\"gray_2\",gray_2);\n\/\/\/\n\/\/\/cv::Mat diff = gray_2 - grad;\n\/\/\/cv::imshow(\"diff\",diff);\n\/\/\/\n\/\/\/if (!equal(gray_2, grad)) {\n\/\/\/ cout << \"Grays are unequal\" << endl;\n\/\/\/} \nmoved track consolidation after assignment algorithm#include \n#include \"RelativeDetector.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\n\nRelativeDetector::RelativeDetector()\n{\n cout << \"RelativeDetector Constructor\" << endl;\n thresh_value_ = 255;\n grad_thresh_value_ = 255;\n\n cluster_process_.set_threshold(0);\n cluster_process_.set_gate(25); \/\/ 15, 50, 100\n cluster_process_.set_min_cluster_size(30); \n\n int erosionElem = cv::MORPH_ELLIPSE;\n int erosionSize = 1;\n int dilationElem = cv::MORPH_ELLIPSE; \/\/ MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE\n int dilationSize = 1; \n\n erosionConfig_ = cv::getStructuringElement( erosionElem,\n cv::Size(2*erosionSize+1, 2*erosionSize+1),\n cv::Point(erosionSize, erosionSize) );\n \n dilationConfig_ = cv::getStructuringElement( dilationElem,\n cv::Size(2*dilationSize+1, 2*dilationSize+1),\n cv::Point(dilationSize, dilationSize) );\n}\n\nRelativeDetector::~RelativeDetector()\n{\n cout << \"RelativeDetector Destructor\" << endl;\n}\n\nvoid RelativeDetector::print()\n{\n cout << \"I am the Relative Detector\" << endl;\n}\n\nvoid RelativeDetector::set_stream(syllo::Stream *stream)\n{\n stream_ = stream;\n}\n\ndouble RelativeDetector::trajectory_diff(std::list &t1,\n std::list &t2)\n{\n \/\/ Calculate differences in trajectories\n double total_diff = 0;\n std::vector diffs;\n int frame = 0;\n std::list::iterator it1 = t1.begin();\n std::list::iterator it2 = t2.begin();\n for(; it1 != t1.end() && it2 != t2.end(); \n it1++, it2++) { \n \n double diff = pow(it1->x - it2->x, 2) + pow(it1->y - it2->y, 2);\n diffs.push_back(cv::Point2d(frame,diff)); \n total_diff += diff;\n frame++; \n }\n \/\/vectors.push_back(diffs);\n \/\/labels.push_back(\"Diff\");\n \/\/styles.push_back(\"linespoints\");\n\n \/\/vectors.push_back(costs);\n \/\/labels.push_back(\"Cost\");\n \/\/styles.push_back(\"linespoints\");\n \/\/plot.plot(vectors, title2, labels, styles);\n \n double mean = total_diff \/ (double)diffs.size();\n double RMSE = sqrt(mean);\n return RMSE;\n}\n\nvoid RelativeDetector::trajectory_polar_diff(std::list &traj,\n std::list &diffs)\n{\n std::list::reverse_iterator it = traj.rbegin();\n cv::Point2d prev;\n for(; it != traj.rend(); it++) {\n if (it == traj.rbegin()) {\n prev = it->undistorted_centroid();\n continue;\n }\n \n cv::Point2d p = it->undistorted_centroid();\n \n \/\/ Convert to polar\n double range = sqrt( pow(p.x,2) + pow(p.y,2) );\n double range_prev = sqrt( pow(prev.x,2) + pow(prev.y,2) ); \n double theta = atan(p.y \/ p.x);\n double theta_prev = atan(prev.y \/ prev.x);\n \/\/\n cv::Point2d polar(range,theta);\n cv::Point2d polar_prev(range_prev, theta_prev);\n \n double range_diff = range - range_prev;\n double theta_diff = theta - theta_prev;\n \n cv::Point2d temp;\n temp.x = range_diff;\n temp.y = theta_diff; \n \n diffs.push_back(temp); \n \n prev = it->undistorted_centroid();\n }\n}\n\nstruct TrajRMSE {\n int ID1;\n int ID2;\n double RMSE;\n};\n\nvoid RelativeDetector::trajectory_similarity(int frame_number, cv::Mat &img)\n{\n \/\/cout << \"==========================================\" << endl;\n std::map > trajectories;\n for (std::map >::iterator \n it = tracks_history_.begin(); it != tracks_history_.end(); ) {\n if (it->second.back().frame() < frame_number) {\n \/\/ Clear out track IDs that are dead\n tracks_history_.erase(it++);\n } else {\n if (it->second.back().is_tracked()) {\n \/\/cout << \"Tracked: \" << it->first << endl;\n \/\/ Compute derivative of each current track's trajectory\n trajectory_polar_diff(it->second, trajectories[it->first]); \n }\n it++;\n }\n }\n\n std::map RMSEs;\n \/\/ Store RMSE between each trajectory in a map\/hash. A string will be used\n \/\/ to hash the values. The string is of the form \"n:m\", where n and m are\n \/\/ the trajectory IDs and n is less than m.\n\n \/\/ Calculate differences between trajectory derivatives\n std::map >::iterator it_1 = trajectories.begin();\n for(; it_1 != trajectories.end(); it_1++) {\n std::map >::iterator it_2 = trajectories.begin();\n for(; it_2 != trajectories.end(); it_2++) {\n \/\/ Determine if this trajectory difference has already been\n \/\/ calculated\n std::string key;\n struct TrajRMSE traj;\n if (it_1->first == it_2->first) {\n \/\/ Don't calculate trajectory diff between two trajectories\n \/\/ with the same ID. This is the same trajectory.\n continue;\n } else if (it_1->first < it_2->first) {\n key = syllo::int2str(it_1->first) + \":\" + syllo::int2str(it_2->first);\n traj.ID1 = it_1->first;\n traj.ID2 = it_2->first;\n } else {\n key = syllo::int2str(it_2->first) + \":\" + syllo::int2str(it_1->first);\n traj.ID1 = it_2->first;\n traj.ID2 = it_1->first;\n }\n\n if (RMSEs.count(key) == 0) { \n double RMSE = trajectory_diff(it_1->second, it_2->second);\n traj.RMSE = RMSE;\n RMSEs[key] = traj;\n \/\/cout << \"--------------\" << endl;\n \/\/cout << it_1->first << \" - \" << it_2->first << \" : \" << RMSE << endl;\n }\n }\n }\n\n \/\/ Print out the RMSEs for this frame:\n \/\/cout << \"-----------------\" << endl;\n for(std::map::iterator it = RMSEs.begin();\n it != RMSEs.end(); it++) {\n \/\/cout << it->first << \": \" << it->second.RMSE << endl;\n \n \/\/ If the RMSE between two trajectories is less than a threshold,\n \/\/ circle the trajectories\n if (it->second.RMSE < 0.017) {\n \/\/ Get the two IDs in the track history and circle them\n cv::Point p1 = tracks_history_[it->second.ID1].back().centroid();\n cv::Point p2 = tracks_history_[it->second.ID2].back().centroid();\n \n \/\/cv::circle(img, p1, 10, cv::Scalar(0,255,255), 1, 8, 0);\n \/\/cv::circle(img, p2, 10, cv::Scalar(0,255,255), 1, 8, 0);\n cv::line(img, p1, p2, cv::Scalar(0,255,255), 1, 8, 0);\n } \n }\n\n cv::imshow(\"SimTraj\", img);\n}\n\nint RelativeDetector::set_frame(int frame_number, const cv::Mat &original)\n{ \n cv::Mat original_w_tracks, original_copy; \n original_w_tracks = original;\n original_copy = original;\n \n \/\/cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR);\n \/\/wb::show_nonzero(original_copy);\n \n \/\/cv::Mat bad_gray;\n \/\/cv::applyColorMap(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::cvtColor(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::imshow(\"bad\", bad_gray);\n \n cv::Mat gray;\n if (original.channels() != 1) { \n Jet2Gray_matlab(original,gray); \n } else {\n gray = original.clone();\n }\n cv::imshow(\"Gray\", gray);\n \n \/\/cv::Mat ndt_img;\n \/\/ndt_.set_frame(gray, ndt_img);\n \/\/cv::imshow(\"ndt\", ndt_img);\n \n \/\/ Compute median\n cv::Mat median;\n cv::medianBlur(gray, median,5);\n cv::imshow(\"median\", median); \n \n \/\/\/ \/\/ Compute estimated gradient\n \/\/\/ cv::Mat grad; \n \/\/\/ wb::gradient_sobel(median, grad);\n \/\/\/ cv::imshow(\"gradient\", grad);\n \/\/\/ \n \/\/\/cv::Mat thresh_grad;\n \/\/\/wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5);\n \/\/\/ cv::imshow(\"grad thresh\", thresh_grad);\n\n cv::Mat thresh_amp; \n#if 1 \n wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5);\n \n#else\n \/\/ TODO: For some reason, using this static threshold kills regular sonar\n \/\/ images, (vs. simulated sonar images), it might have to do with the\n \/\/ number of detected blobs Used for thresholding simulated sonar data\n \/\/ from Gazebo\n cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO);\n#endif\n cv::imshow(\"thresh amp\", thresh_amp);\n \n \/\/\/ cv::Mat thresh_and_grad = thresh_amp + thresh_grad;\n \/\/\/ cv::imshow(\"thresh and grad\", thresh_and_grad); \n cv::Mat erode;\n cv::erode(thresh_amp, erode, erosionConfig_);\n \/\/cv::imshow(\"erode\", erode);\n \n cv::Mat dilate;\n cv::dilate(erode, dilate, dilationConfig_);\n cv::imshow(\"Erode\/Dilate\", dilate); \n \n blob_process_.process_frame(dilate, median, thresh_value_);\n \n cv::Mat blob_img;\n blob_process_.overlay_blobs(gray, blob_img); \n \n blob_process_.overlay_tracks(blob_img, blob_img);\n cv::imshow(\"Blobs\", blob_img); \n \n cv::Mat blob_consolidate;\n blob_process_.consolidate_tracks(gray, blob_consolidate);\n cv::imshow(\"Consolidate\", blob_consolidate); \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Tracking \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n tracks_.clear(); \/\/ clear out the tracks from previous loop\n \n std::vector blobs = blob_process_.blobs();\n std::vector::iterator it = blobs.begin();\n for (; it != blobs.end(); it++) {\n\n \/\/ Have to transform tracks from distorted cartesian\n \/\/ to polar, then to undistorted cartesian\n cv::Point p = it->estimated_centroid();\n\n double x, y;\n if (stream_->type() == syllo::SonarType) { \n double range = stream_->pixel_range(p.y, p.x); \/\/row, col\n double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; \/\/ pi\/180\n y = -range*cos(bearing);\n x = range*sin(bearing);\n } else {\n x = p.x;\n y = p.y;\n }\n \n \/\/it->set_undistorted_centroid(cv::Point2f(p.x,p.y));\n it->set_undistorted_centroid(cv::Point2f(x,y));\n it->set_frame(frame_number);\n \n tracks_history_[it->id()].push_back((wb::Entity)*it);\n \n tracks_.push_back((wb::Entity)*it);\n }\n\n \/\/ Calculate Similarity between current tracks\n this->trajectory_similarity(frame_number, blob_img);\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Display images\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (!hide_windows_) { \n }\n \n return 0;\n}\n\nextern \"C\" {\n Detector *maker(){\n return new RelativeDetector;\n }\n\n class proxy {\n public:\n proxy(){\n \/\/ register the maker with the factory\n \/\/ causes static initialization error plugin_manager_.factory[\"blank_detector\"] = maker;\n plugin_manager_.factory[\"relative_detector\"] = maker;\n }\n };\n \/\/ our one instance of the proxy\n proxy p;\n}\n\n\n\/\/\/ Color map tests\n\/\/\/cv::Mat grad;\n\/\/\/create_gradient(grad, 100, 255);\n\/\/\/cv::imshow(\"gradient\", grad);\n\/\/\/\n\/\/\/cv::Mat jet_matlab;\n\/\/\/Gray2Jet_matlab(grad,jet_matlab);\n\/\/\/cv::imshow(\"jet matlab\", jet_matlab);\n\/\/\/\n\/\/\/cv::Mat gray_2;\n\/\/\/Jet2Gray_matlab(jet_matlab,gray_2);\n\/\/\/cv::imshow(\"gray_2\",gray_2);\n\/\/\/\n\/\/\/cv::Mat diff = gray_2 - grad;\n\/\/\/cv::imshow(\"diff\",diff);\n\/\/\/\n\/\/\/if (!equal(gray_2, grad)) {\n\/\/\/ cout << \"Grays are unequal\" << endl;\n\/\/\/} \n<|endoftext|>"} {"text":"#include \n#include \"RelativeDetector.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\n\nRelativeDetector::RelativeDetector()\n{\n cout << \"RelativeDetector Constructor\" << endl;\n thresh_value_ = 255;\n grad_thresh_value_ = 255;\n\n cluster_process_.set_threshold(0);\n cluster_process_.set_gate(25); \/\/ 15, 50, 100\n cluster_process_.set_min_cluster_size(30); \n\n int erosionElem = cv::MORPH_ELLIPSE;\n int erosionSize = 2;\n int dilationElem = cv::MORPH_ELLIPSE; \/\/ MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE\n int dilationSize = 1; \n\n erosionConfig_ = cv::getStructuringElement( erosionElem,\n cv::Size(2*erosionSize+1, 2*erosionSize+1),\n cv::Point(erosionSize, erosionSize) );\n \n dilationConfig_ = cv::getStructuringElement( dilationElem,\n cv::Size(2*dilationSize+1, 2*dilationSize+1),\n cv::Point(dilationSize, dilationSize) );\n}\n\nRelativeDetector::~RelativeDetector()\n{\n cout << \"RelativeDetector Destructor\" << endl;\n}\n\nvoid RelativeDetector::print()\n{\n cout << \"I am the Relative Detector\" << endl;\n}\n\nvoid RelativeDetector::set_stream(syllo::Stream *stream)\n{\n stream_ = stream;\n}\n\n\nint RelativeDetector::set_frame(int frame_number, const cv::Mat &original)\n{ \n cv::Mat original_w_tracks, original_copy; \n original_w_tracks = original;\n original_copy = original;\n \n \/\/cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR);\n \/\/wb::show_nonzero(original_copy);\n \n \/\/cv::Mat bad_gray;\n \/\/cv::applyColorMap(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::cvtColor(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::imshow(\"bad\", bad_gray);\n \n cv::Mat gray;\n if (original.channels() != 1) { \n Jet2Gray_matlab(original,gray); \n } else {\n gray = original.clone();\n }\n cv::imshow(\"Gray\", gray);\n \n \/\/cv::Mat ndt_img;\n \/\/ndt_.set_frame(gray, ndt_img);\n \/\/cv::imshow(\"ndt\", ndt_img);\n \n \/\/ Compute median\n cv::Mat median;\n cv::medianBlur(gray, median,5);\n cv::imshow(\"median\", median); \n \n \/\/\/ \/\/ Compute estimated gradient\n \/\/\/ cv::Mat grad; \n \/\/\/ wb::gradient_sobel(median, grad);\n \/\/\/ cv::imshow(\"gradient\", grad);\n \/\/\/ \n \/\/\/cv::Mat thresh_grad;\n \/\/\/wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5);\n \/\/\/ cv::imshow(\"grad thresh\", thresh_grad);\n\n cv::Mat thresh_amp;\n#if 0 \n wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5);\n \n#else\n \/\/ Used for thresholding simulated sonar data from Gazebo\n cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO);\n#endif\n cv::imshow(\"thresh amp\", thresh_amp);\n \n \/\/\/ cv::Mat thresh_and_grad = thresh_amp + thresh_grad;\n \/\/\/ cv::imshow(\"thresh and grad\", thresh_and_grad); \n \/\/\/ cv::Mat erode;\n \/\/\/ cv::erode(thresh_amp, erode, erosionConfig_);\n \/\/\/ cv::imshow(\"erode\", erode);\n \/\/\/ \n \/\/cv::Mat dilate;\n \/\/\/ cv::dilate(erode, dilate, dilationConfig_);\n \/\/\/ cv::imshow(\"dilate\", dilate);\n \/\/dilate = thresh_amp; \n \n blob_process_.process_frame(thresh_amp, median, thresh_value_);\n \n cv::Mat blob_img;\n blob_process_.overlay_blobs(gray, blob_img); \n \n blob_process_.overlay_tracks(blob_img, blob_img);\n cv::imshow(\"Blobs\", blob_img); \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Tracking \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n tracks_.clear(); \/\/ clear out the tracks from previous loop\n \n std::vector blobs = blob_process_.blobs();\n std::vector::iterator it = blobs.begin();\n for (; it != blobs.end(); it++) {\n\n \/\/ Have to transform tracks from distorted cartesian\n \/\/ to polar, then to undistorted cartesian\n cv::Point p = it->estimated_centroid();\n\n double x, y;\n if (stream_->type() == syllo::SonarType) { \n double range = stream_->pixel_range(p.y, p.x); \/\/row, col\n double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; \/\/ pi\/180\n y = -range*cos(bearing);\n x = range*sin(bearing);\n } else {\n x = p.x;\n y = p.y;\n }\n \n \/\/it->set_undistorted_centroid(cv::Point2f(p.x,p.y));\n it->set_undistorted_centroid(cv::Point2f(x,y));\n \n tracks_.push_back((wb::Entity)*it);\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Display images\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (!hide_windows_) { \n }\n \n return 0;\n}\n\nextern \"C\" {\n Detector *maker(){\n return new RelativeDetector;\n }\n\n class proxy {\n public:\n proxy(){\n \/\/ register the maker with the factory\n \/\/ causes static initialization error plugin_manager_.factory[\"blank_detector\"] = maker;\n plugin_manager_.factory[\"relative_detector\"] = maker;\n }\n };\n \/\/ our one instance of the proxy\n proxy p;\n}\n\n\n\/\/\/ Color map tests\n\/\/\/cv::Mat grad;\n\/\/\/create_gradient(grad, 100, 255);\n\/\/\/cv::imshow(\"gradient\", grad);\n\/\/\/\n\/\/\/cv::Mat jet_matlab;\n\/\/\/Gray2Jet_matlab(grad,jet_matlab);\n\/\/\/cv::imshow(\"jet matlab\", jet_matlab);\n\/\/\/\n\/\/\/cv::Mat gray_2;\n\/\/\/Jet2Gray_matlab(jet_matlab,gray_2);\n\/\/\/cv::imshow(\"gray_2\",gray_2);\n\/\/\/\n\/\/\/cv::Mat diff = gray_2 - grad;\n\/\/\/cv::imshow(\"diff\",diff);\n\/\/\/\n\/\/\/if (!equal(gray_2, grad)) {\n\/\/\/ cout << \"Grays are unequal\" << endl;\n\/\/\/} \nchanged sim\/real switch#include \n#include \"RelativeDetector.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\n\nRelativeDetector::RelativeDetector()\n{\n cout << \"RelativeDetector Constructor\" << endl;\n thresh_value_ = 255;\n grad_thresh_value_ = 255;\n\n cluster_process_.set_threshold(0);\n cluster_process_.set_gate(25); \/\/ 15, 50, 100\n cluster_process_.set_min_cluster_size(30); \n\n int erosionElem = cv::MORPH_ELLIPSE;\n int erosionSize = 2;\n int dilationElem = cv::MORPH_ELLIPSE; \/\/ MORPH_RECT, MORPH_CROSS, MORPH_ELLIPSE\n int dilationSize = 1; \n\n erosionConfig_ = cv::getStructuringElement( erosionElem,\n cv::Size(2*erosionSize+1, 2*erosionSize+1),\n cv::Point(erosionSize, erosionSize) );\n \n dilationConfig_ = cv::getStructuringElement( dilationElem,\n cv::Size(2*dilationSize+1, 2*dilationSize+1),\n cv::Point(dilationSize, dilationSize) );\n}\n\nRelativeDetector::~RelativeDetector()\n{\n cout << \"RelativeDetector Destructor\" << endl;\n}\n\nvoid RelativeDetector::print()\n{\n cout << \"I am the Relative Detector\" << endl;\n}\n\nvoid RelativeDetector::set_stream(syllo::Stream *stream)\n{\n stream_ = stream;\n}\n\n\nint RelativeDetector::set_frame(int frame_number, const cv::Mat &original)\n{ \n cv::Mat original_w_tracks, original_copy; \n original_w_tracks = original;\n original_copy = original;\n \n \/\/cv::cvtColor(original_copy, original_copy, CV_RGBA2BGR);\n \/\/wb::show_nonzero(original_copy);\n \n \/\/cv::Mat bad_gray;\n \/\/cv::applyColorMap(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::cvtColor(original, bad_gray, CV_BGR2GRAY);\n \/\/cv::imshow(\"bad\", bad_gray);\n \n cv::Mat gray;\n if (original.channels() != 1) { \n Jet2Gray_matlab(original,gray); \n } else {\n gray = original.clone();\n }\n cv::imshow(\"Gray\", gray);\n \n \/\/cv::Mat ndt_img;\n \/\/ndt_.set_frame(gray, ndt_img);\n \/\/cv::imshow(\"ndt\", ndt_img);\n \n \/\/ Compute median\n cv::Mat median;\n cv::medianBlur(gray, median,5);\n cv::imshow(\"median\", median); \n \n \/\/\/ \/\/ Compute estimated gradient\n \/\/\/ cv::Mat grad; \n \/\/\/ wb::gradient_sobel(median, grad);\n \/\/\/ cv::imshow(\"gradient\", grad);\n \/\/\/ \n \/\/\/cv::Mat thresh_grad;\n \/\/\/wb::adaptive_threshold(grad, thresh_grad, grad_thresh_value_, 0.001, 0.002, 10, 5);\n \/\/\/ cv::imshow(\"grad thresh\", thresh_grad);\n\n cv::Mat thresh_amp; \n#if 1 \n wb::adaptive_threshold(median, thresh_amp, thresh_value_, 0.001, 0.002, 10, 5);\n \n#else\n \/\/ TODO: For some reason, using this static threshold kills regular sonar\n \/\/ images, (vs. simulated sonar images), it might have to do with the\n \/\/ number of detected blobs Used for thresholding simulated sonar data\n \/\/ from Gazebo\n cv::threshold(median, thresh_amp, 100, 255, cv::THRESH_TOZERO);\n#endif\n cv::imshow(\"thresh amp\", thresh_amp);\n \n \/\/\/ cv::Mat thresh_and_grad = thresh_amp + thresh_grad;\n \/\/\/ cv::imshow(\"thresh and grad\", thresh_and_grad); \n \/\/\/ cv::Mat erode;\n \/\/\/ cv::erode(thresh_amp, erode, erosionConfig_);\n \/\/\/ cv::imshow(\"erode\", erode);\n \/\/\/ \n \/\/cv::Mat dilate;\n \/\/\/ cv::dilate(erode, dilate, dilationConfig_);\n \/\/\/ cv::imshow(\"dilate\", dilate);\n \/\/dilate = thresh_amp; \n \n blob_process_.process_frame(thresh_amp, median, thresh_value_);\n \n cv::Mat blob_img;\n blob_process_.overlay_blobs(gray, blob_img); \n \n blob_process_.overlay_tracks(blob_img, blob_img);\n cv::imshow(\"Blobs\", blob_img); \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Tracking \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n tracks_.clear(); \/\/ clear out the tracks from previous loop\n \n std::vector blobs = blob_process_.blobs();\n std::vector::iterator it = blobs.begin();\n for (; it != blobs.end(); it++) {\n\n \/\/ Have to transform tracks from distorted cartesian\n \/\/ to polar, then to undistorted cartesian\n cv::Point p = it->estimated_centroid();\n\n double x, y;\n if (stream_->type() == syllo::SonarType) { \n double range = stream_->pixel_range(p.y, p.x); \/\/row, col\n double bearing = stream_->pixel_bearing(p.y, p.x) * 0.017453293; \/\/ pi\/180\n y = -range*cos(bearing);\n x = range*sin(bearing);\n } else {\n x = p.x;\n y = p.y;\n }\n \n \/\/it->set_undistorted_centroid(cv::Point2f(p.x,p.y));\n it->set_undistorted_centroid(cv::Point2f(x,y));\n \n tracks_.push_back((wb::Entity)*it);\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Display images\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (!hide_windows_) { \n }\n \n return 0;\n}\n\nextern \"C\" {\n Detector *maker(){\n return new RelativeDetector;\n }\n\n class proxy {\n public:\n proxy(){\n \/\/ register the maker with the factory\n \/\/ causes static initialization error plugin_manager_.factory[\"blank_detector\"] = maker;\n plugin_manager_.factory[\"relative_detector\"] = maker;\n }\n };\n \/\/ our one instance of the proxy\n proxy p;\n}\n\n\n\/\/\/ Color map tests\n\/\/\/cv::Mat grad;\n\/\/\/create_gradient(grad, 100, 255);\n\/\/\/cv::imshow(\"gradient\", grad);\n\/\/\/\n\/\/\/cv::Mat jet_matlab;\n\/\/\/Gray2Jet_matlab(grad,jet_matlab);\n\/\/\/cv::imshow(\"jet matlab\", jet_matlab);\n\/\/\/\n\/\/\/cv::Mat gray_2;\n\/\/\/Jet2Gray_matlab(jet_matlab,gray_2);\n\/\/\/cv::imshow(\"gray_2\",gray_2);\n\/\/\/\n\/\/\/cv::Mat diff = gray_2 - grad;\n\/\/\/cv::imshow(\"diff\",diff);\n\/\/\/\n\/\/\/if (!equal(gray_2, grad)) {\n\/\/\/ cout << \"Grays are unequal\" << endl;\n\/\/\/} \n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon\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\/\/$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $\n\n#include \n#include \n#include \n#include \n\nvoid register_cairo();\nvoid export_color();\nvoid export_coord();\nvoid export_layer();\nvoid export_parameters();\nvoid export_envelope();\nvoid export_query();\nvoid export_geometry();\nvoid export_image();\nvoid export_image_view();\nvoid export_map();\nvoid export_python();\nvoid export_filter();\nvoid export_rule();\nvoid export_style();\nvoid export_stroke();\nvoid export_feature();\nvoid export_featureset();\nvoid export_datasource();\nvoid export_datasource_cache();\nvoid export_point_symbolizer();\nvoid export_line_symbolizer();\nvoid export_line_pattern_symbolizer();\nvoid export_polygon_symbolizer();\nvoid export_polygon_pattern_symbolizer();\nvoid export_raster_symbolizer();\nvoid export_text_symbolizer();\nvoid export_shield_symbolizer();\nvoid export_font_engine();\nvoid export_projection();\nvoid export_proj_transform();\nvoid export_view_transform();\n\n#include \n#include \n#include \n#ifdef HAVE_CAIRO\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n#include \n#endif\n\nvoid render(const mapnik::Map& map,mapnik::Image32& image, unsigned offset_x = 0, unsigned offset_y = 0)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n mapnik::agg_renderer ren(map,image,offset_x, offset_y);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render2(const mapnik::Map& map,mapnik::Image32& image)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n mapnik::agg_renderer ren(map,image);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n\nvoid render3(const mapnik::Map& map,PycairoSurface* surface, unsigned offset_x = 0, unsigned offset_y = 0)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr s(new Cairo::Surface(surface->surface));\n mapnik::cairo_renderer ren(map,s,offset_x, offset_y);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render4(const mapnik::Map& map,PycairoSurface* surface)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr s(new Cairo::Surface(surface->surface));\n mapnik::cairo_renderer ren(map,s);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render5(const mapnik::Map& map,PycairoContext* context, unsigned offset_x = 0, unsigned offset_y = 0)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr c(new Cairo::Context(context->ctx));\n mapnik::cairo_renderer ren(map,c,offset_x, offset_y);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render6(const mapnik::Map& map,PycairoContext* context)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr c(new Cairo::Context(context->ctx));\n mapnik::cairo_renderer ren(map,c);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\n#endif\n\nvoid render_tile_to_file(const mapnik::Map& map, \n unsigned offset_x, unsigned offset_y,\n unsigned width, unsigned height,\n const std::string& file,\n const std::string& format)\n{\n mapnik::Image32 image(width,height);\n render(map,image,offset_x, offset_y);\n mapnik::save_to_file(image.data(),file,format);\n}\n\nvoid render_to_file1(const mapnik::Map& map,\n const std::string& filename,\n const std::string& format)\n{\n mapnik::Image32 image(map.getWidth(),map.getHeight());\n render(map,image,0,0);\n mapnik::save_to_file(image,filename,format); \n}\n\nvoid render_to_file2(const mapnik::Map& map,\n const std::string& filename)\n{\n mapnik::Image32 image(map.getWidth(),map.getHeight());\n render(map,image,0,0);\n mapnik::save_to_file(image,filename); \n}\n\n\ndouble scale_denominator(mapnik::Map const &map, bool geographic)\n{\n return mapnik::scale_denominator(map, geographic);\n}\n\nvoid translator(mapnik::config_error const & ex) {\n PyErr_SetString(PyExc_UserWarning, ex.what());\n}\n\nunsigned mapnik_version()\n{\n return MAPNIK_VERSION;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(load_map_overloads, load_map, 2, 3);\nBOOST_PYTHON_FUNCTION_OVERLOADS(load_map_string_overloads, load_map_string, 2, 3);\n\nBOOST_PYTHON_MODULE(_mapnik)\n{\n \n using namespace boost::python;\n\n using mapnik::load_map;\n using mapnik::load_map_string;\n using mapnik::save_map;\n\n register_exception_translator(translator);\n register_cairo();\n export_query();\n export_geometry();\n export_feature();\n export_featureset();\n export_datasource();\n export_parameters();\n export_color(); \n export_envelope(); \n export_image();\n export_image_view();\n export_filter();\n export_rule();\n export_style(); \n export_layer();\n export_stroke();\n export_datasource_cache();\n export_point_symbolizer();\n export_line_symbolizer();\n export_line_pattern_symbolizer();\n export_polygon_symbolizer();\n export_polygon_pattern_symbolizer();\n export_raster_symbolizer();\n export_text_symbolizer();\n export_shield_symbolizer();\n export_font_engine();\n export_projection();\n export_proj_transform();\n export_view_transform();\n export_coord();\n export_map();\n\n def(\"render_to_file\",&render_to_file1,\n \"\\n\"\n \"Render Map to file using explicit image type\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render_to_file, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> render_to_file(m,'image32bit.png','png')\\n\"\n \"\\n\"\n \"Format Options:\\n\"\n \"\\n\"\n \"8 bit (paletted) PNG can be requested with 'png256':\\n\"\n \">>> render_to_file(m,'image8bit.png','png256')\\n\"\n \"JPEG quality can be controlled by adding a suffix to\\n\"\n \"'jpeg' between 0 and 100 (default is 85):\\n\"\n \">>> render_to_file(m,'top_quality.jpeg','jpeg100')\\n\"\n \">>> render_to_file(m,'medium_quality.jpeg','jpeg50')\\n\"\n );\n\n def(\"render_to_file\",&render_to_file2,\n \"\\n\"\n \"Render Map to file (type taken from file extension)\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render_to_file, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> render_to_file(m,'image.jpeg')\\n\"\n \"\\n\"\n );\n\n def(\"render_tile_to_file\",&render_tile_to_file,\n \"\\n\"\n \"TODO\\n\"\n \"\\n\"\n ); \n\n \n def(\"render\",&render,\n \"\\n\"\n \"Render Map to an AGG Image32 using offsets\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, Image, render, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> im = Image(m.width,m.height)\\n\"\n \">>> render(m,im,1,1)\\n\"\n \"\\n\"\n ); \n\n def(\"render\",&render2,\n \"\\n\"\n \"Render Map to an AGG Image32\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, Image, render, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> im = Image(m.width,m.height)\\n\"\n \">>> render(m,im)\\n\"\n \"\\n\"\n );\n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n def(\"render\",&render3,\n \"\\n\"\n \"Render Map to Cairo Surface using offsets\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> render(m,surface,1,1)\\n\"\n \"\\n\"\n );\n\n def(\"render\",&render4,\n \"\\n\"\n \"Render Map to Cairo Surface\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> render(m,surface)\\n\"\n \"\\n\"\n );\n\n def(\"render\",&render5,\n \"\\n\"\n \"Render Map to Cairo Context using offsets\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface, Context\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> ctx = Context(surface)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\" \n \">>> render(m,context,1,1)\\n\"\n \"\\n\"\n );\n\n def(\"render\",&render6,\n \"\\n\"\n \"Render Map to Cairo Context\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface, Context\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> ctx = Context(surface)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> render(m,context)\\n\"\n \"\\n\"\n );\n#endif\n\n def(\"scale_denominator\", &scale_denominator,\n \"\\n\"\n \"Return the Map Scale Denominator.\\n\"\n \"Also available as Map.scale_denominator()\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \"\\n\"\n \">>> from mapnik import Map, Projection, scale_denominator, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> scale_denominator(m,Projection(m.srs).geographic)\\n\"\n \"\\n\"\n );\n \n def(\"load_map\", & load_map, load_map_overloads());\n\n def(\"load_map_from_string\", & load_map_string, load_map_string_overloads());\n\n def(\"save_map\", & save_map,\n \"\\n\"\n \"Save Map object to XML file\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, load_map, save_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile_wgs84.xml')\\n\"\n \">>> m.srs\\n\"\n \"'+proj=latlong +datum=WGS84'\\n\"\n \">>> m.srs = '+init=espg:3395'\\n\"\n \">>> save_map(m,'mapfile_mercator.xml')\\n\"\n \"\\n\"\n );\n\n def(\"mapnik_version\", &mapnik_version,\"Get the Mapnik version number\");\n \n using mapnik::symbolizer;\n class_(\"Symbolizer\",no_init)\n ;\n \n register_ptr_to_python();\n}\nminor formatting to render_to_file docstring\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon\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\/\/$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $\n\n#include \n#include \n#include \n#include \n\nvoid register_cairo();\nvoid export_color();\nvoid export_coord();\nvoid export_layer();\nvoid export_parameters();\nvoid export_envelope();\nvoid export_query();\nvoid export_geometry();\nvoid export_image();\nvoid export_image_view();\nvoid export_map();\nvoid export_python();\nvoid export_filter();\nvoid export_rule();\nvoid export_style();\nvoid export_stroke();\nvoid export_feature();\nvoid export_featureset();\nvoid export_datasource();\nvoid export_datasource_cache();\nvoid export_point_symbolizer();\nvoid export_line_symbolizer();\nvoid export_line_pattern_symbolizer();\nvoid export_polygon_symbolizer();\nvoid export_polygon_pattern_symbolizer();\nvoid export_raster_symbolizer();\nvoid export_text_symbolizer();\nvoid export_shield_symbolizer();\nvoid export_font_engine();\nvoid export_projection();\nvoid export_proj_transform();\nvoid export_view_transform();\n\n#include \n#include \n#include \n#ifdef HAVE_CAIRO\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n#include \n#endif\n\nvoid render(const mapnik::Map& map,mapnik::Image32& image, unsigned offset_x = 0, unsigned offset_y = 0)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n mapnik::agg_renderer ren(map,image,offset_x, offset_y);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render2(const mapnik::Map& map,mapnik::Image32& image)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n mapnik::agg_renderer ren(map,image);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n\nvoid render3(const mapnik::Map& map,PycairoSurface* surface, unsigned offset_x = 0, unsigned offset_y = 0)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr s(new Cairo::Surface(surface->surface));\n mapnik::cairo_renderer ren(map,s,offset_x, offset_y);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render4(const mapnik::Map& map,PycairoSurface* surface)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr s(new Cairo::Surface(surface->surface));\n mapnik::cairo_renderer ren(map,s);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render5(const mapnik::Map& map,PycairoContext* context, unsigned offset_x = 0, unsigned offset_y = 0)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr c(new Cairo::Context(context->ctx));\n mapnik::cairo_renderer ren(map,c,offset_x, offset_y);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\nvoid render6(const mapnik::Map& map,PycairoContext* context)\n{\n Py_BEGIN_ALLOW_THREADS\n try\n {\n Cairo::RefPtr c(new Cairo::Context(context->ctx));\n mapnik::cairo_renderer ren(map,c);\n ren.apply();\n }\n catch (...)\n {\n Py_BLOCK_THREADS\n throw;\n }\n Py_END_ALLOW_THREADS\n}\n\n#endif\n\nvoid render_tile_to_file(const mapnik::Map& map, \n unsigned offset_x, unsigned offset_y,\n unsigned width, unsigned height,\n const std::string& file,\n const std::string& format)\n{\n mapnik::Image32 image(width,height);\n render(map,image,offset_x, offset_y);\n mapnik::save_to_file(image.data(),file,format);\n}\n\nvoid render_to_file1(const mapnik::Map& map,\n const std::string& filename,\n const std::string& format)\n{\n mapnik::Image32 image(map.getWidth(),map.getHeight());\n render(map,image,0,0);\n mapnik::save_to_file(image,filename,format); \n}\n\nvoid render_to_file2(const mapnik::Map& map,\n const std::string& filename)\n{\n mapnik::Image32 image(map.getWidth(),map.getHeight());\n render(map,image,0,0);\n mapnik::save_to_file(image,filename); \n}\n\n\ndouble scale_denominator(mapnik::Map const &map, bool geographic)\n{\n return mapnik::scale_denominator(map, geographic);\n}\n\nvoid translator(mapnik::config_error const & ex) {\n PyErr_SetString(PyExc_UserWarning, ex.what());\n}\n\nunsigned mapnik_version()\n{\n return MAPNIK_VERSION;\n}\n\nBOOST_PYTHON_FUNCTION_OVERLOADS(load_map_overloads, load_map, 2, 3);\nBOOST_PYTHON_FUNCTION_OVERLOADS(load_map_string_overloads, load_map_string, 2, 3);\n\nBOOST_PYTHON_MODULE(_mapnik)\n{\n \n using namespace boost::python;\n\n using mapnik::load_map;\n using mapnik::load_map_string;\n using mapnik::save_map;\n\n register_exception_translator(translator);\n register_cairo();\n export_query();\n export_geometry();\n export_feature();\n export_featureset();\n export_datasource();\n export_parameters();\n export_color(); \n export_envelope(); \n export_image();\n export_image_view();\n export_filter();\n export_rule();\n export_style(); \n export_layer();\n export_stroke();\n export_datasource_cache();\n export_point_symbolizer();\n export_line_symbolizer();\n export_line_pattern_symbolizer();\n export_polygon_symbolizer();\n export_polygon_pattern_symbolizer();\n export_raster_symbolizer();\n export_text_symbolizer();\n export_shield_symbolizer();\n export_font_engine();\n export_projection();\n export_proj_transform();\n export_view_transform();\n export_coord();\n export_map();\n\n def(\"render_to_file\",&render_to_file1,\n \"\\n\"\n \"Render Map to file using explicit image type.\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render_to_file, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> render_to_file(m,'image32bit.png','png')\\n\"\n \"\\n\"\n \"8 bit (paletted) PNG can be requested with 'png256':\\n\"\n \">>> render_to_file(m,'8bit_image.png','png256')\\n\"\n \"\\n\"\n \"JPEG quality can be controlled by adding a suffix to\\n\"\n \"'jpeg' between 0 and 100 (default is 85):\\n\"\n \">>> render_to_file(m,'top_quality.jpeg','jpeg100')\\n\"\n \">>> render_to_file(m,'medium_quality.jpeg','jpeg50')\\n\"\n );\n\n def(\"render_to_file\",&render_to_file2,\n \"\\n\"\n \"Render Map to file (type taken from file extension)\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render_to_file, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> render_to_file(m,'image.jpeg')\\n\"\n \"\\n\"\n );\n\n def(\"render_tile_to_file\",&render_tile_to_file,\n \"\\n\"\n \"TODO\\n\"\n \"\\n\"\n ); \n\n \n def(\"render\",&render,\n \"\\n\"\n \"Render Map to an AGG Image32 using offsets\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, Image, render, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> im = Image(m.width,m.height)\\n\"\n \">>> render(m,im,1,1)\\n\"\n \"\\n\"\n ); \n\n def(\"render\",&render2,\n \"\\n\"\n \"Render Map to an AGG Image32\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, Image, render, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> im = Image(m.width,m.height)\\n\"\n \">>> render(m,im)\\n\"\n \"\\n\"\n );\n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n def(\"render\",&render3,\n \"\\n\"\n \"Render Map to Cairo Surface using offsets\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> render(m,surface,1,1)\\n\"\n \"\\n\"\n );\n\n def(\"render\",&render4,\n \"\\n\"\n \"Render Map to Cairo Surface\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> render(m,surface)\\n\"\n \"\\n\"\n );\n\n def(\"render\",&render5,\n \"\\n\"\n \"Render Map to Cairo Context using offsets\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface, Context\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> ctx = Context(surface)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\" \n \">>> render(m,context,1,1)\\n\"\n \"\\n\"\n );\n\n def(\"render\",&render6,\n \"\\n\"\n \"Render Map to Cairo Context\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, render, load_map\\n\"\n \">>> from cairo import SVGSurface, Context\\n\"\n \">>> surface = SVGSurface('image.svg', m.width, m.height)\\n\"\n \">>> ctx = Context(surface)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> render(m,context)\\n\"\n \"\\n\"\n );\n#endif\n\n def(\"scale_denominator\", &scale_denominator,\n \"\\n\"\n \"Return the Map Scale Denominator.\\n\"\n \"Also available as Map.scale_denominator()\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \"\\n\"\n \">>> from mapnik import Map, Projection, scale_denominator, load_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile.xml')\\n\"\n \">>> scale_denominator(m,Projection(m.srs).geographic)\\n\"\n \"\\n\"\n );\n \n def(\"load_map\", & load_map, load_map_overloads());\n\n def(\"load_map_from_string\", & load_map_string, load_map_string_overloads());\n\n def(\"save_map\", & save_map,\n \"\\n\"\n \"Save Map object to XML file\\n\"\n \"\\n\"\n \"Usage:\\n\"\n \">>> from mapnik import Map, load_map, save_map\\n\"\n \">>> m = Map(256,256)\\n\"\n \">>> load_map(m,'mapfile_wgs84.xml')\\n\"\n \">>> m.srs\\n\"\n \"'+proj=latlong +datum=WGS84'\\n\"\n \">>> m.srs = '+init=espg:3395'\\n\"\n \">>> save_map(m,'mapfile_mercator.xml')\\n\"\n \"\\n\"\n );\n\n def(\"mapnik_version\", &mapnik_version,\"Get the Mapnik version number\");\n \n using mapnik::symbolizer;\n class_(\"Symbolizer\",no_init)\n ;\n \n register_ptr_to_python();\n}\n<|endoftext|>"} {"text":"\/** @copyright\n * Copyright (c) 2017 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 MCP2515Can.cxx\n * This file implements the CAN driver for the MCP2515 CAN Controller.\n *\n * @author Stuart W. Baker\n * @date 3 January 2017\n *\/\n\n#include \"MCP2515Can.hxx\"\n\n#include \n\nconst MCP2515Can::MCP2515Baud MCP2515Can::baudTable[] =\n{\n \/* 20 MHz clock source\n * TQ = (2 * BRP) \/ freq = (2 * 4) \/ 20 MHz = 400 nsec\n * Baud = 125 kHz\n * bit time = 1 \/ 125 kHz = 8 usec = 20 TQ\n * SyncSeg = 1 TQ\n * PropSeg = 7 TQ\n * PS1 = 8 TQ\n * PS2 = 4 TQ\n * sample time = (1 TQ + 7 TQ + 8 TQ) \/ 20 TQ = 80%\n * SJW = PS2 - 1 = 4 - 1 = 3\n * SJW = 3 * 400 nsec = 1.2 usec\n *\/\n {20000000, 125000, {(4 - 1), (2 - 1)},\n {(7 - 1), (8 - 1), 0, 1},\n {(4 - 1), 0, 0}},\n \/* 8 MHz clock source\n * TQ = (2 * BRP) \/ freq = (2 * 2) \/ 8 MHz = 500 nsec\n * Baud = 125 kHz\n * bit time = 1 \/ 125 kHz = 8 usec = 16 TQ\n * SyncSeg = 1 TQ\n * PropSeg = 4 TQ\n * PS1 = 8 TQ\n * PS2 = 3 TQ\n * sample time = (1 TQ + 4 TQ + 8 TQ) \/ 16 TQ = 81.25%\n * SJW = PS2 - 1 = 3 - 1 = 2\n * SJW = 2 * 500 nsec = 1 usec\n *\/\n {8000000, 125000, {(2 - 1), (2 - 1)},\n {(4 - 1), (8 - 1), 0, 1},\n {(3 - 1), 0, 0}}\n};\n\n\n\/*\n * init()\n *\/\nvoid MCP2515Can::init(const char *spi_name, uint32_t freq, uint32_t baud)\n{\n spi = ::open(spi_name, O_RDWR);\n HASSERT(spi >= 0);\n\n \/* reset device *\/\n reset();\n\n \/* wait until device is in configuration mode *\/\n while ((register_read(CANSTAT) & 0xE0) != 0x80);\n\n \/* find valid timing settings for the requested frequency and buad rates *\/\n for (size_t i = 0; i < (sizeof(baudTable) \/ sizeof(baudTable[0])); ++i)\n {\n if (baudTable[i].freq == freq && baudTable[i].baud == baud)\n {\n register_write(CNF1, baudTable[i].cnf1.data);\n register_write(CNF2, baudTable[i].cnf2.data);\n register_write(CNF3, baudTable[i].cnf3.data);\n\n \/* setup RX Buf 0 and 1 to receive any message *\/\n register_write(RXB0CTRL, 0x60);\n register_write(RXB1CTRL, 0x60);\n\n \/* enable error and receive interrupts *\/\n register_write(CANINTE, MERR | ERRI | RX1I | RX0I);\n\n \/* put the device into normal operation mode *\/\n register_write(CANCTRL, 0x00);\n\n \/* wait until device is in normal mode *\/\n while ((register_read(CANSTAT) & 0xE0) != 0x00);\n\n return;\n }\n }\n\n \/* unsupported frequency *\/\n HASSERT(0);\n}\n\n\/*\n * enable()\n *\/\nvoid MCP2515Can::enable()\n{\n \/* there is a mutex lock above us, so the following sequence is atomic *\/\n if (!is_created())\n {\n \/* start the thread *\/\n \/** @todo make this the highest possible thread priority *\/\n start(name, 0, 1024);\n }\n\n \/* reset device *\/\n \/\/reset();\n\n interrupt_enable();\n}\n\n\/*\n * disable()\n *\/\nvoid MCP2515Can::disable()\n{\n interrupt_disable();\n\n register_write(TXB0CTRL, 0x00);\n register_write(TXB1CTRL, 0x00);\n portENTER_CRITICAL();\n \/* flush out any transmit data in the pipleline *\/\n txBuf->flush();\n txPending = 0;\n portEXIT_CRITICAL();\n}\n\n\/* \n * tx_msg_locked()\n *\/\nvoid MCP2515Can::tx_msg_locked()\n{\n \/* the node lock_ will be locked by the caller *\/\n if (txPending < 3)\n {\n struct can_frame *can_frame;\n\n \/* find an empty buffer *\/\n int index = 0;\n if (txPending & 0x1)\n {\n \/* buffer 0 already in use *\/\n index = 1;\n }\n\n portENTER_CRITICAL();\n if (txBuf->data_read_pointer(&can_frame))\n {\n Buffer tx_buf(can_frame);\n txBuf->consume(1);\n txBuf->signal_condition();\n portEXIT_CRITICAL();\n\n txPending |= (0x1 << index);\n\n \/* bump up priority of the other buffer so it will transmit first\n * if it is pending\n *\/\n bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03);\n \/* load the tranmsit buffer *\/\n buffer_write(index, tx_buf.get_payload());\n \/* request to send at lowest priority *\/\n bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B);\n \/* enable transmit interrupt *\/\n bit_modify(CANINTE, TX0I << index, TX0I << index);\n }\n else\n {\n portEXIT_CRITICAL();\n }\n }\n}\n\n\/*\n * rx_msg()\n *\/\nvoid MCP2515Can::rx_msg(int index)\n{\n Buffer rx_buf;\n buffer_read(index, rx_buf.get_payload());\n struct can_frame *can_frame;\n\n portENTER_CRITICAL();\n if (rxBuf->data_write_pointer(&can_frame))\n {\n rx_buf.build_struct_can_frame(can_frame);\n rxBuf->advance(1);\n ++numReceivedPackets_;\n rxBuf->signal_condition();\n }\n else\n {\n \/* receive overrun occured *\/\n ++overrunCount;\n }\n portEXIT_CRITICAL();\n}\n\n\/*\n * entry()\n *\/\nvoid *MCP2515Can::entry()\n{\n for ( ; \/* forever *\/ ; )\n {\n#if MCP2515_DEBUG\n int result = sem.timedwait(SEC_TO_NSEC(1));\n lock_.lock();\n\n if (result != 0)\n {\n spi_ioc_transfer xfer[2];\n memset(xfer, 0, sizeof(xfer));\n uint8_t wr_data[2] = {READ, 0};\n xfer[0].tx_buf = (unsigned long)wr_data;\n xfer[0].len = sizeof(wr_data);\n xfer[1].rx_buf = (unsigned long)regs;\n xfer[1].len = sizeof(regs);\n xfer[1].cs_change = 1;\n ::ioctl(spi, SPI_IOC_MESSAGE(2), xfer);\n lock_.unlock();\n continue;\n }\n#else\n sem.wait();\n lock_.lock();\n#endif\n \/* read status flags *\/\n uint8_t canintf = register_read(CANINTF);\n\n if (canintf & MERR)\n {\n \/* message error interrupt active *\/\n }\n if (canintf & ERRI)\n {\n \/* error interrupt active *\/\n register_write(TXB0CTRL, 0x00);\n register_write(TXB1CTRL, 0x00);\n\n portENTER_CRITICAL();\n ++softErrorCount;\n \/* flush out any transmit data in the pipleline *\/\n txBuf->flush();\n txBuf->signal_condition();\n portEXIT_CRITICAL();\n\n txPending = 0;\n }\n if (canintf & RX0I)\n {\n \/* receive interrupt active *\/\n rx_msg(0);\n }\n\n if (txPending)\n {\n \/* transmit interrupt active and transmission complete *\/\n if (canintf & TX0I)\n {\n txPending &= ~0x1;\n bit_modify(CANINTE, 0, TX0I);\n bit_modify(CANINTF, 0, TX0I);\n ++numTransmittedPackets_;\n }\n if (canintf & TX1I)\n {\n txPending &= ~0x2;\n bit_modify(CANINTE, 0, TX1I);\n bit_modify(CANINTF, 0, TX1I);\n ++numTransmittedPackets_;\n }\n\n tx_msg_locked();\n }\n\n \/* Refresh status flags just in case RX1 buffer became active\n * before we could finish reading out RX0 buffer. This ussually\n * won't happen because we should be able to respond to incoming\n * messages fast enough to only use RX0 buffer.\n *\/\n canintf = register_read(CANINTF);\n if (canintf & RX1I)\n {\n \/* receive interrupt active *\/\n rx_msg(1);\n }\n lock_.unlock();\n\n interrupt_enable();\n }\n\n return NULL;\n}\n\n\/* \n * interrupt_handler()\n *\/\nvoid MCP2515Can::interrupt_handler()\n{\n int woken = false;\n interrupt_disable();\n sem.post_from_isr(&woken);\n os_isr_exit_yield_test(woken);\n}\nUpdate MCP2515 driver to configure the SPI bus settings.\/** @copyright\n * Copyright (c) 2017 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 MCP2515Can.cxx\n * This file implements the CAN driver for the MCP2515 CAN Controller.\n *\n * @author Stuart W. Baker\n * @date 3 January 2017\n *\/\n\n#include \"MCP2515Can.hxx\"\n\n#include \n\nconst MCP2515Can::MCP2515Baud MCP2515Can::baudTable[] =\n{\n \/* 20 MHz clock source\n * TQ = (2 * BRP) \/ freq = (2 * 4) \/ 20 MHz = 400 nsec\n * Baud = 125 kHz\n * bit time = 1 \/ 125 kHz = 8 usec = 20 TQ\n * SyncSeg = 1 TQ\n * PropSeg = 7 TQ\n * PS1 = 8 TQ\n * PS2 = 4 TQ\n * sample time = (1 TQ + 7 TQ + 8 TQ) \/ 20 TQ = 80%\n * SJW = PS2 - 1 = 4 - 1 = 3\n * SJW = 3 * 400 nsec = 1.2 usec\n *\/\n {20000000, 125000, {(4 - 1), (2 - 1)},\n {(7 - 1), (8 - 1), 0, 1},\n {(4 - 1), 0, 0}},\n \/* 8 MHz clock source\n * TQ = (2 * BRP) \/ freq = (2 * 2) \/ 8 MHz = 500 nsec\n * Baud = 125 kHz\n * bit time = 1 \/ 125 kHz = 8 usec = 16 TQ\n * SyncSeg = 1 TQ\n * PropSeg = 4 TQ\n * PS1 = 8 TQ\n * PS2 = 3 TQ\n * sample time = (1 TQ + 4 TQ + 8 TQ) \/ 16 TQ = 81.25%\n * SJW = PS2 - 1 = 3 - 1 = 2\n * SJW = 2 * 500 nsec = 1 usec\n *\/\n {8000000, 125000, {(2 - 1), (2 - 1)},\n {(4 - 1), (8 - 1), 0, 1},\n {(3 - 1), 0, 0}}\n};\n\n\n\/*\n * init()\n *\/\nvoid MCP2515Can::init(const char *spi_name, uint32_t freq, uint32_t baud)\n{\n spi = ::open(spi_name, O_RDWR);\n HASSERT(spi >= 0);\n\n \/* configure SPI bus settings *\/\n uint8_t spi_mode = SPI_MODE_0;\n uint8_t spi_bpw = 8;\n uint32_t spi_max_speed_hz = freq \/ 4;\n ::ioctl(spi, SPI_IOC_WR_MODE, &spi_mode);\n ::ioctl(spi, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw);\n ::ioctl(spi, SPI_IOC_WR_MAX_SPEED_HZ, &spi_max_speed_hz);\n\n \/* reset device *\/\n reset();\n\n \/* wait until device is in configuration mode *\/\n while ((register_read(CANSTAT) & 0xE0) != 0x80);\n\n \/* find valid timing settings for the requested frequency and buad rates *\/\n for (size_t i = 0; i < (sizeof(baudTable) \/ sizeof(baudTable[0])); ++i)\n {\n if (baudTable[i].freq == freq && baudTable[i].baud == baud)\n {\n register_write(CNF1, baudTable[i].cnf1.data);\n register_write(CNF2, baudTable[i].cnf2.data);\n register_write(CNF3, baudTable[i].cnf3.data);\n\n \/* setup RX Buf 0 and 1 to receive any message *\/\n register_write(RXB0CTRL, 0x60);\n register_write(RXB1CTRL, 0x60);\n\n \/* enable error and receive interrupts *\/\n register_write(CANINTE, MERR | ERRI | RX1I | RX0I);\n\n \/* put the device into normal operation mode *\/\n register_write(CANCTRL, 0x00);\n\n \/* wait until device is in normal mode *\/\n while ((register_read(CANSTAT) & 0xE0) != 0x00);\n\n return;\n }\n }\n\n \/* unsupported frequency *\/\n HASSERT(0);\n}\n\n\/*\n * enable()\n *\/\nvoid MCP2515Can::enable()\n{\n \/* there is a mutex lock above us, so the following sequence is atomic *\/\n if (!is_created())\n {\n \/* start the thread *\/\n \/** @todo make this the highest possible thread priority *\/\n start(name, 0, 1024);\n }\n\n \/* reset device *\/\n \/\/reset();\n\n interrupt_enable();\n}\n\n\/*\n * disable()\n *\/\nvoid MCP2515Can::disable()\n{\n interrupt_disable();\n\n register_write(TXB0CTRL, 0x00);\n register_write(TXB1CTRL, 0x00);\n portENTER_CRITICAL();\n \/* flush out any transmit data in the pipleline *\/\n txBuf->flush();\n txPending = 0;\n portEXIT_CRITICAL();\n}\n\n\/* \n * tx_msg_locked()\n *\/\nvoid MCP2515Can::tx_msg_locked()\n{\n \/* the node lock_ will be locked by the caller *\/\n if (txPending < 3)\n {\n struct can_frame *can_frame;\n\n \/* find an empty buffer *\/\n int index = 0;\n if (txPending & 0x1)\n {\n \/* buffer 0 already in use *\/\n index = 1;\n }\n\n portENTER_CRITICAL();\n if (txBuf->data_read_pointer(&can_frame))\n {\n Buffer tx_buf(can_frame);\n txBuf->consume(1);\n txBuf->signal_condition();\n portEXIT_CRITICAL();\n\n txPending |= (0x1 << index);\n\n \/* bump up priority of the other buffer so it will transmit first\n * if it is pending\n *\/\n bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03);\n \/* load the tranmsit buffer *\/\n buffer_write(index, tx_buf.get_payload());\n \/* request to send at lowest priority *\/\n bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B);\n \/* enable transmit interrupt *\/\n bit_modify(CANINTE, TX0I << index, TX0I << index);\n }\n else\n {\n portEXIT_CRITICAL();\n }\n }\n}\n\n\/*\n * rx_msg()\n *\/\nvoid MCP2515Can::rx_msg(int index)\n{\n Buffer rx_buf;\n buffer_read(index, rx_buf.get_payload());\n struct can_frame *can_frame;\n\n portENTER_CRITICAL();\n if (rxBuf->data_write_pointer(&can_frame))\n {\n rx_buf.build_struct_can_frame(can_frame);\n rxBuf->advance(1);\n ++numReceivedPackets_;\n rxBuf->signal_condition();\n }\n else\n {\n \/* receive overrun occured *\/\n ++overrunCount;\n }\n portEXIT_CRITICAL();\n}\n\n\/*\n * entry()\n *\/\nvoid *MCP2515Can::entry()\n{\n for ( ; \/* forever *\/ ; )\n {\n#if MCP2515_DEBUG\n int result = sem.timedwait(SEC_TO_NSEC(1));\n lock_.lock();\n\n if (result != 0)\n {\n spi_ioc_transfer xfer[2];\n memset(xfer, 0, sizeof(xfer));\n uint8_t wr_data[2] = {READ, 0};\n xfer[0].tx_buf = (unsigned long)wr_data;\n xfer[0].len = sizeof(wr_data);\n xfer[1].rx_buf = (unsigned long)regs;\n xfer[1].len = sizeof(regs);\n xfer[1].cs_change = 1;\n ::ioctl(spi, SPI_IOC_MESSAGE(2), xfer);\n lock_.unlock();\n continue;\n }\n#else\n sem.wait();\n lock_.lock();\n#endif\n \/* read status flags *\/\n uint8_t canintf = register_read(CANINTF);\n\n if (canintf & MERR)\n {\n \/* message error interrupt active *\/\n }\n if (canintf & ERRI)\n {\n \/* error interrupt active *\/\n register_write(TXB0CTRL, 0x00);\n register_write(TXB1CTRL, 0x00);\n\n portENTER_CRITICAL();\n ++softErrorCount;\n \/* flush out any transmit data in the pipleline *\/\n txBuf->flush();\n txBuf->signal_condition();\n portEXIT_CRITICAL();\n\n txPending = 0;\n }\n if (canintf & RX0I)\n {\n \/* receive interrupt active *\/\n rx_msg(0);\n }\n\n if (txPending)\n {\n \/* transmit interrupt active and transmission complete *\/\n if (canintf & TX0I)\n {\n txPending &= ~0x1;\n bit_modify(CANINTE, 0, TX0I);\n bit_modify(CANINTF, 0, TX0I);\n ++numTransmittedPackets_;\n }\n if (canintf & TX1I)\n {\n txPending &= ~0x2;\n bit_modify(CANINTE, 0, TX1I);\n bit_modify(CANINTF, 0, TX1I);\n ++numTransmittedPackets_;\n }\n\n tx_msg_locked();\n }\n\n \/* Refresh status flags just in case RX1 buffer became active\n * before we could finish reading out RX0 buffer. This ussually\n * won't happen because we should be able to respond to incoming\n * messages fast enough to only use RX0 buffer.\n *\/\n canintf = register_read(CANINTF);\n if (canintf & RX1I)\n {\n \/* receive interrupt active *\/\n rx_msg(1);\n }\n lock_.unlock();\n\n interrupt_enable();\n }\n\n return NULL;\n}\n\n\/* \n * interrupt_handler()\n *\/\nvoid MCP2515Can::interrupt_handler()\n{\n int woken = false;\n interrupt_disable();\n sem.post_from_isr(&woken);\n os_isr_exit_yield_test(woken);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2006-2008 The FLWOR 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#include \"stdafx.h\"\n\n#include \"common\/shared_types.h\"\n#include \"types\/typeops.h\"\n\n#include \"functions\/function.h\"\n#include \"functions\/function_impl.h\"\n\n#include \"functions\/func_parse_fragment.h\"\n\n#include \"system\/globalenv.h\"\n\n#include \"compiler\/expression\/expr_consts.h\"\n\n\nnamespace zorba\n{\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid populate_context_parse_fragment_impl(static_context* sctx)\n{\n xqtref_t lParseOptType =\n GENV_TYPESYSTEM.create_node_type(\n store::StoreConsts::elementNode,\n createQName(\"http:\/\/www.zorba-xquery.com\/modules\/xml-options\",\"\",\"options\"),\n NULL,\n TypeConstants::QUANT_ONE,\n false,\n false\n );\n\n {\n DECL_WITH_KIND(sctx, fn_zorba_xml_parse,\n (createQName(\"http:\/\/www.zorba-xquery.com\/modules\/xml\",\"\",\"parse\"), \n GENV_TYPESYSTEM.STRING_TYPE_QUESTION, \n lParseOptType, \n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR),\n FunctionConsts::FN_ZORBA_XML_PARSE_2);\n }\n}\n\n}\n\n\/* vim:set et sw=2 ts=2: *\/\nFixed the quantity of the options parameter from ONE to QUESTION.\/*\n * Copyright 2006-2008 The FLWOR 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#include \"stdafx.h\"\n\n#include \"common\/shared_types.h\"\n#include \"types\/typeops.h\"\n\n#include \"functions\/function.h\"\n#include \"functions\/function_impl.h\"\n\n#include \"functions\/func_parse_fragment.h\"\n\n#include \"system\/globalenv.h\"\n\n#include \"compiler\/expression\/expr_consts.h\"\n\n\nnamespace zorba\n{\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid populate_context_parse_fragment_impl(static_context* sctx)\n{\n xqtref_t lParseOptType =\n GENV_TYPESYSTEM.create_node_type(\n store::StoreConsts::elementNode,\n createQName(\"http:\/\/www.zorba-xquery.com\/modules\/xml-options\",\"\",\"options\"),\n NULL,\n TypeConstants::QUANT_QUESTION,\n false,\n false\n );\n\n {\n DECL_WITH_KIND(sctx, fn_zorba_xml_parse,\n (createQName(\"http:\/\/www.zorba-xquery.com\/modules\/xml\",\"\",\"parse\"), \n GENV_TYPESYSTEM.STRING_TYPE_QUESTION, \n lParseOptType, \n GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR),\n FunctionConsts::FN_ZORBA_XML_PARSE_2);\n }\n}\n\n}\n\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Massachusetts Institute of Technology\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"global_mapper_ros\/global_mapper_ros.h\"\n#include \"global_mapper\/global_mapper.h\"\n#include \"global_mapper\/params.h\"\n\nnamespace global_mapper {\n\nGlobalMapperRos::GlobalMapperRos(volatile std::sig_atomic_t* stop_signal_ptr)\n : stop_signal_ptr_(stop_signal_ptr),\n publish_voxel_map_(false),\n nh_(),\n pnh_(\"~\"),\n tf_listener_(tf_buffer_) {\n tf_buffer_.setUsingDedicatedThread(true);\n\n GetParams();\n InitSubscribers();\n InitPublishers();\n}\n\nvoid GlobalMapperRos::GetParams() {\n fla_utils::SafeGetParam(pnh_, \"map_frame\", params_.map_frame);\n\n \/\/ pixel map params\n std::vector pixel_xy_min(2, 0.0);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/xy_min\", pixel_xy_min);\n std::copy(pixel_xy_min.begin(), pixel_xy_min.end(), params_.pixel_xy_min);\n\n std::vector pixel_xy_max(2, 0.0);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/xy_max\", pixel_xy_max);\n std::copy(pixel_xy_max.begin(), pixel_xy_max.end(), params_.pixel_xy_max);\n\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/resolution\", params_.pixel_resolution);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/init_value\", params_.pixel_init_value);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/bound_min\", params_.pixel_bound_min);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/bound_max\", params_.pixel_bound_max);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/min_z_abs\", params_.pixel_min_z_abs);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/max_z_abs\", params_.pixel_max_z_abs);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/use_rel_flatten\", params_.pixel_use_rel_flatten);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/min_z_rel\", params_.pixel_min_z_rel);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/max_z_rel\", params_.pixel_max_z_rel);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/publish_map\", publish_pixel_map_);\n\n \/\/ voxel map params\n std::vector voxel_xyz_min(3, 0.0);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/xyz_min\", voxel_xyz_min);\n std::copy(voxel_xyz_min.begin(), voxel_xyz_min.end(), params_.voxel_xyz_min);\n\n std::vector voxel_xyz_max(3, 0.0);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/xyz_max\", voxel_xyz_max);\n std::copy(voxel_xyz_max.begin(), voxel_xyz_max.end(), params_.voxel_xyz_max);\n\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/resolution\", params_.voxel_resolution);\n\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/init_value\", params_.voxel_init_value);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/bound_min\", params_.voxel_bound_min);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/bound_max\", params_.voxel_bound_max);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/min_z_abs\", params_.voxel_min_z_abs);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/max_z_abs\", params_.voxel_max_z_abs);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/use_rel_cropping\", params_.voxel_use_rel_cropping);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/min_z_rel\", params_.voxel_min_z_rel);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/max_z_rel\", params_.voxel_max_z_rel);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/hit_inc\", params_.voxel_hit_inc);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/miss_inc\", params_.voxel_miss_inc);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/publish_map\", publish_voxel_map_);\n}\n\nvoid GlobalMapperRos::InitSubscribers() {\n point_cloud_sub_ = pnh_.subscribe(\"cloud_topic\", 10, &GlobalMapperRos::PointCloudCallback, this);\n}\n\nvoid GlobalMapperRos::InitPublishers() {\n pixel_map_pub_ = pnh_.advertise(\"pixel_map_topic\", 1);\n voxel_map_pub_ = pnh_.advertise(\"voxel_map_topic\", 1);\n map_pub_timer_ = nh_.createTimer(ros::Duration(1.0), &GlobalMapperRos::PublishMap, this);\n}\n\n\/*\n Return a RGB colour value given a scalar v in the range [vmin,vmax]\n In this case each colour component ranges from 0 (no contribution) to\n 1 (fully saturated). The colour is clipped at the end of the scales if v is outside\n the range [vmin,vmax]\n*\/\nvoid GlobalMapperRos::GrayscaleToRGBJet(double v, double vmin, double vmax, std::vector* rgb) {\n double dv;\n\n if (v < vmin)\n v = vmin;\n if (v > vmax)\n v = vmax;\n dv = vmax - vmin;\n\n if (v < (vmin + 0.25 * dv)) {\n rgb->at(0) = 0;\n rgb->at(1) = 4 * (v - vmin) \/ dv;\n } else if (v < (vmin + 0.5 * dv)) {\n rgb->at(0) = 0;\n rgb->at(2) = 1 + 4 * (vmin + 0.25 * dv - v) \/ dv;\n } else if (v < (vmin + 0.75 * dv)) {\n rgb->at(0) = 4 * (v - vmin - 0.5 * dv) \/ dv;\n rgb->at(2) = 0;\n } else {\n rgb->at(1) = 1 + 4 * (vmin + 0.75 * dv - v) \/ dv;\n rgb->at(2) = 0;\n }\n}\n\nvoid GlobalMapperRos::PopulateVoxelMapMsg(visualization_msgs::MarkerArray* marker_array) {\n \/\/ check for bad input\n if (marker_array == nullptr) {\n return;\n }\n\n geometry_msgs::TransformStamped transform_stamped;\n Eigen::Vector3d transform;\n try {\n transform_stamped = tf_buffer_.lookupTransform(\"world\", \"body\",\n ros::Time(0), ros::Duration(1.0));\n\n transform(0) = transform_stamped.transform.translation.x;\n transform(1) = transform_stamped.transform.translation.y;\n transform(2) = transform_stamped.transform.translation.z;\n } catch (tf2::TransformException &ex) {\n ROS_WARN(\"[world_database_master_ros] OnGetTransform failed with %s\", ex.what());\n\n transform(0) = std::numeric_limits::quiet_NaN();\n transform(1) = std::numeric_limits::quiet_NaN();\n transform(2) = std::numeric_limits::quiet_NaN();\n }\n\n \/\/ get occuppied voxels\n double xyz[3] = {0.0};\n Eigen::Map xyz_map(&xyz[0]);\n std::vector occ_inds;\n for (int i = 0; i < global_mapper_ptr_->voxel_map_ptr_->num_cells; ++i) {\n global_mapper_ptr_->voxel_map_ptr_->indToLoc(i, xyz);\n\n if (global_mapper_ptr_->voxel_map_ptr_->readValue(xyz) > 0.6) {\n if((xyz_map - transform).norm() < 20.0) {\n occ_inds.push_back(i);\n }\n }\n }\n\n marker_array->markers.resize(occ_inds.size());\n std::vector rgb(3, 1.0);\n for (int i = 0; i < occ_inds.size(); ++i) {\n visualization_msgs::Marker& marker = marker_array->markers[i];\n\n \/\/ create voxel marker\n marker.header.frame_id = params_.map_frame;\n marker.header.stamp = ros::Time::now();\n marker.id = i;\n marker.type = visualization_msgs::Marker::CUBE;\n marker.action = visualization_msgs::Marker::ADD;\n\n \/\/ orientation\n marker.pose.orientation.x = 0.0;\n marker.pose.orientation.y = 0.0;\n marker.pose.orientation.z = 0.0;\n marker.pose.orientation.w = 1.0;\n\n \/\/ scale\n marker.scale.x = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[0];\n marker.scale.y = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[1];\n marker.scale.z = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[2];\n\n \/\/ position\n global_mapper_ptr_->voxel_map_ptr_->indToLoc(occ_inds[i], xyz);\n marker.pose.position.x = xyz[0];\n marker.pose.position.y = xyz[1];\n marker.pose.position.z = xyz[2];\n\n \/\/ color\n GrayscaleToRGBJet(marker.pose.position.z,\n global_mapper_ptr_->voxel_map_ptr_->xyz0[2],\n global_mapper_ptr_->voxel_map_ptr_->xyz1[2],\n &rgb);\n marker.color.r = static_cast(rgb[0]);\n marker.color.g = static_cast(rgb[1]);\n marker.color.b = static_cast(rgb[2]);\n marker.color.a = 1.0f;\n }\n}\n\nvoid GlobalMapperRos::PopulatePixelMapMsg(nav_msgs::OccupancyGrid* occupancy_grid) {\n \/\/ check for bad input\n if (occupancy_grid == nullptr) {\n return;\n }\n\n \/\/ header\n occupancy_grid->header.frame_id = params_.map_frame;\n occupancy_grid->header.stamp = ros::Time::now();\n\n \/\/ metadata\n occupancy_grid->info.resolution = global_mapper_ptr_->pixel_map_ptr_->metersPerPixel;\n occupancy_grid->info.width = global_mapper_ptr_->pixel_map_ptr_->dimensions[0];\n occupancy_grid->info.height = global_mapper_ptr_->pixel_map_ptr_->dimensions[1];\n occupancy_grid->info.origin.position.x = 0.0;\n occupancy_grid->info.origin.position.y = 0.0;\n occupancy_grid->info.origin.position.z = 0.0;\n\n \/\/ data\n float occ_value = 0.0;\n double xy[2] = {0.0};\n occupancy_grid->data.resize(global_mapper_ptr_->pixel_map_ptr_->num_cells);\n for (int i = 0; i < global_mapper_ptr_->pixel_map_ptr_->num_cells; ++i) {\n \/\/ get xy location\n global_mapper_ptr_->pixel_map_ptr_->indToLoc(i, xy);\n\n \/\/ get pixel value and scale\n occ_value = global_mapper_ptr_->pixel_map_ptr_->readValue(xy);\n occ_value *= 100.0;\n occupancy_grid->data[i] = static_cast(occ_value + 0.5);\n }\n}\n\nvoid GlobalMapperRos::PublishMap(const ros::TimerEvent& event) {\n \/\/ lock\n std::lock_guard map_lock(global_mapper_ptr_->map_mutex());\n\n \/\/ voxel map\n if (publish_voxel_map_) {\n visualization_msgs::MarkerArray marker_array;\n PopulateVoxelMapMsg(&marker_array);\n voxel_map_pub_.publish(marker_array);\n }\n\n \/\/ pixel_map\n if (publish_pixel_map_) {\n nav_msgs::OccupancyGrid occupancy_grid;\n PopulatePixelMapMsg(&occupancy_grid);\n pixel_map_pub_.publish(occupancy_grid);\n }\n}\n\nvoid GlobalMapperRos::PointCloudCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_ptr) {\n \/\/ get transform\n const std::string target_frame = params_.map_frame;\n geometry_msgs::TransformStamped transform_stamped;\n \/\/ try to get correct transform\n try {\n transform_stamped = tf_buffer_.lookupTransform(target_frame, cloud_ptr->header.frame_id,\n ros::Time(cloud_ptr->header.stamp),\n ros::Duration(0.02));\n } catch (tf2::TransformException &ex) {\n ROS_WARN(\"%s\", ex.what());\n return;\n }\n\n sensor_msgs::PointCloud2 cloud_out;\n tf2::doTransform(*cloud_ptr, cloud_out, transform_stamped);\n\n pcl::PointCloud cloud;\n pcl::fromROSMsg(cloud_out, cloud);\n \n \/\/ \/\/ push to mapper\n global_mapper_ptr_->PushPointCloud(cloud.makeShared());\n}\n\nvoid GlobalMapperRos::Run() {\n \/\/ start mapping thread\n global_mapper_ptr_ = std::unique_ptr(new GlobalMapper(stop_signal_ptr_, params_));\n global_mapper_ptr_->Run();\n\n \/\/ handle ros callbacks\n ros::spin();\n}\n\n} \/\/ namespace global_mapper\nCleanup voxel visualization code.\/\/ Copyright 2017 Massachusetts Institute of Technology\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"global_mapper_ros\/global_mapper_ros.h\"\n#include \"global_mapper\/global_mapper.h\"\n#include \"global_mapper\/params.h\"\n\nnamespace global_mapper {\n\nGlobalMapperRos::GlobalMapperRos(volatile std::sig_atomic_t* stop_signal_ptr)\n : stop_signal_ptr_(stop_signal_ptr),\n publish_voxel_map_(false),\n nh_(),\n pnh_(\"~\"),\n tf_listener_(tf_buffer_) {\n tf_buffer_.setUsingDedicatedThread(true);\n\n GetParams();\n InitSubscribers();\n InitPublishers();\n}\n\nvoid GlobalMapperRos::GetParams() {\n fla_utils::SafeGetParam(pnh_, \"map_frame\", params_.map_frame);\n\n \/\/ pixel map params\n std::vector pixel_xy_min(2, 0.0);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/xy_min\", pixel_xy_min);\n std::copy(pixel_xy_min.begin(), pixel_xy_min.end(), params_.pixel_xy_min);\n\n std::vector pixel_xy_max(2, 0.0);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/xy_max\", pixel_xy_max);\n std::copy(pixel_xy_max.begin(), pixel_xy_max.end(), params_.pixel_xy_max);\n\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/resolution\", params_.pixel_resolution);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/init_value\", params_.pixel_init_value);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/bound_min\", params_.pixel_bound_min);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/bound_max\", params_.pixel_bound_max);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/min_z_abs\", params_.pixel_min_z_abs);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/max_z_abs\", params_.pixel_max_z_abs);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/use_rel_flatten\", params_.pixel_use_rel_flatten);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/min_z_rel\", params_.pixel_min_z_rel);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/max_z_rel\", params_.pixel_max_z_rel);\n fla_utils::SafeGetParam(pnh_, \"pixel_map\/publish_map\", publish_pixel_map_);\n\n \/\/ voxel map params\n std::vector voxel_xyz_min(3, 0.0);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/xyz_min\", voxel_xyz_min);\n std::copy(voxel_xyz_min.begin(), voxel_xyz_min.end(), params_.voxel_xyz_min);\n\n std::vector voxel_xyz_max(3, 0.0);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/xyz_max\", voxel_xyz_max);\n std::copy(voxel_xyz_max.begin(), voxel_xyz_max.end(), params_.voxel_xyz_max);\n\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/resolution\", params_.voxel_resolution);\n\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/init_value\", params_.voxel_init_value);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/bound_min\", params_.voxel_bound_min);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/bound_max\", params_.voxel_bound_max);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/min_z_abs\", params_.voxel_min_z_abs);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/max_z_abs\", params_.voxel_max_z_abs);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/use_rel_cropping\", params_.voxel_use_rel_cropping);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/min_z_rel\", params_.voxel_min_z_rel);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/max_z_rel\", params_.voxel_max_z_rel);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/hit_inc\", params_.voxel_hit_inc);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/miss_inc\", params_.voxel_miss_inc);\n fla_utils::SafeGetParam(pnh_, \"voxel_map\/publish_map\", publish_voxel_map_);\n}\n\nvoid GlobalMapperRos::InitSubscribers() {\n point_cloud_sub_ = pnh_.subscribe(\"cloud_topic\", 10, &GlobalMapperRos::PointCloudCallback, this);\n}\n\nvoid GlobalMapperRos::InitPublishers() {\n pixel_map_pub_ = pnh_.advertise(\"pixel_map_topic\", 1);\n voxel_map_pub_ = pnh_.advertise(\"voxel_map_topic\", 1);\n map_pub_timer_ = nh_.createTimer(ros::Duration(0.2), &GlobalMapperRos::PublishMap, this);\n}\n\n\/*\n Return a RGB colour value given a scalar v in the range [vmin,vmax]\n In this case each colour component ranges from 0 (no contribution) to\n 1 (fully saturated). The colour is clipped at the end of the scales if v is outside\n the range [vmin,vmax]\n*\/\nvoid GlobalMapperRos::GrayscaleToRGBJet(double v, double vmin, double vmax, std::vector* rgb) {\n double dv;\n\n if (v < vmin)\n v = vmin;\n if (v > vmax)\n v = vmax;\n dv = vmax - vmin;\n\n if (v < (vmin + 0.25 * dv)) {\n rgb->at(0) = 0;\n rgb->at(1) = 4 * (v - vmin) \/ dv;\n } else if (v < (vmin + 0.5 * dv)) {\n rgb->at(0) = 0;\n rgb->at(2) = 1 + 4 * (vmin + 0.25 * dv - v) \/ dv;\n } else if (v < (vmin + 0.75 * dv)) {\n rgb->at(0) = 4 * (v - vmin - 0.5 * dv) \/ dv;\n rgb->at(2) = 0;\n } else {\n rgb->at(1) = 1 + 4 * (vmin + 0.75 * dv - v) \/ dv;\n rgb->at(2) = 0;\n }\n}\n\nvoid GlobalMapperRos::PopulateVoxelMapMsg(visualization_msgs::MarkerArray* marker_array) {\n \/\/ check for bad input\n if (marker_array == nullptr) {\n return;\n }\n\n geometry_msgs::TransformStamped transform_stamped;\n Eigen::Vector3d transform;\n try {\n transform_stamped = tf_buffer_.lookupTransform(\"world\", \"body\",\n ros::Time(0), ros::Duration(1.0));\n transform(0) = transform_stamped.transform.translation.x;\n transform(1) = transform_stamped.transform.translation.y;\n transform(2) = transform_stamped.transform.translation.z;\n } catch (tf2::TransformException &ex) {\n ROS_WARN(\"[world_database_master_ros] OnGetTransform failed with %s\", ex.what());\n\n transform(0) = std::numeric_limits::quiet_NaN();\n transform(1) = std::numeric_limits::quiet_NaN();\n transform(2) = std::numeric_limits::quiet_NaN();\n }\n\n \/\/ get occuppied voxels\n double xyz[3] = {0.0};\n Eigen::Map xyz_map(&xyz[0]);\n std::vector occ_inds;\n\n int min_ixyz[3];\n int max_ixyz[3];\n\n const double subgrid_half_size[3] = {10,10,3};\n\n const double min_xyz[3] = {transform[0] - subgrid_half_size[0], \n transform[1] - subgrid_half_size[1],\n transform[2] - subgrid_half_size[2]};\n\n const double max_xyz[3] = {transform[0] + subgrid_half_size[0], \n transform[1] + subgrid_half_size[1],\n transform[2] + subgrid_half_size[2]};\n\n\n global_mapper_ptr_->voxel_map_ptr_->worldToTable(min_xyz, min_ixyz);\n global_mapper_ptr_->voxel_map_ptr_->worldToTable(max_xyz, max_ixyz);\n\n int voxel_index = 0;\n for (int x = min_ixyz[0]; x < max_ixyz[0]; x++) {\n for (int y = min_ixyz[1]; y < max_ixyz[1]; y++) {\n for (int z = min_ixyz[2]; z < max_ixyz[2]; z++) {\n int ixyz[3] = {x, y, z};\n if(global_mapper_ptr_->voxel_map_ptr_->readValue(ixyz) > 0.6) {\n voxel_index = global_mapper_ptr_->voxel_map_ptr_->getInd(ixyz);\n occ_inds.push_back(voxel_index);\n }\n }\n }\n }\n\n marker_array->markers.resize(occ_inds.size());\n std::vector rgb(3, 1.0);\n for (int i = 0; i < occ_inds.size(); ++i) {\n visualization_msgs::Marker& marker = marker_array->markers[i];\n\n \/\/ create voxel marker\n marker.header.frame_id = params_.map_frame;\n marker.header.stamp = ros::Time::now();\n marker.id = i;\n marker.type = visualization_msgs::Marker::CUBE;\n marker.action = visualization_msgs::Marker::ADD;\n\n \/\/ orientation\n marker.pose.orientation.x = 0.0;\n marker.pose.orientation.y = 0.0;\n marker.pose.orientation.z = 0.0;\n marker.pose.orientation.w = 1.0;\n\n \/\/ scale\n marker.scale.x = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[0];\n marker.scale.y = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[1];\n marker.scale.z = global_mapper_ptr_->voxel_map_ptr_->metersPerPixel[2];\n\n \/\/ position\n global_mapper_ptr_->voxel_map_ptr_->indToLoc(occ_inds[i], xyz);\n marker.pose.position.x = xyz[0];\n marker.pose.position.y = xyz[1];\n marker.pose.position.z = xyz[2];\n\n \/\/ color\n GrayscaleToRGBJet(marker.pose.position.z,\n global_mapper_ptr_->voxel_map_ptr_->xyz0[2],\n global_mapper_ptr_->voxel_map_ptr_->xyz1[2],\n &rgb);\n marker.color.r = static_cast(rgb[0]);\n marker.color.g = static_cast(rgb[1]);\n marker.color.b = static_cast(rgb[2]);\n marker.color.a = 1.0f;\n }\n}\n\nvoid GlobalMapperRos::PopulatePixelMapMsg(nav_msgs::OccupancyGrid* occupancy_grid) {\n \/\/ check for bad input\n if (occupancy_grid == nullptr) {\n return;\n }\n\n \/\/ header\n occupancy_grid->header.frame_id = params_.map_frame;\n occupancy_grid->header.stamp = ros::Time::now();\n\n \/\/ metadata\n occupancy_grid->info.resolution = global_mapper_ptr_->pixel_map_ptr_->metersPerPixel;\n occupancy_grid->info.width = global_mapper_ptr_->pixel_map_ptr_->dimensions[0];\n occupancy_grid->info.height = global_mapper_ptr_->pixel_map_ptr_->dimensions[1];\n occupancy_grid->info.origin.position.x = 0.0;\n occupancy_grid->info.origin.position.y = 0.0;\n occupancy_grid->info.origin.position.z = 0.0;\n\n \/\/ data\n float occ_value = 0.0;\n double xy[2] = {0.0};\n occupancy_grid->data.resize(global_mapper_ptr_->pixel_map_ptr_->num_cells);\n for (int i = 0; i < global_mapper_ptr_->pixel_map_ptr_->num_cells; ++i) {\n \/\/ get xy location\n global_mapper_ptr_->pixel_map_ptr_->indToLoc(i, xy);\n\n \/\/ get pixel value and scale\n occ_value = global_mapper_ptr_->pixel_map_ptr_->readValue(xy);\n occ_value *= 100.0;\n occupancy_grid->data[i] = static_cast(occ_value + 0.5);\n }\n}\n\nvoid GlobalMapperRos::PublishMap(const ros::TimerEvent& event) {\n \/\/ lock\n \/\/ std::lock_guard map_lock(global_mapper_ptr_->map_mutex());\n\n \/\/ voxel map\n if (publish_voxel_map_) {\n double start_time = ros::Time::now().toSec();\n visualization_msgs::MarkerArray marker_array;\n PopulateVoxelMapMsg(&marker_array);\n std::cout << \"(global_mapper) PopulateVoxelMapMsg took \" << ros::Time::now().toSec() - start_time << \" seconds\" << std::endl;\n voxel_map_pub_.publish(marker_array);\n }\n\n \/\/ pixel_map\n if (publish_pixel_map_) {\n nav_msgs::OccupancyGrid occupancy_grid;\n PopulatePixelMapMsg(&occupancy_grid);\n pixel_map_pub_.publish(occupancy_grid);\n }\n}\n\nvoid GlobalMapperRos::PointCloudCallback(const sensor_msgs::PointCloud2::ConstPtr& cloud_ptr) {\n \/\/ get transform\n const std::string target_frame = params_.map_frame;\n geometry_msgs::TransformStamped transform_stamped;\n \/\/ try to get correct transform\n try {\n transform_stamped = tf_buffer_.lookupTransform(target_frame, cloud_ptr->header.frame_id,\n ros::Time(cloud_ptr->header.stamp),\n ros::Duration(0.02));\n } catch (tf2::TransformException &ex) {\n ROS_WARN(\"%s\", ex.what());\n return;\n }\n\n sensor_msgs::PointCloud2 cloud_out;\n tf2::doTransform(*cloud_ptr, cloud_out, transform_stamped);\n\n pcl::PointCloud cloud;\n pcl::fromROSMsg(cloud_out, cloud);\n \n \/\/ push to mapper\n global_mapper_ptr_->PushPointCloud(cloud.makeShared());\n}\n\nvoid GlobalMapperRos::Run() {\n \/\/ start mapping thread\n global_mapper_ptr_ = std::unique_ptr(new GlobalMapper(stop_signal_ptr_, params_));\n global_mapper_ptr_->Run();\n\n \/\/ handle ros callbacks\n ros::spin();\n}\n\n} \/\/ namespace global_mapper\n<|endoftext|>"} {"text":"\/\/ Print each number in the range specified by two integers.\n\n#include \n\nusing std::cout;\nusing std::cin;\n\nvoid print_range(int lo, int hi)\n{\n if (lo > hi)\n print_range(hi, lo);\n for (int i = lo; i != hi; ++i)\n cout << i << \" \";\n}\n\nint main()\n{\n int low = 0, high = 0;\n cout << \"please input two integers:\\n\";\n cin >> low >> high;\n print_range(low, high);\n return 0;\n}\nFixed #438\/\/ Print each number in the range specified by two integers.\n\n#include \n\nusing std::cout;\nusing std::cin;\n\nvoid print_range(int lo, int hi)\n{\n if (lo > hi)\n {\n print_range(hi, lo);\n return;\n }\n for (int i = lo; i != hi; ++i)\n cout << i << \" \";\n}\n\nint main()\n{\n int low = 0, high = 0;\n cout << \"please input two integers:\\n\";\n cin >> low >> high;\n print_range(low, high);\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \"include\/Sales_item.h\"\n\nint main()\n{\n Sales_item currItem, valItem;\n if (std::cin >> currItem)\n {\n int cnt = 1;\n while (std::cin >> valItem)\n {\n if (valItem.isbn() == currItem.isbn())\n ++cnt;\n else \n {\n std::cout << currItem << \" occurs \"\n << cnt << \" times \" << std::endl;\n currItem = valItem;\n cnt = 1;\n }\n }\n \n std::cout << currItem << \" occurs \"\n << cnt << \" times \" << std::endl;\n }\n return 0;\n}\n\nUpdate ex1_23.cpp#include \n#include \"include\/Sales_item.h\"\n\nint main()\n{\n Sales_item currItem, valItem;\n if (std::cin >> currItem)\n {\n int cnt = 1;\n while (std::cin >> valItem)\n {\n if (valItem.isbn() == currItem.isbn())\n {\n ++cnt;\n }\n else\n {\n std::cout << currItem << \" occurs \" << cnt << \" times \" << std::endl;\n currItem = valItem;\n cnt = 1;\n }\n }\n std::cout << currItem << \" occurs \"<< cnt << \" times \" << std::endl;\n }\n return 0;\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\/bug_report_util.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_version_info.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_version_info.h\"\n#include \"chrome\/browser\/browser_process_impl.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_util.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/net\/url_fetcher.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"grit\/locale_settings.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"unicode\/locid.h\"\n\n#include \n\nnamespace {\n\nconst int kBugReportVersion = 1;\n\nconst char kReportPhishingUrl[] =\n \"http:\/\/www.google.com\/safebrowsing\/report_phish\/\";\n\n\/\/ URL to post bug reports to.\nconst char* const kBugReportPostUrl =\n \"https:\/\/feedback2-test.corp.google.com\/tools\/feedback\/chrome\/__submit\";\n\nconst char* const kProtBufMimeType = \"application\/x-protobuf\";\nconst char* const kPngMimeType = \"image\/png\";\n\n\/\/ Tags we use in product specific data\nconst char* const kPageTitleTag = \"PAGE TITLE\";\nconst char* const kProblemTypeTag = \"PROBLEM TYPE\";\nconst char* const kChromeVersionTag = \"CHROME VERSION\";\nconst char* const kOsVersionTag = \"OS VERSION\";\n\n\n} \/\/ namespace\n\n\/\/ Simple URLFetcher::Delegate to clean up URLFetcher on completion.\nclass BugReportUtil::PostCleanup : public URLFetcher::Delegate {\n public:\n PostCleanup();\n\n \/\/ Overridden from URLFetcher::Delegate.\n virtual void OnURLFetchComplete(const URLFetcher* source,\n const GURL& url,\n const URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data);\n private:\n DISALLOW_COPY_AND_ASSIGN(PostCleanup);\n};\n\nBugReportUtil::PostCleanup::PostCleanup() {\n}\n\nvoid BugReportUtil::PostCleanup::OnURLFetchComplete(\n const URLFetcher* source,\n const GURL& url,\n const URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data) {\n \/\/ if not 204, something went wrong\n if (response_code != 204)\n LOG(WARNING) << \"Submission to feedback server failed. Response code: \" <<\n response_code << std::endl;\n \/\/ Delete the URLFetcher.\n delete source;\n \/\/ And then delete ourselves.\n delete this;\n}\n\n\/\/ static\nvoid BugReportUtil::SetOSVersion(std::string *os_version) {\n#if defined(OS_WIN)\n OSVERSIONINFO osvi;\n ZeroMemory(&osvi, sizeof(OSVERSIONINFO));\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n\n if (GetVersionEx(&osvi)) {\n *os_version = StringPrintf(\"%d.%d.%d %S\",\n osvi.dwMajorVersion,\n osvi.dwMinorVersion,\n osvi.dwBuildNumber,\n osvi.szCSDVersion);\n } else {\n *os_version = \"unknown\";\n }\n#elif defined(OS_MACOSX)\n int32 major;\n int32 minor;\n int32 bugFix;\n base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &bugFix);\n *os_version = StringPrintf(\"%d.%d.%d\", major, minor, bugFix);\n#else\n *os_version = \"unknown\";\n#endif\n}\n\n\/\/ static\nvoid BugReportUtil::AddFeedbackData(\n userfeedback::ExternalExtensionSubmit* feedback_data,\n const std::string& key, const std::string& value) {\n \/\/ Create log_value object and add it to the web_data object\n userfeedback::ProductSpecificData log_value;\n log_value.set_key(key);\n log_value.set_value(value);\n userfeedback::WebData* web_data = feedback_data->mutable_web_data();\n *(web_data->add_product_specific_data()) = log_value;\n}\n\n\/\/ static\nvoid BugReportUtil::SendReport(Profile* profile,\n const std::string& page_title_text,\n int problem_type,\n const std::string& page_url_text,\n const std::string& user_email_text,\n const std::string& description,\n const char* png_data,\n int png_data_length,\n int png_width,\n#if defined(OS_CHROMEOS)\n int png_height,\n const chromeos::LogDictionaryType* const sys_info) {\n#else\n int png_height) {\n#endif\n GURL post_url(kBugReportPostUrl);\n\n \/\/ Create google feedback protocol buffer objects\n userfeedback::ExternalExtensionSubmit feedback_data;\n \/\/ type id set to 0, unused field but needs to be initialized to 0\n feedback_data.set_type_id(0);\n\n userfeedback::CommonData* common_data = feedback_data.mutable_common_data();\n userfeedback::WebData* web_data = feedback_data.mutable_web_data();\n\n \/\/ Set GAIA id to 0. We're not using gaia id's for recording\n \/\/ use feedback - we're using the e-mail field, allows users to\n \/\/ submit feedback from incognito mode and specify any mail id\n \/\/ they wish\n common_data->set_gaia_id(0);\n\n \/\/ Add the page title.\n AddFeedbackData(&feedback_data, std::string(kPageTitleTag),\n page_title_text);\n\n AddFeedbackData(&feedback_data, std::string(kProblemTypeTag),\n StringPrintf(\"%d\\r\\n\", problem_type));\n\n \/\/ Add the user e-mail to the feedback object\n common_data->set_user_email(user_email_text);\n\n \/\/ Add the description to the feedback object\n common_data->set_description(description);\n\n \/\/ Add the language\n std::string chrome_locale = g_browser_process->GetApplicationLocale();\n common_data->set_source_descripton_language(chrome_locale);\n\n \/\/ Set the url\n web_data->set_url(page_url_text);\n\n \/\/ Add the Chrome version\n std::string chrome_version;\n scoped_ptr version_info(\n chrome_app::GetChromeVersionInfo());\n if (version_info.get()) {\n chrome_version = WideToUTF8(version_info->product_name()) + \" - \" +\n WideToUTF8(version_info->file_version()) +\n \" (\" + WideToUTF8(version_info->last_change()) + \")\";\n }\n\n if (!chrome_version.empty())\n AddFeedbackData(&feedback_data, std::string(kChromeVersionTag),\n chrome_version);\n\n \/\/ Add OS version (eg, for WinXP SP2: \"5.1.2600 Service Pack 2\").\n std::string os_version = \"\";\n SetOSVersion(&os_version);\n AddFeedbackData(&feedback_data, std::string(kOsVersionTag), os_version);\n\n#if defined(OS_CHROMEOS)\n for (chromeos::LogDictionaryType::const_iterator i = sys_info->begin();\n i != sys_info->end(); ++i)\n AddFeedbackData(&feedback_data, i->first, i->second);\n#endif\n\n \/\/ Include the page image if we have one.\n if (png_data) {\n userfeedback::PostedScreenshot screenshot;\n screenshot.set_mime_type(kPngMimeType);\n \/\/ Set the dimensions of the screenshot\n userfeedback::Dimensions dimensions;\n dimensions.set_width(static_cast(png_width));\n dimensions.set_height(static_cast(png_height));\n *(screenshot.mutable_dimensions()) = dimensions;\n screenshot.set_binary_content(std::string(png_data, png_data_length));\n\n \/\/ Set the screenshot object in feedback\n *(feedback_data.mutable_screenshot()) = screenshot;\n }\n\n \/\/ We have the body of our POST, so send it off to the server.\n URLFetcher* fetcher = new URLFetcher(post_url, URLFetcher::POST,\n new BugReportUtil::PostCleanup);\n fetcher->set_request_context(profile->GetRequestContext());\n\n std::string post_body;\n feedback_data.SerializeToString(&post_body);\n fetcher->set_upload_data(std::string(kProtBufMimeType), post_body);\n fetcher->Start();\n}\n\n\/\/ static\nvoid BugReportUtil::ReportPhishing(TabContents* currentTab,\n const std::string& phishing_url) {\n currentTab->controller().LoadURL(\n safe_browsing_util::GeneratePhishingReportUrl(\n kReportPhishingUrl, phishing_url),\n GURL(),\n PageTransition::LINK);\n}\nFlipped feedback URL to production servers.\/\/ 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\/bug_report_util.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_version_info.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_version_info.h\"\n#include \"chrome\/browser\/browser_process_impl.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_util.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/net\/url_fetcher.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"grit\/locale_settings.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"unicode\/locid.h\"\n\n#include \n\nnamespace {\n\nconst int kBugReportVersion = 1;\n\nconst char kReportPhishingUrl[] =\n \"http:\/\/www.google.com\/safebrowsing\/report_phish\/\";\n\n\/\/ URL to post bug reports to.\nconst char* const kBugReportPostUrl =\n \"https:\/\/www.google.com\/tools\/feedback\/chrome\/__submit\";\n\nconst char* const kProtBufMimeType = \"application\/x-protobuf\";\nconst char* const kPngMimeType = \"image\/png\";\n\n\/\/ Tags we use in product specific data\nconst char* const kPageTitleTag = \"PAGE TITLE\";\nconst char* const kProblemTypeTag = \"PROBLEM TYPE\";\nconst char* const kChromeVersionTag = \"CHROME VERSION\";\nconst char* const kOsVersionTag = \"OS VERSION\";\n\n\n} \/\/ namespace\n\n\/\/ Simple URLFetcher::Delegate to clean up URLFetcher on completion.\nclass BugReportUtil::PostCleanup : public URLFetcher::Delegate {\n public:\n PostCleanup();\n\n \/\/ Overridden from URLFetcher::Delegate.\n virtual void OnURLFetchComplete(const URLFetcher* source,\n const GURL& url,\n const URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data);\n private:\n DISALLOW_COPY_AND_ASSIGN(PostCleanup);\n};\n\nBugReportUtil::PostCleanup::PostCleanup() {\n}\n\nvoid BugReportUtil::PostCleanup::OnURLFetchComplete(\n const URLFetcher* source,\n const GURL& url,\n const URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data) {\n \/\/ if not 204, something went wrong\n if (response_code != 204)\n LOG(WARNING) << \"Submission to feedback server failed. Response code: \" <<\n response_code << std::endl;\n \/\/ Delete the URLFetcher.\n delete source;\n \/\/ And then delete ourselves.\n delete this;\n}\n\n\/\/ static\nvoid BugReportUtil::SetOSVersion(std::string *os_version) {\n#if defined(OS_WIN)\n OSVERSIONINFO osvi;\n ZeroMemory(&osvi, sizeof(OSVERSIONINFO));\n osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n\n if (GetVersionEx(&osvi)) {\n *os_version = StringPrintf(\"%d.%d.%d %S\",\n osvi.dwMajorVersion,\n osvi.dwMinorVersion,\n osvi.dwBuildNumber,\n osvi.szCSDVersion);\n } else {\n *os_version = \"unknown\";\n }\n#elif defined(OS_MACOSX)\n int32 major;\n int32 minor;\n int32 bugFix;\n base::SysInfo::OperatingSystemVersionNumbers(&major, &minor, &bugFix);\n *os_version = StringPrintf(\"%d.%d.%d\", major, minor, bugFix);\n#else\n *os_version = \"unknown\";\n#endif\n}\n\n\/\/ static\nvoid BugReportUtil::AddFeedbackData(\n userfeedback::ExternalExtensionSubmit* feedback_data,\n const std::string& key, const std::string& value) {\n \/\/ Create log_value object and add it to the web_data object\n userfeedback::ProductSpecificData log_value;\n log_value.set_key(key);\n log_value.set_value(value);\n userfeedback::WebData* web_data = feedback_data->mutable_web_data();\n *(web_data->add_product_specific_data()) = log_value;\n}\n\n\/\/ static\nvoid BugReportUtil::SendReport(Profile* profile,\n const std::string& page_title_text,\n int problem_type,\n const std::string& page_url_text,\n const std::string& user_email_text,\n const std::string& description,\n const char* png_data,\n int png_data_length,\n int png_width,\n#if defined(OS_CHROMEOS)\n int png_height,\n const chromeos::LogDictionaryType* const sys_info) {\n#else\n int png_height) {\n#endif\n GURL post_url(kBugReportPostUrl);\n\n \/\/ Create google feedback protocol buffer objects\n userfeedback::ExternalExtensionSubmit feedback_data;\n \/\/ type id set to 0, unused field but needs to be initialized to 0\n feedback_data.set_type_id(0);\n\n userfeedback::CommonData* common_data = feedback_data.mutable_common_data();\n userfeedback::WebData* web_data = feedback_data.mutable_web_data();\n\n \/\/ Set GAIA id to 0. We're not using gaia id's for recording\n \/\/ use feedback - we're using the e-mail field, allows users to\n \/\/ submit feedback from incognito mode and specify any mail id\n \/\/ they wish\n common_data->set_gaia_id(0);\n\n \/\/ Add the page title.\n AddFeedbackData(&feedback_data, std::string(kPageTitleTag),\n page_title_text);\n\n AddFeedbackData(&feedback_data, std::string(kProblemTypeTag),\n StringPrintf(\"%d\\r\\n\", problem_type));\n\n \/\/ Add the user e-mail to the feedback object\n common_data->set_user_email(user_email_text);\n\n \/\/ Add the description to the feedback object\n common_data->set_description(description);\n\n \/\/ Add the language\n std::string chrome_locale = g_browser_process->GetApplicationLocale();\n common_data->set_source_descripton_language(chrome_locale);\n\n \/\/ Set the url\n web_data->set_url(page_url_text);\n\n \/\/ Add the Chrome version\n std::string chrome_version;\n scoped_ptr version_info(\n chrome_app::GetChromeVersionInfo());\n if (version_info.get()) {\n chrome_version = WideToUTF8(version_info->product_name()) + \" - \" +\n WideToUTF8(version_info->file_version()) +\n \" (\" + WideToUTF8(version_info->last_change()) + \")\";\n }\n\n if (!chrome_version.empty())\n AddFeedbackData(&feedback_data, std::string(kChromeVersionTag),\n chrome_version);\n\n \/\/ Add OS version (eg, for WinXP SP2: \"5.1.2600 Service Pack 2\").\n std::string os_version = \"\";\n SetOSVersion(&os_version);\n AddFeedbackData(&feedback_data, std::string(kOsVersionTag), os_version);\n\n#if defined(OS_CHROMEOS)\n for (chromeos::LogDictionaryType::const_iterator i = sys_info->begin();\n i != sys_info->end(); ++i)\n AddFeedbackData(&feedback_data, i->first, i->second);\n#endif\n\n \/\/ Include the page image if we have one.\n if (png_data) {\n userfeedback::PostedScreenshot screenshot;\n screenshot.set_mime_type(kPngMimeType);\n \/\/ Set the dimensions of the screenshot\n userfeedback::Dimensions dimensions;\n dimensions.set_width(static_cast(png_width));\n dimensions.set_height(static_cast(png_height));\n *(screenshot.mutable_dimensions()) = dimensions;\n screenshot.set_binary_content(std::string(png_data, png_data_length));\n\n \/\/ Set the screenshot object in feedback\n *(feedback_data.mutable_screenshot()) = screenshot;\n }\n\n \/\/ We have the body of our POST, so send it off to the server.\n URLFetcher* fetcher = new URLFetcher(post_url, URLFetcher::POST,\n new BugReportUtil::PostCleanup);\n fetcher->set_request_context(profile->GetRequestContext());\n\n std::string post_body;\n feedback_data.SerializeToString(&post_body);\n fetcher->set_upload_data(std::string(kProtBufMimeType), post_body);\n fetcher->Start();\n}\n\n\/\/ static\nvoid BugReportUtil::ReportPhishing(TabContents* currentTab,\n const std::string& phishing_url) {\n currentTab->controller().LoadURL(\n safe_browsing_util::GeneratePhishingReportUrl(\n kReportPhishingUrl, phishing_url),\n GURL(),\n PageTransition::LINK);\n}\n<|endoftext|>"} {"text":"#include \"selfdrive\/ui\/replay\/camera.h\"\n\n#include \n#include \n\nconst int YUV_BUF_COUNT = 50;\n\nCameraServer::CameraServer() {\n camera_thread_ = std::thread(&CameraServer::thread, this);\n}\n\nCameraServer::~CameraServer() {\n queue_.push({});\n camera_thread_.join();\n vipc_server_.reset(nullptr);\n}\n\nvoid CameraServer::startVipcServer() {\n std::cout << (vipc_server_ ? \"start\" : \"restart\") << \" vipc server\" << std::endl;\n vipc_server_.reset(new VisionIpcServer(\"camerad\"));\n for (auto &cam : cameras_) {\n if (cam.width > 0 && cam.height > 0) {\n vipc_server_->create_buffers(cam.rgb_type, UI_BUF_COUNT, true, cam.width, cam.height);\n vipc_server_->create_buffers(cam.yuv_type, YUV_BUF_COUNT, false, cam.width, cam.height);\n }\n }\n vipc_server_->start_listener();\n}\n\nvoid CameraServer::thread() {\n while (true) {\n const auto [type, fr, eidx] = queue_.pop();\n if (!fr) break;\n\n auto &cam = cameras_[type];\n \/\/ start|restart the vipc server if frame size changed\n if (cam.width != fr->width || cam.height != fr->height) {\n cam.width = fr->width;\n cam.height = fr->height;\n std::cout << \"camera[\" << type << \"] frame size \" << cam.width << \"x\" << cam.height << std::endl;\n startVipcServer();\n }\n\n \/\/ send frame\n if (auto dat = fr->get(eidx.getSegmentId())) {\n auto [rgb_dat, yuv_dat] = *dat;\n VisionIpcBufExtra extra = {\n .frame_id = eidx.getFrameId(),\n .timestamp_sof = eidx.getTimestampSof(),\n .timestamp_eof = eidx.getTimestampEof(),\n };\n\n VisionBuf *rgb_buf = vipc_server_->get_buffer(cam.rgb_type);\n memcpy(rgb_buf->addr, rgb_dat, fr->getRGBSize());\n VisionBuf *yuv_buf = vipc_server_->get_buffer(cam.yuv_type);\n memcpy(yuv_buf->addr, yuv_dat, fr->getYUVSize());\n\n vipc_server_->send(rgb_buf, &extra, false);\n vipc_server_->send(yuv_buf, &extra, false);\n } else {\n std::cout << \"camera[\" << type << \"] failed to get frame:\" << eidx.getSegmentId() << std::endl;\n }\n }\n}\nreplay\/camera: fix incorrect console output (#22491)#include \"selfdrive\/ui\/replay\/camera.h\"\n\n#include \n#include \n\nconst int YUV_BUF_COUNT = 50;\n\nCameraServer::CameraServer() {\n camera_thread_ = std::thread(&CameraServer::thread, this);\n}\n\nCameraServer::~CameraServer() {\n queue_.push({});\n camera_thread_.join();\n vipc_server_.reset(nullptr);\n}\n\nvoid CameraServer::startVipcServer() {\n std::cout << (vipc_server_ ? \"restart\" : \"start\") << \" vipc server\" << std::endl;\n vipc_server_.reset(new VisionIpcServer(\"camerad\"));\n for (auto &cam : cameras_) {\n if (cam.width > 0 && cam.height > 0) {\n vipc_server_->create_buffers(cam.rgb_type, UI_BUF_COUNT, true, cam.width, cam.height);\n vipc_server_->create_buffers(cam.yuv_type, YUV_BUF_COUNT, false, cam.width, cam.height);\n }\n }\n vipc_server_->start_listener();\n}\n\nvoid CameraServer::thread() {\n while (true) {\n const auto [type, fr, eidx] = queue_.pop();\n if (!fr) break;\n\n auto &cam = cameras_[type];\n \/\/ start|restart the vipc server if frame size changed\n if (cam.width != fr->width || cam.height != fr->height) {\n cam.width = fr->width;\n cam.height = fr->height;\n std::cout << \"camera[\" << type << \"] frame size \" << cam.width << \"x\" << cam.height << std::endl;\n startVipcServer();\n }\n\n \/\/ send frame\n if (auto dat = fr->get(eidx.getSegmentId())) {\n auto [rgb_dat, yuv_dat] = *dat;\n VisionIpcBufExtra extra = {\n .frame_id = eidx.getFrameId(),\n .timestamp_sof = eidx.getTimestampSof(),\n .timestamp_eof = eidx.getTimestampEof(),\n };\n\n VisionBuf *rgb_buf = vipc_server_->get_buffer(cam.rgb_type);\n memcpy(rgb_buf->addr, rgb_dat, fr->getRGBSize());\n VisionBuf *yuv_buf = vipc_server_->get_buffer(cam.yuv_type);\n memcpy(yuv_buf->addr, yuv_dat, fr->getYUVSize());\n\n vipc_server_->send(rgb_buf, &extra, false);\n vipc_server_->send(yuv_buf, &extra, false);\n } else {\n std::cout << \"camera[\" << type << \"] failed to get frame:\" << eidx.getSegmentId() << std::endl;\n }\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"beast.hpp\"\n#include \"server_core.hpp\"\n\nnamespace msrv {\n\nclass BeastConnectionContext;\n\nclass BeastListener : public std::enable_shared_from_this\n{\npublic:\n BeastListener(\n asio::io_context* ioContext,\n BeastConnectionContext* connectionContext,\n const asio::ip::tcp::endpoint& endpoint);\n\n ~BeastListener();\n\n void run();\n\nprivate:\n void accept();\n void handleAccept(const boost::system::error_code& error);\n\n asio::io_context* ioContext_;\n BeastConnectionContext* connectionContext_;\n\n asio::ip::tcp::acceptor acceptor_;\n asio::ip::tcp::socket peerSocket_;\n asio::ip::tcp::endpoint peerEndpoint_;\n};\n\n}\nfix compilation with clang#pragma once\n\n#include \"beast.hpp\"\n#include \"server_core.hpp\"\n\nnamespace msrv {\n\nstruct BeastConnectionContext;\n\nclass BeastListener : public std::enable_shared_from_this\n{\npublic:\n BeastListener(\n asio::io_context* ioContext,\n BeastConnectionContext* connectionContext,\n const asio::ip::tcp::endpoint& endpoint);\n\n ~BeastListener();\n\n void run();\n\nprivate:\n void accept();\n void handleAccept(const boost::system::error_code& error);\n\n asio::io_context* ioContext_;\n BeastConnectionContext* connectionContext_;\n\n asio::ip::tcp::acceptor acceptor_;\n asio::ip::tcp::socket peerSocket_;\n asio::ip::tcp::endpoint peerEndpoint_;\n};\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: brokenpackageint.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 16:46:10 $\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 _SAL_CONFIG_H_\n#include \"sal\/config.h\"\n#endif\n\n#ifndef INCLUDED_SFX2_DLLAPI_H\n#include \"sfx2\/dllapi.h\"\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_BROKENPACKAGEREQUEST_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONAPPROVE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TASK_XINTERACTIONDISAPPROVE_HPP_\n#include \n#endif\n\n#ifndef __FRAMEWORK_DISPATCH_INTERACTION_HXX_\n#include \n#endif\n\nusing namespace ::framework;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > SfxContinuationApprove;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > SfxContinuationDisapprove;\n\nclass SFX2_DLLPUBLIC RequestPackageReparation : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n ::com::sun::star::uno::Any m_aRequest;\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > m_lContinuations;\n\n SfxContinuationApprove* m_pApprove;\n SfxContinuationDisapprove* m_pDisapprove;\n\npublic:\n RequestPackageReparation( ::rtl::OUString aName );\n\n sal_Bool isApproved() { return m_pApprove->isSelected(); }\n\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest()\n throw( ::com::sun::star::uno::RuntimeException );\n\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > SAL_CALL getContinuations()\n throw( ::com::sun::star::uno::RuntimeException );\n};\n\nclass SFX2_DLLPUBLIC NotifyBrokenPackage : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n ::com::sun::star::uno::Any m_aRequest;\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > m_lContinuations;\n\n ContinuationAbort* m_pAbort;\n\npublic:\n NotifyBrokenPackage( ::rtl::OUString aName );\n\n sal_Bool isAborted() { return m_pAbort->isSelected(); }\n\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest()\n throw( ::com::sun::star::uno::RuntimeException );\n\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > SAL_CALL getContinuations()\n throw( ::com::sun::star::uno::RuntimeException );\n};\n\nINTEGRATION: CWS changefileheader (1.4.732); FILE MERGED 2008\/04\/01 15:38:14 thb 1.4.732.3: #i85898# Stripping all external header guards 2008\/04\/01 12:40:32 thb 1.4.732.2: #i85898# Stripping all external header guards 2008\/03\/31 13:37:53 rt 1.4.732.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: brokenpackageint.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"sal\/config.h\"\n#include \"sfx2\/dllapi.h\"\n#include \n#include \n#include \n#include \n\nusing namespace ::framework;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > SfxContinuationApprove;\ntypedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > SfxContinuationDisapprove;\n\nclass SFX2_DLLPUBLIC RequestPackageReparation : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n ::com::sun::star::uno::Any m_aRequest;\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > m_lContinuations;\n\n SfxContinuationApprove* m_pApprove;\n SfxContinuationDisapprove* m_pDisapprove;\n\npublic:\n RequestPackageReparation( ::rtl::OUString aName );\n\n sal_Bool isApproved() { return m_pApprove->isSelected(); }\n\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest()\n throw( ::com::sun::star::uno::RuntimeException );\n\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > SAL_CALL getContinuations()\n throw( ::com::sun::star::uno::RuntimeException );\n};\n\nclass SFX2_DLLPUBLIC NotifyBrokenPackage : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >\n{\n ::com::sun::star::uno::Any m_aRequest;\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > m_lContinuations;\n\n ContinuationAbort* m_pAbort;\n\npublic:\n NotifyBrokenPackage( ::rtl::OUString aName );\n\n sal_Bool isAborted() { return m_pAbort->isSelected(); }\n\n virtual ::com::sun::star::uno::Any SAL_CALL getRequest()\n throw( ::com::sun::star::uno::RuntimeException );\n\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation >\n > SAL_CALL getContinuations()\n throw( ::com::sun::star::uno::RuntimeException );\n};\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Set.h\n\/\/ Set\n\/\/\n\/\/ Created by Antonio Seprano on 10\/08\/14.\n\/\/ Copyright (c) 2014 Antonio Seprano. All rights reserved.\n\/\/\n\n#include \n#include \n#include \n#include \n\n#ifndef _SET_HPP\n#define _SET_HPP\n\ntemplate >\nclass Set {\npublic:\n\ttypedef _T\t\t\t\t value_type;\n\ttypedef _Allocator\tallocator_type;\n\t\nprivate:\n\ttypedef Set _SET;\n\t\npublic:\n\ttypedef typename std::vector::iterator\t\t\t\titerator;\n\ttypedef typename std::vector::const_iterator\tconst_iterator;\n\t\n\t\/\/ Empty set\n\tSet() {};\n\t\n\t\/\/ Set with initializer list\n\tSet(const std::initializer_list& l) {\n\t\t_set.reserve(l.size());\n\t\t\n\t\tfor (const auto& value : l) {\n\t\t\tinsert(value);\n\t\t}\n\t}\n\t\n\tSet(std::initializer_list&& l) {\n\t\t_set.reserve(l.size());\n\t\t\n\t\tfor (auto& value : l) {\n\t\t\tinsert(std::move(value));\n\t\t}\n\t}\n\t\n\t\/\/ Copy constructor\n\tSet(const _SET& s) {\n\t\t_set = s._set;\n\t}\n\t\n\t\/\/ Move constructor\n\tSet(_SET&& s) {\n\t\t_set = std::move(s._set);\n\t}\n\t\n\t\/\/ Copy assignment\n\t_SET& operator=(const _SET& s) noexcept {\n\t\t_set = s._set;\n\t\treturn *this;\n\t}\n\t\n\t\/\/ Move assignment\n\t_SET& operator=(_SET&& s) noexcept {\n\t\t_set = std::move(s._set);\n\t\treturn *this;\n\t}\n\t\n\titerator begin() noexcept {\n\t\treturn _set.begin();\n\t}\n\t\n\tconst_iterator begin() const noexcept {\n\t\treturn _set.begin();\n\t}\n\t\n\titerator end() noexcept {\n\t\treturn _set.end();\n\t};\n\t\n\tconst_iterator end() const noexcept {\n\t\treturn _set.end();\n\t}\n\t\n\tsize_t size() const noexcept {\n\t\treturn _set.size();\n\t}\n\t\n\tbool empty() const noexcept {\n\t\treturn _set.empty();\n\t}\n\t\n\tvoid clear() noexcept {\n\t\t_set.clear();\n\t}\n\t\n\titerator find(const value_type& value) noexcept {\n\t\tfor (auto it = _set.begin(); it != _set.end(); it++) {\n\t\t\tif (*it == value) return it;\n\t\t}\n\t\t\n\t\treturn _set.end();\n\t}\n\t\n\tconst_iterator find(const value_type& value) const noexcept {\n\t\treturn (const_iterator)find(value);\n\t}\n\t\n\tsize_t count(const value_type& value) const noexcept {\n\t\tsize_t ret{};\n\t\t\n\t\tfor (const auto& v : _set) {\n\t\t\tif (v == value) {\n\t\t\t\tret++;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tbool operator==(const _SET& s) const noexcept {\n\t\treturn this->contains(s, false) && s.contains(*this, false);\n\t}\n\t\n\tbool operator!=(const _SET& s) const noexcept {\n\t\treturn !(*this == s);\n\t};\n\t\n\tbool operator<(const _SET& s) const noexcept {\n\t\tif (size() != s.size()) {\n\t\t\treturn size() < s.size();\n\t\t}\n\t\t\n\t\tauto it1=begin(), it2=s.begin();\n\t\t\n\t\twhile (it1 != end() && it2 != s.end()) {\n\t\t\tif (*it1 < *it2) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (*it1 > *it2) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tit1++;\n\t\t\tit2++;\n\t\t};\n\t\t\n\t\treturn false;\n\t}\n\t\n\t\n\t\/\/ Insert new value\n\t\/\/ unique = true => values must be unique (no duplicate values allowed)\n\t_SET& insert(const value_type& value, bool unique = false) noexcept {\n\t\tif (!unique || find(value) == _set.end()) {\n\t\t\tauto it = begin();\n\t\t\t\n\t\t\twhile (it != end() && *it < value) {\n\t\t\t\tit++;\n\t\t\t}\n\t\t\t\n\t\t\t_set.insert(it, value);\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t_SET& insert(value_type&& value, bool unique = false) noexcept {\n\t\tif (!unique || find(value) == _set.end()) {\n\t\t\tauto it = begin();\n\t\t\t\n\t\t\twhile (it != end() && *it < value) {\n\t\t\t\tit++;\n\t\t\t}\n\t\t\t\n\t\t\t_set.insert(it, std::move(value));\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t\n\t_SET operator+(const value_type& value) const noexcept {\n\t\treturn _SET{*this}+_SET{value};\n\t}\n\t\n\t_SET operator+(value_type&& value) const noexcept {\n\t\treturn _SET{*this}+_SET{std::move(value)};\n\t}\n\t\n\t_SET operator+(const _SET& s) const noexcept {\n\t\t_SET ret{*this};\n\t\t\n\t\tfor (const auto& value : s) {\n\t\t\tret.insert(value);\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t_SET operator+(_SET&& s) const noexcept {\n\t\t_SET ret{*this};\n\t\t\n\t\tfor (auto& value : s) {\n\t\t\tret.insert(std::move(value));\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t\n\t_SET& operator+=(const value_type& value) noexcept {\n\t\tinsert(value);\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator+=(value_type&& value) noexcept {\n\t\tinsert(std::move(value));\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator+=(const _SET& s) noexcept {\n\t\tfor (const auto& value : s) {\n\t\t\tinsert(value);\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator+=(_SET&& s) noexcept {\n\t\tfor (auto& value : s) {\n\t\t\tinsert(std::move(value));\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t\n\t_SET operator-(const value_type& value) const noexcept {\n\t\t_SET ret{*this};\n\t\tret.erase(value);\n\t\treturn ret;\n\t}\n\t\n\t_SET operator-(const _SET& s) const noexcept {\n\t\t_SET ret{*this};\n\t\tfor (const auto& v : s) {\n\t\t\tret.erase(v);\n\t\t}\n\t\treturn ret;\n\t}\n\t\n\t_SET& operator-=(const value_type& value) noexcept {\n\t\t_set.erase(value);\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator-=(const _SET& s) noexcept {\n\t\tfor (const auto& value : s) {\n\t\t\t_set.erase(value);\n\t\t}\n\t\treturn *this;\n\t}\n\t\n\t\n\tSet<_SET> operator*(const _SET& other) noexcept {\n\t\tSet<_SET> ret;\n\t\t\n\t\tif (!this->empty() && !other.empty()) {\n\t\t\tfor (const auto& v1 : _set) {\n\t\t\t\tfor (const auto& v2 : other) {\n\t\t\t\t\tret.insert(_SET{v1,v2});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t\n\t_SET intersection(const _SET& s) noexcept {\n\t\t_SET s1, s2;\n\t\t\n\t\tif (s.size() <= size()) {\n\t\t\ts1 = s;\n\t\t\ts2 = *this;\n\t\t}\n\t\telse {\n\t\t\ts1 = *this;\n\t\t\ts2 = s;\n\t\t}\n\t\t\n\t\tfor (const auto &v : s1) {\n\t\t\tif (!s2.contains(v)) s1.erase(v);\n\t\t}\n\t\t\n\t\treturn s1;\n\t}\n\t\n\tbool contains(const value_type& value) const noexcept {\n\t\treturn contains(_SET{value});\n\t}\n\t\n\tbool contains(const _SET& s, bool strict = false) const noexcept {\n\t\tfor (const auto& value : s) {\n\t\t\tbool found{false};\n\t\t\t\n\t\t\tfor (const auto& v : _set) {\n\t\t\t\tif (v == value) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!found) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn strict ? (s.size() != size()) : true;\n\t}\n\t\n\ttemplate\n\tvoid insert(InputIterator first, InputIterator last) {\n\t\tfor (auto it = first; it != last; it++) {\n\t\t\t_set.insert(*it);\n\t\t}\n\t};\n\t\n\titerator erase(const_iterator position) {\n\t\treturn _set.erase(position);\n\t}\n\t\n\titerator erase(const_iterator first, const_iterator last) {\n\t\treturn _set.erase(first,last);\n\t}\n\t\n\tsize_t erase(const value_type& value, bool all = false) {\n\t\tsize_t ret{};\n\t\t\n\t\tif (!all) {\n\t\t\tauto it = find(value);\n\t\t\t\n\t\t\tif (it != end()) {\n\t\t\t\terase(it);\n\t\t\t\tret++;\n\t\t\t}\n\t\t\t\n\t\t\treturn ret;\n\t\t}\n\t\t\n\t\tfor (auto it = _set.begin(); it != _set.end(); it++) {\n\t\t\tif (*it == value) {\n\t\t\t\t_set.erase(it);\n\t\t\t\t++ret;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t_SET& unique() noexcept {\n\t\tfor (auto i = begin(); i != end(); i++) {\n\t\t\tauto j = i+1;\n\t\t\t\n\t\t\twhile (j != end()) {\n\t\t\t\tif (*i == *j) {\n\t\t\t\t\t_set.erase(j);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\nprivate:\n\tstd::vector _set;\n};\n\n#endif \/* defined(_SET_HPP) *\/\n[add] Changed Set::intersection() to Set::intersectionWith()\/\/\n\/\/ Set.h\n\/\/ Set\n\/\/\n\/\/ Created by Antonio Seprano on 10\/08\/14.\n\/\/ Copyright (c) 2014 Antonio Seprano. All rights reserved.\n\/\/\n\n#include \n#include \n#include \n#include \n\n#ifndef _SET_HPP\n#define _SET_HPP\n\ntemplate, class _Allocator = std::allocator<_T>>\nclass Set {\npublic:\n\ttypedef _T\t\t\t\t value_type;\n\ttypedef _Allocator\tallocator_type;\n\ttypedef _Compare value_compare;\n\t\nprivate:\n\ttypedef Set _SET;\n\t\npublic:\n\ttypedef typename std::vector::iterator\t\t\t\titerator;\n\ttypedef typename std::vector::const_iterator\tconst_iterator;\n\t\n\t\/\/ Empty set\n\tSet() {};\n\t\n\t\/\/ Set with initializer list\n\tSet(const std::initializer_list& l) {\n\t\t_set.reserve(l.size());\n\t\t\n\t\tfor (const auto& value : l) {\n\t\t\tinsert(value);\n\t\t}\n\t}\n\t\n\tSet(std::initializer_list&& l) {\n\t\t_set.reserve(l.size());\n\t\t\n\t\tfor (auto& value : l) {\n\t\t\tinsert(std::move(value));\n\t\t}\n\t}\n\t\n\t\/\/ Copy constructor\n\tSet(const _SET& s) {\n\t\t_set = s._set;\n\t}\n\t\n\t\/\/ Move constructor\n\tSet(_SET&& s) {\n\t\t_set = std::move(s._set);\n\t}\n\t\n\t\/\/ Copy assignment\n\t_SET& operator=(const _SET& s) noexcept {\n\t\t_set = s._set;\n\t\treturn *this;\n\t}\n\t\n\t\/\/ Move assignment\n\t_SET& operator=(_SET&& s) noexcept {\n\t\t_set = std::move(s._set);\n\t\treturn *this;\n\t}\n\t\n\titerator begin() noexcept {\n\t\treturn _set.begin();\n\t}\n\t\n\tconst_iterator begin() const noexcept {\n\t\treturn _set.begin();\n\t}\n\t\n\titerator end() noexcept {\n\t\treturn _set.end();\n\t};\n\t\n\tconst_iterator end() const noexcept {\n\t\treturn _set.end();\n\t}\n\t\n\tsize_t size() const noexcept {\n\t\treturn _set.size();\n\t}\n\t\n\tbool empty() const noexcept {\n\t\treturn _set.empty();\n\t}\n\t\n\tvoid clear() noexcept {\n\t\t_set.clear();\n\t}\n\t\n\titerator find(const value_type& value) noexcept {\n\t\tfor (auto it = _set.begin(); it != _set.end(); it++) {\n\t\t\tif (*it == value) return it;\n\t\t}\n\t\t\n\t\treturn _set.end();\n\t}\n\t\n\tconst_iterator find(const value_type& value) const noexcept {\n\t\treturn (const_iterator)find(value);\n\t}\n\t\n\tsize_t count(const value_type& value) const noexcept {\n\t\tsize_t ret{};\n\t\t\n\t\tfor (const auto& v : _set) {\n\t\t\tif (v == value) {\n\t\t\t\tret++;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\tbool operator==(const _SET& s) const noexcept {\n\t\treturn this->contains(s, false) && s.contains(*this, false);\n\t}\n\t\n\tbool operator!=(const _SET& s) const noexcept {\n\t\treturn !(*this == s);\n\t};\n\t\n\tbool operator<(const _SET& s) const noexcept {\n\t\tif (size() != s.size()) {\n\t\t\treturn size() < s.size();\n\t\t}\n\t\t\n\t\tauto it1=begin(), it2=s.begin();\n\t\t\n\t\twhile (it1 != end() && it2 != s.end()) {\n\t\t\tif (*it1 < *it2) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse if (*it1 > *it2) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tit1++;\n\t\t\tit2++;\n\t\t};\n\t\t\n\t\treturn false;\n\t}\n\t\n\t\n\t\/\/ Insert new value\n\t\/\/ unique = true => values must be unique (no duplicate values allowed)\n\t_SET& insert(const value_type& value, bool unique = false) noexcept {\n\t\tif (!unique || this->find(value) == _set.end()) {\n\t\t\tauto it = begin();\n\t\t\t\n\t\t\twhile (it != end() && value_compare()(*it, value)) {\n\t\t\t\tit++;\n\t\t\t}\n\t\t\t\n\t\t\t_set.insert(it, value);\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t_SET& insert(value_type&& value, bool unique = false) noexcept {\n\t\tif (!unique || find(value) == _set.end()) {\n\t\t\tauto it = begin();\n\t\t\t\n\t\t\twhile (it != end() && value_compare()(*it, value)) {\n\t\t\t\tit++;\n\t\t\t}\n\t\t\t\n\t\t\t_set.insert(it, std::move(value));\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t\n\t_SET operator+(const value_type& value) const noexcept {\n\t\treturn _SET{*this}+_SET{value};\n\t}\n\t\n\t_SET operator+(value_type&& value) const noexcept {\n\t\treturn _SET{*this}+_SET{std::move(value)};\n\t}\n\t\n\t_SET operator+(const _SET& s) const noexcept {\n\t\t_SET ret{*this};\n\t\t\n\t\tfor (const auto& value : s) {\n\t\t\tret.insert(value);\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t_SET operator+(_SET&& s) const noexcept {\n\t\t_SET ret{*this};\n\t\t\n\t\tfor (auto& value : s) {\n\t\t\tret.insert(std::move(value));\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t\n\t_SET& operator+=(const value_type& value) noexcept {\n\t\tinsert(value);\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator+=(value_type&& value) noexcept {\n\t\tinsert(std::move(value));\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator+=(const _SET& s) noexcept {\n\t\tfor (const auto& value : s) {\n\t\t\tinsert(value);\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator+=(_SET&& s) noexcept {\n\t\tfor (auto& value : s) {\n\t\t\tinsert(std::move(value));\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\n\t\n\t_SET operator-(const value_type& value) const noexcept {\n\t\t_SET ret{*this};\n\t\tret.erase(value);\n\t\treturn ret;\n\t}\n\t\n\t_SET operator-(const _SET& s) const noexcept {\n\t\t_SET ret{*this};\n\t\tfor (const auto& v : s) {\n\t\t\tret.erase(v);\n\t\t}\n\t\treturn ret;\n\t}\n\t\n\t_SET& operator-=(const value_type& value) noexcept {\n\t\t_set.erase(value);\n\t\treturn *this;\n\t}\n\t\n\t_SET& operator-=(const _SET& s) noexcept {\n\t\tfor (const auto& value : s) {\n\t\t\t_set.erase(value);\n\t\t}\n\t\treturn *this;\n\t}\n\t\n\t\n\tSet<_SET> operator*(const _SET& other) noexcept {\n\t\tSet<_SET> ret;\n\t\t\n\t\tif (!this->empty() && !other.empty()) {\n\t\t\tfor (const auto& v1 : _set) {\n\t\t\t\tfor (const auto& v2 : other) {\n\t\t\t\t\tret.insert(_SET{v1,v2});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t\n\t_SET intersectionWith(const _SET& s) noexcept {\n\t\t_SET s1, s2;\n\t\t\n\t\tif (s.size() <= size()) {\n\t\t\ts1 = s;\n\t\t\ts2 = *this;\n\t\t}\n\t\telse {\n\t\t\ts1 = *this;\n\t\t\ts2 = s;\n\t\t}\n\t\t\n\t\tfor (const auto &v : s1) {\n\t\t\tif (!s2.contains(v)) s1.erase(v);\n\t\t}\n\t\t\n\t\treturn s1;\n\t}\n\t\n\tbool contains(const value_type& value) const noexcept {\n\t\treturn contains(_SET{value});\n\t}\n\t\n\tbool contains(const _SET& s, bool strict = false) const noexcept {\n\t\tfor (const auto& value : s) {\n\t\t\tbool found{false};\n\t\t\t\n\t\t\tfor (const auto& v : _set) {\n\t\t\t\tif (v == value) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (!found) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn strict ? (s.size() != size()) : true;\n\t}\n\t\n\ttemplate\n\tvoid insert(InputIterator first, InputIterator last) {\n\t\tfor (auto it = first; it != last; it++) {\n\t\t\t_set.insert(*it);\n\t\t}\n\t};\n\t\n\titerator erase(const_iterator position) {\n\t\treturn _set.erase(position);\n\t}\n\t\n\titerator erase(const_iterator first, const_iterator last) {\n\t\treturn _set.erase(first,last);\n\t}\n\t\n\tsize_t erase(const value_type& value, bool all = false) {\n\t\tsize_t ret{};\n\t\t\n\t\tif (!all) {\n\t\t\tauto it = find(value);\n\t\t\t\n\t\t\tif (it != end()) {\n\t\t\t\terase(it);\n\t\t\t\tret++;\n\t\t\t}\n\t\t\t\n\t\t\treturn ret;\n\t\t}\n\t\t\n\t\tfor (auto it = _set.begin(); it != _set.end(); it++) {\n\t\t\tif (*it == value) {\n\t\t\t\t_set.erase(it);\n\t\t\t\t++ret;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\n\t_SET& unique() noexcept {\n\t\tfor (auto i = begin(); i != end(); i++) {\n\t\t\tauto j = i+1;\n\t\t\t\n\t\t\twhile (j != end()) {\n\t\t\t\tif (*i == *j) {\n\t\t\t\t\t_set.erase(j);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tj++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn *this;\n\t}\n\t\nprivate:\n\tstd::vector _set;\n};\n\n#endif \/* defined(_SET_HPP) *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace cli\n{\n\n\tSession::Session(const mtp::DevicePtr &device):\n\t\t_device(device),\n\t\t_session(_device->OpenSession(1)),\n\t\t_gdi(_session->GetDeviceInfo()),\n\t\t_cd(mtp::Session::Root),\n\t\t_running(true)\n\t{\n\t\tusing namespace mtp;\n\t\tusing namespace std::placeholders;\n\n\t\tprintf(\"%s\\n\", _gdi.VendorExtensionDesc.c_str());\n\t\tprintf(\"%s \", _gdi.Manufacturer.c_str());\n\t\tprintf(\"%s \", _gdi.Model.c_str());\n\t\tprintf(\"%s \", _gdi.DeviceVersion.c_str());\n\t\t\/\/printf(\"%s\", _gdi.SerialNumber.c_str());\n\t\tprintf(\"\\n\");\n\t\tprintf(\"supported op codes: \");\n\t\tfor(OperationCode code : _gdi.OperationsSupported)\n\t\t{\n\t\t\tprintf(\"%04x \", (unsigned)code);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tprintf(\"supported properties: \");\n\t\tfor(u16 code : _gdi.DevicePropertiesSupported)\n\t\t{\n\t\t\tprintf(\"%04x \", (unsigned)code);\n\t\t}\n\t\tprintf(\"\\n\");\n\n\t\tAddCommand(\"help\",\t\t\tmake_function([this]() -> void { Help(); }));\n\n\t\tAddCommand(\"ls\",\t\t\tmake_function([this]() -> void { List(); }));\n\t\tAddCommand(\"list\",\t\t\tmake_function([this]() -> void { List(); }));\n\t\tAddCommand(\"list\", \t\t\tmake_function([this](mtp::u32 parent) -> void { List(parent); }));\n\n\t\tAddCommand(\"quit\", \t\t\tmake_function([this]() -> void { Quit(); }));\n\t\tAddCommand(\"exit\", \t\t\tmake_function([this]() -> void { Quit(); }));\n\n\t\tAddCommand(\"cd\", \t\t\tmake_function([this](const Path &path) -> void { ChangeDirectory(path); }));\n\t\tAddCommand(\"rm\", \t\t\tmake_function([this](const LocalPath &path) -> void { Delete(path); }));\n\t\tAddCommand(\"get\", \t\t\tmake_function([this](const LocalPath &path) -> void { Get(path); }));\n\n\t\tAddCommand(\"storages\", make_function([this]() -> void { ListStorages(); }));\n\t\tAddCommand(\"device-properties\", make_function([this]() -> void { ListDeviceProperties(); }));\n\t}\n\n\tchar ** Session::CompletionCallback(const char *text, int start, int end)\n\t{\n\t\tif (start == 0)\n\t\t{\n\t\t\tchar **comp = static_cast(calloc(sizeof(char *), _commands.size() + 1));\n\t\t\tauto it = _commands.begin();\n\t\t\tsize_t i = 0, n = _commands.size();\n\t\t\tfor(; n--; ++it)\n\t\t\t{\n\t\t\t\tif (end != 0 && it->first.compare(0, end, text) != 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcomp[i++] = strdup(it->first.c_str());\n\t\t\t}\n\t\t\tif (i == 0) \/\/readline silently dereference matches[0]\n\t\t\t{\n\t\t\t\tfree(comp);\n\t\t\t\tcomp = NULL;\n\t\t\t};\n\t\t\treturn comp;\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tvoid Session::InteractiveInput()\n\t{\n\t\tusing namespace mtp;\n\t\tstd::string prompt(_gdi.Manufacturer + \" \" + _gdi.Model + \"> \"), input;\n\t\tcli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); });\n\n\t\twhile (_running && cli::CommandLine::Get().ReadLine(prompt, input))\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tTokens tokens;\n\t\t\t\tTokenizer(input, tokens);\n\t\t\t\tif (tokens.empty())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tstd::string cmdName = tokens.front();\n\t\t\t\ttokens.pop_front();\n\t\t\t\tauto cmd = _commands.find(cmdName);\n\t\t\t\tif (cmd == _commands.end())\n\t\t\t\t\tthrow std::runtime_error(\"invalid command \" + cmdName);\n\n\t\t\t\tcmd->second->Execute(tokens);\n\t\t\t}\n\t\t\tcatch(const std::exception &ex)\n\t\t\t{ printf(\"error: %s\\n\", ex.what()); }\n\t\t}\n\t}\n\n\tmtp::u32 Session::Resolve(const Path &path)\n\t{\n\t\tmtp::u32 id = _cd;\n\t\tfor(size_t p = 0; p < path.size(); )\n\t\t{\n\t\t\tsize_t next = path.find('\/', p);\n\t\t\tif (next == path.npos)\n\t\t\t\tnext = path.size();\n\n\t\t\tstd::string entity(path.substr(p, next - p));\n\t\t\tauto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id);\n\t\t\tbool found = false;\n\t\t\tfor(auto object : objectList.ObjectHandles)\n\t\t\t{\n\t\t\t\tstd::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename);\n\t\t\t\tif (name == entity)\n\t\t\t\t{\n\t\t\t\t\tid = object;\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found)\n\t\t\t\tthrow std::runtime_error(\"could not find \" + entity + \" in path \" + path.substr(0, p));\n\t\t\tp = next + 1;\n\t\t}\n\t\treturn id;\n\t}\n\n\tvoid Session::List(mtp::u32 parent)\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent);\n\n\t\tfor(u32 objectId : handles.ObjectHandles)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmsg::ObjectInfo info = _session->GetObjectInfo(objectId);\n\t\t\t\tprintf(\"%-10u %04hx %s %u %ux%u, %s\\n\", objectId, info.ObjectFormat, info.Filename.c_str(), info.ObjectCompressedSize, info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str());\n\t\t\t}\n\t\t\tcatch(const std::exception &ex)\n\t\t\t{\n\t\t\t\tprintf(\"error: %s\\n\", ex.what());\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid Session::ListStorages()\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::StorageIDs list = _session->GetStorageIDs();\n\t\tfor(size_t i = 0; i < list.StorageIDs.size(); ++i)\n\t\t{\n\t\t\tmsg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]);\n\t\t\tprintf(\"%08d volume: %s, description: %s\\n\", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str());\n\t\t}\n\t}\n\n\tvoid Session::Help()\n\t{\n\t\tprintf(\"Available commands are:\\n\");\n\t\tfor(auto i : _commands)\n\t\t{\n\t\t\tprintf(\"\\t%s\\n\", i.first.c_str());\n\t\t}\n\t}\n\n\tvoid Session::Get(const LocalPath &dst, mtp::u32 srcId)\n\t{\n\t\t_session->GetObject(srcId, std::make_shared(dst));\n\t}\n\n\tvoid Session::Get(mtp::u32 srcId)\n\t{\n\t\tauto info = _session->GetObjectInfo(srcId);\n\t\tprintf(\"filename = %s\\n\", info.Filename.c_str());\n\t\tGet(LocalPath(info.Filename), srcId);\n\t}\n\n\tvoid Session::Put(mtp::u32 parentId, const LocalPath &src)\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = src;\n\t\toi.ObjectFormat = ObjectFormatFromFilename(src);\n\n\t\tstd::shared_ptr objectInput(new ObjectInputStream(src));\n\t\toi.SetSize(objectInput->GetSize());\n\n\t\tauto noi = _session->SendObjectInfo(oi, 0, parentId);\n\t\tprintf(\"new object id = %u\\n\", noi.ObjectId);\n\t\t_session->SendObject(objectInput);\n\t\tprintf(\"done\\n\");\n\t}\n\n\tvoid Session::MakeDirectory(mtp::u32 parentId, const std::string & name)\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = name;\n\t\toi.ObjectFormat = ObjectFormat::Association;\n\t\t_session->SendObjectInfo(oi, 0, parentId);\n\t}\n\n\tvoid Session::Delete(mtp::u32 id)\n\t{\n\t\t_session->DeleteObject(id);\n\t}\n\n\tvoid Session::ListProperties(mtp::u32 id)\n\t{\n\t\tauto ops = _session->GetObjectPropsSupported(id);\n\t\tprintf(\"properties supported: \");\n\t\tfor(mtp::u16 prop: ops.ObjectPropCodes)\n\t\t{\n\t\t\tprintf(\"%02x \", prop);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tvoid Session::ListDeviceProperties()\n\t{\n\t\tusing namespace mtp;\n\t\tfor(u16 code : _gdi.DevicePropertiesSupported)\n\t\t{\n\t\t\tif ((code & 0xff00) != 0x5000 )\n\t\t\t\tcontinue;\n\t\t\tprintf(\"property code: %04x\\n\", (unsigned)code);\n\t\t\tByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code);\n\t\t\tHexDump(\"value\", data);\n\t\t}\n\t}\n\n}\nput newline only for ctrl-d exit#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace cli\n{\n\n\tSession::Session(const mtp::DevicePtr &device):\n\t\t_device(device),\n\t\t_session(_device->OpenSession(1)),\n\t\t_gdi(_session->GetDeviceInfo()),\n\t\t_cd(mtp::Session::Root),\n\t\t_running(true)\n\t{\n\t\tusing namespace mtp;\n\t\tusing namespace std::placeholders;\n\n\t\tprintf(\"%s\\n\", _gdi.VendorExtensionDesc.c_str());\n\t\tprintf(\"%s \", _gdi.Manufacturer.c_str());\n\t\tprintf(\"%s \", _gdi.Model.c_str());\n\t\tprintf(\"%s \", _gdi.DeviceVersion.c_str());\n\t\t\/\/printf(\"%s\", _gdi.SerialNumber.c_str());\n\t\tprintf(\"\\n\");\n\t\tprintf(\"supported op codes: \");\n\t\tfor(OperationCode code : _gdi.OperationsSupported)\n\t\t{\n\t\t\tprintf(\"%04x \", (unsigned)code);\n\t\t}\n\t\tprintf(\"\\n\");\n\t\tprintf(\"supported properties: \");\n\t\tfor(u16 code : _gdi.DevicePropertiesSupported)\n\t\t{\n\t\t\tprintf(\"%04x \", (unsigned)code);\n\t\t}\n\t\tprintf(\"\\n\");\n\n\t\tAddCommand(\"help\",\t\t\tmake_function([this]() -> void { Help(); }));\n\n\t\tAddCommand(\"ls\",\t\t\tmake_function([this]() -> void { List(); }));\n\t\tAddCommand(\"list\",\t\t\tmake_function([this]() -> void { List(); }));\n\t\tAddCommand(\"list\", \t\t\tmake_function([this](mtp::u32 parent) -> void { List(parent); }));\n\n\t\tAddCommand(\"quit\", \t\t\tmake_function([this]() -> void { Quit(); }));\n\t\tAddCommand(\"exit\", \t\t\tmake_function([this]() -> void { Quit(); }));\n\n\t\tAddCommand(\"cd\", \t\t\tmake_function([this](const Path &path) -> void { ChangeDirectory(path); }));\n\t\tAddCommand(\"rm\", \t\t\tmake_function([this](const LocalPath &path) -> void { Delete(path); }));\n\t\tAddCommand(\"get\", \t\t\tmake_function([this](const LocalPath &path) -> void { Get(path); }));\n\n\t\tAddCommand(\"storages\", make_function([this]() -> void { ListStorages(); }));\n\t\tAddCommand(\"device-properties\", make_function([this]() -> void { ListDeviceProperties(); }));\n\t}\n\n\tchar ** Session::CompletionCallback(const char *text, int start, int end)\n\t{\n\t\tif (start == 0)\n\t\t{\n\t\t\tchar **comp = static_cast(calloc(sizeof(char *), _commands.size() + 1));\n\t\t\tauto it = _commands.begin();\n\t\t\tsize_t i = 0, n = _commands.size();\n\t\t\tfor(; n--; ++it)\n\t\t\t{\n\t\t\t\tif (end != 0 && it->first.compare(0, end, text) != 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tcomp[i++] = strdup(it->first.c_str());\n\t\t\t}\n\t\t\tif (i == 0) \/\/readline silently dereference matches[0]\n\t\t\t{\n\t\t\t\tfree(comp);\n\t\t\t\tcomp = NULL;\n\t\t\t};\n\t\t\treturn comp;\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tvoid Session::InteractiveInput()\n\t{\n\t\tusing namespace mtp;\n\t\tstd::string prompt(_gdi.Manufacturer + \" \" + _gdi.Model + \"> \"), input;\n\t\tcli::CommandLine::Get().SetCallback([this](const char *text, int start, int end) -> char ** { return CompletionCallback(text, start, end); });\n\n\t\twhile (cli::CommandLine::Get().ReadLine(prompt, input))\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tTokens tokens;\n\t\t\t\tTokenizer(input, tokens);\n\t\t\t\tif (tokens.empty())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tstd::string cmdName = tokens.front();\n\t\t\t\ttokens.pop_front();\n\t\t\t\tauto cmd = _commands.find(cmdName);\n\t\t\t\tif (cmd == _commands.end())\n\t\t\t\t\tthrow std::runtime_error(\"invalid command \" + cmdName);\n\n\t\t\t\tcmd->second->Execute(tokens);\n\t\t\t\tif (!_running) \/\/do not put newline\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\tcatch(const std::exception &ex)\n\t\t\t{ printf(\"error: %s\\n\", ex.what()); }\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tmtp::u32 Session::Resolve(const Path &path)\n\t{\n\t\tmtp::u32 id = _cd;\n\t\tfor(size_t p = 0; p < path.size(); )\n\t\t{\n\t\t\tsize_t next = path.find('\/', p);\n\t\t\tif (next == path.npos)\n\t\t\t\tnext = path.size();\n\n\t\t\tstd::string entity(path.substr(p, next - p));\n\t\t\tauto objectList = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, id);\n\t\t\tbool found = false;\n\t\t\tfor(auto object : objectList.ObjectHandles)\n\t\t\t{\n\t\t\t\tstd::string name = _session->GetObjectStringProperty(object, mtp::ObjectProperty::ObjectFilename);\n\t\t\t\tif (name == entity)\n\t\t\t\t{\n\t\t\t\t\tid = object;\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found)\n\t\t\t\tthrow std::runtime_error(\"could not find \" + entity + \" in path \" + path.substr(0, p));\n\t\t\tp = next + 1;\n\t\t}\n\t\treturn id;\n\t}\n\n\tvoid Session::List(mtp::u32 parent)\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::ObjectHandles handles = _session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent);\n\n\t\tfor(u32 objectId : handles.ObjectHandles)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmsg::ObjectInfo info = _session->GetObjectInfo(objectId);\n\t\t\t\tprintf(\"%-10u %04hx %s %u %ux%u, %s\\n\", objectId, info.ObjectFormat, info.Filename.c_str(), info.ObjectCompressedSize, info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str());\n\t\t\t}\n\t\t\tcatch(const std::exception &ex)\n\t\t\t{\n\t\t\t\tprintf(\"error: %s\\n\", ex.what());\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid Session::ListStorages()\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::StorageIDs list = _session->GetStorageIDs();\n\t\tfor(size_t i = 0; i < list.StorageIDs.size(); ++i)\n\t\t{\n\t\t\tmsg::StorageInfo si = _session->GetStorageInfo(list.StorageIDs[i]);\n\t\t\tprintf(\"%08d volume: %s, description: %s\\n\", list.StorageIDs[i], si.VolumeLabel.c_str(), si.StorageDescription.c_str());\n\t\t}\n\t}\n\n\tvoid Session::Help()\n\t{\n\t\tprintf(\"Available commands are:\\n\");\n\t\tfor(auto i : _commands)\n\t\t{\n\t\t\tprintf(\"\\t%s\\n\", i.first.c_str());\n\t\t}\n\t}\n\n\tvoid Session::Get(const LocalPath &dst, mtp::u32 srcId)\n\t{\n\t\t_session->GetObject(srcId, std::make_shared(dst));\n\t}\n\n\tvoid Session::Get(mtp::u32 srcId)\n\t{\n\t\tauto info = _session->GetObjectInfo(srcId);\n\t\tprintf(\"filename = %s\\n\", info.Filename.c_str());\n\t\tGet(LocalPath(info.Filename), srcId);\n\t}\n\n\tvoid Session::Put(mtp::u32 parentId, const LocalPath &src)\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = src;\n\t\toi.ObjectFormat = ObjectFormatFromFilename(src);\n\n\t\tstd::shared_ptr objectInput(new ObjectInputStream(src));\n\t\toi.SetSize(objectInput->GetSize());\n\n\t\tauto noi = _session->SendObjectInfo(oi, 0, parentId);\n\t\tprintf(\"new object id = %u\\n\", noi.ObjectId);\n\t\t_session->SendObject(objectInput);\n\t\tprintf(\"done\\n\");\n\t}\n\n\tvoid Session::MakeDirectory(mtp::u32 parentId, const std::string & name)\n\t{\n\t\tusing namespace mtp;\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = name;\n\t\toi.ObjectFormat = ObjectFormat::Association;\n\t\t_session->SendObjectInfo(oi, 0, parentId);\n\t}\n\n\tvoid Session::Delete(mtp::u32 id)\n\t{\n\t\t_session->DeleteObject(id);\n\t}\n\n\tvoid Session::ListProperties(mtp::u32 id)\n\t{\n\t\tauto ops = _session->GetObjectPropsSupported(id);\n\t\tprintf(\"properties supported: \");\n\t\tfor(mtp::u16 prop: ops.ObjectPropCodes)\n\t\t{\n\t\t\tprintf(\"%02x \", prop);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\tvoid Session::ListDeviceProperties()\n\t{\n\t\tusing namespace mtp;\n\t\tfor(u16 code : _gdi.DevicePropertiesSupported)\n\t\t{\n\t\t\tif ((code & 0xff00) != 0x5000 )\n\t\t\t\tcontinue;\n\t\t\tprintf(\"property code: %04x\\n\", (unsigned)code);\n\t\t\tByteArray data = _session->GetDeviceProperty((mtp::DeviceProperty)code);\n\t\t\tHexDump(\"value\", data);\n\t\t}\n\t}\n\n}\n<|endoftext|>"} {"text":"#include \"cmainwindow.h\"\r\n#include \"ui_cmainwindow.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\ninline bool analyzeFrame(const QImage& frame, unsigned int threshold)\r\n{\r\n\tif (frame.depth() != 32)\r\n\t\treturn true;\r\n\r\n\tconst int w = frame.width(), h = frame.height();\r\n\tconst int sampleSquareSize = 20;\r\n\tconst int sampleStrideW = w \/ sampleSquareSize, sampleStrideH = h \/ sampleSquareSize;\r\n\tuint64_t pixelsValueSum = 0;\r\n\tfor (int y = 0; y < h; y += sampleStrideH)\r\n\t{\r\n\t\tconst uint32_t* scanLine = (const uint32_t*) frame.scanLine(y);\r\n\t\tfor (int x = 0; x < w; x += sampleStrideW)\r\n\t\t{\r\n\t\t\t\/\/ TODO: support non-32 bpp images\r\n\t\t\t\/\/ TODO: vectorization\r\n\t\t\tconst uint32_t pixel = scanLine[y];\r\n\t\t\tpixelsValueSum += ((pixel & 0x00FF0000) >> 16) + ((pixel & 0x0000FF00) >> 8) + (pixel & 0x000000FF);\r\n\t\t}\r\n\t}\r\n\r\n\tconst auto avgValue = pixelsValueSum \/ ((uint64_t) w \/ sampleStrideW * (uint64_t) h \/ sampleStrideH * 3ull);\r\n\tqDebug() << \"Frame metric:\" << avgValue;\r\n\treturn avgValue >= threshold;\r\n}\r\n\r\nCMainWindow::CMainWindow(QWidget *parent) :\r\n\tQMainWindow(parent),\r\n\tui(new Ui::CMainWindow)\r\n{\r\n\tui->setupUi(this);\r\n\r\n\tui->_displayWidget->installEventFilter(this);\r\n\r\n\tconnect(&_frameGrabber, &ProxyVideoSurface::frameReceived, [this](QImage frame) {\r\n\t\tif (!frame.isNull() && ui->_btnEnableProbing->isChecked())\r\n\t\t{\r\n\t\t\t\/\/ This is the first frame upon connecting to the camera\r\n\t\t\tif (_frame.isNull())\r\n\t\t\t{\r\n\t\t\t\tif (!analyzeFrame(frame, ui->_threshold->value()))\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Disconnect and schedule re-check\r\n\t\t\t\t\tstopCamera();\r\n\t\t\t\t\tQTimer::singleShot(10000, [this](){\r\n\t\t\t\t\t\tstartCamera();\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse \/\/ Not the first frame - apparently, we're streaming a live picture\r\n\t\t\t\t \/\/ Avoid checking every single frame\r\n\t\t\t{\r\n\t\t\t\tstatic uint32_t frameCounter = 0;\r\n\t\t\t\t++frameCounter;\r\n\r\n\t\t\t\tif (frameCounter > 30)\r\n\t\t\t\t{\r\n\t\t\t\t\tframeCounter = 0;\r\n\t\t\t\t\tif (!analyzeFrame(frame, ui->_threshold->value()))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ Diisconnect and schedule re-check\r\n\t\t\t\t\t\tstopCamera();\r\n\t\t\t\t\t\tQTimer::singleShot(10000, [this](){\r\n\t\t\t\t\t\t\tstartCamera();\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_frame = frame;\r\n\t\tui->_displayWidget->update();\r\n\t});\r\n\r\n\tconnect(ui->_btnConnect, &QPushButton::clicked, [this](bool connect){\r\n\t\tui->_btnConnect->setChecked(!connect);\r\n\t\tif (connect)\r\n\t\t\tstartCamera();\r\n\t\telse\r\n\t\t\tstopCamera();\r\n\t});\r\n\r\n\tstartCamera();\r\n}\r\n\r\nCMainWindow::~CMainWindow()\r\n{\r\n\tstopCamera();\r\n\tdelete ui;\r\n}\r\n\r\nbool CMainWindow::eventFilter(QObject* \/*object*\/, QEvent* event)\r\n{\r\n\tif (event->type() == QEvent::Paint)\r\n\t{\r\n\t\tQWidget * widget = ui->_displayWidget;\r\n\t\tQPainter painter(widget);\r\n\t\tif (!_frame.isNull())\r\n\t\t\tpainter.drawImage(widget->geometry(), _frame);\r\n\t\telse\r\n\t\t\tpainter.fillRect(widget->geometry(), Qt::darkGray);\r\n\t\tpainter.end();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid CMainWindow::startCamera()\r\n{\r\n\tif (!_camera)\r\n\t{\r\n\t\tconst auto cameras = QCameraInfo::availableCameras();\r\n\t\tif (cameras.empty())\r\n\t\t\treturn;\r\n\r\n\t\tconst auto& cameraInfo = cameras.front();\r\n\t\tif (cameraInfo.isNull())\r\n\t\t\treturn;\r\n\r\n\t\tqDebug() << \"Creating the camera\" << cameraInfo.description();\r\n\t\t_camera = std::make_shared(cameraInfo);\r\n\t\t_camera->setViewfinder(&_frameGrabber);\r\n\r\n\t\tqDebug() << \"Connecting to the camera\";\r\n\t\tconnect(_camera.get(), &QCamera::stateChanged, [this](const QCamera::State state){\r\n\t\t\tif (state == QCamera::ActiveState)\r\n\t\t\t{\r\n\t\t\t\tui->_btnConnect->setChecked(true);\r\n\t\t\t\tsetWindowTitle(\"Connected\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tui->_btnConnect->setChecked(false);\r\n\t\t\t\tsetWindowTitle(\"Not Connected\");\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\r\n\t_camera->load();\r\n\t_camera->start();\r\n}\r\n\r\nvoid CMainWindow::stopCamera()\r\n{\r\n\tif (_camera)\r\n\t{\r\n\t\t_camera->stop();\r\n\t\t_camera->unload();\r\n\t\t_frame = QImage();\r\n\t}\r\n\r\n\tsetWindowTitle(\"Not Connected\");\r\n}\r\nMinor fixes#include \"cmainwindow.h\"\r\n#include \"ui_cmainwindow.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\ninline bool analyzeFrame(const QImage& frame, unsigned int threshold)\r\n{\r\n\tif (frame.depth() != 32)\r\n\t\treturn true;\r\n\r\n\tconst int w = frame.width(), h = frame.height();\r\n\tconst int sampleSquareSize = 20;\r\n\tconst int sampleStrideW = w \/ sampleSquareSize, sampleStrideH = h \/ sampleSquareSize;\r\n\tuint64_t pixelsValueSum = 0;\r\n\tfor (int y = 0; y < h; y += sampleStrideH)\r\n\t{\r\n\t\tconst uint32_t* scanLine = (const uint32_t*) frame.scanLine(y);\r\n\t\tfor (int x = 0; x < w; x += sampleStrideW)\r\n\t\t{\r\n\t\t\t\/\/ TODO: support non-32 bpp images\r\n\t\t\t\/\/ TODO: vectorization\r\n\t\t\tconst uint32_t pixel = scanLine[y];\r\n\t\t\tpixelsValueSum += ((pixel & 0x00FF0000) >> 16) + ((pixel & 0x0000FF00) >> 8) + (pixel & 0x000000FF);\r\n\t\t}\r\n\t}\r\n\r\n\tconst auto avgValue = pixelsValueSum \/ ((uint64_t) w \/ sampleStrideW * (uint64_t) h \/ sampleStrideH * 3ull);\r\n\tqDebug() << \"Frame metric:\" << avgValue;\r\n\treturn avgValue >= threshold;\r\n}\r\n\r\nCMainWindow::CMainWindow(QWidget *parent) :\r\n\tQMainWindow(parent),\r\n\tui(new Ui::CMainWindow)\r\n{\r\n\tui->setupUi(this);\r\n\r\n\tui->_displayWidget->installEventFilter(this);\r\n\r\n\tconnect(&_frameGrabber, &ProxyVideoSurface::frameReceived, [this](QImage frame) {\r\n\t\tif (!frame.isNull() && ui->_btnEnableProbing->isChecked())\r\n\t\t{\r\n\t\t\t\/\/ This is the first frame upon connecting to the camera\r\n\t\t\tif (_frame.isNull())\r\n\t\t\t{\r\n\t\t\t\tif (!analyzeFrame(frame, ui->_threshold->value()))\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Disconnect and schedule re-check\r\n\t\t\t\t\tstopCamera();\r\n\t\t\t\t\tQTimer::singleShot(10000, [this](){\r\n\t\t\t\t\t\tstartCamera();\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse \/\/ Not the first frame - apparently, we're streaming a live picture\r\n\t\t\t\t \/\/ Avoid checking every single frame\r\n\t\t\t{\r\n\t\t\t\tstatic uint32_t frameCounter = 0;\r\n\t\t\t\t++frameCounter;\r\n\r\n\t\t\t\tif (frameCounter > 30)\r\n\t\t\t\t{\r\n\t\t\t\t\tframeCounter = 0;\r\n\t\t\t\t\tif (!analyzeFrame(frame, ui->_threshold->value()))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t\/\/ Diisconnect and schedule re-check\r\n\t\t\t\t\t\tstopCamera();\r\n\t\t\t\t\t\tQTimer::singleShot(10000, [this](){\r\n\t\t\t\t\t\t\tstartCamera();\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_frame = frame;\r\n\t\tui->_displayWidget->update();\r\n\t});\r\n\r\n\tconnect(ui->_btnConnect, &QPushButton::clicked, [this](bool connect){\r\n\t\tui->_btnConnect->setChecked(!connect);\r\n\t\tif (connect)\r\n\t\t\tstartCamera();\r\n\t\telse\r\n\t\t\tstopCamera();\r\n\t});\r\n\r\n\tstartCamera();\r\n}\r\n\r\nCMainWindow::~CMainWindow()\r\n{\r\n\tstopCamera();\r\n\tdelete ui;\r\n}\r\n\r\nbool CMainWindow::eventFilter(QObject* \/*object*\/, QEvent* event)\r\n{\r\n\tif (event->type() == QEvent::Paint)\r\n\t{\r\n\t\tQWidget * widget = ui->_displayWidget;\r\n\t\tQPainter painter(widget);\r\n\t\tif (!_frame.isNull())\r\n\t\t\tpainter.drawImage(widget->geometry(), _frame);\r\n\t\telse\r\n\t\t\tpainter.fillRect(widget->geometry(), Qt::darkGray);\r\n\t\tpainter.end();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid CMainWindow::startCamera()\r\n{\r\n\tif (!_camera)\r\n\t{\r\n\t\tconst auto cameras = QCameraInfo::availableCameras();\r\n\t\tfor (const QCameraInfo& cameraInfo : cameras)\r\n\t\t{\r\n\t\t\tif (cameraInfo.isNull())\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tqDebug() << \"Creating the camera\" << cameraInfo.description();\r\n\t\t\t_camera = std::make_shared(cameraInfo);\r\n\t\t\tif (!_camera->isAvailable())\r\n\t\t\t{\r\n\t\t\t\t_camera.reset();\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\t_camera->setViewfinder(&_frameGrabber);\r\n\r\n\t\t\tconnect(_camera.get(), &QCamera::stateChanged, [this](const QCamera::State state){\r\n\t\t\t\tif (state == QCamera::ActiveState)\r\n\t\t\t\t{\r\n\t\t\t\t\tui->_btnConnect->setChecked(true);\r\n\t\t\t\t\tsetWindowTitle(\"Connected\");\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tui->_btnConnect->setChecked(false);\r\n\t\t\t\t\tsetWindowTitle(\"Not Connected\");\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tif (_camera)\r\n\t{\r\n\t\tqDebug() << \"Connecting to the camera\";\r\n\t\t_camera->load();\r\n\t\t_camera->start();\r\n\t}\r\n}\r\n\r\nvoid CMainWindow::stopCamera()\r\n{\r\n\tif (_camera)\r\n\t{\r\n\t\tqDebug() << \"Disconnecting from the camera\";\r\n\t\t_camera->stop();\r\n\t\t_camera->unload();\r\n\t\t_frame = QImage();\r\n\t}\r\n\r\n\tsetWindowTitle(\"Not Connected\");\r\n}\r\n<|endoftext|>"} {"text":"\/*\n\t\t\t\tCopyright \n\t\tSee file COPYING for copying conditions.*\/\n\n#include \"engine\/engine.h\"\n\n#include \"server\/zone\/managers\/resource\/ResourceManager.h\"\n#include \"ResourceShiftTask.h\"\n#include \"resourcespawner\/SampleTask.h\"\n#include \"resourcespawner\/SampleResultsTask.h\"\n#include \"server\/zone\/managers\/resource\/InterplanetarySurvey.h\"\n#include \"server\/zone\/managers\/resource\/InterplanetarySurveyTask.h\"\n#include \"server\/zone\/objects\/resource\/ResourceContainer.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectDeltaMessage3.h\"\n#include \"server\/zone\/objects\/player\/sui\/listbox\/SuiListBox.h\"\n\nvoid ResourceManagerImplementation::initialize() {\n\tlua = new Lua();\n\tlua->init();\n\n\tif(!loadConfigData()) {\n\n\t\tloadDefaultConfig();\n\n\t\tinfo(\"***** ERROR in configuration, using default values\");\n\t}\n\n\tresourceSpawner->init();\n\n\tstartResourceSpawner();\n\tloadSurveyData();\n}\n\nbool ResourceManagerImplementation::loadConfigFile() {\n\treturn lua->runFile(\"scripts\/managers\/resource_manager.lua\");\n}\nvoid ResourceManagerImplementation::loadSurveyData() {\n\tinfo(\"Loading survey data form surveys.db\");\n\tObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance();\n\tObjectDatabase* surveyDatabase = ObjectDatabaseManager::instance()->loadObjectDatabase(\"surveys\", true);\n\tif (surveyDatabase == NULL) {\n\t\terror(\"Could not load the survey database.\");\n\t\treturn;\n\t}\n\tint i = 0;\n\ttry {\n\t\tObjectDatabaseIterator iterator(surveyDatabase);\n\n\t\tuint64 objectID;\n\n\t\twhile (iterator.getNextKey(objectID)) {\n\t\t\tCore::getObjectBroker()->lookUp(objectID);\n\t\t\t++i;\n\t\t}\n\t} catch (DatabaseException& e) {\n\t\terror(\"Database exception in DirectorManager::loadSurveyData(): \"\t+ e.getMessage());\n\t}\n\tinfo(String::valueOf(i) + \" surveys loaded.\", true);\n}\nint ResourceManagerImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {\n\tif (eventType == ObserverEventType::POSTURECHANGED) {\n\t\tCreatureObject* creature = cast( observable);\n\t\t\/\/ Cancel Sampling on posture change\n\t\tReference task = creature->getPendingTask(\"sample\").castTo( );\n\t\tReference sampleResultsTask = creature->getPendingTask(\"sampleresults\").castTo( );\n\n\t\tif (task != NULL) {\n\n\t\t\ttask->stopSampling();\n\t\t\t\/\/creature->removePendingTask(\"sample\");\n\n\t\t\tif(sampleResultsTask != NULL) {\n\t\t\t\tsampleResultsTask->cancel();\n\t\t\t\tcreature->removePendingTask(\"sampleresults\");\n\t\t\t}\n\n\t\t\tcreature->sendSystemMessage(\"@survey:sample_cancel\");\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nbool ResourceManagerImplementation::loadConfigData() {\n\tif (!loadConfigFile())\n\t\treturn false;\n\n\tbool loadFromScript = lua->getGlobalInt(\"buildInitialResourcesFromScript\");\n\n\tString zonesString = lua->getGlobalString(\"activeZones\");\n\n\tStringTokenizer zonesTokens(zonesString);\n\tzonesTokens.setDelimeter(\",\");\n\n\twhile(zonesTokens.hasMoreTokens()) {\n\t\tString zoneName;\n\t\tzonesTokens.getStringToken(zoneName);\n\t\tresourceSpawner->addZone(zoneName);\n\t}\n\n\tshiftInterval = lua->getGlobalInt(\"averageShiftTime\");\n\n\tint aveduration = lua->getGlobalInt(\"aveduration\");\n\tfloat spawnThrottling = float(lua->getGlobalInt(\"spawnThrottling\")) \/ 100.0f;\n\tint lowerGateOverride = lua->getGlobalInt(\"lowerGateOverride\");\n\tint maxSpawnQuantity = lua->getGlobalInt(\"maxSpawnQuantity\");\n\n\tresourceSpawner->setSpawningParameters(loadFromScript, aveduration,\n\t\t\tspawnThrottling, lowerGateOverride, maxSpawnQuantity);\n\n\tString jtlResources = lua->getGlobalString(\"jtlresources\");\n\n\tStringTokenizer jtlTokens(jtlResources);\n\tjtlTokens.setDelimeter(\",\");\n\n\twhile(jtlTokens.hasMoreTokens()) {\n\t\tString token;\n\t\tjtlTokens.getStringToken(token);\n\t\tresourceSpawner->addJtlResource(token);\n\t}\n\n\tLuaObject minpoolinc = lua->getGlobalObject(\"minimumpoolincludes\");\n\tString minpoolexc = lua->getGlobalString(\"minimumpoolexcludes\");\n\tresourceSpawner->initializeMinimumPool(minpoolinc, minpoolexc);\n\n\tLuaObject randpoolinc = lua->getGlobalObject(\"randompoolincludes\");\n\tString randpoolexc = lua->getGlobalString(\"randompoolexcludes\");\n\tint randpoolsize = lua->getGlobalInt(\"randompoolsize\");\n\tresourceSpawner->initializeRandomPool(randpoolinc, randpoolexc, randpoolsize);\n\n\tLuaObject fixedpoolinc = lua->getGlobalObject(\"fixedpoolincludes\");\n\tString fixedpoolexc = lua->getGlobalString(\"fixedpoolexcludes\");\n\tresourceSpawner->initializeFixedPool(fixedpoolinc, fixedpoolexc);\n\n\tString natpoolinc = lua->getGlobalString(\"nativepoolincludes\");\n\tString natpoolexc = lua->getGlobalString(\"nativepoolexcludes\");\n\tresourceSpawner->initializeNativePool(natpoolinc, natpoolexc);\n\n\treturn true;\n}\n\nvoid ResourceManagerImplementation::loadDefaultConfig() {\n\n\tresourceSpawner->addZone(\"corellia\");\n\tresourceSpawner->addZone(\"lok\");\n\tresourceSpawner->addZone(\"yavin4\");\n\tresourceSpawner->addZone(\"dantooine\");\n\tresourceSpawner->addZone(\"dathomir\");\n\tresourceSpawner->addZone(\"naboo\");\n\tresourceSpawner->addZone(\"rori\");\n\tresourceSpawner->addZone(\"talus\");\n\tresourceSpawner->addZone(\"tatooine\");\n\tresourceSpawner->addZone(\"endor\");\n\n\tshiftInterval = 7200000;\n\tresourceSpawner->setSpawningParameters(1, 86400, 90, 1000, 0);\n}\n\nvoid ResourceManagerImplementation::stop() {\n\n\n}\n\nvoid ResourceManagerImplementation::startResourceSpawner() {\n\tLocker _locker(_this.get());\n\n\tresourceSpawner->start();\n\n\tReference resourceShift = new ResourceShiftTask(_this.get().get());\n\tresourceShift->schedule(shiftInterval);\n}\n\nvoid ResourceManagerImplementation::shiftResources() {\n\tLocker _locker(_this.get());\n\n\tresourceSpawner->shiftResources();\n\n\tReference resourceShift = new ResourceShiftTask(_this.get().get());\n\tresourceShift->schedule(shiftInterval);\n}\n\nint ResourceManagerImplementation::getResourceRecycleType(ResourceSpawn* resource) {\n\treturn resourceSpawner->sendResourceRecycleType(resource);\n}\n\nvoid ResourceManagerImplementation::sendResourceListForSurvey(CreatureObject* playerCreature, const int toolType, const String& surveyType) {\n\tReadLocker locker(_this.get());\n\n\tresourceSpawner->sendResourceListForSurvey(playerCreature, toolType, surveyType);\n}\n\nResourceContainer* ResourceManagerImplementation::harvestResource(CreatureObject* player, const String& type, const int quantity) {\n\treturn resourceSpawner->harvestResource(player, type, quantity);\n}\nbool ResourceManagerImplementation::harvestResourceToPlayer(CreatureObject* player, ResourceSpawn* resourceSpawn, const int quantity) {\n\treturn resourceSpawner->harvestResource(player, resourceSpawn, quantity);\n}\n\nvoid ResourceManagerImplementation::sendSurvey(CreatureObject* playerCreature, const String& resname) {\n\tresourceSpawner->sendSurvey(playerCreature, resname);\n}\n\nvoid ResourceManagerImplementation::sendSample(CreatureObject* playerCreature, const String& resname, const String& sampleAnimation) {\n\tresourceSpawner->sendSample(playerCreature, resname, sampleAnimation);\n\n\tplayerCreature->registerObserver(ObserverEventType::POSTURECHANGED, _this.get());\n}\n\nvoid ResourceManagerImplementation::createResourceSpawn(CreatureObject* playerCreature, const String& restype) {\n\tLocker _locker(_this.get());\n\n\tResourceSpawn* resourceSpawn = resourceSpawner->manualCreateResourceSpawn(restype);\n\n\tif (resourceSpawn != NULL) {\n\t\tStringBuffer buffer;\n\t\tbuffer << \"Spawned \" << resourceSpawn->getName() << \" of type \" << resourceSpawn->getType();\n\n\t\tplayerCreature->sendSystemMessage(buffer.toString());\n\t} else {\n\t\tplayerCreature->sendSystemMessage(\"Could not create spawn \" + restype);\n\t}\n\n}\n\nResourceSpawn* ResourceManagerImplementation::getResourceSpawn(const String& spawnName) {\n\tResourceSpawn* spawn = NULL;\n\n\tReadLocker locker(_this.get());\n\n\tResourceMap* resourceMap = resourceSpawner->getResourceMap();\n\n\tspawn = resourceMap->get(spawnName.toLowerCase());\n\n\treturn spawn;\n}\n\nResourceSpawn* ResourceManagerImplementation::getCurrentSpawn(const String& restype, const String& zoneName) {\n\treturn resourceSpawner->getCurrentSpawn(restype, zoneName);\n}\n\nvoid ResourceManagerImplementation::getResourceListByType(Vector >& list, int type, const String& zoneName) {\n\tlist.removeAll();\n\n\tReadLocker locker(_this.get());\n\n\tManagedReference resourceSpawn;\n\n\ttry {\n\t\tResourceMap* resourceMap = resourceSpawner->getResourceMap();\n\n\t\tZoneResourceMap* zoneMap = resourceMap->getZoneResourceList(zoneName);\n\n\t\tif (zoneMap != NULL) {\n\t\t\tfor (int i = 0; i < zoneMap->size(); ++i) {\n\t\t\t\tresourceSpawn = zoneMap->get(i);\n\n\t\t\t\tif (!resourceSpawn->inShift())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (type == 9){\n\t\t\t\t\tif (resourceSpawn->isType(\"radioactive\"))\n\t\t\t\t\t\tlist.add(resourceSpawn);\n\t\t\t\t}\n\n\t\t\t\telse if (resourceSpawn->getSurveyToolType() == type) {\n\t\t\t\t\tlist.add(resourceSpawn);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t} catch (Exception& e) {\n\t\terror(e.getMessage());\n\t\te.printStackTrace();\n\t}\n}\n\nuint32 ResourceManagerImplementation::getAvailablePowerFromPlayer(CreatureObject* player) {\n\tSceneObject* inventory = player->getSlottedObject(\"inventory\");\n\tuint32 power = 0;\n\n\tfor (int i = 0; i < inventory->getContainerObjectsSize(); i++) {\n\t\tReference obj = inventory->getContainerObject(i).castTo();\n\n\t\tif (obj == NULL || !obj->isResourceContainer())\n\t\t\tcontinue;\n\n\t\tResourceContainer* rcno = cast( obj.get());\n\t\tManagedReference spawn = rcno->getSpawnObject();\n\n\t\tif (spawn == NULL || !spawn->isEnergy())\n\t\t\tcontinue;\n\n\t\tint quantity = rcno->getQuantity();\n\t\tint pe = spawn->getValueOf(CraftingManager::PE); \/\/ potential energy\n\n\t\tfloat modifier = MAX(1.0f, pe \/ 500.0f);\n\n\t\tpower += (uint32) (modifier * quantity);\n\t}\n\n\treturn power;\n}\n\nvoid ResourceManagerImplementation::removePowerFromPlayer(CreatureObject* player, uint32 power) {\n\tif (power == 0)\n\t\treturn;\n\n\tSceneObject* inventory = player->getSlottedObject(\"inventory\");\n\n\tuint32 containerPower = 0;\n\n\tfor (int i = 0; i < inventory->getContainerObjectsSize() && power > 0; ++i) {\n\t\tManagedReference obj = inventory->getContainerObject(i);\n\n\t\tif (obj == NULL || !obj->isResourceContainer())\n\t\t\tcontinue;\n\n\t\tResourceContainer* rcno = cast( obj.get());\n\t\tManagedReference spawn = rcno->getSpawnObject();\n\n\t\tif (spawn == NULL || !spawn->isEnergy())\n\t\t\tcontinue;\n\n\t\tint quantity = rcno->getQuantity();\n\t\tint pe = spawn->getValueOf(CraftingManager::PE); \/\/ potential energy\n\n\t\tfloat modifier = MAX(1.0f, pe \/ 500.0f);\n\n\t\tcontainerPower = modifier * quantity;\n\n\t\tif (containerPower > power) {\n\t\t\tuint32 consumedUnits = (uint64) power \/ modifier;\n\t\t\trcno->setQuantity(quantity - consumedUnits);\n\n\t\t\tResourceContainerObjectDeltaMessage3* drcno3 = new ResourceContainerObjectDeltaMessage3(rcno);\n\t\t\tdrcno3->updateQuantity();\n\t\t\tdrcno3->close();\n\t\t\tplayer->sendMessage(drcno3);\n\t\t\treturn;\n\t\t} else {\n\t\t\trcno->destroyObjectFromWorld(true);\n\t\t\trcno->destroyObjectFromDatabase(true);\n\t\t}\n\n\t\tpower -= containerPower;\n\t}\n}\nvoid ResourceManagerImplementation::givePlayerResource(CreatureObject* playerCreature, const String& restype, const int quantity) {\n\tManagedReference spawn = getResourceSpawn(restype);\n\n\tif(spawn == NULL) {\n\t\tplayerCreature->sendSystemMessage(\"Selected spawn does not exist.\");\n\t\treturn;\n\t}\n\n\tManagedReference inventory = playerCreature->getSlottedObject(\"inventory\");\n\n\tif(inventory != NULL && !inventory->hasFullContainerObjects()) {\n\n\t\tResourceContainer* newResource = spawn->createResource(quantity);\n\n\t\tif(newResource != NULL) {\n\t\t\tspawn->extractResource(\"\", quantity);\n\t\t\tif (inventory->transferObject(newResource, -1, true)) {\n\t\t\t\tinventory->broadcastObject(newResource, true);\n\t\t\t} else {\n\t\t\t\tnewResource->destroyObjectFromDatabase(true);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool ResourceManagerImplementation::isRecycledResource(ResourceSpawn* resource) {\n\treturn resourceSpawner->isRecycledResource(resource);\n}\n\nResourceSpawn* ResourceManagerImplementation::getRecycledVersion(ResourceSpawn* resource) {\n\treturn resourceSpawner->getRecycledVersion(resource);\n}\n\n\/\/\/ Resource Deed Methods\nvoid ResourceManagerImplementation::addNodeToListBox(SuiListBox* sui, const String& nodeName) {\n\tresourceSpawner->addNodeToListBox(sui, nodeName);\n}\n\nvoid ResourceManagerImplementation::addPlanetsToListBox(SuiListBox* sui) {\n\tresourceSpawner->addPlanetsToListBox(sui);\n}\nString ResourceManagerImplementation::getPlanetByIndex(int idx) {\n\treturn resourceSpawner->getPlanetByIndex(idx);\n}\nString ResourceManagerImplementation::addParentNodeToListBox(SuiListBox* sui, const String& currentNode) {\n\treturn resourceSpawner->addParentNodeToListBox(sui, currentNode);\n}\n\nvoid ResourceManagerImplementation::listResourcesForPlanetOnScreen(CreatureObject* creature, const String& planet) {\n\tLocker locker(_this.get());\n\n\tresourceSpawner->listResourcesForPlanetOnScreen(creature, planet);\n}\n\nString ResourceManagerImplementation::healthCheck() {\n\treturn resourceSpawner->healthCheck();\n}\n\nString ResourceManagerImplementation::dumpResources() {\n\tLocker locker(_this.get());\n\n\treturn resourceSpawner->dumpResources();\n}\n\nString ResourceManagerImplementation::despawnResource(String& resourceName) {\n\n\tManagedReference spawn = getResourceSpawn(resourceName);\n\tif(spawn == NULL) {\n\t\treturn \"Spawn not Found\";\n\t}\n\n\tspawn->setDespawned(time(0) - 1);\n\tresourceSpawner->shiftResources();\n\n\treturn resourceName + \" despawned.\";\n}\n[Fixed] stability issue\/*\n\t\t\t\tCopyright \n\t\tSee file COPYING for copying conditions.*\/\n\n#include \"engine\/engine.h\"\n\n#include \"server\/zone\/managers\/resource\/ResourceManager.h\"\n#include \"ResourceShiftTask.h\"\n#include \"resourcespawner\/SampleTask.h\"\n#include \"resourcespawner\/SampleResultsTask.h\"\n#include \"server\/zone\/managers\/resource\/InterplanetarySurvey.h\"\n#include \"server\/zone\/managers\/resource\/InterplanetarySurveyTask.h\"\n#include \"server\/zone\/objects\/resource\/ResourceContainer.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectDeltaMessage3.h\"\n#include \"server\/zone\/objects\/player\/sui\/listbox\/SuiListBox.h\"\n\nvoid ResourceManagerImplementation::initialize() {\n\tlua = new Lua();\n\tlua->init();\n\n\tif(!loadConfigData()) {\n\n\t\tloadDefaultConfig();\n\n\t\tinfo(\"***** ERROR in configuration, using default values\");\n\t}\n\n\tresourceSpawner->init();\n\n\tstartResourceSpawner();\n\tloadSurveyData();\n}\n\nbool ResourceManagerImplementation::loadConfigFile() {\n\treturn lua->runFile(\"scripts\/managers\/resource_manager.lua\");\n}\nvoid ResourceManagerImplementation::loadSurveyData() {\n\tinfo(\"Loading survey data form surveys.db\");\n\tObjectDatabaseManager* dbManager = ObjectDatabaseManager::instance();\n\tObjectDatabase* surveyDatabase = ObjectDatabaseManager::instance()->loadObjectDatabase(\"surveys\", true);\n\tif (surveyDatabase == NULL) {\n\t\terror(\"Could not load the survey database.\");\n\t\treturn;\n\t}\n\tint i = 0;\n\ttry {\n\t\tObjectDatabaseIterator iterator(surveyDatabase);\n\n\t\tuint64 objectID;\n\n\t\twhile (iterator.getNextKey(objectID)) {\n\t\t\tCore::getObjectBroker()->lookUp(objectID);\n\t\t\t++i;\n\t\t}\n\t} catch (DatabaseException& e) {\n\t\terror(\"Database exception in DirectorManager::loadSurveyData(): \"\t+ e.getMessage());\n\t}\n\tinfo(String::valueOf(i) + \" surveys loaded.\", true);\n}\nint ResourceManagerImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {\n\tif (eventType == ObserverEventType::POSTURECHANGED) {\n\t\tCreatureObject* creature = cast( observable);\n\t\t\/\/ Cancel Sampling on posture change\n\t\tReference task = creature->getPendingTask(\"sample\").castTo( );\n\t\tReference sampleResultsTask = creature->getPendingTask(\"sampleresults\").castTo( );\n\n\t\tif (task != NULL) {\n\n\t\t\ttask->stopSampling();\n\t\t\t\/\/creature->removePendingTask(\"sample\");\n\n\t\t\tif(sampleResultsTask != NULL) {\n\t\t\t\tsampleResultsTask->cancel();\n\t\t\t\tcreature->removePendingTask(\"sampleresults\");\n\t\t\t}\n\n\t\t\tcreature->sendSystemMessage(\"@survey:sample_cancel\");\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nbool ResourceManagerImplementation::loadConfigData() {\n\tif (!loadConfigFile())\n\t\treturn false;\n\n\tbool loadFromScript = lua->getGlobalInt(\"buildInitialResourcesFromScript\");\n\n\tString zonesString = lua->getGlobalString(\"activeZones\");\n\n\tStringTokenizer zonesTokens(zonesString);\n\tzonesTokens.setDelimeter(\",\");\n\n\twhile(zonesTokens.hasMoreTokens()) {\n\t\tString zoneName;\n\t\tzonesTokens.getStringToken(zoneName);\n\t\tresourceSpawner->addZone(zoneName);\n\t}\n\n\tshiftInterval = lua->getGlobalInt(\"averageShiftTime\");\n\n\tint aveduration = lua->getGlobalInt(\"aveduration\");\n\tfloat spawnThrottling = float(lua->getGlobalInt(\"spawnThrottling\")) \/ 100.0f;\n\tint lowerGateOverride = lua->getGlobalInt(\"lowerGateOverride\");\n\tint maxSpawnQuantity = lua->getGlobalInt(\"maxSpawnQuantity\");\n\n\tresourceSpawner->setSpawningParameters(loadFromScript, aveduration,\n\t\t\tspawnThrottling, lowerGateOverride, maxSpawnQuantity);\n\n\tString jtlResources = lua->getGlobalString(\"jtlresources\");\n\n\tStringTokenizer jtlTokens(jtlResources);\n\tjtlTokens.setDelimeter(\",\");\n\n\twhile(jtlTokens.hasMoreTokens()) {\n\t\tString token;\n\t\tjtlTokens.getStringToken(token);\n\t\tresourceSpawner->addJtlResource(token);\n\t}\n\n\tLuaObject minpoolinc = lua->getGlobalObject(\"minimumpoolincludes\");\n\tString minpoolexc = lua->getGlobalString(\"minimumpoolexcludes\");\n\tresourceSpawner->initializeMinimumPool(minpoolinc, minpoolexc);\n\n\tLuaObject randpoolinc = lua->getGlobalObject(\"randompoolincludes\");\n\tString randpoolexc = lua->getGlobalString(\"randompoolexcludes\");\n\tint randpoolsize = lua->getGlobalInt(\"randompoolsize\");\n\tresourceSpawner->initializeRandomPool(randpoolinc, randpoolexc, randpoolsize);\n\n\tLuaObject fixedpoolinc = lua->getGlobalObject(\"fixedpoolincludes\");\n\tString fixedpoolexc = lua->getGlobalString(\"fixedpoolexcludes\");\n\tresourceSpawner->initializeFixedPool(fixedpoolinc, fixedpoolexc);\n\n\tString natpoolinc = lua->getGlobalString(\"nativepoolincludes\");\n\tString natpoolexc = lua->getGlobalString(\"nativepoolexcludes\");\n\tresourceSpawner->initializeNativePool(natpoolinc, natpoolexc);\n\n\treturn true;\n}\n\nvoid ResourceManagerImplementation::loadDefaultConfig() {\n\n\tresourceSpawner->addZone(\"corellia\");\n\tresourceSpawner->addZone(\"lok\");\n\tresourceSpawner->addZone(\"yavin4\");\n\tresourceSpawner->addZone(\"dantooine\");\n\tresourceSpawner->addZone(\"dathomir\");\n\tresourceSpawner->addZone(\"naboo\");\n\tresourceSpawner->addZone(\"rori\");\n\tresourceSpawner->addZone(\"talus\");\n\tresourceSpawner->addZone(\"tatooine\");\n\tresourceSpawner->addZone(\"endor\");\n\n\tshiftInterval = 7200000;\n\tresourceSpawner->setSpawningParameters(1, 86400, 90, 1000, 0);\n}\n\nvoid ResourceManagerImplementation::stop() {\n\n\n}\n\nvoid ResourceManagerImplementation::startResourceSpawner() {\n\tLocker _locker(_this.get());\n\n\tresourceSpawner->start();\n\n\tReference resourceShift = new ResourceShiftTask(_this.get().get());\n\tresourceShift->schedule(shiftInterval);\n}\n\nvoid ResourceManagerImplementation::shiftResources() {\n\tLocker _locker(_this.get());\n\n\tresourceSpawner->shiftResources();\n\n\tReference resourceShift = new ResourceShiftTask(_this.get().get());\n\tresourceShift->schedule(shiftInterval);\n}\n\nint ResourceManagerImplementation::getResourceRecycleType(ResourceSpawn* resource) {\n\treturn resourceSpawner->sendResourceRecycleType(resource);\n}\n\nvoid ResourceManagerImplementation::sendResourceListForSurvey(CreatureObject* playerCreature, const int toolType, const String& surveyType) {\n\tReadLocker locker(_this.get());\n\n\tresourceSpawner->sendResourceListForSurvey(playerCreature, toolType, surveyType);\n}\n\nResourceContainer* ResourceManagerImplementation::harvestResource(CreatureObject* player, const String& type, const int quantity) {\n\treturn resourceSpawner->harvestResource(player, type, quantity);\n}\nbool ResourceManagerImplementation::harvestResourceToPlayer(CreatureObject* player, ResourceSpawn* resourceSpawn, const int quantity) {\n\treturn resourceSpawner->harvestResource(player, resourceSpawn, quantity);\n}\n\nvoid ResourceManagerImplementation::sendSurvey(CreatureObject* playerCreature, const String& resname) {\n\tresourceSpawner->sendSurvey(playerCreature, resname);\n}\n\nvoid ResourceManagerImplementation::sendSample(CreatureObject* playerCreature, const String& resname, const String& sampleAnimation) {\n\tresourceSpawner->sendSample(playerCreature, resname, sampleAnimation);\n\n\tplayerCreature->registerObserver(ObserverEventType::POSTURECHANGED, _this.get());\n}\n\nvoid ResourceManagerImplementation::createResourceSpawn(CreatureObject* playerCreature, const String& restype) {\n\tLocker _locker(_this.get());\n\n\tResourceSpawn* resourceSpawn = resourceSpawner->manualCreateResourceSpawn(restype);\n\n\tif (resourceSpawn != NULL) {\n\t\tStringBuffer buffer;\n\t\tbuffer << \"Spawned \" << resourceSpawn->getName() << \" of type \" << resourceSpawn->getType();\n\n\t\tplayerCreature->sendSystemMessage(buffer.toString());\n\t} else {\n\t\tplayerCreature->sendSystemMessage(\"Could not create spawn \" + restype);\n\t}\n\n}\n\nResourceSpawn* ResourceManagerImplementation::getResourceSpawn(const String& spawnName) {\n\tResourceSpawn* spawn = NULL;\n\n\tReadLocker locker(_this.get());\n\n\tResourceMap* resourceMap = resourceSpawner->getResourceMap();\n\n\tspawn = resourceMap->get(spawnName.toLowerCase());\n\n\treturn spawn;\n}\n\nResourceSpawn* ResourceManagerImplementation::getCurrentSpawn(const String& restype, const String& zoneName) {\n\treturn resourceSpawner->getCurrentSpawn(restype, zoneName);\n}\n\nvoid ResourceManagerImplementation::getResourceListByType(Vector >& list, int type, const String& zoneName) {\n\tlist.removeAll();\n\n\tReadLocker locker(_this.get());\n\n\tManagedReference resourceSpawn;\n\n\ttry {\n\t\tResourceMap* resourceMap = resourceSpawner->getResourceMap();\n\n\t\tZoneResourceMap* zoneMap = resourceMap->getZoneResourceList(zoneName);\n\n\t\tif (zoneMap != NULL) {\n\t\t\tfor (int i = 0; i < zoneMap->size(); ++i) {\n\t\t\t\tresourceSpawn = zoneMap->get(i);\n\n\t\t\t\tif (!resourceSpawn->inShift())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (type == 9){\n\t\t\t\t\tif (resourceSpawn->isType(\"radioactive\"))\n\t\t\t\t\t\tlist.add(resourceSpawn);\n\t\t\t\t}\n\n\t\t\t\telse if (resourceSpawn->getSurveyToolType() == type) {\n\t\t\t\t\tlist.add(resourceSpawn);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t} catch (Exception& e) {\n\t\terror(e.getMessage());\n\t\te.printStackTrace();\n\t}\n}\n\nuint32 ResourceManagerImplementation::getAvailablePowerFromPlayer(CreatureObject* player) {\n\tSceneObject* inventory = player->getSlottedObject(\"inventory\");\n\tuint32 power = 0;\n\n\tfor (int i = 0; i < inventory->getContainerObjectsSize(); i++) {\n\t\tReference obj = inventory->getContainerObject(i).castTo();\n\n\t\tif (obj == NULL || !obj->isResourceContainer())\n\t\t\tcontinue;\n\n\t\tResourceContainer* rcno = cast( obj.get());\n\t\tManagedReference spawn = rcno->getSpawnObject();\n\n\t\tif (spawn == NULL || !spawn->isEnergy())\n\t\t\tcontinue;\n\n\t\tint quantity = rcno->getQuantity();\n\t\tint pe = spawn->getValueOf(CraftingManager::PE); \/\/ potential energy\n\n\t\tfloat modifier = MAX(1.0f, pe \/ 500.0f);\n\n\t\tpower += (uint32) (modifier * quantity);\n\t}\n\n\treturn power;\n}\n\nvoid ResourceManagerImplementation::removePowerFromPlayer(CreatureObject* player, uint32 power) {\n\tif (power == 0)\n\t\treturn;\n\n\tSceneObject* inventory = player->getSlottedObject(\"inventory\");\n\n\tuint32 containerPower = 0;\n\n\tfor (int i = 0; i < inventory->getContainerObjectsSize() && power > 0; ++i) {\n\t\tManagedReference obj = inventory->getContainerObject(i);\n\n\t\tif (obj == NULL || !obj->isResourceContainer())\n\t\t\tcontinue;\n\n\t\tResourceContainer* rcno = cast( obj.get());\n\n\t\tLocker locker(rcno);\n\n\t\tManagedReference spawn = rcno->getSpawnObject();\n\n\t\tif (spawn == NULL || !spawn->isEnergy())\n\t\t\tcontinue;\n\n\t\tint quantity = rcno->getQuantity();\n\t\tint pe = spawn->getValueOf(CraftingManager::PE); \/\/ potential energy\n\n\t\tfloat modifier = MAX(1.0f, pe \/ 500.0f);\n\n\t\tcontainerPower = modifier * quantity;\n\n\t\tif (containerPower > power) {\n\t\t\tuint32 consumedUnits = (uint64) power \/ modifier;\n\t\t\trcno->setQuantity(quantity - consumedUnits);\n\n\t\t\tResourceContainerObjectDeltaMessage3* drcno3 = new ResourceContainerObjectDeltaMessage3(rcno);\n\t\t\tdrcno3->updateQuantity();\n\t\t\tdrcno3->close();\n\t\t\tplayer->sendMessage(drcno3);\n\t\t\treturn;\n\t\t} else {\n\t\t\trcno->destroyObjectFromWorld(true);\n\t\t\trcno->destroyObjectFromDatabase(true);\n\t\t}\n\n\t\tpower -= containerPower;\n\t}\n}\nvoid ResourceManagerImplementation::givePlayerResource(CreatureObject* playerCreature, const String& restype, const int quantity) {\n\tManagedReference spawn = getResourceSpawn(restype);\n\n\tif(spawn == NULL) {\n\t\tplayerCreature->sendSystemMessage(\"Selected spawn does not exist.\");\n\t\treturn;\n\t}\n\n\tManagedReference inventory = playerCreature->getSlottedObject(\"inventory\");\n\n\tif(inventory != NULL && !inventory->hasFullContainerObjects()) {\n\n\t\tResourceContainer* newResource = spawn->createResource(quantity);\n\n\t\tif(newResource != NULL) {\n\t\t\tspawn->extractResource(\"\", quantity);\n\t\t\tif (inventory->transferObject(newResource, -1, true)) {\n\t\t\t\tinventory->broadcastObject(newResource, true);\n\t\t\t} else {\n\t\t\t\tnewResource->destroyObjectFromDatabase(true);\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool ResourceManagerImplementation::isRecycledResource(ResourceSpawn* resource) {\n\treturn resourceSpawner->isRecycledResource(resource);\n}\n\nResourceSpawn* ResourceManagerImplementation::getRecycledVersion(ResourceSpawn* resource) {\n\treturn resourceSpawner->getRecycledVersion(resource);\n}\n\n\/\/\/ Resource Deed Methods\nvoid ResourceManagerImplementation::addNodeToListBox(SuiListBox* sui, const String& nodeName) {\n\tresourceSpawner->addNodeToListBox(sui, nodeName);\n}\n\nvoid ResourceManagerImplementation::addPlanetsToListBox(SuiListBox* sui) {\n\tresourceSpawner->addPlanetsToListBox(sui);\n}\nString ResourceManagerImplementation::getPlanetByIndex(int idx) {\n\treturn resourceSpawner->getPlanetByIndex(idx);\n}\nString ResourceManagerImplementation::addParentNodeToListBox(SuiListBox* sui, const String& currentNode) {\n\treturn resourceSpawner->addParentNodeToListBox(sui, currentNode);\n}\n\nvoid ResourceManagerImplementation::listResourcesForPlanetOnScreen(CreatureObject* creature, const String& planet) {\n\tLocker locker(_this.get());\n\n\tresourceSpawner->listResourcesForPlanetOnScreen(creature, planet);\n}\n\nString ResourceManagerImplementation::healthCheck() {\n\treturn resourceSpawner->healthCheck();\n}\n\nString ResourceManagerImplementation::dumpResources() {\n\tLocker locker(_this.get());\n\n\treturn resourceSpawner->dumpResources();\n}\n\nString ResourceManagerImplementation::despawnResource(String& resourceName) {\n\n\tManagedReference spawn = getResourceSpawn(resourceName);\n\tif(spawn == NULL) {\n\t\treturn \"Spawn not Found\";\n\t}\n\n\tspawn->setDespawned(time(0) - 1);\n\tresourceSpawner->shiftResources();\n\n\treturn resourceName + \" despawned.\";\n}\n<|endoftext|>"} {"text":"#include \"specter\/ViewResources.hpp\"\n\nnamespace specter\n{\nstatic logvisor::Module Log(\"specter::ViewResources\");\n\nvoid ViewResources::init(boo::IGraphicsDataFactory* factory, FontCache* fcache,\n const IThemeData* theme, float pf)\n{\n if (!factory || !fcache || !theme)\n Log.report(logvisor::Fatal, \"all arguments of ViewResources::init() must be non-null\");\n m_pixelFactor = pf;\n m_factory = factory;\n m_theme = theme;\n m_fcache = fcache;\n unsigned dpi = 72.f * m_pixelFactor;\n\n m_curveFont = fcache->prepCurvesFont(factory, AllCharFilter, false, 8.f, dpi);\n\n m_resData = factory->commitTransaction(\n [&](boo::IGraphicsDataFactory::Context& ctx) -> bool\n {\n switch (ctx.platform())\n {\n case boo::IGraphicsDataFactory::Platform::OGL:\n init(static_cast(ctx), *theme, fcache);\n break;\n#if _WIN32\n case boo::IGraphicsDataFactory::Platform::D3D11:\n case boo::IGraphicsDataFactory::Platform::D3D12:\n init(static_cast(ctx), *theme, fcache);\n break;\n#endif\n#if BOO_HAS_METAL\n case boo::IGraphicsDataFactory::Platform::Metal:\n init(static_cast(ctx), *theme, fcache);\n break;\n#endif\n#if BOO_HAS_VULKAN\n case boo::IGraphicsDataFactory::Platform::Vulkan:\n init(static_cast(ctx), *theme, fcache);\n break;\n#endif\n default:\n Log.report(logvisor::Fatal, _S(\"unable to init view system for %s\"), ctx.platformName());\n }\n return true;\n });\n}\n\nvoid ViewResources::prepFontCacheSync()\n{\n unsigned dpi = 72.f * m_pixelFactor;\n if (m_fcacheInterrupt) return;\n m_mainFont = m_fcache->prepMainFont(m_factory, AllCharFilter, false, 10.f, dpi);\n if (m_fcacheInterrupt) return;\n m_monoFont = m_fcache->prepMonoFont(m_factory, AllCharFilter, false, 10.f, dpi);\n if (m_fcacheInterrupt) return;\n m_heading14 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 14.f, dpi);\n if (m_fcacheInterrupt) return;\n m_heading18 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 18.f, dpi);\n if (m_fcacheInterrupt) return;\n m_titleFont = m_fcache->prepMainFont(m_factory, LatinCharFilter, false, 36.f, dpi);\n if (m_fcacheInterrupt) return;\n m_fcache->closeBuiltinFonts();\n m_fcacheReady = true;\n}\n\nvoid ViewResources::prepFontCacheAsync(boo::IWindow* window)\n{\n m_fcacheReady = false;\n m_fcacheThread = std::thread([this, window]()\n {\n window->getLoadContextDataFactory();\n prepFontCacheSync();\n });\n}\n\nvoid ViewResources::resetPixelFactor(float pf)\n{\n m_pixelFactor = pf;\n unsigned dpi = 72.f * m_pixelFactor;\n m_curveFont = m_fcache->prepCurvesFont(m_factory, AllCharFilter, false, 8.f, dpi);\n prepFontCacheSync();\n}\n\nvoid ViewResources::resetTheme(const IThemeData* theme)\n{\n m_theme = theme;\n}\n\n}\nOpenGL enum change#include \"specter\/ViewResources.hpp\"\n\nnamespace specter\n{\nstatic logvisor::Module Log(\"specter::ViewResources\");\n\nvoid ViewResources::init(boo::IGraphicsDataFactory* factory, FontCache* fcache,\n const IThemeData* theme, float pf)\n{\n if (!factory || !fcache || !theme)\n Log.report(logvisor::Fatal, \"all arguments of ViewResources::init() must be non-null\");\n m_pixelFactor = pf;\n m_factory = factory;\n m_theme = theme;\n m_fcache = fcache;\n unsigned dpi = 72.f * m_pixelFactor;\n\n m_curveFont = fcache->prepCurvesFont(factory, AllCharFilter, false, 8.f, dpi);\n\n m_resData = factory->commitTransaction(\n [&](boo::IGraphicsDataFactory::Context& ctx) -> bool\n {\n switch (ctx.platform())\n {\n case boo::IGraphicsDataFactory::Platform::OpenGL:\n init(static_cast(ctx), *theme, fcache);\n break;\n#if _WIN32\n case boo::IGraphicsDataFactory::Platform::D3D11:\n case boo::IGraphicsDataFactory::Platform::D3D12:\n init(static_cast(ctx), *theme, fcache);\n break;\n#endif\n#if BOO_HAS_METAL\n case boo::IGraphicsDataFactory::Platform::Metal:\n init(static_cast(ctx), *theme, fcache);\n break;\n#endif\n#if BOO_HAS_VULKAN\n case boo::IGraphicsDataFactory::Platform::Vulkan:\n init(static_cast(ctx), *theme, fcache);\n break;\n#endif\n default:\n Log.report(logvisor::Fatal, _S(\"unable to init view system for %s\"), ctx.platformName());\n }\n return true;\n });\n}\n\nvoid ViewResources::prepFontCacheSync()\n{\n unsigned dpi = 72.f * m_pixelFactor;\n if (m_fcacheInterrupt) return;\n m_mainFont = m_fcache->prepMainFont(m_factory, AllCharFilter, false, 10.f, dpi);\n if (m_fcacheInterrupt) return;\n m_monoFont = m_fcache->prepMonoFont(m_factory, AllCharFilter, false, 10.f, dpi);\n if (m_fcacheInterrupt) return;\n m_heading14 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 14.f, dpi);\n if (m_fcacheInterrupt) return;\n m_heading18 = m_fcache->prepMainFont(m_factory, LatinAndJapaneseCharFilter, false, 18.f, dpi);\n if (m_fcacheInterrupt) return;\n m_titleFont = m_fcache->prepMainFont(m_factory, LatinCharFilter, false, 36.f, dpi);\n if (m_fcacheInterrupt) return;\n m_fcache->closeBuiltinFonts();\n m_fcacheReady = true;\n}\n\nvoid ViewResources::prepFontCacheAsync(boo::IWindow* window)\n{\n m_fcacheReady = false;\n m_fcacheThread = std::thread([this, window]()\n {\n window->getLoadContextDataFactory();\n prepFontCacheSync();\n });\n}\n\nvoid ViewResources::resetPixelFactor(float pf)\n{\n m_pixelFactor = pf;\n unsigned dpi = 72.f * m_pixelFactor;\n m_curveFont = m_fcache->prepCurvesFont(m_factory, AllCharFilter, false, 8.f, dpi);\n prepFontCacheSync();\n}\n\nvoid ViewResources::resetTheme(const IThemeData* theme)\n{\n m_theme = theme;\n}\n\n}\n<|endoftext|>"} {"text":"#include \"chimera\/visitor.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace chimera;\nusing namespace clang;\nusing boost::algorithm::join;\n\n\/\/ TODO: Support template functions.\n\/\/ TODO: Detect missing copy constructors, possibly using:\n\/\/ hasUserDeclaredCopyConstructor()\n\/\/ hasCopyConstructorWithConstParam ()\n\/\/ TODO: Mark abstract classes as noncopyable?\n\nchimera::Visitor::Visitor(clang::CompilerInstance *ci,\n std::unique_ptr cc)\n: context_(&(ci->getASTContext()))\n, printing_policy_(ci->getLangOpts())\n, config_(std::move(cc))\n{\n \/\/ Do nothing.\n}\n\nbool chimera::Visitor::VisitDecl(Decl *decl)\n{\n \/\/ Only visit declarations in namespaces we are configured to read.\n if (!IsEnclosed(decl))\n return true;\n\n if (isa(decl))\n GenerateClassTemplate(cast(decl));\n else if (isa(decl))\n GenerateCXXRecord(cast(decl));\n else if (isa(decl))\n GenerateEnum(cast(decl));\n else if (isa(decl))\n GenerateGlobalVar(cast(decl));\n else if (isa(decl))\n GenerateGlobalFunction(cast(decl));\n\n return true;\n}\n\nbool chimera::Visitor::GenerateCXXRecord(CXXRecordDecl *const decl)\n{\n \/\/ Only traverse CXX records that contain the actual class definition.\n if (!decl->hasDefinition() || decl->getDefinition() != decl)\n return false;\n\n \/\/ Open a stream object unique to this CXX record's mangled name.\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n \/\/ Get configuration, and use any overrides if they exist.\n if (config_->DumpOverride(decl, *stream))\n return true;\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n if (node.IsNull())\n return false; \/\/ Explicitly suppressed.\n\n *stream << \"::boost::python::class_<\"\n << decl->getTypeForDecl()->getCanonicalTypeInternal().getAsString(printing_policy_);\n\n const YAML::Node &noncopyable_node = node[\"noncopyable\"];\n if (noncopyable_node && noncopyable_node.as(false))\n *stream << \", ::boost::noncopyable\";\n\n if (const YAML::Node &held_type_node = node[\"held_type\"])\n *stream << \", \" << held_type_node.as();\n\n std::vector base_names;\n\n if (const YAML::Node &bases_node = node[\"bases\"])\n base_names = bases_node.as >();\n else\n base_names = GetBaseClassNames(decl);\n\n if (!base_names.empty())\n {\n *stream << \", ::boost::python::bases<\"\n << join(base_names, \", \") << \" >\";\n }\n\n *stream << \" >(\\\"\" << decl->getNameAsString()\n << \"\\\", boost::python::no_init)\\n\";\n\n \/\/ Methods\n std::set overloaded_method_names;\n\n for (CXXMethodDecl *const method_decl : decl->methods())\n {\n if (method_decl->getAccess() != AS_public)\n continue; \/\/ skip protected and private members\n\n if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n {\n GenerateCXXConstructor(\n *stream, decl, cast(method_decl));\n }\n else if (method_decl->isOverloadedOperator())\n ; \/\/ TODO: Wrap overloaded operators.\n else if (method_decl->isStatic())\n {\n \/\/ TODO: Missing the dot.\n if (GenerateFunction(*stream, decl, method_decl))\n overloaded_method_names.insert(method_decl->getNameAsString());\n }\n else\n {\n \/\/ TODO: Missing the dot.\n GenerateFunction(*stream, decl, method_decl);\n }\n }\n\n \/\/ Static methods MUST be declared after overloads are defined.\n for (const std::string &method_name : overloaded_method_names)\n *stream << \".staticmethod(\\\"\" << method_name << \"\\\")\\n\";\n\n \/\/ Fields\n for (FieldDecl *const field_decl : decl->fields())\n {\n if (field_decl->getAccess() != AS_public)\n continue; \/\/ skip protected and private fields\n\n GenerateField(*stream, decl, field_decl);\n }\n\n for (Decl *const child_decl : decl->decls())\n {\n if (isa(child_decl))\n GenerateStaticField(*stream, decl, cast(child_decl));\n }\n\n *stream << \";\\n\";\n \n return true;\n}\n\nbool chimera::Visitor::GenerateCXXConstructor(\n chimera::Stream &stream,\n CXXRecordDecl *class_decl,\n CXXConstructorDecl *decl)\n{\n decl = decl->getCanonicalDecl();\n\n if (decl->isDeleted())\n return false;\n\n std::vector argument_types;\n\n for (ParmVarDecl *param_decl : decl->params())\n argument_types.push_back(param_decl->getType().getAsString(printing_policy_));\n\n stream << \".def(::boost::python::init<\"\n << join(argument_types, \", \")\n << \">())\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateFunction(\n chimera::Stream &stream,\n CXXRecordDecl *class_decl, FunctionDecl *decl)\n{\n decl = decl->getCanonicalDecl();\n\n if (decl->isDeleted())\n return false;\n\n \/\/ Get configuration, and use any overrides if they exist.\n if (config_->DumpOverride(decl, stream))\n return true;\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n if (node.IsNull())\n return false; \/\/ Explicitly suppressed.\n\n \/\/ Extract the pointer type of this function declaration.\n QualType pointer_type;\n if (class_decl && !cast(decl)->isStatic())\n {\n pointer_type = context_->getMemberPointerType(\n decl->getType(), class_decl->getTypeForDecl());\n }\n else\n {\n pointer_type = context_->getPointerType(decl->getType());\n }\n pointer_type = pointer_type.getCanonicalType();\n\n \/\/ Extract the return type of this function declaration.\n const QualType return_qual_type = decl->getReturnType();\n const Type *return_type = return_qual_type.getTypePtr();\n\n \/\/ First, check if a return_value_policy was specified for this function.\n std::string return_value_policy\n = node[\"return_value_policy\"].as(\"\");\n\n \/\/ Next, check if a return_value_policy is defined on the return type.\n if (return_value_policy.empty())\n {\n const YAML::Node &type_node = config_->GetType(return_qual_type);\n return_value_policy\n = type_node[\"return_value_policy\"].as(\"\");\n }\n\n \/\/ Finally, try the default return_value_policy. This is only acceptable if\n \/\/ the output is copy constructable.\n if (return_value_policy.empty())\n {\n if (return_type->isReferenceType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << decl->getQualifiedNameAsString()\n << \"' with signature '\"\n << decl->getType().getAsString(printing_policy_)\n << \"' because it returns a reference and no\"\n \" 'return_value_policy' was specified.\\n\";\n return false;\n }\n else if (return_type->isPointerType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << decl->getQualifiedNameAsString()\n << \"' with signature '\"\n << decl->getType().getAsString(printing_policy_)\n << \"' because it returns a pointer and no\"\n \" 'return_value_policy' was specified.\\n\";\n return false;\n }\n \/\/ TODO: Check if return_type is non-copyable.\n }\n\n \/\/ If we are inside a class declaration, this is being called within a\n \/\/ builder pattern and will start with '.' since it is a member function.\n if (class_decl)\n stream << \".\";\n\n \/\/ Create the actual function declaration here using its name and its\n \/\/ full pointer reference.\n stream << \"def(\\\"\" << decl->getNameAsString() << \"\\\"\"\n << \", static_cast<\" << pointer_type.getAsString(printing_policy_) << \">(&\"\n << decl->getQualifiedNameAsString() << \")\";\n\n \/\/ If a return value policy was specified, insert it after the function.\n if (!return_value_policy.empty())\n {\n stream << \", ::boost::python::return_value_policy<\"\n << return_value_policy << \" >\";\n }\n\n \/\/ Construct a list of the arguments that are provided to this function,\n \/\/ and define named arguments for them based on their c++ names.\n const auto params = GetParameterNames(decl);\n if (!params.empty())\n {\n \/\/ TODO: Suppress any default parameters that occur after the first\n \/\/ non-default to default transition. This can only occur if evaluating\n \/\/ the default value of one or more parameters failed.\n\n \/\/ TODO: Assign names to unnamed arguments.\n\n std::vector python_args;\n for (const auto ¶m : params)\n {\n std::stringstream python_arg;\n python_arg << \"::boost::python::arg(\\\"\" << param.first << \"\\\")\";\n\n if (!param.second.empty())\n python_arg << \" = \" << param.second;\n\n python_args.push_back(python_arg.str());\n }\n\n stream << \", (\" << join(python_args, \", \") << \")\";\n }\n\n stream << \")\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateField(\n chimera::Stream &stream,\n clang::CXXRecordDecl *class_decl,\n clang::FieldDecl *decl)\n{\n if (decl->getType().isConstQualified())\n stream << \".def_readonly\";\n else\n stream << \".def_readwrite\";\n\n \/\/ TODO: Check if a copy constructor is defined for this type.\n\n stream << \"(\\\"\" << decl->getNameAsString() << \"\\\",\"\n << \" &\" << decl->getQualifiedNameAsString() << \")\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateStaticField(\n chimera::Stream &stream,\n clang::CXXRecordDecl *class_decl,\n clang::VarDecl *decl)\n{\n if (decl->getAccess() != AS_public)\n return false;\n else if (!decl->isStaticDataMember())\n return false;\n\n stream << \".add_static_property(\\\"\" << decl->getNameAsString() << \"\\\", \"\n << \"[]() { return \" << decl->getQualifiedNameAsString() << \"; }\";\n\n if (!decl->getType().isConstQualified())\n {\n stream << \"[](\" << decl->getType().getAsString(printing_policy_) << \" value) { \"\n << decl->getQualifiedNameAsString() << \" = value; }\";\n }\n\n stream << \")\\n\";\n\n return true;\n}\n\nbool chimera::Visitor::GenerateClassTemplate(clang::ClassTemplateDecl *decl)\n{\n if (decl != decl->getCanonicalDecl())\n return false;\n\n for (ClassTemplateSpecializationDecl *spec_decl : decl->specializations())\n {\n if (spec_decl->getSpecializationKind() == TSK_Undeclared)\n continue;\n\n CXXRecordDecl *decl = spec_decl->getTypeForDecl()->getAsCXXRecordDecl();\n GenerateCXXRecord(decl);\n }\n\n return true;\n}\n\nbool chimera::Visitor::GenerateEnum(clang::EnumDecl *decl)\n{\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n *stream << \"::boost::python::enum_<\"\n << decl->getQualifiedNameAsString()\n << \">(\\\"\" << decl->getNameAsString() << \"\\\")\\n\";\n\n for (EnumConstantDecl *constant_decl : decl->enumerators())\n {\n *stream << \".value(\\\"\" << constant_decl->getNameAsString() << \"\\\", \"\n << constant_decl->getQualifiedNameAsString() << \")\\n\";\n }\n\n *stream << \";\\n\";\n\n return true;\n}\n\nbool chimera::Visitor::GenerateGlobalVar(clang::VarDecl *decl)\n{\n if (!decl->isFileVarDecl())\n return false;\n else if (!decl->isThisDeclarationADefinition())\n return false;\n\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n *stream << \"::boost::python::scope().attr(\\\"\" << decl->getNameAsString()\n << \"\\\") = \" << decl->getQualifiedNameAsString() << \";\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateGlobalFunction(clang::FunctionDecl *decl)\n{\n if (isa(decl))\n return false;\n else if (decl->isOverloadedOperator())\n return false; \/\/ TODO: Wrap overloaded operators.\n\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n return GenerateFunction(*stream, nullptr, decl);\n}\n\nstd::vector chimera::Visitor::GetBaseClassNames(\n CXXRecordDecl *decl) const\n{\n std::vector base_names;\n\n for (CXXBaseSpecifier &base_decl : decl->bases())\n {\n if (base_decl.getAccessSpecifier() != AS_public)\n continue;\n\n \/\/ TODO: Filter out transitive base classes.\n\n CXXRecordDecl *const base_record_decl\n = base_decl.getType()->getAsCXXRecordDecl();\n const QualType base_record_type\n = base_record_decl->getTypeForDecl()->getCanonicalTypeInternal();\n\n base_names.push_back(base_record_type.getAsString(printing_policy_));\n }\n\n return base_names;\n}\n\nstd::vector>\n chimera::Visitor::GetParameterNames(clang::FunctionDecl *decl) const\n{\n std::vector> params;\n\n for (ParmVarDecl *param_decl : decl->params())\n {\n const std::string param_name = param_decl->getNameAsString();\n const Type *param_type = param_decl->getType().getTypePtr();\n std::string param_value;\n\n if (param_decl->hasDefaultArg()\n && !param_decl->hasUninstantiatedDefaultArg()\n && !param_decl->hasUnparsedDefaultArg())\n {\n Expr *default_expr = param_decl->getDefaultArg();\n assert(default_expr);\n\n Expr::EvalResult result;\n bool success;\n\n if (param_type->isReferenceType())\n success = default_expr->EvaluateAsLValue(result, *context_);\n else\n success = default_expr->EvaluateAsRValue(result, *context_);\n\n if (success)\n {\n param_value = result.Val.getAsString(\n *context_, param_decl->getType());\n }\n else if (default_expr->hasNonTrivialCall(*context_))\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Unable to evaluate non-trivial call in default\"\n \" value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n else\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Failed to evaluate default value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n }\n\n params.push_back(std::make_pair(param_name, param_value));\n }\n\n return params;\n}\n\nbool chimera::Visitor::IsEnclosed(Decl *decl) const\n{\n \/\/ Filter over the namespaces and only traverse ones that are enclosed\n \/\/ by one of the configuration namespaces.\n for (const auto &it : config_->GetNamespaces())\n {\n if (decl->getDeclContext() && it->Encloses(decl->getDeclContext()))\n {\n return true;\n }\n }\n return false;\n}\nFixed whitespace and printing method pointer_type.#include \"chimera\/visitor.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace chimera;\nusing namespace clang;\nusing boost::algorithm::join;\n\n\/\/ TODO: Support template functions.\n\/\/ TODO: Detect missing copy constructors, possibly using:\n\/\/ hasUserDeclaredCopyConstructor()\n\/\/ hasCopyConstructorWithConstParam ()\n\/\/ TODO: Mark abstract classes as noncopyable?\n\nchimera::Visitor::Visitor(clang::CompilerInstance *ci,\n std::unique_ptr cc)\n: context_(&(ci->getASTContext()))\n, printing_policy_(ci->getLangOpts())\n, config_(std::move(cc))\n{\n \/\/ Do nothing.\n}\n\nbool chimera::Visitor::VisitDecl(Decl *decl)\n{\n \/\/ Only visit declarations in namespaces we are configured to read.\n if (!IsEnclosed(decl))\n return true;\n\n if (isa(decl))\n GenerateClassTemplate(cast(decl));\n else if (isa(decl))\n GenerateCXXRecord(cast(decl));\n else if (isa(decl))\n GenerateEnum(cast(decl));\n else if (isa(decl))\n GenerateGlobalVar(cast(decl));\n else if (isa(decl))\n GenerateGlobalFunction(cast(decl));\n\n return true;\n}\n\nbool chimera::Visitor::GenerateCXXRecord(CXXRecordDecl *const decl)\n{\n \/\/ Only traverse CXX records that contain the actual class definition.\n if (!decl->hasDefinition() || decl->getDefinition() != decl)\n return false;\n\n \/\/ Open a stream object unique to this CXX record's mangled name.\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n \/\/ Get configuration, and use any overrides if they exist.\n if (config_->DumpOverride(decl, *stream))\n return true;\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n if (node.IsNull())\n return false; \/\/ Explicitly suppressed.\n\n *stream << \"::boost::python::class_<\"\n << decl->getTypeForDecl()->getCanonicalTypeInternal().getAsString(printing_policy_);\n\n const YAML::Node &noncopyable_node = node[\"noncopyable\"];\n if (noncopyable_node && noncopyable_node.as(false))\n *stream << \", ::boost::noncopyable\";\n\n if (const YAML::Node &held_type_node = node[\"held_type\"])\n *stream << \", \" << held_type_node.as();\n\n std::vector base_names;\n\n if (const YAML::Node &bases_node = node[\"bases\"])\n base_names = bases_node.as >();\n else\n base_names = GetBaseClassNames(decl);\n\n if (!base_names.empty())\n {\n *stream << \", ::boost::python::bases<\"\n << join(base_names, \", \") << \" >\";\n }\n\n *stream << \" >(\\\"\" << decl->getNameAsString()\n << \"\\\", boost::python::no_init)\\n\";\n\n \/\/ Methods\n std::set overloaded_method_names;\n\n for (CXXMethodDecl *const method_decl : decl->methods())\n {\n if (method_decl->getAccess() != AS_public)\n continue; \/\/ skip protected and private members\n\n if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n ; \/\/ do nothing\n else if (isa(method_decl))\n {\n GenerateCXXConstructor(\n *stream, decl, cast(method_decl));\n }\n else if (method_decl->isOverloadedOperator())\n ; \/\/ TODO: Wrap overloaded operators.\n else if (method_decl->isStatic())\n {\n \/\/ TODO: Missing the dot.\n if (GenerateFunction(*stream, decl, method_decl))\n overloaded_method_names.insert(method_decl->getNameAsString());\n }\n else\n {\n \/\/ TODO: Missing the dot.\n GenerateFunction(*stream, decl, method_decl);\n }\n }\n\n \/\/ Static methods MUST be declared after overloads are defined.\n for (const std::string &method_name : overloaded_method_names)\n *stream << \".staticmethod(\\\"\" << method_name << \"\\\")\\n\";\n\n \/\/ Fields\n for (FieldDecl *const field_decl : decl->fields())\n {\n if (field_decl->getAccess() != AS_public)\n continue; \/\/ skip protected and private fields\n\n GenerateField(*stream, decl, field_decl);\n }\n\n for (Decl *const child_decl : decl->decls())\n {\n if (isa(child_decl))\n GenerateStaticField(*stream, decl, cast(child_decl));\n }\n\n *stream << \";\\n\";\n \n return true;\n}\n\nbool chimera::Visitor::GenerateCXXConstructor(\n chimera::Stream &stream,\n CXXRecordDecl *class_decl,\n CXXConstructorDecl *decl)\n{\n decl = decl->getCanonicalDecl();\n\n if (decl->isDeleted())\n return false;\n\n std::vector argument_types;\n\n for (ParmVarDecl *param_decl : decl->params())\n argument_types.push_back(param_decl->getType().getAsString(printing_policy_));\n\n stream << \".def(::boost::python::init<\"\n << join(argument_types, \", \")\n << \">())\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateFunction(\n chimera::Stream &stream,\n CXXRecordDecl *class_decl, FunctionDecl *decl)\n{\n decl = decl->getCanonicalDecl();\n\n if (decl->isDeleted())\n return false;\n\n \/\/ Get configuration, and use any overrides if they exist.\n if (config_->DumpOverride(decl, stream))\n return true;\n\n const YAML::Node &node = config_->GetDeclaration(decl);\n if (node.IsNull())\n return false; \/\/ Explicitly suppressed.\n\n \/\/ Extract the pointer type of this function declaration.\n QualType pointer_type;\n if (class_decl && !cast(decl)->isStatic())\n {\n pointer_type = context_->getMemberPointerType(\n decl->getType(), class_decl->getTypeForDecl());\n }\n else\n {\n pointer_type = context_->getPointerType(decl->getType());\n }\n pointer_type = pointer_type.getCanonicalType();\n\n \/\/ Extract the return type of this function declaration.\n const QualType return_qual_type = decl->getReturnType();\n const Type *return_type = return_qual_type.getTypePtr();\n\n \/\/ First, check if a return_value_policy was specified for this function.\n std::string return_value_policy\n = node[\"return_value_policy\"].as(\"\");\n\n \/\/ Next, check if a return_value_policy is defined on the return type.\n if (return_value_policy.empty())\n {\n const YAML::Node &type_node = config_->GetType(return_qual_type);\n return_value_policy\n = type_node[\"return_value_policy\"].as(\"\");\n }\n\n \/\/ Finally, try the default return_value_policy. This is only acceptable if\n \/\/ the output is copy constructable.\n if (return_value_policy.empty())\n {\n if (return_type->isReferenceType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << pointer_type.getAsString(printing_policy_)\n << \"' because it returns a reference and no\"\n \" 'return_value_policy' was specified.\\n\";\n return false;\n }\n else if (return_type->isPointerType())\n {\n std::cerr\n << \"Warning: Skipped method '\"\n << pointer_type.getAsString(printing_policy_)\n << \"' because it returns a pointer and no\"\n \" 'return_value_policy' was specified.\\n\";\n return false;\n }\n \/\/ TODO: Check if return_type is non-copyable.\n }\n\n \/\/ If we are inside a class declaration, this is being called within a\n \/\/ builder pattern and will start with '.' since it is a member function.\n if (class_decl)\n stream << \".\";\n\n \/\/ Create the actual function declaration here using its name and its\n \/\/ full pointer reference.\n stream << \"def(\\\"\" << decl->getNameAsString() << \"\\\"\"\n << \", static_cast<\" << pointer_type.getAsString(printing_policy_) << \">(&\"\n << decl->getQualifiedNameAsString() << \")\";\n\n \/\/ If a return value policy was specified, insert it after the function.\n if (!return_value_policy.empty())\n {\n stream << \", ::boost::python::return_value_policy<\"\n << return_value_policy << \" >\";\n }\n\n \/\/ Construct a list of the arguments that are provided to this function,\n \/\/ and define named arguments for them based on their c++ names.\n const auto params = GetParameterNames(decl);\n if (!params.empty())\n {\n \/\/ TODO: Suppress any default parameters that occur after the first\n \/\/ non-default to default transition. This can only occur if evaluating\n \/\/ the default value of one or more parameters failed.\n\n \/\/ TODO: Assign names to unnamed arguments.\n\n std::vector python_args;\n for (const auto ¶m : params)\n {\n std::stringstream python_arg;\n python_arg << \"::boost::python::arg(\\\"\" << param.first << \"\\\")\";\n\n if (!param.second.empty())\n python_arg << \" = \" << param.second;\n\n python_args.push_back(python_arg.str());\n }\n\n stream << \", (\" << join(python_args, \", \") << \")\";\n }\n\n stream << \")\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateField(\n chimera::Stream &stream,\n clang::CXXRecordDecl *class_decl,\n clang::FieldDecl *decl)\n{\n if (decl->getType().isConstQualified())\n stream << \".def_readonly\";\n else\n stream << \".def_readwrite\";\n\n \/\/ TODO: Check if a copy constructor is defined for this type.\n\n stream << \"(\\\"\" << decl->getNameAsString() << \"\\\",\"\n << \" &\" << decl->getQualifiedNameAsString() << \")\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateStaticField(\n chimera::Stream &stream,\n clang::CXXRecordDecl *class_decl,\n clang::VarDecl *decl)\n{\n if (decl->getAccess() != AS_public)\n return false;\n else if (!decl->isStaticDataMember())\n return false;\n\n stream << \".add_static_property(\\\"\" << decl->getNameAsString() << \"\\\", \"\n << \"[]() { return \" << decl->getQualifiedNameAsString() << \"; }\";\n\n if (!decl->getType().isConstQualified())\n {\n stream << \"[](\" << decl->getType().getAsString(printing_policy_) << \" value) { \"\n << decl->getQualifiedNameAsString() << \" = value; }\";\n }\n\n stream << \")\\n\";\n\n return true;\n}\n\nbool chimera::Visitor::GenerateClassTemplate(clang::ClassTemplateDecl *decl)\n{\n if (decl != decl->getCanonicalDecl())\n return false;\n\n for (ClassTemplateSpecializationDecl *spec_decl : decl->specializations())\n {\n if (spec_decl->getSpecializationKind() == TSK_Undeclared)\n continue;\n\n CXXRecordDecl *decl = spec_decl->getTypeForDecl()->getAsCXXRecordDecl();\n GenerateCXXRecord(decl);\n }\n\n return true;\n}\n\nbool chimera::Visitor::GenerateEnum(clang::EnumDecl *decl)\n{\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n *stream << \"::boost::python::enum_<\"\n << decl->getQualifiedNameAsString()\n << \">(\\\"\" << decl->getNameAsString() << \"\\\")\\n\";\n\n for (EnumConstantDecl *constant_decl : decl->enumerators())\n {\n *stream << \".value(\\\"\" << constant_decl->getNameAsString() << \"\\\", \"\n << constant_decl->getQualifiedNameAsString() << \")\\n\";\n }\n\n *stream << \";\\n\";\n\n return true;\n}\n\nbool chimera::Visitor::GenerateGlobalVar(clang::VarDecl *decl)\n{\n if (!decl->isFileVarDecl())\n return false;\n else if (!decl->isThisDeclarationADefinition())\n return false;\n\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n *stream << \"::boost::python::scope().attr(\\\"\" << decl->getNameAsString()\n << \"\\\") = \" << decl->getQualifiedNameAsString() << \";\\n\";\n return true;\n}\n\nbool chimera::Visitor::GenerateGlobalFunction(clang::FunctionDecl *decl)\n{\n if (isa(decl))\n return false;\n else if (decl->isOverloadedOperator())\n return false; \/\/ TODO: Wrap overloaded operators.\n\n auto stream = config_->GetOutputFile(decl);\n if (!stream)\n return false;\n\n return GenerateFunction(*stream, nullptr, decl);\n}\n\nstd::vector chimera::Visitor::GetBaseClassNames(\n CXXRecordDecl *decl) const\n{\n std::vector base_names;\n\n for (CXXBaseSpecifier &base_decl : decl->bases())\n {\n if (base_decl.getAccessSpecifier() != AS_public)\n continue;\n\n \/\/ TODO: Filter out transitive base classes.\n\n CXXRecordDecl *const base_record_decl\n = base_decl.getType()->getAsCXXRecordDecl();\n const QualType base_record_type\n = base_record_decl->getTypeForDecl()->getCanonicalTypeInternal();\n\n base_names.push_back(base_record_type.getAsString(printing_policy_));\n }\n\n return base_names;\n}\n\nstd::vector>\n chimera::Visitor::GetParameterNames(clang::FunctionDecl *decl) const\n{\n std::vector> params;\n\n for (ParmVarDecl *param_decl : decl->params())\n {\n const std::string param_name = param_decl->getNameAsString();\n const Type *param_type = param_decl->getType().getTypePtr();\n std::string param_value;\n\n if (param_decl->hasDefaultArg()\n && !param_decl->hasUninstantiatedDefaultArg()\n && !param_decl->hasUnparsedDefaultArg())\n {\n Expr *default_expr = param_decl->getDefaultArg();\n assert(default_expr);\n\n Expr::EvalResult result;\n bool success;\n\n if (param_type->isReferenceType())\n success = default_expr->EvaluateAsLValue(result, *context_);\n else\n success = default_expr->EvaluateAsRValue(result, *context_);\n\n if (success)\n {\n param_value = result.Val.getAsString(\n *context_, param_decl->getType());\n }\n else if (default_expr->hasNonTrivialCall(*context_))\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Unable to evaluate non-trivial call in default\"\n \" value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n else\n {\n \/\/ TODO: How do we print the decl with argument + return types?\n std::cerr\n << \"Warning: Failed to evaluate default value for parameter\"\n << \" '\" << param_name << \"' of method\"\n << \" '\" << decl->getQualifiedNameAsString() << \"'.\\n\";\n }\n }\n\n params.push_back(std::make_pair(param_name, param_value));\n }\n\n return params;\n}\n\nbool chimera::Visitor::IsEnclosed(Decl *decl) const\n{\n \/\/ Filter over the namespaces and only traverse ones that are enclosed\n \/\/ by one of the configuration namespaces.\n for (const auto &it : config_->GetNamespaces())\n {\n if (decl->getDeclContext() && it->Encloses(decl->getDeclContext()))\n {\n return true;\n }\n }\n return false;\n}\n<|endoftext|>"} {"text":"\/\/ -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-\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 version 2\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Authors:\n * Caner Candan \n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if __cplusplus > 199711L\nnamespace std_or_boost = std;\n#include \n#include \n#else\n#include \n#include \n#include \nnamespace std_or_boost = boost;\n#endif\n\ntypedef dim::representation::Route EOT;\n\nint main (int argc, char *argv[])\n{\n \/*************************\n * Initialisation de MPI *\n *************************\/\n\n \/\/ boost::mpi::environment env(argc, argv, MPI_THREAD_MULTIPLE, true);\n \/\/ boost::mpi::communicator world;\n\n \/****************************\n * Il faut au moins 4 nœuds *\n ****************************\/\n\n \/\/ const size_t ALL = world.size();\n \/\/ const size_t RANK = world.rank();\n\n \/************************\n * Initialisation de EO *\n ************************\/\n\n eoParser parser(argc, argv);\n eoState state; \/\/ keeps all things allocated\n dim::core::State state_dim; \/\/ keeps all things allocated\n\n \/*****************************\n * Definition des paramètres *\n *****************************\/\n\n \/\/ N\n unsigned nislands = parser.createParam(unsigned(4), \"nislands\", \"Number of islands (see --smp)\", 'N', \"Islands Model\").value();\n \/\/ a\n double alphaP = parser.createParam(double(0.2), \"alpha\", \"Alpha Probability\", 'a', \"Islands Model\").value();\n \/\/ A\n double alphaF = parser.createParam(double(0.01), \"alphaF\", \"Alpha Fitness\", 'A', \"Islands Model\").value();\n \/\/ b\n double betaP = parser.createParam(double(0.01), \"beta\", \"Beta Probability\", 'b', \"Islands Model\").value();\n \/\/ d\n double probaSame = parser.createParam(double(100.\/nislands), \"probaSame\", \"Probability for an individual to stay in the same island\", 'd', \"Islands Model\").value();\n \/\/ I\n bool initG = parser.createParam(bool(true), \"initG\", \"initG\", 'I', \"Islands Model\").value();\n unsigned nmigrations = parser.createParam(unsigned(1), \"nmigrations\", \"Number of migrations to do at each generation (0=all individuals are migrated)\", 0, \"Islands Model\").value();\n unsigned stepTimer = parser.createParam(unsigned(0), \"stepTimer\", \"stepTimer\", 0, \"Islands Model\").value();\n bool deltaUpdate = parser.createParam(bool(true), \"deltaUpdate\", \"deltaUpdate\", 0, \"Islands Model\").value();\n bool deltaFeedback = parser.createParam(bool(true), \"deltaFeedback\", \"deltaFeedback\", 0, \"Islands Model\").value();\n double sensitivity = 1 \/ parser.createParam(double(1.), \"sensitivity\", \"sensitivity of delta{t} (1\/sensitivity)\", 0, \"Islands Model\").value();\n std::string rewardStrategy = parser.createParam(std::string(\"best\"), \"rewardStrategy\", \"Strategy of rewarding: best or avg\", 0, \"Islands Model\").value();\n\n \/*********************************\n * Déclaration des composants EO *\n *********************************\/\n\n std::string tspInstance = parser.getORcreateParam(std::string(\"benchs\/ali535.xml\"), \"tspInstance\", \"filename of the instance for TSP problem\", 0, \"Problem\").value();\n\n dim::evaluation::Route mainEval;\n eoEvalFuncCounter eval(mainEval);\n\n unsigned popSize = parser.getORcreateParam(unsigned(100), \"popSize\", \"Population Size\", 'P', \"Evolution Engine\").value();\n\n double targetFitness = parser.getORcreateParam(double(0), \"targetFitness\", \"Stop when fitness reaches\",'T', \"Stopping criterion\").value();\n unsigned maxGen = parser.getORcreateParam(unsigned(10000), \"maxGen\", \"Maximum number of generations () = none)\",'G',\"Stopping criterion\").value();\n\n std::string monitorPrefix = parser.getORcreateParam(std::string(\"result\"), \"monitorPrefix\", \"Monitor prefix filenames\", '\\0', \"Output\").value();\n\n std::map< std::string, eoMonOp* > mapOperators;\n std::vector< std::string > operatorsOrder;\n\n mapOperators[\"swap\"] = new eoSwapMutation;\t\toperatorsOrder.push_back(\"swap\");\n mapOperators[\"shift\"] = new eoShiftMutation;\t\toperatorsOrder.push_back(\"shift\");\n mapOperators[\"inversion\"] = new eoInversionMutation;\toperatorsOrder.push_back(\"inversion\");\n\n mapOperators[\"first_improve_swap\"] = new eoFirstImprovementSwapMutation(eval);\n operatorsOrder.push_back(\"first_improve_swap\");\n mapOperators[\"first_improve_shift\"] = new eoFirstImprovementShiftMutation(eval);\n operatorsOrder.push_back(\"first_improve_shift\");\n mapOperators[\"first_improve_inversion\"] = new eoFirstImprovementInversionMutation(eval);\n operatorsOrder.push_back(\"first_improve_inversion\");\n\n mapOperators[\"relative_best_improve_swap\"] = new eoRelativeBestImprovementSwapMutation(eval);\n operatorsOrder.push_back(\"relative_best_improve_swap\");\n mapOperators[\"relative_best_improve_shift\"] = new eoRelativeBestImprovementShiftMutation(eval);\n operatorsOrder.push_back(\"relative_best_improve_shift\");\n mapOperators[\"relative_best_improve_inversion\"] = new eoRelativeBestImprovementInversionMutation(eval);\n operatorsOrder.push_back(\"relative_best_improve_inversion\");\n\n mapOperators[\"best_improve_swap\"] = new eoBestImprovementSwapMutation(eval);\n operatorsOrder.push_back(\"best_improve_swap\");\n mapOperators[\"best_improve_shift\"] = new eoBestImprovementShiftMutation(eval);\n operatorsOrder.push_back(\"best_improve_shift\");\n mapOperators[\"best_improve_inversion\"] = new eoBestImprovementInversionMutation(eval);\n operatorsOrder.push_back(\"best_improve_inversion\");\n\n mapOperators[\"2swap\"] = new eoSwapMutation(2);\toperatorsOrder.push_back(\"2swap\");\n mapOperators[\"2opt\"] = new eoTwoOptMutation;\toperatorsOrder.push_back(\"2opt\");\n\n std::ostringstream ssOrder, ssOrder2;\n ssOrder << \"Set an operator between \" << operatorsOrder[0];\n ssOrder2 << \"List of operators separeted by a comma. Select operators between \" << operatorsOrder[0];\n for ( size_t k = 1; k < operatorsOrder.size(); ++k )\n\t{\n\t ssOrder << \",\" << operatorsOrder[k];\n\t ssOrder2 << \",\" << operatorsOrder[k];\n\t}\n\n std::vector operatorsVec(nislands, \"\");\n\n for (size_t i = 0; i < nislands; ++i)\n\t{\n\t std::ostringstream ss;\n\t ss << \"operator\" << i;\n\t operatorsVec[i] = parser.createParam(std::string(operatorsOrder[ i % operatorsOrder.size() ]), ss.str(), ssOrder.str(), 0, \"Islands Model\").value();\n\t}\n\n \/\/ O\n std::string operators = parser.createParam(std::string(\"\"), \"operators\", ssOrder2.str(), 'O', \"Islands Model\").value();\n\n if (!operators.empty())\n\t{\n\t boost::split(operatorsVec, operators, boost::is_any_of(\",\"));\n\t}\n\n \/**************\n * EO routine *\n **************\/\n\n make_parallel(parser);\n make_verbose(parser);\n make_help(parser);\n\n dim::initialization::TSPLibGraph::load( tspInstance ); \/\/ Instance\n dim::initialization::Route init ; \/\/ Sol. Random Init.\n dim::core::Pop& pop = dim::do_make::detail::pop(parser, state, init);\n\n \/\/ smp\n\n \/**********************************\n * Déclaration des composants DIM *\n **********************************\/\n\n dim::core::ThreadsRunner< EOT > tr;\n\n std::vector< dim::core::Pop* > islandPop(nislands);\n std::vector< dim::core::IslandData* > islandData(nislands);\n\n dim::core::MigrationMatrix probabilities( nislands );\n dim::core::InitMatrix initmatrix( initG, probaSame );\n\n initmatrix( probabilities );\n std::cout << probabilities;\n\n std::cout << \"size: \" << dim::initialization::TSPLibGraph::size() << std::endl;\n\n for (size_t i = 0; i < nislands; ++i)\n\t{\n\t std::cout << \"island \" << i << std::endl;\n\n\t islandPop[i] = new dim::core::Pop(popSize, init);\n\t islandData[i] = new dim::core::IslandData(nislands, i);\n\n\t std::cout << islandData[i]->size() << \" \" << islandData[i]->rank() << \" \" << operatorsVec[ islandData[i]->rank() ] << std::endl;\n\n\t islandData[i]->proba = probabilities(i);\n\t apply(eval, *(islandPop[i]));\n\n\t \/****************************************\n\t * Distribution des opérateurs aux iles *\n\t ****************************************\/\n\n\t eoMonOp* ptMon = mapOperators[ operatorsVec[ islandData[i]->rank() ] ];\n\n\t dim::evolver::Base* ptEvolver = new dim::evolver::Easy( \/*eval*\/mainEval, *ptMon );\n\t state_dim.storeFunctor(ptEvolver);\n\n\t dim::feedbacker::Base* ptFeedbacker = new dim::feedbacker::smp::Easy(islandPop, islandData, alphaF);\n\t state_dim.storeFunctor(ptFeedbacker);\n\n\t dim::vectorupdater::Reward* ptReward = NULL;\n\t if (rewardStrategy == \"best\")\n\t\t{\n\t\t ptReward = new dim::vectorupdater::Best(alphaP, betaP);\n\t\t}\n\t else\n\t\t{\n\t\t ptReward = new dim::vectorupdater::Average(alphaP, betaP);\n\t\t}\n\t state_dim.storeFunctor(ptReward);\n\n\t dim::vectorupdater::Base* ptUpdater = new dim::vectorupdater::Easy(*ptReward);\n\t state_dim.storeFunctor(ptUpdater);\n\n\t dim::memorizer::Base* ptMemorizer = new dim::memorizer::Easy();\n\t state_dim.storeFunctor(ptMemorizer);\n\n\t dim::migrator::Base* ptMigrator = new dim::migrator::smp::Easy(islandPop, islandData, monitorPrefix);\n\t state_dim.storeFunctor(ptMigrator);\n\n\t dim::continuator::Base& continuator = dim::do_make::continuator(parser, state, eval);\n\t dim::utils::CheckPoint& checkpoint = dim::do_make::checkpoint(parser, state, continuator, *(islandData[i]), 1, stepTimer);\n\n\t dim::algo::Base* ptIsland = new dim::algo::smp::Easy( *ptEvolver, *ptFeedbacker, *ptUpdater, *ptMemorizer, *ptMigrator, checkpoint, islandPop, islandData, monitorPrefix );\n\t state_dim.storeFunctor(ptIsland);\n\n\t ptEvolver->size(nislands);\n\t ptFeedbacker->size(nislands);\n\t ptReward->size(nislands);\n\t ptUpdater->size(nislands);\n\t ptMemorizer->size(nislands);\n\t ptMigrator->size(nislands);\n\t ptIsland->size(nislands);\n\n\t ptEvolver->rank(i);\n\t ptFeedbacker->rank(i);\n\t ptReward->rank(i);\n\t ptUpdater->rank(i);\n\t ptMemorizer->rank(i);\n\t ptMigrator->rank(i);\n\t ptIsland->rank(i);\n\n\t tr.add(*ptIsland);\n\t}\n\n dim::core::IslandData data(nislands);\n tr(pop, data);\n\n for (size_t i = 0; i < nislands; ++i)\n\t{\n\t delete islandPop[i];\n\t delete islandData[i];\n\t}\n\n for ( std::map< std::string, eoMonOp* >::iterator it = mapOperators.begin(); it != mapOperators.end(); ++it )\n \t{\n \t delete it->second;\n \t}\n\n return 0;\n}\n* ..\/..\/..\/application\/TSP\/tsp.cpp: fixed a missing param value for result location\/\/ -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-\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 version 2\n * as published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n * Authors:\n * Caner Candan \n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if __cplusplus > 199711L\nnamespace std_or_boost = std;\n#include \n#include \n#else\n#include \n#include \n#include \nnamespace std_or_boost = boost;\n#endif\n\ntypedef dim::representation::Route EOT;\n\nint main (int argc, char *argv[])\n{\n \/*************************\n * Initialisation de MPI *\n *************************\/\n\n \/\/ boost::mpi::environment env(argc, argv, MPI_THREAD_MULTIPLE, true);\n \/\/ boost::mpi::communicator world;\n\n \/****************************\n * Il faut au moins 4 nœuds *\n ****************************\/\n\n \/\/ const size_t ALL = world.size();\n \/\/ const size_t RANK = world.rank();\n\n \/************************\n * Initialisation de EO *\n ************************\/\n\n eoParser parser(argc, argv);\n eoState state; \/\/ keeps all things allocated\n dim::core::State state_dim; \/\/ keeps all things allocated\n\n \/*****************************\n * Definition des paramètres *\n *****************************\/\n\n \/\/ N\n unsigned nislands = parser.createParam(unsigned(4), \"nislands\", \"Number of islands (see --smp)\", 'N', \"Islands Model\").value();\n \/\/ a\n double alphaP = parser.createParam(double(0.2), \"alpha\", \"Alpha Probability\", 'a', \"Islands Model\").value();\n \/\/ A\n double alphaF = parser.createParam(double(0.01), \"alphaF\", \"Alpha Fitness\", 'A', \"Islands Model\").value();\n \/\/ b\n double betaP = parser.createParam(double(0.01), \"beta\", \"Beta Probability\", 'b', \"Islands Model\").value();\n \/\/ d\n double probaSame = parser.createParam(double(100.\/nislands), \"probaSame\", \"Probability for an individual to stay in the same island\", 'd', \"Islands Model\").value();\n \/\/ I\n bool initG = parser.createParam(bool(true), \"initG\", \"initG\", 'I', \"Islands Model\").value();\n unsigned nmigrations = parser.createParam(unsigned(1), \"nmigrations\", \"Number of migrations to do at each generation (0=all individuals are migrated)\", 0, \"Islands Model\").value();\n unsigned stepTimer = parser.createParam(unsigned(0), \"stepTimer\", \"stepTimer\", 0, \"Islands Model\").value();\n bool deltaUpdate = parser.createParam(bool(true), \"deltaUpdate\", \"deltaUpdate\", 0, \"Islands Model\").value();\n bool deltaFeedback = parser.createParam(bool(true), \"deltaFeedback\", \"deltaFeedback\", 0, \"Islands Model\").value();\n double sensitivity = 1 \/ parser.createParam(double(1.), \"sensitivity\", \"sensitivity of delta{t} (1\/sensitivity)\", 0, \"Islands Model\").value();\n std::string rewardStrategy = parser.createParam(std::string(\"best\"), \"rewardStrategy\", \"Strategy of rewarding: best or avg\", 0, \"Islands Model\").value();\n\n \/*********************************\n * Déclaration des composants EO *\n *********************************\/\n\n std::string tspInstance = parser.getORcreateParam(std::string(\"benchs\/ali535.xml\"), \"tspInstance\", \"filename of the instance for TSP problem\", 0, \"Problem\").value();\n\n dim::evaluation::Route mainEval;\n eoEvalFuncCounter eval(mainEval);\n\n unsigned popSize = parser.getORcreateParam(unsigned(100), \"popSize\", \"Population Size\", 'P', \"Evolution Engine\").value();\n\n double targetFitness = parser.getORcreateParam(double(0), \"targetFitness\", \"Stop when fitness reaches\",'T', \"Stopping criterion\").value();\n unsigned maxGen = parser.getORcreateParam(unsigned(10000), \"maxGen\", \"Maximum number of generations () = none)\",'G',\"Stopping criterion\").value();\n\n std::string monitorPrefix = parser.getORcreateParam(std::string(\"result\"), \"monitorPrefix\", \"Monitor prefix filenames\", '\\0', \"Output\").value();\n\n std::map< std::string, eoMonOp* > mapOperators;\n std::vector< std::string > operatorsOrder;\n\n mapOperators[\"swap\"] = new eoSwapMutation;\t\toperatorsOrder.push_back(\"swap\");\n mapOperators[\"shift\"] = new eoShiftMutation;\t\toperatorsOrder.push_back(\"shift\");\n mapOperators[\"inversion\"] = new eoInversionMutation;\toperatorsOrder.push_back(\"inversion\");\n\n mapOperators[\"first_improve_swap\"] = new eoFirstImprovementSwapMutation(eval);\n operatorsOrder.push_back(\"first_improve_swap\");\n mapOperators[\"first_improve_shift\"] = new eoFirstImprovementShiftMutation(eval);\n operatorsOrder.push_back(\"first_improve_shift\");\n mapOperators[\"first_improve_inversion\"] = new eoFirstImprovementInversionMutation(eval);\n operatorsOrder.push_back(\"first_improve_inversion\");\n\n mapOperators[\"relative_best_improve_swap\"] = new eoRelativeBestImprovementSwapMutation(eval);\n operatorsOrder.push_back(\"relative_best_improve_swap\");\n mapOperators[\"relative_best_improve_shift\"] = new eoRelativeBestImprovementShiftMutation(eval);\n operatorsOrder.push_back(\"relative_best_improve_shift\");\n mapOperators[\"relative_best_improve_inversion\"] = new eoRelativeBestImprovementInversionMutation(eval);\n operatorsOrder.push_back(\"relative_best_improve_inversion\");\n\n mapOperators[\"best_improve_swap\"] = new eoBestImprovementSwapMutation(eval);\n operatorsOrder.push_back(\"best_improve_swap\");\n mapOperators[\"best_improve_shift\"] = new eoBestImprovementShiftMutation(eval);\n operatorsOrder.push_back(\"best_improve_shift\");\n mapOperators[\"best_improve_inversion\"] = new eoBestImprovementInversionMutation(eval);\n operatorsOrder.push_back(\"best_improve_inversion\");\n\n mapOperators[\"2swap\"] = new eoSwapMutation(2);\toperatorsOrder.push_back(\"2swap\");\n mapOperators[\"2opt\"] = new eoTwoOptMutation;\toperatorsOrder.push_back(\"2opt\");\n\n std::ostringstream ssOrder, ssOrder2;\n ssOrder << \"Set an operator between \" << operatorsOrder[0];\n ssOrder2 << \"List of operators separeted by a comma. Select operators between \" << operatorsOrder[0];\n for ( size_t k = 1; k < operatorsOrder.size(); ++k )\n\t{\n\t ssOrder << \",\" << operatorsOrder[k];\n\t ssOrder2 << \",\" << operatorsOrder[k];\n\t}\n\n std::vector operatorsVec(nislands, \"\");\n\n for (size_t i = 0; i < nislands; ++i)\n\t{\n\t std::ostringstream ss;\n\t ss << \"operator\" << i;\n\t operatorsVec[i] = parser.createParam(std::string(operatorsOrder[ i % operatorsOrder.size() ]), ss.str(), ssOrder.str(), 0, \"Islands Model\").value();\n\t}\n\n \/\/ O\n std::string operators = parser.createParam(std::string(\"\"), \"operators\", ssOrder2.str(), 'O', \"Islands Model\").value();\n\n if (!operators.empty())\n\t{\n\t boost::split(operatorsVec, operators, boost::is_any_of(\",\"));\n\t}\n\n \/**************\n * EO routine *\n **************\/\n\n make_parallel(parser);\n make_verbose(parser);\n make_help(parser);\n\n dim::initialization::TSPLibGraph::load( tspInstance ); \/\/ Instance\n dim::initialization::Route init ; \/\/ Sol. Random Init.\n dim::core::Pop& pop = dim::do_make::detail::pop(parser, state, init);\n\n \/\/ smp\n\n \/**********************************\n * Déclaration des composants DIM *\n **********************************\/\n\n dim::core::ThreadsRunner< EOT > tr;\n\n std::vector< dim::core::Pop* > islandPop(nislands);\n std::vector< dim::core::IslandData* > islandData(nislands);\n\n dim::core::MigrationMatrix probabilities( nislands );\n dim::core::InitMatrix initmatrix( initG, probaSame );\n\n initmatrix( probabilities );\n std::cout << probabilities;\n\n std::cout << \"size: \" << dim::initialization::TSPLibGraph::size() << std::endl;\n\n for (size_t i = 0; i < nislands; ++i)\n\t{\n\t std::cout << \"island \" << i << std::endl;\n\n\t islandPop[i] = new dim::core::Pop(popSize, init);\n\t islandData[i] = new dim::core::IslandData(nislands, i);\n\n\t std::cout << islandData[i]->size() << \" \" << islandData[i]->rank() << \" \" << operatorsVec[ islandData[i]->rank() ] << std::endl;\n\n\t islandData[i]->proba = probabilities(i);\n\t apply(eval, *(islandPop[i]));\n\n\t \/****************************************\n\t * Distribution des opérateurs aux iles *\n\t ****************************************\/\n\n\t eoMonOp* ptMon = mapOperators[ operatorsVec[ islandData[i]->rank() ] ];\n\n\t dim::evolver::Base* ptEvolver = new dim::evolver::Easy( \/*eval*\/mainEval, *ptMon );\n\t state_dim.storeFunctor(ptEvolver);\n\n\t dim::feedbacker::Base* ptFeedbacker = new dim::feedbacker::smp::Easy(islandPop, islandData, alphaF, monitorPrefix);\n\t state_dim.storeFunctor(ptFeedbacker);\n\n\t dim::vectorupdater::Reward* ptReward = NULL;\n\t if (rewardStrategy == \"best\")\n\t\t{\n\t\t ptReward = new dim::vectorupdater::Best(alphaP, betaP);\n\t\t}\n\t else\n\t\t{\n\t\t ptReward = new dim::vectorupdater::Average(alphaP, betaP);\n\t\t}\n\t state_dim.storeFunctor(ptReward);\n\n\t dim::vectorupdater::Base* ptUpdater = new dim::vectorupdater::Easy(*ptReward);\n\t state_dim.storeFunctor(ptUpdater);\n\n\t dim::memorizer::Base* ptMemorizer = new dim::memorizer::Easy();\n\t state_dim.storeFunctor(ptMemorizer);\n\n\t dim::migrator::Base* ptMigrator = new dim::migrator::smp::Easy(islandPop, islandData, monitorPrefix);\n\t state_dim.storeFunctor(ptMigrator);\n\n\t dim::continuator::Base& continuator = dim::do_make::continuator(parser, state, eval);\n\t dim::utils::CheckPoint& checkpoint = dim::do_make::checkpoint(parser, state, continuator, *(islandData[i]), 1, stepTimer);\n\n\t dim::algo::Base* ptIsland = new dim::algo::smp::Easy( *ptEvolver, *ptFeedbacker, *ptUpdater, *ptMemorizer, *ptMigrator, checkpoint, islandPop, islandData, monitorPrefix );\n\t state_dim.storeFunctor(ptIsland);\n\n\t ptEvolver->size(nislands);\n\t ptFeedbacker->size(nislands);\n\t ptReward->size(nislands);\n\t ptUpdater->size(nislands);\n\t ptMemorizer->size(nislands);\n\t ptMigrator->size(nislands);\n\t ptIsland->size(nislands);\n\n\t ptEvolver->rank(i);\n\t ptFeedbacker->rank(i);\n\t ptReward->rank(i);\n\t ptUpdater->rank(i);\n\t ptMemorizer->rank(i);\n\t ptMigrator->rank(i);\n\t ptIsland->rank(i);\n\n\t tr.add(*ptIsland);\n\t}\n\n dim::core::IslandData data(nislands);\n tr(pop, data);\n\n for (size_t i = 0; i < nislands; ++i)\n\t{\n\t delete islandPop[i];\n\t delete islandData[i];\n\t}\n\n for ( std::map< std::string, eoMonOp* >::iterator it = mapOperators.begin(); it != mapOperators.end(); ++it )\n \t{\n \t delete it->second;\n \t}\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: appinit.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: mav $ $Date: 2002-09-10 11:01:40 $\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 \"appinit.hxx\"\n#include \"cmdlineargs.hxx\"\n#include \"officeacceptthread.hxx\"\n\n#ifndef _COM_SUN_STAR_REGISTRY_XSIMPLEREGISTRY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_BOOTSTRAP_HXX_\n#include \n#endif\n#ifndef _OSL_FILE_HXX_\n#include \n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include \n#endif\n#ifndef _RTL_URI_HXX_\n#include \n#endif\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_REGPATHHELPER_HXX_\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _TOOLS_TEMPFILE_HXX\n#include \n#endif\n#ifndef _UCBHELPER_CONFIGURATIONKEYS_HXX_\n#include \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_INTERNALOPTIONS_HXX\n#include \n#endif\n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII))\n#define DEFINE_CONST_OUSTRING(CONSTASCII) OUString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII))\n\n#define DESKTOP_TEMPDIRNAME \"soffice.tmp\"\n\nusing namespace rtl;\nusing namespace vos;\nusing namespace desktop;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::registry;\n\nextern desktop::CommandLineArgs* GetCommandLineArgs();\nextern desktop::OOfficeAcceptorThread* pOfficeAcceptThread;\n\nstatic String aCurrentTempURL;\n\n\n\/\/ -----------------------------------------------------------------------------\n\nstatic bool configureUcb(bool bServer, rtl::OUString const & rPortalConnect)\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (sb93797) ::configureUcb\" );\n Reference< XMultiServiceFactory >\n xServiceFactory( comphelper::getProcessServiceFactory() );\n if (!xServiceFactory.is())\n {\n DBG_ERROR(\"configureUcb(): No XMultiServiceFactory\");\n return false;\n }\n\n rtl::OUString aPipe;\n vos::OSecurity().getUserIdent(aPipe);\n\n rtl::OUStringBuffer aPortal;\n if (rPortalConnect.getLength() != 0)\n {\n aPortal.append(sal_Unicode(','));\n aPortal.append(rPortalConnect);\n }\n\n Sequence< Any > aArgs(6);\n aArgs[0]\n <<= rtl::OUString::createFromAscii(bServer ?\n UCB_CONFIGURATION_KEY1_SERVER :\n UCB_CONFIGURATION_KEY1_LOCAL);\n aArgs[1]\n <<= rtl::OUString::createFromAscii(UCB_CONFIGURATION_KEY2_OFFICE);\n aArgs[2] <<= rtl::OUString::createFromAscii(\"PIPE\");\n aArgs[3] <<= aPipe;\n aArgs[4] <<= rtl::OUString::createFromAscii(\"PORTAL\");\n aArgs[5] <<= aPortal.makeStringAndClear();\n\n return ::ucb::ContentBroker::initialize( xServiceFactory, aArgs ) != false;\n}\n\n\nReference< XMultiServiceFactory > createApplicationServiceManager()\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::createApplicationServiceManager\" );\n\n try\n {\n Reference xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext();\n Reference xMS(xComponentContext->getServiceManager(), UNO_QUERY);\n\n return xMS;\n }\n catch( ::com::sun::star::uno::Exception& )\n {\n }\n\n return Reference< XMultiServiceFactory >();\n}\n\nvoid destroyApplicationServiceManager( Reference< XMultiServiceFactory >& xSMgr )\n{\n Reference< XPropertySet > xProps( xSMgr, UNO_QUERY );\n if ( xProps.is() )\n {\n try\n {\n Reference< XComponent > xComp;\n if (xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( \"DefaultContext\" ))) >>= xComp )\n {\n xComp->dispose();\n }\n }\n catch ( UnknownPropertyException& )\n {\n }\n }\n}\n\nvoid registerServices( Reference< XMultiServiceFactory >& xSMgr )\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::registerServices\" );\n\n \/\/ read command line parameters\n ::rtl::OUString conDcp;\n ::rtl::OUString aClientDisplay;\n ::rtl::OUString aUserDir;\n ::rtl::OUString aTmpString;\n sal_Bool bHeadlessMode = sal_False;\n\n \/\/ interpret command line arguments\n CommandLineArgs* pCmdLine = GetCommandLineArgs();\n\n \/\/ read accept string from configuration\n if ( !Application::IsRemoteServer() )\n conDcp = SvtStartOptions().GetConnectionURL();\n\n if ( pCmdLine->GetAcceptString( aTmpString ))\n conDcp = aTmpString;\n pCmdLine->GetUserDir( aUserDir );\n\n if ( Application::IsRemoteServer() )\n {\n bHeadlessMode = pCmdLine->IsHeadless();\n pCmdLine->GetClientDisplay( aClientDisplay );\n }\n\n if ( bHeadlessMode )\n Application::EnableHeadlessMode();\n\n if ( conDcp.getLength() > 0 )\n {\n \/\/ accept incoming connections (scripting and one rvp)\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::OOfficeAcceptorThread::OOfficeAcceptorThread\" );\n pOfficeAcceptThread = new OOfficeAcceptorThread( xSMgr, conDcp, bHeadlessMode, aClientDisplay, aUserDir );\n pOfficeAcceptThread->create();\n }\n\n \/\/ improves parallel processing on Sun ONE Webtop\n \/\/ servicemanager up -> copy user installation\n if ( Application::IsRemoteServer() )\n {\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) createInstance com.sun.star.portal.InstallUser\" );\n Any aAny;\n Reference xRef = xSMgr->createInstanceWithArguments(\n OUString::createFromAscii( \"com.sun.star.portal.InstallUser\" ),\n Sequence( &aAny, 1 ) );\n }\n\n ::rtl::OUString aPortalConnect;\n bool bServer = (bool) pCmdLine->IsServer();\n\n pCmdLine->GetPortalConnectString( aPortalConnect );\n if ( !configureUcb( bServer, aPortalConnect ) )\n {\n DBG_ERROR( \"Can't configure UCB\" );\n exit(-1);\n }\n\n\/\/ UCB_Helper::Initialize(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n createTemporaryDirectory();\n}\n\nvoid createTemporaryDirectory()\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::createTemporaryDirectory\" );\n\n \/\/ remove possible old directory and base directory\n SvtPathOptions aOpt;\n SvtInternalOptions aInternalOpt;\n\n \/\/ set temp base directory\n ::rtl::OUString aTempBaseURL( aOpt.GetTempPath() );\n sal_Int32 nLength = aTempBaseURL.getLength();\n if ( aTempBaseURL.matchAsciiL( \"\/\", 1, nLength-1 ) )\n aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 );\n\n String aOldTempURL = aInternalOpt.GetCurrentTempURL();\n if ( aOldTempURL.Len() > 0 )\n {\n \/\/ remove old temporary directory\n ::utl::UCBContentHelper::Kill( aOldTempURL );\n }\n\n String aRet;\n ::rtl::OUString aTempPath( aTempBaseURL );\n\n \/\/ create new current temporary directory\n ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTempBaseURL, aRet );\n ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath );\n aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath );\n if ( !aTempPath.getLength() )\n {\n ::osl::File::getTempDirURL( aTempBaseURL );\n\n sal_Int32 nLength = aTempBaseURL.getLength();\n if ( aTempBaseURL.matchAsciiL( \"\/\", 1, nLength-1 ) )\n aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 );\n\n aTempPath = aTempBaseURL;\n ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath );\n aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath );\n }\n\n \/\/ set new current temporary directory\n ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aTempPath, aRet );\n aInternalOpt.SetCurrentTempURL( aRet );\n aCurrentTempURL = aRet;\n}\n\nvoid removeTemporaryDirectory()\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::removeTemporaryDirectory\" );\n\n \/\/ remove current temporary directory\n if ( aCurrentTempURL.Len() > 0 )\n {\n if ( ::utl::UCBContentHelper::Kill( aCurrentTempURL ) )\n SvtInternalOptions().SetCurrentTempURL( String() );\n }\n}\n#103426# Ignore -server cmdline parameter if not correcr env\/*************************************************************************\n *\n * $RCSfile: appinit.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: cd $ $Date: 2002-09-23 11:05:07 $\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 \"appinit.hxx\"\n#include \"cmdlineargs.hxx\"\n#include \"officeacceptthread.hxx\"\n\n#ifndef _COM_SUN_STAR_REGISTRY_XSIMPLEREGISTRY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_\n#include \n#endif\n\n#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_BOOTSTRAP_HXX_\n#include \n#endif\n#ifndef _OSL_FILE_HXX_\n#include \n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include \n#endif\n#ifndef _RTL_URI_HXX_\n#include \n#endif\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_REGPATHHELPER_HXX_\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _TOOLS_TEMPFILE_HXX\n#include \n#endif\n#ifndef _UCBHELPER_CONFIGURATIONKEYS_HXX_\n#include \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifndef INCLUDED_SVTOOLS_STARTOPTIONS_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX\n#include \n#endif\n#ifndef INCLUDED_SVTOOLS_INTERNALOPTIONS_HXX\n#include \n#endif\n\n#define DEFINE_CONST_UNICODE(CONSTASCII) UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII))\n#define DEFINE_CONST_OUSTRING(CONSTASCII) OUString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII))\n\n#define DESKTOP_TEMPDIRNAME \"soffice.tmp\"\n\nusing namespace rtl;\nusing namespace vos;\nusing namespace desktop;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::registry;\n\nextern desktop::CommandLineArgs* GetCommandLineArgs();\nextern desktop::OOfficeAcceptorThread* pOfficeAcceptThread;\n\nstatic String aCurrentTempURL;\n\n\n\/\/ -----------------------------------------------------------------------------\n\nstatic bool configureUcb(bool bServer, rtl::OUString const & rPortalConnect)\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (sb93797) ::configureUcb\" );\n Reference< XMultiServiceFactory >\n xServiceFactory( comphelper::getProcessServiceFactory() );\n if (!xServiceFactory.is())\n {\n DBG_ERROR(\"configureUcb(): No XMultiServiceFactory\");\n return false;\n }\n\n rtl::OUString aPipe;\n vos::OSecurity().getUserIdent(aPipe);\n\n rtl::OUStringBuffer aPortal;\n if (rPortalConnect.getLength() != 0)\n {\n aPortal.append(sal_Unicode(','));\n aPortal.append(rPortalConnect);\n }\n\n Sequence< Any > aArgs(6);\n aArgs[0]\n <<= rtl::OUString::createFromAscii(bServer ?\n UCB_CONFIGURATION_KEY1_SERVER :\n UCB_CONFIGURATION_KEY1_LOCAL);\n aArgs[1]\n <<= rtl::OUString::createFromAscii(UCB_CONFIGURATION_KEY2_OFFICE);\n aArgs[2] <<= rtl::OUString::createFromAscii(\"PIPE\");\n aArgs[3] <<= aPipe;\n aArgs[4] <<= rtl::OUString::createFromAscii(\"PORTAL\");\n aArgs[5] <<= aPortal.makeStringAndClear();\n\n return ::ucb::ContentBroker::initialize( xServiceFactory, aArgs ) != false;\n}\n\n\nReference< XMultiServiceFactory > createApplicationServiceManager()\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::createApplicationServiceManager\" );\n\n try\n {\n Reference xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext();\n Reference xMS(xComponentContext->getServiceManager(), UNO_QUERY);\n\n return xMS;\n }\n catch( ::com::sun::star::uno::Exception& )\n {\n }\n\n return Reference< XMultiServiceFactory >();\n}\n\nvoid destroyApplicationServiceManager( Reference< XMultiServiceFactory >& xSMgr )\n{\n Reference< XPropertySet > xProps( xSMgr, UNO_QUERY );\n if ( xProps.is() )\n {\n try\n {\n Reference< XComponent > xComp;\n if (xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( \"DefaultContext\" ))) >>= xComp )\n {\n xComp->dispose();\n }\n }\n catch ( UnknownPropertyException& )\n {\n }\n }\n}\n\nvoid registerServices( Reference< XMultiServiceFactory >& xSMgr )\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::registerServices\" );\n\n \/\/ read command line parameters\n ::rtl::OUString conDcp;\n ::rtl::OUString aClientDisplay;\n ::rtl::OUString aUserDir;\n ::rtl::OUString aTmpString;\n sal_Bool bHeadlessMode = sal_False;\n\n \/\/ interpret command line arguments\n CommandLineArgs* pCmdLine = GetCommandLineArgs();\n\n \/\/ read accept string from configuration\n if ( !Application::IsRemoteServer() )\n conDcp = SvtStartOptions().GetConnectionURL();\n\n if ( pCmdLine->GetAcceptString( aTmpString ))\n conDcp = aTmpString;\n pCmdLine->GetUserDir( aUserDir );\n\n if ( Application::IsRemoteServer() )\n {\n bHeadlessMode = pCmdLine->IsHeadless();\n pCmdLine->GetClientDisplay( aClientDisplay );\n }\n\n if ( bHeadlessMode )\n Application::EnableHeadlessMode();\n\n if ( conDcp.getLength() > 0 )\n {\n \/\/ accept incoming connections (scripting and one rvp)\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::OOfficeAcceptorThread::OOfficeAcceptorThread\" );\n pOfficeAcceptThread = new OOfficeAcceptorThread( xSMgr, conDcp, bHeadlessMode, aClientDisplay, aUserDir );\n pOfficeAcceptThread->create();\n }\n\n \/\/ improves parallel processing on Sun ONE Webtop\n \/\/ servicemanager up -> copy user installation\n if ( Application::IsRemoteServer() )\n {\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) createInstance com.sun.star.portal.InstallUser\" );\n Any aAny;\n Reference xRef = xSMgr->createInstanceWithArguments(\n OUString::createFromAscii( \"com.sun.star.portal.InstallUser\" ),\n Sequence( &aAny, 1 ) );\n }\n else if ( pCmdLine->IsServer() )\n {\n \/\/ Check some mandatory environment states if \"-server\" is possible. Otherwise ignore\n \/\/ this parameter.\n Reference< com::sun::star::container::XContentEnumerationAccess > rContent( xSMgr , UNO_QUERY );\n if( rContent.is() )\n {\n OUString sPortalService = OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.portal.InstallUser\" ) );\n Reference < com::sun::star::container::XEnumeration > rEnum = rContent->createContentEnumeration( sPortalService );\n if ( !rEnum.is() )\n {\n \/\/ Reset server parameter so it is ignored in the furthermore startup process\n pCmdLine->SetBoolParam( CommandLineArgs::CMD_BOOLPARAM_SERVER, sal_False );\n }\n }\n }\n\n ::rtl::OUString aPortalConnect;\n bool bServer = (bool) pCmdLine->IsServer();\n\n pCmdLine->GetPortalConnectString( aPortalConnect );\n if ( !configureUcb( bServer, aPortalConnect ) )\n {\n DBG_ERROR( \"Can't configure UCB\" );\n exit(-1);\n }\n\n\/\/ UCB_Helper::Initialize(); !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n createTemporaryDirectory();\n}\n\nvoid createTemporaryDirectory()\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::createTemporaryDirectory\" );\n\n \/\/ remove possible old directory and base directory\n SvtPathOptions aOpt;\n SvtInternalOptions aInternalOpt;\n\n \/\/ set temp base directory\n ::rtl::OUString aTempBaseURL( aOpt.GetTempPath() );\n sal_Int32 nLength = aTempBaseURL.getLength();\n if ( aTempBaseURL.matchAsciiL( \"\/\", 1, nLength-1 ) )\n aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 );\n\n String aOldTempURL = aInternalOpt.GetCurrentTempURL();\n if ( aOldTempURL.Len() > 0 )\n {\n \/\/ remove old temporary directory\n ::utl::UCBContentHelper::Kill( aOldTempURL );\n }\n\n String aRet;\n ::rtl::OUString aTempPath( aTempBaseURL );\n\n \/\/ create new current temporary directory\n ::utl::LocalFileHelper::ConvertURLToPhysicalName( aTempBaseURL, aRet );\n ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath );\n aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath );\n if ( !aTempPath.getLength() )\n {\n ::osl::File::getTempDirURL( aTempBaseURL );\n\n sal_Int32 nLength = aTempBaseURL.getLength();\n if ( aTempBaseURL.matchAsciiL( \"\/\", 1, nLength-1 ) )\n aTempBaseURL = aTempBaseURL.copy( 0, nLength - 1 );\n\n aTempPath = aTempBaseURL;\n ::osl::FileBase::getFileURLFromSystemPath( aRet, aTempPath );\n aTempPath = ::utl::TempFile::SetTempNameBaseDirectory( aTempPath );\n }\n\n \/\/ set new current temporary directory\n ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aTempPath, aRet );\n aInternalOpt.SetCurrentTempURL( aRet );\n aCurrentTempURL = aRet;\n}\n\nvoid removeTemporaryDirectory()\n{\n RTL_LOGFILE_CONTEXT( aLog, \"desktop (cd100003) ::removeTemporaryDirectory\" );\n\n \/\/ remove current temporary directory\n if ( aCurrentTempURL.Len() > 0 )\n {\n if ( ::utl::UCBContentHelper::Kill( aCurrentTempURL ) )\n SvtInternalOptions().SetCurrentTempURL( String() );\n }\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/reflex:$Id$\n\/\/ Author: Stefan Roiser 2006\n\n\/\/ Copyright CERN, CH-1211 Geneva 23, 2004-2010, All rights reserved.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\n#ifndef REFLEX_BUILD\n# define REFLEX_BUILD\n#endif\n\n#include \"NameLookup.h\"\n#include \"Reflex\/Base.h\"\n#include \"Reflex\/Scope.h\"\n#include \"Reflex\/Type.h\"\n#include \"Reflex\/Tools.h\"\n#include \"Reflex\/internal\/OwnedMember.h\"\n\n#include \n#include \n\n\/\/______________________________________________________________________________\nReflex::NameLookup::NameLookup(const std::string& name, const Scope& current):\n fLookupName(name),\n fPosNamePart(0),\n fPosNamePartLen(std::string::npos),\n fCurrentScope(current),\n fPartialSuccess(false) {\n \/\/ Initialize a NameLookup object used internally to keep track of lookup\n \/\/ states.\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Type\nReflex::NameLookup::LookupType(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup up a (possibly scoped) type name appearing in the scope context\n \/\/ current. This is the public interface for type lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Scope\nReflex::NameLookup::LookupScope(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup up a (possibly scoped) scope name appearing in the scope context\n \/\/ current. This is the public interface for scope lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\n\/*\n \/\/______________________________________________________________________________\n Reflex::Member LookupMember(const std::string& nam, const Scope& current )\n {\n \/\/ Lookup up a (possibly scoped) member name appearing in the scope context\n \/\/ current. This is the public interface for member lookup.\n NameLookup lookup(nam, current);\n \/\/ this will not work, member lookup is too different from type lookup...\n return lookup.Lookup();\n }\n *\/\n\n\/\/______________________________________________________________________________\ntemplate T\nReflex::NameLookup::Lookup(bool isTemplateExpanded \/* = false *\/) {\n \/\/ Lookup a type using fLookupName, fCurrentScope.\n\n Scope startScope = fCurrentScope;\n T result;\n\n fPartialSuccess = false;\n fPosNamePart = 0;\n fPosNamePartLen = std::string::npos;\n FindNextScopePos();\n\n if (fPosNamePart == 2) {\n fLookedAtUsingDir.clear();\n \/\/ ::A...\n fCurrentScope = Scope::GlobalScope();\n result = LookupInScope();\n } else {\n \/\/ A...\n result = LookupInUnknownScope();\n }\n\n if (!isTemplateExpanded && !result && fLookupName.find('<') != std::string::npos) {\n \/\/ We need to replace the template argument both of this type\n \/\/ and any of it enclosing type:\n \/\/ myspace::mytop::mytype\n\n std::ostringstream tmp;\n\n for (size_t i = 0, level = 0, sofar = 0; i < fLookupName.size(); ++i) {\n if (level == 0) {\n tmp << fLookupName.substr(sofar, i + 1 - sofar);\n sofar = i + 1;\n }\n\n switch (fLookupName[i]) {\n case '<': ++level; break;\n case '>': --level; \/\/ intentional fall through to the ',' case\n case ',':\n\n if (level == (1 - (unsigned int) (fLookupName[i] == '>'))) {\n std::string arg(fLookupName.substr(sofar, i - sofar));\n\n size_t p = arg.size();\n\n while (p > 0 && (arg[p - 1] == '*' || arg[p - 1] == '&' || arg[p - 1] == ' '))\n --p;\n\n std::string end(arg.substr(p));\n arg.erase(p);\n\n const char* start = arg.c_str();\n\n while (strncmp(start, \"const \", 6) == 0)\n start += 6;\n\n tmp << arg.substr(0, start - arg.c_str());\n\n while (strncmp(start, \"std::\", 5) == 0)\n start += 5;\n\n arg.erase(0, start - arg.c_str());\n\n Reflex::Type type(LookupType(arg, startScope));\n\n if (type) {\n if (type.Name() != \"Double32_t\" && type.Name() != \"Float16_t\") {\n \/\/ Use the real type rather than the typedef unless\n \/\/ this is Double32_t or Float16_t\n type = type.FinalType();\n }\n tmp << type.Name(Reflex::SCOPED | Reflex::QUALIFIED);\n } else {\n tmp << arg;\n }\n tmp << end;\n\n tmp << fLookupName[i];\n\n sofar = i + 1;\n }\n break;\n } \/\/ switch\n }\n NameLookup next(tmp.str(), startScope);\n return next.Lookup(true);\n }\n\n\n return result;\n} \/\/ Lookup\n\n\n\/\/______________________________________________________________________________\ntemplate T\nReflex::NameLookup::LookupInScope() {\n \/\/ Lookup a type in fCurrentScope.\n \/\/ Checks sub-types, sub-scopes, using directives, and base classes for\n \/\/ the name given by fLookupName, fPosNamePart, and fPosNamePartLen.\n \/\/ If the name part is found, and another name part follows in fPosNamePart,\n \/\/ LookupTypeInScope requests the scope found to lookup the next name\n \/\/ part. fPartialMatch reflexts that the left part of the name was matched;\n \/\/ even if the trailing part of fLookupName cannot be found, the lookup\n \/\/ cannot continue on declaring scopes and has to fail.\n \/\/ A list of lookups performed in namespaces pulled in via using directives is\n \/\/ kept in fLookedAtUsingDir, to prevent infinite loops due to\n \/\/ namespace A{using namespace B;} namespace B{using namespace A;}\n \/\/ loops.\n \/\/ The lookup does not take the declaration order into account; the result of\n \/\/ parts of the lookup algorithm which depend on the order will be unpredictable.\n\n if (!fCurrentScope) {\n return Dummy::Get();\n }\n\n \/\/ prevent inf loop from\n \/\/ ns A { using ns B; } ns B {using ns A;}\n if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end()) {\n return Dummy::Get();\n }\n\n \/\/ global scope can use hashed containers:\n if (fCurrentScope == Scope::GlobalScope()) {\n Type freeType(Type::ByName(fLookupName.c_str() + fPosNamePart));\n\n if (freeType.Id()) {\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: lookup up '%s', partial success with subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return freeType;\n }\n\n if (freeType.IsTypedef()) {\n fCurrentScope = freeType.FinalType();\n } else {\n fCurrentScope = freeType;\n }\n return LookupInScope();\n }\n\n Scope freeScope(Scope::ByName(fLookupName.c_str() + fPosNamePart));\n\n \/\/ only take namespaces into account - classes were checked as part of SubType\n if (freeScope.Id() && freeScope.IsNamespace()) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return (T) (freeScope);\n }\n fCurrentScope = freeScope;\n return LookupInScope();\n }\n } \/\/ end of: if global scope\n else {\n \/\/ if not global scope\n\n size_t len = fCurrentScope.SubTypeSize();\n size_t i = 0;\n\n for (Type_Iterator it = fCurrentScope.SubType_Begin(); i < len; ++it, ++i) {\n const Type& type = *it;\n const TypeBase* base = type.ToTypeBase();\n\n if (base) {\n size_t pos;\n const std::string& name(base->SimpleName(pos));\n\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: looking up '%s', considering subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: lookup up '%s', partial success with subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return type;\n }\n\n if (it->IsTypedef()) {\n fCurrentScope = it->FinalType();\n } else {\n fCurrentScope = type;\n }\n return LookupInScope();\n }\n }\n }\n\n Scope_Iterator subscope_end(fCurrentScope.SubScope_End());\n\n for (Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != subscope_end; ++in) {\n \/\/ only take namespaces into account - classes were checked as part of SubType\n if (in->IsNamespace()) {\n const Scope& scope = *in;\n const ScopeBase* base = scope.ToScopeBase();\n\n if (base) {\n size_t pos;\n const std::string& name(base->SimpleName(pos));\n\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return (T) (*in);\n }\n fCurrentScope = (Scope) (*in);\n return LookupInScope();\n }\n }\n }\n }\n } \/\/ end of: if not global scope\n\n if (fCurrentScope.UsingDirectiveSize()) {\n fLookedAtUsingDir.insert(fCurrentScope);\n Scope storeCurrentScope = fCurrentScope;\n Scope_Iterator usingscope_end(storeCurrentScope.UsingDirective_End());\n\n for (Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != usingscope_end; ++si) {\n fCurrentScope = *si;\n T t = LookupInScope();\n\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n if (!fPosNamePart) { \/\/ only for \"BaseClass...\", not for \"A::BaseClass...\"\n Base_Iterator base_end(fCurrentScope.Base_End());\n\n for (Base_Iterator bi = fCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n if (!fLookupName.compare(fPosNamePart, fPosNamePartLen, bi->Name())) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return bi->ToType();\n }\n fCurrentScope = bi->ToType().FinalType();\n return LookupInScope();\n }\n }\n }\n\n if (fCurrentScope.BaseSize()) {\n Scope storeCurrentScope = fCurrentScope;\n Base_Iterator base_end(storeCurrentScope.Base_End());\n\n for (Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n fCurrentScope = bi->ToScope();\n T t = LookupInScope();\n\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n return Dummy::Get();\n} \/\/ LookupInScope\n\n\n\/\/______________________________________________________________________________\ntemplate T\nReflex::NameLookup::LookupInUnknownScope() {\n \/\/ Lookup a type in fCurrentScope and its declaring scopes.\n for (fPartialSuccess = false; !fPartialSuccess && fCurrentScope; fCurrentScope = fCurrentScope.DeclaringScope()) {\n fLookedAtUsingDir.clear();\n T t = LookupInScope();\n\n if (fPartialSuccess) {\n return t;\n }\n\n if (fCurrentScope.IsTopScope()) {\n break;\n }\n }\n return Dummy::Get();\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Member\nReflex::NameLookup::LookupMember(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup a member.\n if (Tools::GetBasePosition(nam)) {\n return LookupMemberQualified(nam);\n }\n return LookupMemberUnqualified(nam, current);\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Member\nReflex::NameLookup::LookupMemberQualified(const std::string& nam) {\n \/\/ Lookup of a qualified member.\n Scope bscope = Scope::ByName(Tools::GetScopeName(nam));\n\n if (bscope) {\n return LookupMemberUnqualified(Tools::GetBaseName(nam), bscope);\n }\n return Dummy::Member();\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Member\nReflex::NameLookup::LookupMemberUnqualified(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup of an unqualified member.\n {\n Member m = current.MemberByName(nam);\n\n if (m) {\n return m;\n }\n }\n\n for (Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si) {\n Member m = LookupMember(nam, *si);\n\n if (m) {\n return m;\n }\n }\n\n for (Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++bi) {\n Member m = LookupMember(nam, bi->ToScope());\n\n if (m) {\n return m;\n }\n }\n\n if (!current.IsTopScope()) {\n return LookupMember(nam, current.DeclaringScope());\n }\n return Dummy::Member();\n} \/\/ LookupMemberUnqualified\n\n\n\/\/______________________________________________________________________________\nReflex::Type\nReflex::NameLookup::AccessControl(const Type& typ,\n const Scope& \/*current*\/) {\n \/\/ Check access.\n \/\/ if (typ.IsPublic()) {\n \/\/ return true;\n \/\/ }\n \/\/ else if (typ.IsProtected() && current.HasBase(typ.DeclaringScope())) {\n \/\/ return true;\n \/\/ }\n return typ;\n}\n\n\n\/\/______________________________________________________________________________\nvoid\nReflex::NameLookup::FindNextScopePos() {\n \/\/ Move fPosNamePart to point to the next scope in fLookupName, updating\n \/\/ fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize\n \/\/ fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart\n \/\/ will be set to std::string::npos and fPosNamePartLen will be set to 0.\n if (fPosNamePartLen != std::string::npos) {\n \/\/ we know the length, so jump\n fPosNamePart += fPosNamePartLen + 2;\n\n if (fPosNamePart > fLookupName.length()) {\n \/\/ past the string's end?\n fPosNamePart = std::string::npos;\n fPosNamePartLen = 0;\n return;\n }\n } else {\n \/\/ uninitialized\n \/\/ set fPosNamePartLen and check that fLookupName doesn't start with '::'\n fPosNamePart = 0;\n\n if (!fLookupName.compare(0, 2, \"::\")) {\n fPosNamePart = 2;\n }\n }\n size_t start = 0; \/\/ yes, we should use it... Think of \"int MyClass::*\" where the scope is \"MyClass\", not \"int MyClass\"\n fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart), start);\n\n if (!fPosNamePartLen) { \/\/ no next \"::\"\n fPosNamePartLen = fLookupName.length();\n } else { \/\/ no \"::\"\n fPosNamePartLen -= 2;\n }\n} \/\/ FindNextScopePos\nfix illegal initialisation of a const string& from a const char*\/\/ @(#)root\/reflex:$Id$\n\/\/ Author: Stefan Roiser 2006\n\n\/\/ Copyright CERN, CH-1211 Geneva 23, 2004-2010, All rights reserved.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\n#ifndef REFLEX_BUILD\n# define REFLEX_BUILD\n#endif\n\n#include \"NameLookup.h\"\n#include \"Reflex\/Base.h\"\n#include \"Reflex\/Scope.h\"\n#include \"Reflex\/Type.h\"\n#include \"Reflex\/Tools.h\"\n#include \"Reflex\/internal\/OwnedMember.h\"\n\n#include \n#include \n\n\/\/______________________________________________________________________________\nReflex::NameLookup::NameLookup(const std::string& name, const Scope& current):\n fLookupName(name),\n fPosNamePart(0),\n fPosNamePartLen(std::string::npos),\n fCurrentScope(current),\n fPartialSuccess(false) {\n \/\/ Initialize a NameLookup object used internally to keep track of lookup\n \/\/ states.\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Type\nReflex::NameLookup::LookupType(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup up a (possibly scoped) type name appearing in the scope context\n \/\/ current. This is the public interface for type lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Scope\nReflex::NameLookup::LookupScope(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup up a (possibly scoped) scope name appearing in the scope context\n \/\/ current. This is the public interface for scope lookup.\n NameLookup lookup(nam, current);\n return lookup.Lookup();\n}\n\n\n\/*\n \/\/______________________________________________________________________________\n Reflex::Member LookupMember(const std::string& nam, const Scope& current )\n {\n \/\/ Lookup up a (possibly scoped) member name appearing in the scope context\n \/\/ current. This is the public interface for member lookup.\n NameLookup lookup(nam, current);\n \/\/ this will not work, member lookup is too different from type lookup...\n return lookup.Lookup();\n }\n *\/\n\n\/\/______________________________________________________________________________\ntemplate T\nReflex::NameLookup::Lookup(bool isTemplateExpanded \/* = false *\/) {\n \/\/ Lookup a type using fLookupName, fCurrentScope.\n\n Scope startScope = fCurrentScope;\n T result;\n\n fPartialSuccess = false;\n fPosNamePart = 0;\n fPosNamePartLen = std::string::npos;\n FindNextScopePos();\n\n if (fPosNamePart == 2) {\n fLookedAtUsingDir.clear();\n \/\/ ::A...\n fCurrentScope = Scope::GlobalScope();\n result = LookupInScope();\n } else {\n \/\/ A...\n result = LookupInUnknownScope();\n }\n\n if (!isTemplateExpanded && !result && fLookupName.find('<') != std::string::npos) {\n \/\/ We need to replace the template argument both of this type\n \/\/ and any of it enclosing type:\n \/\/ myspace::mytop::mytype\n\n std::ostringstream tmp;\n\n for (size_t i = 0, level = 0, sofar = 0; i < fLookupName.size(); ++i) {\n if (level == 0) {\n tmp << fLookupName.substr(sofar, i + 1 - sofar);\n sofar = i + 1;\n }\n\n switch (fLookupName[i]) {\n case '<': ++level; break;\n case '>': --level; \/\/ intentional fall through to the ',' case\n case ',':\n\n if (level == (1 - (unsigned int) (fLookupName[i] == '>'))) {\n std::string arg(fLookupName.substr(sofar, i - sofar));\n\n size_t p = arg.size();\n\n while (p > 0 && (arg[p - 1] == '*' || arg[p - 1] == '&' || arg[p - 1] == ' '))\n --p;\n\n std::string end(arg.substr(p));\n arg.erase(p);\n\n const char* start = arg.c_str();\n\n while (strncmp(start, \"const \", 6) == 0)\n start += 6;\n\n tmp << arg.substr(0, start - arg.c_str());\n\n while (strncmp(start, \"std::\", 5) == 0)\n start += 5;\n\n arg.erase(0, start - arg.c_str());\n\n Reflex::Type type(LookupType(arg, startScope));\n\n if (type) {\n if (type.Name() != \"Double32_t\" && type.Name() != \"Float16_t\") {\n \/\/ Use the real type rather than the typedef unless\n \/\/ this is Double32_t or Float16_t\n type = type.FinalType();\n }\n tmp << type.Name(Reflex::SCOPED | Reflex::QUALIFIED);\n } else {\n tmp << arg;\n }\n tmp << end;\n\n tmp << fLookupName[i];\n\n sofar = i + 1;\n }\n break;\n } \/\/ switch\n }\n NameLookup next(tmp.str(), startScope);\n return next.Lookup(true);\n }\n\n\n return result;\n} \/\/ Lookup\n\n\n\/\/______________________________________________________________________________\ntemplate T\nReflex::NameLookup::LookupInScope() {\n \/\/ Lookup a type in fCurrentScope.\n \/\/ Checks sub-types, sub-scopes, using directives, and base classes for\n \/\/ the name given by fLookupName, fPosNamePart, and fPosNamePartLen.\n \/\/ If the name part is found, and another name part follows in fPosNamePart,\n \/\/ LookupTypeInScope requests the scope found to lookup the next name\n \/\/ part. fPartialMatch reflexts that the left part of the name was matched;\n \/\/ even if the trailing part of fLookupName cannot be found, the lookup\n \/\/ cannot continue on declaring scopes and has to fail.\n \/\/ A list of lookups performed in namespaces pulled in via using directives is\n \/\/ kept in fLookedAtUsingDir, to prevent infinite loops due to\n \/\/ namespace A{using namespace B;} namespace B{using namespace A;}\n \/\/ loops.\n \/\/ The lookup does not take the declaration order into account; the result of\n \/\/ parts of the lookup algorithm which depend on the order will be unpredictable.\n\n if (!fCurrentScope) {\n return Dummy::Get();\n }\n\n \/\/ prevent inf loop from\n \/\/ ns A { using ns B; } ns B {using ns A;}\n if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end()) {\n return Dummy::Get();\n }\n\n \/\/ global scope can use hashed containers:\n if (fCurrentScope == Scope::GlobalScope()) {\n Type freeType(Type::ByName(fLookupName.c_str() + fPosNamePart));\n\n if (freeType.Id()) {\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: lookup up '%s', partial success with subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return freeType;\n }\n\n if (freeType.IsTypedef()) {\n fCurrentScope = freeType.FinalType();\n } else {\n fCurrentScope = freeType;\n }\n return LookupInScope();\n }\n\n Scope freeScope(Scope::ByName(fLookupName.c_str() + fPosNamePart));\n\n \/\/ only take namespaces into account - classes were checked as part of SubType\n if (freeScope.Id() && freeScope.IsNamespace()) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return (T) (freeScope);\n }\n fCurrentScope = freeScope;\n return LookupInScope();\n }\n } \/\/ end of: if global scope\n else {\n \/\/ if not global scope\n\n size_t len = fCurrentScope.SubTypeSize();\n size_t i = 0;\n\n for (Type_Iterator it = fCurrentScope.SubType_Begin(); i < len; ++it, ++i) {\n const Type& type = *it;\n const TypeBase* base = type.ToTypeBase();\n\n if (base) {\n size_t pos;\n const std::string name(base->SimpleName(pos));\n\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: looking up '%s', considering subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n \/\/fprintf(stderr, \"Reflex::NameLookup::LookupInScope: lookup up '%s', partial success with subscope '%s' ...\\n\", fLookupName.c_str(), name.c_str());\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return type;\n }\n\n if (it->IsTypedef()) {\n fCurrentScope = it->FinalType();\n } else {\n fCurrentScope = type;\n }\n return LookupInScope();\n }\n }\n }\n\n Scope_Iterator subscope_end(fCurrentScope.SubScope_End());\n\n for (Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != subscope_end; ++in) {\n \/\/ only take namespaces into account - classes were checked as part of SubType\n if (in->IsNamespace()) {\n const Scope& scope = *in;\n const ScopeBase* base = scope.ToScopeBase();\n\n if (base) {\n size_t pos;\n const std::string name(base->SimpleName(pos));\n\n if (\n (fLookupName[fPosNamePart] == name[pos]) &&\n !fLookupName.compare(fPosNamePart, fPosNamePartLen, name, pos, name.length())\n ) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return (T) (*in);\n }\n fCurrentScope = (Scope) (*in);\n return LookupInScope();\n }\n }\n }\n }\n } \/\/ end of: if not global scope\n\n if (fCurrentScope.UsingDirectiveSize()) {\n fLookedAtUsingDir.insert(fCurrentScope);\n Scope storeCurrentScope = fCurrentScope;\n Scope_Iterator usingscope_end(storeCurrentScope.UsingDirective_End());\n\n for (Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != usingscope_end; ++si) {\n fCurrentScope = *si;\n T t = LookupInScope();\n\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n if (!fPosNamePart) { \/\/ only for \"BaseClass...\", not for \"A::BaseClass...\"\n Base_Iterator base_end(fCurrentScope.Base_End());\n\n for (Base_Iterator bi = fCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n if (!fLookupName.compare(fPosNamePart, fPosNamePartLen, bi->Name())) {\n fPartialSuccess = true;\n fLookedAtUsingDir.clear();\n FindNextScopePos();\n\n if (fPosNamePart == std::string::npos) {\n return bi->ToType();\n }\n fCurrentScope = bi->ToType().FinalType();\n return LookupInScope();\n }\n }\n }\n\n if (fCurrentScope.BaseSize()) {\n Scope storeCurrentScope = fCurrentScope;\n Base_Iterator base_end(storeCurrentScope.Base_End());\n\n for (Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != base_end; ++bi) {\n fCurrentScope = bi->ToScope();\n T t = LookupInScope();\n\n if (fPartialSuccess) {\n return t;\n }\n }\n fCurrentScope = storeCurrentScope;\n }\n\n return Dummy::Get();\n} \/\/ LookupInScope\n\n\n\/\/______________________________________________________________________________\ntemplate T\nReflex::NameLookup::LookupInUnknownScope() {\n \/\/ Lookup a type in fCurrentScope and its declaring scopes.\n for (fPartialSuccess = false; !fPartialSuccess && fCurrentScope; fCurrentScope = fCurrentScope.DeclaringScope()) {\n fLookedAtUsingDir.clear();\n T t = LookupInScope();\n\n if (fPartialSuccess) {\n return t;\n }\n\n if (fCurrentScope.IsTopScope()) {\n break;\n }\n }\n return Dummy::Get();\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Member\nReflex::NameLookup::LookupMember(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup a member.\n if (Tools::GetBasePosition(nam)) {\n return LookupMemberQualified(nam);\n }\n return LookupMemberUnqualified(nam, current);\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Member\nReflex::NameLookup::LookupMemberQualified(const std::string& nam) {\n \/\/ Lookup of a qualified member.\n Scope bscope = Scope::ByName(Tools::GetScopeName(nam));\n\n if (bscope) {\n return LookupMemberUnqualified(Tools::GetBaseName(nam), bscope);\n }\n return Dummy::Member();\n}\n\n\n\/\/______________________________________________________________________________\nReflex::Member\nReflex::NameLookup::LookupMemberUnqualified(const std::string& nam,\n const Scope& current) {\n \/\/ Lookup of an unqualified member.\n {\n Member m = current.MemberByName(nam);\n\n if (m) {\n return m;\n }\n }\n\n for (Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si) {\n Member m = LookupMember(nam, *si);\n\n if (m) {\n return m;\n }\n }\n\n for (Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++bi) {\n Member m = LookupMember(nam, bi->ToScope());\n\n if (m) {\n return m;\n }\n }\n\n if (!current.IsTopScope()) {\n return LookupMember(nam, current.DeclaringScope());\n }\n return Dummy::Member();\n} \/\/ LookupMemberUnqualified\n\n\n\/\/______________________________________________________________________________\nReflex::Type\nReflex::NameLookup::AccessControl(const Type& typ,\n const Scope& \/*current*\/) {\n \/\/ Check access.\n \/\/ if (typ.IsPublic()) {\n \/\/ return true;\n \/\/ }\n \/\/ else if (typ.IsProtected() && current.HasBase(typ.DeclaringScope())) {\n \/\/ return true;\n \/\/ }\n return typ;\n}\n\n\n\/\/______________________________________________________________________________\nvoid\nReflex::NameLookup::FindNextScopePos() {\n \/\/ Move fPosNamePart to point to the next scope in fLookupName, updating\n \/\/ fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize\n \/\/ fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart\n \/\/ will be set to std::string::npos and fPosNamePartLen will be set to 0.\n if (fPosNamePartLen != std::string::npos) {\n \/\/ we know the length, so jump\n fPosNamePart += fPosNamePartLen + 2;\n\n if (fPosNamePart > fLookupName.length()) {\n \/\/ past the string's end?\n fPosNamePart = std::string::npos;\n fPosNamePartLen = 0;\n return;\n }\n } else {\n \/\/ uninitialized\n \/\/ set fPosNamePartLen and check that fLookupName doesn't start with '::'\n fPosNamePart = 0;\n\n if (!fLookupName.compare(0, 2, \"::\")) {\n fPosNamePart = 2;\n }\n }\n size_t start = 0; \/\/ yes, we should use it... Think of \"int MyClass::*\" where the scope is \"MyClass\", not \"int MyClass\"\n fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart), start);\n\n if (!fPosNamePartLen) { \/\/ no next \"::\"\n fPosNamePartLen = fLookupName.length();\n } else { \/\/ no \"::\"\n fPosNamePartLen -= 2;\n }\n} \/\/ FindNextScopePos\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 \"remoting\/base\/encoder_vp8.h\"\n\n#include \"base\/logging.h\"\n#include \"media\/base\/callback.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/proto\/video.pb.h\"\n\nextern \"C\" {\n#define VPX_CODEC_DISABLE_COMPAT 1\n#include \"third_party\/libvpx\/source\/libvpx\/vpx\/vpx_codec.h\"\n#include \"third_party\/libvpx\/source\/libvpx\/vpx\/vpx_encoder.h\"\n#include \"third_party\/libvpx\/source\/libvpx\/vpx\/vp8cx.h\"\n}\n\nnamespace remoting {\n\nEncoderVp8::EncoderVp8()\n : initialized_(false),\n codec_(NULL),\n image_(NULL),\n last_timestamp_(0) {\n}\n\nEncoderVp8::~EncoderVp8() {\n if (initialized_) {\n vpx_codec_err_t ret = vpx_codec_destroy(codec_.get());\n DCHECK(ret == VPX_CODEC_OK) << \"Failed to destroy codec\";\n }\n}\n\nbool EncoderVp8::Init(int width, int height) {\n codec_.reset(new vpx_codec_ctx_t());\n image_.reset(new vpx_image_t());\n memset(image_.get(), 0, sizeof(vpx_image_t));\n\n image_->fmt = VPX_IMG_FMT_YV12;\n\n \/\/ libvpx seems to require both to be assigned.\n image_->d_w = width;\n image_->w = width;\n image_->d_h = height;\n image_->h = height;\n\n vpx_codec_enc_cfg_t config;\n const vpx_codec_iface_t* algo = vpx_codec_vp8_cx();\n CHECK(algo);\n vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0);\n if (ret != VPX_CODEC_OK)\n return false;\n\n \/\/ TODO(hclam): Tune the parameters to better suit the application.\n config.rc_target_bitrate = width * height * config.rc_target_bitrate\n \/ config.g_w \/ config.g_h;\n config.g_w = width;\n config.g_h = height;\n config.g_pass = VPX_RC_ONE_PASS;\n config.g_profile = 1;\n config.g_threads = 2;\n config.rc_min_quantizer = 0;\n config.rc_max_quantizer = 15;\n config.g_timebase.num = 1;\n config.g_timebase.den = 30;\n\n if (vpx_codec_enc_init(codec_.get(), algo, &config, 0))\n return false;\n return true;\n}\n\nstatic int clip_byte(int x) {\n if (x > 255)\n return 255;\n else if (x < 0)\n return 0;\n else\n return x;\n}\n\nbool EncoderVp8::PrepareImage(scoped_refptr capture_data) {\n const int plane_size = capture_data->width() * capture_data->height();\n\n if (!yuv_image_.get()) {\n\n \/\/ YUV image size is 1.5 times of a plane. Multiplication is performed first\n \/\/ to avoid rounding error.\n const int size = plane_size * 3 \/ 2;\n\n yuv_image_.reset(new uint8[size]);\n\n \/\/ Reset image value to 128 so we just need to fill in the y plane.\n memset(yuv_image_.get(), 128, size);\n\n \/\/ Fill in the information for |image_|.\n unsigned char* image = reinterpret_cast(yuv_image_.get());\n image_->planes[0] = image;\n image_->planes[1] = image + plane_size;\n\n \/\/ The V plane starts from 1.25 of the plane size.\n image_->planes[2] = image + plane_size + plane_size \/ 4;\n\n \/\/ In YV12 Y plane has full width, UV plane has half width because of\n \/\/ subsampling.\n image_->stride[0] = image_->w;\n image_->stride[1] = image_->w \/ 2;\n image_->stride[2] = image_->w \/ 2;\n }\n\n \/\/ And then do RGB->YUV conversion.\n \/\/ Currently we just produce the Y channel as the average of RGB. This will\n \/\/ giv ae gray scale image after conversion.\n \/\/ TODO(sergeyu): Move this code to a separate routine.\n \/\/ TODO(sergeyu): Optimize this code.\n DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32)\n << \"Only RGB32 is supported\";\n uint8* in = capture_data->data_planes().data[0];\n const int in_stride = capture_data->data_planes().strides[0];\n uint8* y_out = yuv_image_.get();\n uint8* u_out = yuv_image_.get() + plane_size;\n uint8* v_out = yuv_image_.get() + plane_size + plane_size \/ 4;\n const int out_stride = image_->stride[0];\n for (int i = 0; i < capture_data->height(); ++i) {\n for (int j = 0; j < capture_data->width(); ++j) {\n \/\/ Since the input pixel format is RGB32, there are 4 bytes per pixel.\n uint8* pixel = in + 4 * j;\n y_out[j] = clip_byte(((pixel[2] * 66 + pixel[1] * 129 +\n pixel[0] * 25 + 128) >> 8) + 16);\n if (i % 2 == 0 && j % 2 == 0) {\n u_out[j \/ 2] = clip_byte(((pixel[2] * -38 + pixel[1] * -74 +\n pixel[0] * 112 + 128) >> 8) + 128);\n v_out[j \/ 2] = clip_byte(((pixel[2] * 112 + pixel[1] * -94 +\n pixel[1] * -18 + 128) >> 8) + 128);\n }\n }\n in += in_stride;\n y_out += out_stride;\n if (i % 2 == 0) {\n u_out += out_stride \/ 2;\n v_out += out_stride \/ 2;\n }\n }\n return true;\n}\n\nvoid EncoderVp8::Encode(scoped_refptr capture_data,\n bool key_frame,\n DataAvailableCallback* data_available_callback) {\n if (!initialized_) {\n bool ret = Init(capture_data->width(), capture_data->height());\n \/\/ TODO(hclam): Handle error better.\n DCHECK(ret) << \"Initialization of encoder failed\";\n initialized_ = ret;\n }\n\n if (!PrepareImage(capture_data)) {\n NOTREACHED() << \"Can't image data for encoding\";\n }\n\n \/\/ Do the actual encoding.\n vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(),\n last_timestamp_,\n 1, 0, VPX_DL_REALTIME);\n DCHECK_EQ(ret, VPX_CODEC_OK)\n << \"Encoding error: \" << vpx_codec_err_to_string(ret) << \"\\n\"\n << \"Details: \" << vpx_codec_error(codec_.get()) << \"\\n\"\n << vpx_codec_error_detail(codec_.get());\n\n \/\/ TODO(hclam): fix this.\n last_timestamp_ += 100;\n\n \/\/ Read the encoded data.\n vpx_codec_iter_t iter = NULL;\n bool got_data = false;\n\n \/\/ TODO(hclam): Make sure we get exactly one frame from the packet.\n \/\/ TODO(hclam): We should provide the output buffer to avoid one copy.\n VideoPacket* message = new VideoPacket();\n\n while (!got_data) {\n const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(),\n &iter);\n if (!packet)\n continue;\n\n switch (packet->kind) {\n case VPX_CODEC_CX_FRAME_PKT:\n got_data = true;\n \/\/ TODO(sergeyu): Split each frame into multiple partitions.\n message->set_data(packet->data.frame.buf, packet->data.frame.sz);\n break;\n default:\n break;\n }\n }\n\n message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8);\n message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET |\n VideoPacket::LAST_PARTITION);\n\n data_available_callback->Run(message);\n delete data_available_callback;\n}\n\n} \/\/ namespace remoting\nChromoting host to convert only changed regions\/\/ 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 \"remoting\/base\/encoder_vp8.h\"\n\n#include \"base\/logging.h\"\n#include \"media\/base\/callback.h\"\n#include \"media\/base\/yuv_convert.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/proto\/video.pb.h\"\n\nextern \"C\" {\n#define VPX_CODEC_DISABLE_COMPAT 1\n#include \"third_party\/libvpx\/source\/libvpx\/vpx\/vpx_codec.h\"\n#include \"third_party\/libvpx\/source\/libvpx\/vpx\/vpx_encoder.h\"\n#include \"third_party\/libvpx\/source\/libvpx\/vpx\/vp8cx.h\"\n}\n\nnamespace remoting {\n\nEncoderVp8::EncoderVp8()\n : initialized_(false),\n codec_(NULL),\n image_(NULL),\n last_timestamp_(0) {\n}\n\nEncoderVp8::~EncoderVp8() {\n if (initialized_) {\n vpx_codec_err_t ret = vpx_codec_destroy(codec_.get());\n DCHECK(ret == VPX_CODEC_OK) << \"Failed to destroy codec\";\n }\n}\n\nbool EncoderVp8::Init(int width, int height) {\n codec_.reset(new vpx_codec_ctx_t());\n image_.reset(new vpx_image_t());\n memset(image_.get(), 0, sizeof(vpx_image_t));\n\n image_->fmt = VPX_IMG_FMT_YV12;\n\n \/\/ libvpx seems to require both to be assigned.\n image_->d_w = width;\n image_->w = width;\n image_->d_h = height;\n image_->h = height;\n\n vpx_codec_enc_cfg_t config;\n const vpx_codec_iface_t* algo = vpx_codec_vp8_cx();\n CHECK(algo);\n vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0);\n if (ret != VPX_CODEC_OK)\n return false;\n\n \/\/ TODO(hclam): Tune the parameters to better suit the application.\n config.rc_target_bitrate = width * height * config.rc_target_bitrate\n \/ config.g_w \/ config.g_h;\n config.g_w = width;\n config.g_h = height;\n config.g_pass = VPX_RC_ONE_PASS;\n config.g_profile = 1;\n config.g_threads = 2;\n config.rc_min_quantizer = 0;\n config.rc_max_quantizer = 15;\n config.g_timebase.num = 1;\n config.g_timebase.den = 30;\n\n if (vpx_codec_enc_init(codec_.get(), algo, &config, 0))\n return false;\n return true;\n}\n\nstatic int RoundToTwosMultiple(int x) {\n return x & (~1);\n}\n\n\/\/ Align the sides of the rectange to multiples of 2.\nstatic gfx::Rect AlignRect(const gfx::Rect& rect, int width, int height) {\n CHECK(rect.width() > 0 && rect.height() > 0);\n int x = RoundToTwosMultiple(rect.x());\n int y = RoundToTwosMultiple(rect.y());\n int right = std::min(RoundToTwosMultiple(rect.right() + 1),\n RoundToTwosMultiple(width));\n int bottom = std::min(RoundToTwosMultiple(rect.bottom() + 1),\n RoundToTwosMultiple(height));\n\n \/\/ Do the final check to make sure the width and height are not negative.\n gfx::Rect r(x, y, right - x, bottom - y);\n if (r.width() <= 0 || r.height() <= 0) {\n r.set_width(0);\n r.set_height(0);\n }\n return r;\n}\n\nbool EncoderVp8::PrepareImage(scoped_refptr capture_data) {\n const int plane_size = capture_data->width() * capture_data->height();\n\n if (!yuv_image_.get()) {\n\n \/\/ YUV image size is 1.5 times of a plane. Multiplication is performed first\n \/\/ to avoid rounding error.\n const int size = plane_size * 3 \/ 2;\n\n yuv_image_.reset(new uint8[size]);\n\n \/\/ Reset image value to 128 so we just need to fill in the y plane.\n memset(yuv_image_.get(), 128, size);\n\n \/\/ Fill in the information for |image_|.\n unsigned char* image = reinterpret_cast(yuv_image_.get());\n image_->planes[0] = image;\n image_->planes[1] = image + plane_size;\n\n \/\/ The V plane starts from 1.25 of the plane size.\n image_->planes[2] = image + plane_size + plane_size \/ 4;\n\n \/\/ In YV12 Y plane has full width, UV plane has half width because of\n \/\/ subsampling.\n image_->stride[0] = image_->w;\n image_->stride[1] = image_->w \/ 2;\n image_->stride[2] = image_->w \/ 2;\n }\n\n \/\/ Perform RGB->YUV conversion.\n if (capture_data->pixel_format() != media::VideoFrame::RGB32) {\n LOG(ERROR) << \"Only RGB32 is supported\";\n return false;\n }\n\n const InvalidRects& rects = capture_data->dirty_rects();\n const uint8* in = capture_data->data_planes().data[0];\n const int in_stride = capture_data->data_planes().strides[0];\n uint8* y_out = yuv_image_.get();\n uint8* u_out = yuv_image_.get() + plane_size;\n uint8* v_out = yuv_image_.get() + plane_size + plane_size \/ 4;\n const int y_stride = image_->stride[0];\n const int uv_stride = image_->stride[1];\n\n for (InvalidRects::const_iterator r = rects.begin(); r != rects.end(); ++r) {\n gfx::Rect rect = AlignRect(*r, image_->w, image_->h);\n int in_offset = in_stride * rect.y() + 4 * rect.x();\n int y_offset = y_stride * rect.y() + rect.x();\n int uv_offset = (uv_stride * rect.y() + rect.x()) \/ 2;\n\n media::ConvertRGB32ToYUV(in + in_offset,\n y_out + y_offset,\n u_out + uv_offset,\n v_out + uv_offset,\n rect.width(),\n rect.height(),\n in_stride,\n y_stride,\n uv_stride);\n }\n return true;\n}\n\nvoid EncoderVp8::Encode(scoped_refptr capture_data,\n bool key_frame,\n DataAvailableCallback* data_available_callback) {\n if (!initialized_) {\n bool ret = Init(capture_data->width(), capture_data->height());\n \/\/ TODO(hclam): Handle error better.\n DCHECK(ret) << \"Initialization of encoder failed\";\n initialized_ = ret;\n }\n\n if (!PrepareImage(capture_data)) {\n NOTREACHED() << \"Can't image data for encoding\";\n }\n\n \/\/ Do the actual encoding.\n vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(),\n last_timestamp_,\n 1, 0, VPX_DL_REALTIME);\n DCHECK_EQ(ret, VPX_CODEC_OK)\n << \"Encoding error: \" << vpx_codec_err_to_string(ret) << \"\\n\"\n << \"Details: \" << vpx_codec_error(codec_.get()) << \"\\n\"\n << vpx_codec_error_detail(codec_.get());\n\n \/\/ TODO(hclam): fix this.\n last_timestamp_ += 100;\n\n \/\/ Read the encoded data.\n vpx_codec_iter_t iter = NULL;\n bool got_data = false;\n\n \/\/ TODO(hclam): Make sure we get exactly one frame from the packet.\n \/\/ TODO(hclam): We should provide the output buffer to avoid one copy.\n VideoPacket* message = new VideoPacket();\n\n while (!got_data) {\n const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(),\n &iter);\n if (!packet)\n continue;\n\n switch (packet->kind) {\n case VPX_CODEC_CX_FRAME_PKT:\n got_data = true;\n \/\/ TODO(sergeyu): Split each frame into multiple partitions.\n message->set_data(packet->data.frame.buf, packet->data.frame.sz);\n break;\n default:\n break;\n }\n }\n\n message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8);\n message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET |\n VideoPacket::LAST_PARTITION);\n\n data_available_callback->Run(message);\n delete data_available_callback;\n}\n\n} \/\/ namespace remoting\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 \"base\/logging.h\"\n#include \"media\/base\/callback.h\"\n#include \"media\/base\/media.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/base\/encoder_vp8.h\"\n#include \"remoting\/proto\/video.pb.h\"\n\nextern \"C\" {\n#define VPX_CODEC_DISABLE_COMPAT 1\n#include \"third_party\/libvpx\/include\/vpx\/vpx_codec.h\"\n#include \"third_party\/libvpx\/include\/vpx\/vpx_encoder.h\"\n#include \"third_party\/libvpx\/include\/vpx\/vp8cx.h\"\n}\n\nnamespace remoting {\n\nEncoderVp8::EncoderVp8()\n : initialized_(false),\n codec_(NULL),\n image_(NULL),\n last_timestamp_(0) {\n}\n\nEncoderVp8::~EncoderVp8() {\n if (initialized_) {\n vpx_codec_err_t ret = vpx_codec_destroy(codec_.get());\n DCHECK(ret == VPX_CODEC_OK) << \"Failed to destroy codec\";\n }\n}\n\nbool EncoderVp8::Init(int width, int height) {\n codec_.reset(new vpx_codec_ctx_t());\n image_.reset(new vpx_image_t());\n memset(image_.get(), 0, sizeof(vpx_image_t));\n\n image_->fmt = VPX_IMG_FMT_YV12;\n\n \/\/ libvpx seems to require both to be assigned.\n image_->d_w = width;\n image_->w = width;\n image_->d_h = height;\n image_->h = height;\n\n vpx_codec_enc_cfg_t config;\n const vpx_codec_iface_t* algo =\n (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress();\n CHECK(algo);\n vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0);\n if (ret != VPX_CODEC_OK)\n return false;\n\n \/\/ TODO(hclam): Tune the parameters to better suit the application.\n config.rc_target_bitrate = width * height * config.rc_target_bitrate\n \/ config.g_w \/ config.g_h;\n config.g_w = width;\n config.g_h = height;\n config.g_pass = VPX_RC_ONE_PASS;\n config.g_profile = 1;\n config.g_threads = 2;\n config.rc_min_quantizer = 0;\n config.rc_max_quantizer = 15;\n config.g_timebase.num = 1;\n config.g_timebase.den = 30;\n\n if (vpx_codec_enc_init(codec_.get(), algo, &config, 0))\n return false;\n return true;\n}\n\nstatic int clip_byte(int x) {\n if (x > 255)\n return 255;\n else if (x < 0)\n return 0;\n else\n return x;\n}\n\nbool EncoderVp8::PrepareImage(scoped_refptr capture_data) {\n const int plane_size = capture_data->width() * capture_data->height();\n\n if (!yuv_image_.get()) {\n\n \/\/ YUV image size is 1.5 times of a plane. Multiplication is performed first\n \/\/ to avoid rounding error.\n const int size = plane_size * 3 \/ 2;\n\n yuv_image_.reset(new uint8[size]);\n\n \/\/ Reset image value to 128 so we just need to fill in the y plane.\n memset(yuv_image_.get(), 128, size);\n\n \/\/ Fill in the information for |image_|.\n unsigned char* image = reinterpret_cast(yuv_image_.get());\n image_->planes[0] = image;\n image_->planes[1] = image + plane_size;\n\n \/\/ The V plane starts from 1.25 of the plane size.\n image_->planes[2] = image + plane_size + plane_size \/ 4;\n\n \/\/ In YV12 Y plane has full width, UV plane has half width because of\n \/\/ subsampling.\n image_->stride[0] = image_->w;\n image_->stride[1] = image_->w \/ 2;\n image_->stride[2] = image_->w \/ 2;\n }\n\n \/\/ And then do RGB->YUV conversion.\n \/\/ Currently we just produce the Y channel as the average of RGB. This will\n \/\/ giv ae gray scale image after conversion.\n \/\/ TODO(sergeyu): Move this code to a separate routine.\n \/\/ TODO(sergeyu): Optimize this code.\n DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32)\n << \"Only RGB32 is supported\";\n uint8* in = capture_data->data_planes().data[0];\n const int in_stride = capture_data->data_planes().strides[0];\n uint8* y_out = yuv_image_.get();\n uint8* u_out = yuv_image_.get() + plane_size;\n uint8* v_out = yuv_image_.get() + plane_size + plane_size \/ 4;\n const int out_stride = image_->stride[0];\n for (int i = 0; i < capture_data->height(); ++i) {\n for (int j = 0; j < capture_data->width(); ++j) {\n \/\/ Since the input pixel format is RGB32, there are 4 bytes per pixel.\n uint8* pixel = in + 4 * j;\n y_out[j] = clip_byte(((pixel[0] * 66 + pixel[1] * 129 +\n pixel[2] * 25 + 128) >> 8) + 16);\n if (i % 2 == 0 && j % 2 == 0) {\n u_out[j \/ 2] = clip_byte(((pixel[0] * -38 + pixel[1] * -74 +\n pixel[2] * 112 + 128) >> 8) + 128);\n v_out[j \/ 2] = clip_byte(((pixel[0] * 112 + pixel[1] * -94 +\n pixel[2] * -18 + 128) >> 8) + 128);\n }\n }\n in += in_stride;\n y_out += out_stride;\n if (i % 2 == 0) {\n u_out += out_stride \/ 2;\n v_out += out_stride \/ 2;\n }\n }\n return true;\n}\n\nvoid EncoderVp8::Encode(scoped_refptr capture_data,\n bool key_frame,\n DataAvailableCallback* data_available_callback) {\n if (!initialized_) {\n bool ret = Init(capture_data->width(), capture_data->height());\n \/\/ TODO(hclam): Handle error better.\n DCHECK(ret) << \"Initialization of encoder failed\";\n initialized_ = ret;\n }\n\n if (!PrepareImage(capture_data)) {\n NOTREACHED() << \"Can't image data for encoding\";\n }\n\n \/\/ Do the actual encoding.\n vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(),\n last_timestamp_,\n 1, 0, VPX_DL_REALTIME);\n DCHECK_EQ(ret, VPX_CODEC_OK)\n << \"Encoding error: \" << vpx_codec_err_to_string(ret) << \"\\n\"\n << \"Details: \" << vpx_codec_error(codec_.get()) << \"\\n\"\n << vpx_codec_error_detail(codec_.get());\n\n \/\/ TODO(hclam): fix this.\n last_timestamp_ += 100;\n\n \/\/ Read the encoded data.\n vpx_codec_iter_t iter = NULL;\n bool got_data = false;\n\n \/\/ TODO(hclam): Make sure we get exactly one frame from the packet.\n \/\/ TODO(hclam): We should provide the output buffer to avoid one copy.\n VideoPacket* message = new VideoPacket();\n\n while (!got_data) {\n const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(),\n &iter);\n if (!packet)\n continue;\n\n switch (packet->kind) {\n case VPX_CODEC_CX_FRAME_PKT:\n got_data = true;\n message->set_data(packet->data.frame.buf, packet->data.frame.sz);\n break;\n default:\n break;\n }\n }\n\n message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8);\n message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET);\n\n data_available_callback->Run(message);\n delete data_available_callback;\n}\n\n} \/\/ namespace remoting\nRefactor ZLib and Verbatim encoders.\/\/ 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 \"base\/logging.h\"\n#include \"media\/base\/callback.h\"\n#include \"media\/base\/media.h\"\n#include \"remoting\/base\/capture_data.h\"\n#include \"remoting\/base\/encoder_vp8.h\"\n#include \"remoting\/proto\/video.pb.h\"\n\nextern \"C\" {\n#define VPX_CODEC_DISABLE_COMPAT 1\n#include \"third_party\/libvpx\/include\/vpx\/vpx_codec.h\"\n#include \"third_party\/libvpx\/include\/vpx\/vpx_encoder.h\"\n#include \"third_party\/libvpx\/include\/vpx\/vp8cx.h\"\n}\n\nnamespace remoting {\n\nEncoderVp8::EncoderVp8()\n : initialized_(false),\n codec_(NULL),\n image_(NULL),\n last_timestamp_(0) {\n}\n\nEncoderVp8::~EncoderVp8() {\n if (initialized_) {\n vpx_codec_err_t ret = vpx_codec_destroy(codec_.get());\n DCHECK(ret == VPX_CODEC_OK) << \"Failed to destroy codec\";\n }\n}\n\nbool EncoderVp8::Init(int width, int height) {\n codec_.reset(new vpx_codec_ctx_t());\n image_.reset(new vpx_image_t());\n memset(image_.get(), 0, sizeof(vpx_image_t));\n\n image_->fmt = VPX_IMG_FMT_YV12;\n\n \/\/ libvpx seems to require both to be assigned.\n image_->d_w = width;\n image_->w = width;\n image_->d_h = height;\n image_->h = height;\n\n vpx_codec_enc_cfg_t config;\n const vpx_codec_iface_t* algo =\n (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress();\n CHECK(algo);\n vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0);\n if (ret != VPX_CODEC_OK)\n return false;\n\n \/\/ TODO(hclam): Tune the parameters to better suit the application.\n config.rc_target_bitrate = width * height * config.rc_target_bitrate\n \/ config.g_w \/ config.g_h;\n config.g_w = width;\n config.g_h = height;\n config.g_pass = VPX_RC_ONE_PASS;\n config.g_profile = 1;\n config.g_threads = 2;\n config.rc_min_quantizer = 0;\n config.rc_max_quantizer = 15;\n config.g_timebase.num = 1;\n config.g_timebase.den = 30;\n\n if (vpx_codec_enc_init(codec_.get(), algo, &config, 0))\n return false;\n return true;\n}\n\nstatic int clip_byte(int x) {\n if (x > 255)\n return 255;\n else if (x < 0)\n return 0;\n else\n return x;\n}\n\nbool EncoderVp8::PrepareImage(scoped_refptr capture_data) {\n const int plane_size = capture_data->width() * capture_data->height();\n\n if (!yuv_image_.get()) {\n\n \/\/ YUV image size is 1.5 times of a plane. Multiplication is performed first\n \/\/ to avoid rounding error.\n const int size = plane_size * 3 \/ 2;\n\n yuv_image_.reset(new uint8[size]);\n\n \/\/ Reset image value to 128 so we just need to fill in the y plane.\n memset(yuv_image_.get(), 128, size);\n\n \/\/ Fill in the information for |image_|.\n unsigned char* image = reinterpret_cast(yuv_image_.get());\n image_->planes[0] = image;\n image_->planes[1] = image + plane_size;\n\n \/\/ The V plane starts from 1.25 of the plane size.\n image_->planes[2] = image + plane_size + plane_size \/ 4;\n\n \/\/ In YV12 Y plane has full width, UV plane has half width because of\n \/\/ subsampling.\n image_->stride[0] = image_->w;\n image_->stride[1] = image_->w \/ 2;\n image_->stride[2] = image_->w \/ 2;\n }\n\n \/\/ And then do RGB->YUV conversion.\n \/\/ Currently we just produce the Y channel as the average of RGB. This will\n \/\/ giv ae gray scale image after conversion.\n \/\/ TODO(sergeyu): Move this code to a separate routine.\n \/\/ TODO(sergeyu): Optimize this code.\n DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32)\n << \"Only RGB32 is supported\";\n uint8* in = capture_data->data_planes().data[0];\n const int in_stride = capture_data->data_planes().strides[0];\n uint8* y_out = yuv_image_.get();\n uint8* u_out = yuv_image_.get() + plane_size;\n uint8* v_out = yuv_image_.get() + plane_size + plane_size \/ 4;\n const int out_stride = image_->stride[0];\n for (int i = 0; i < capture_data->height(); ++i) {\n for (int j = 0; j < capture_data->width(); ++j) {\n \/\/ Since the input pixel format is RGB32, there are 4 bytes per pixel.\n uint8* pixel = in + 4 * j;\n y_out[j] = clip_byte(((pixel[2] * 66 + pixel[1] * 129 +\n pixel[0] * 25 + 128) >> 8) + 16);\n if (i % 2 == 0 && j % 2 == 0) {\n u_out[j \/ 2] = clip_byte(((pixel[2] * -38 + pixel[1] * -74 +\n pixel[0] * 112 + 128) >> 8) + 128);\n v_out[j \/ 2] = clip_byte(((pixel[2] * 112 + pixel[1] * -94 +\n pixel[1] * -18 + 128) >> 8) + 128);\n }\n }\n in += in_stride;\n y_out += out_stride;\n if (i % 2 == 0) {\n u_out += out_stride \/ 2;\n v_out += out_stride \/ 2;\n }\n }\n return true;\n}\n\nvoid EncoderVp8::Encode(scoped_refptr capture_data,\n bool key_frame,\n DataAvailableCallback* data_available_callback) {\n if (!initialized_) {\n bool ret = Init(capture_data->width(), capture_data->height());\n \/\/ TODO(hclam): Handle error better.\n DCHECK(ret) << \"Initialization of encoder failed\";\n initialized_ = ret;\n }\n\n if (!PrepareImage(capture_data)) {\n NOTREACHED() << \"Can't image data for encoding\";\n }\n\n \/\/ Do the actual encoding.\n vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(),\n last_timestamp_,\n 1, 0, VPX_DL_REALTIME);\n DCHECK_EQ(ret, VPX_CODEC_OK)\n << \"Encoding error: \" << vpx_codec_err_to_string(ret) << \"\\n\"\n << \"Details: \" << vpx_codec_error(codec_.get()) << \"\\n\"\n << vpx_codec_error_detail(codec_.get());\n\n \/\/ TODO(hclam): fix this.\n last_timestamp_ += 100;\n\n \/\/ Read the encoded data.\n vpx_codec_iter_t iter = NULL;\n bool got_data = false;\n\n \/\/ TODO(hclam): Make sure we get exactly one frame from the packet.\n \/\/ TODO(hclam): We should provide the output buffer to avoid one copy.\n VideoPacket* message = new VideoPacket();\n\n while (!got_data) {\n const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(),\n &iter);\n if (!packet)\n continue;\n\n switch (packet->kind) {\n case VPX_CODEC_CX_FRAME_PKT:\n got_data = true;\n message->set_data(packet->data.frame.buf, packet->data.frame.sz);\n break;\n default:\n break;\n }\n }\n\n message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8);\n message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET);\n\n data_available_callback->Run(message);\n delete data_available_callback;\n}\n\n} \/\/ namespace remoting\n<|endoftext|>"} {"text":"\/*\n\n Copyright (c) 2013, Ford Motor Company\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided with the\n distribution.\n\n Neither the name of the Ford Motor Company nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \"application_manager\/commands\/mobile\/perform_audio_pass_thru_request.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/application_impl.h\"\n#include \"application_manager\/message_helper.h\"\n#include \"config_profile\/profile.h\"\n#include \"utils\/helpers.h\"\n\nnamespace application_manager {\n\nnamespace commands {\n\nnamespace str = strings;\n\nPerformAudioPassThruRequest::PerformAudioPassThruRequest(\n const MessageSharedPtr& message)\n : CommandRequestImpl(message),\n is_active_tts_speak_(false),\n result_tts_speak_(mobile_apis::Result::SUCCESS) {\n subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout);\n}\n\nPerformAudioPassThruRequest::~PerformAudioPassThruRequest() {\n}\n\nvoid PerformAudioPassThruRequest::onTimeOut() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n FinishTTSSpeak();\n CommandRequestImpl::onTimeOut();\n}\n\nbool PerformAudioPassThruRequest::Init() {\n default_timeout_ +=\n (((*message_)[str::msg_params][str::max_duration].asUInt()));\n return true;\n}\n\nvoid PerformAudioPassThruRequest::Run() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n ApplicationSharedPtr app =\n ApplicationManagerImpl::instance()->application(connection_key());\n\n if (!app) {\n LOG4CXX_ERROR(logger_, \"APPLICATION_NOT_REGISTERED\");\n SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);\n return;\n }\n\n if (mobile_api::HMILevel::HMI_NONE == app->hmi_level()) {\n LOG4CXX_ERROR(logger_, \"application isn't activated\");\n SendResponse(false, mobile_apis::Result::REJECTED);\n return;\n }\n\n if (IsWhiteSpaceExist()) {\n LOG4CXX_ERROR(logger_,\n \"Incoming perform audio pass thru has contains \"\n \"\\\\t\\\\n \\\\\\\\t \\\\\\\\n\"\n \" text contains only whitespace in initialPrompt\");\n SendResponse(false, mobile_apis::Result::INVALID_DATA);\n return;\n }\n\n if ((*message_)[str::msg_params].keyExists(str::initial_prompt) &&\n (0 < (*message_)[str::msg_params][str::initial_prompt].length())) {\n \/\/ In case TTS Speak, subscribe on notification\n SendSpeakRequest();\n SendPerformAudioPassThruRequest();\n } else {\n SendPerformAudioPassThruRequest();\n SendRecordStartNotification();\n StartMicrophoneRecording();\n }\n}\n\nvoid PerformAudioPassThruRequest::on_event(const event_engine::Event& event) {\n LOG4CXX_AUTO_TRACE(logger_);\n using namespace helpers;\n\n const smart_objects::SmartObject& message = event.smart_object();\n\n switch (event.id()) {\n case hmi_apis::FunctionID::UI_PerformAudioPassThru: {\n LOG4CXX_INFO(logger_, \"Received UI_PerformAudioPassThru\");\n\n if (!WaitTTSSpeak())\n return;\n\n mobile_apis::Result::eType mobile_code =\n GetMobileResultCode(static_cast(\n message[strings::params][hmi_response::code].asUInt()));\n\n \/\/ in case perform audio is started by other request skip stopping\n if (mobile_apis::Result::REJECTED == mobile_code) {\n LOG4CXX_ERROR(logger_, \"Request was rejected\");\n SendResponse(false, mobile_code, NULL, &(message[strings::msg_params]));\n return;\n }\n\n FinishTTSSpeak();\n\n std::string return_info;\n const bool result =\n Compare(\n mobile_code,\n mobile_apis::Result::SUCCESS,\n mobile_apis::Result::RETRY,\n mobile_apis::Result::WARNINGS);\n\n const bool is_result_ok =\n Compare(\n mobile_code,\n mobile_apis::Result::SUCCESS,\n mobile_apis::Result::WARNINGS);\n\n if (is_result_ok &&\n mobile_apis::Result::UNSUPPORTED_RESOURCE == result_tts_speak_) {\n mobile_code = mobile_apis::Result::WARNINGS;\n return_info = \"Unsupported phoneme type sent in a prompt\";\n }\n\n SendResponse(result, mobile_code, return_info.c_str(),\n &(message[strings::msg_params]));\n break;\n }\n case hmi_apis::FunctionID::TTS_Speak: {\n LOG4CXX_INFO(logger_, \"Received TTS_Speak event\");\n result_tts_speak_ = GetMobileResultCode(\n static_cast(\n message[strings::params][hmi_response::code].asUInt()));\n is_active_tts_speak_ = false;\n if (mobile_apis::Result::SUCCESS == result_tts_speak_) {\n SendRecordStartNotification();\n StartMicrophoneRecording();\n\n \/\/ update request timeout to get time for perform audio recording\n ApplicationManagerImpl::instance()->\n updateRequestTimeout(connection_key(),\n correlation_id(),\n default_timeout());\n }\n break;\n }\n case hmi_apis::FunctionID::TTS_OnResetTimeout: {\n LOG4CXX_INFO(logger_, \"Received TTS_OnResetTimeout event\");\n\n ApplicationManagerImpl::instance()->updateRequestTimeout(\n connection_key(), correlation_id(), default_timeout());\n break;\n }\n default: {\n LOG4CXX_ERROR(logger_, \"Received unknown event\" << event.id());\n return;\n }\n }\n}\n\nvoid PerformAudioPassThruRequest::SendSpeakRequest() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n using namespace hmi_apis;\n using namespace smart_objects;\n\n SmartObject msg_params = smart_objects::SmartObject(SmartType_Map);\n\n if ((*message_)[str::msg_params].keyExists(str::initial_prompt) &&\n (0 < (*message_)[str::msg_params][str::initial_prompt].length())) {\n for (uint32_t i = 0;\n i < (*message_)[str::msg_params][str::initial_prompt].length();\n ++i) {\n msg_params[hmi_request::tts_chunks][i][str::text] =\n (*message_)[str::msg_params][str::initial_prompt][i][str::text];\n msg_params[hmi_request::tts_chunks][i][str::type] =\n (*message_)[str::msg_params][str::initial_prompt][i][str::type];\n }\n \/\/ app_id\n msg_params[strings::app_id] = connection_key();\n msg_params[hmi_request::speak_type] = Common_MethodName::AUDIO_PASS_THRU;\n is_active_tts_speak_ = true;\n SendHMIRequest(FunctionID::TTS_Speak, &msg_params, true);\n }\n}\n\nvoid PerformAudioPassThruRequest::SendPerformAudioPassThruRequest() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n smart_objects::SmartObject msg_params = smart_objects::SmartObject(\n smart_objects::SmartType_Map);\n\n msg_params[str::app_id] = connection_key();\n\n msg_params[hmi_request::max_duration] =\n (*message_)[str::msg_params][str::max_duration];\n\n msg_params[hmi_request::audio_pass_display_texts] =\n smart_objects::SmartObject(smart_objects::SmartType_Array);\n\n if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text1)) {\n msg_params[hmi_request::audio_pass_display_texts]\n [0][hmi_request::field_name] = static_cast\n (hmi_apis::Common_TextFieldName::audioPassThruDisplayText1);\n msg_params[hmi_request::audio_pass_display_texts]\n [0][hmi_request::field_text] =\n (*message_)[str::msg_params][str::audio_pass_display_text1];\n }\n\n if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text2)) {\n msg_params[hmi_request::audio_pass_display_texts]\n [1][hmi_request::field_name] = static_cast\n (hmi_apis::Common_TextFieldName::audioPassThruDisplayText2);\n msg_params[hmi_request::audio_pass_display_texts]\n [1][hmi_request::field_text] =\n (*message_)[str::msg_params][str::audio_pass_display_text2];\n }\n\n if ((*message_)[str::msg_params].keyExists(str::mute_audio)) {\n msg_params[str::mute_audio] =\n (*message_)[str::msg_params][str::mute_audio].asBool();\n } else {\n \/\/ If omitted, the value is set to true\n msg_params[str::mute_audio] = true;\n }\n\n SendHMIRequest(hmi_apis::FunctionID::UI_PerformAudioPassThru,\n &msg_params, true);\n}\n\nvoid PerformAudioPassThruRequest::SendRecordStartNotification() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n smart_objects::SmartObject msg_params = smart_objects::SmartObject(\n smart_objects::SmartType_Map);\n msg_params[strings::app_id] = connection_key();\n\n CreateHMINotification(hmi_apis::FunctionID::UI_OnRecordStart, msg_params);\n}\n\nvoid PerformAudioPassThruRequest::StartMicrophoneRecording() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n ApplicationManagerImpl::instance()->begin_audio_pass_thru();\n\n ApplicationManagerImpl::instance()->StartAudioPassThruThread(\n connection_key(), correlation_id(),\n (*message_)[str::msg_params][str::max_duration].asInt(),\n (*message_)[str::msg_params][str::sampling_rate].asInt(),\n (*message_)[str::msg_params][str::bits_per_sample].asInt(),\n (*message_)[str::msg_params][str::audio_type].asInt());\n}\n\nbool PerformAudioPassThruRequest::IsWhiteSpaceExist() {\n LOG4CXX_AUTO_TRACE(logger_);\n const char* str = NULL;\n\n if ((*message_)[strings::msg_params].keyExists(strings::initial_prompt)) {\n const smart_objects::SmartArray* ip_array =\n (*message_)[strings::msg_params][strings::initial_prompt].asArray();\n\n smart_objects::SmartArray::const_iterator it_ip = ip_array->begin();\n smart_objects::SmartArray::const_iterator it_ip_end = ip_array->end();\n\n for (; it_ip != it_ip_end; ++it_ip) {\n str = (*it_ip)[strings::text].asCharArray();\n if (strlen(str) && !CheckSyntax(str)) {\n LOG4CXX_ERROR(logger_, \"Invalid initial_prompt syntax check failed\");\n return true;\n }\n }\n }\n\n if ((*message_)[strings::msg_params].\n keyExists(strings::audio_pass_display_text1)) {\n\n str = (*message_)[strings::msg_params]\n [strings::audio_pass_display_text1].asCharArray();\n if (!CheckSyntax(str)) {\n LOG4CXX_ERROR(logger_,\n \"Invalid audio_pass_display_text1 value syntax check failed\");\n return true;\n }\n }\n\n if ((*message_)[strings::msg_params].\n keyExists(strings::audio_pass_display_text2)) {\n\n str = (*message_)[strings::msg_params]\n [strings::audio_pass_display_text2].asCharArray();\n if (!CheckSyntax(str)) {\n LOG4CXX_ERROR(logger_,\n \"Invalid audio_pass_display_text2 value syntax check failed\");\n return true;\n }\n }\n return false;\n}\n\nvoid PerformAudioPassThruRequest::FinishTTSSpeak(){\n LOG4CXX_AUTO_TRACE(logger_);\n if (ApplicationManagerImpl::instance()->end_audio_pass_thru()) {\n ApplicationManagerImpl::instance()->\n StopAudioPassThru(connection_key());\n }\n if (!is_active_tts_speak_) {\n LOG4CXX_DEBUG(logger_, \"TTS Speak is inactive.\");\n return;\n }\n is_active_tts_speak_ = false;\n SendHMIRequest(hmi_apis::FunctionID::TTS_StopSpeaking, NULL);\n}\n\nbool PerformAudioPassThruRequest::WaitTTSSpeak() {\n LOG4CXX_AUTO_TRACE(logger_);\n uint32_t default_timeout_msec =\n profile::Profile::instance()->default_timeout();\n TimevalStruct start_time = date_time::DateTime::getCurrentTime();\n\n \/\/ Waiting for TTS_Speak\n while (is_active_tts_speak_) {\n int64_t difference_between_start_current_time\n = date_time::DateTime::calculateTimeSpan(start_time);\n \/\/ Send GENERIC_ERROR after default timeout\n if (difference_between_start_current_time > default_timeout_msec) {\n LOG4CXX_ERROR(logger_, \"Expired timeout for TTS.Speak response\");\n \/\/ Don't using onTimeOut(), becouse there default time is bigger than\n \/\/ Default time in *.ini file\n FinishTTSSpeak();\n SendResponse(false, mobile_apis::Result::eType::GENERIC_ERROR,\n \"Expired timeout for TTS.Speak response\");\n return false;\n }\n }\n return true;\n}\n\n} \/\/ namespace commands\n\n} \/\/ namespace application_manager\nAdd logs to WaitTTSSpeak method.\/*\n\n Copyright (c) 2013, Ford Motor Company\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided with the\n distribution.\n\n Neither the name of the Ford Motor Company nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"application_manager\/commands\/mobile\/perform_audio_pass_thru_request.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/application_impl.h\"\n#include \"application_manager\/message_helper.h\"\n#include \"config_profile\/profile.h\"\n#include \"utils\/helpers.h\"\n\nnamespace application_manager {\n\nnamespace commands {\n\nnamespace str = strings;\n\nPerformAudioPassThruRequest::PerformAudioPassThruRequest(\n const MessageSharedPtr& message)\n : CommandRequestImpl(message),\n is_active_tts_speak_(false),\n result_tts_speak_(mobile_apis::Result::SUCCESS) {\n subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout);\n}\n\nPerformAudioPassThruRequest::~PerformAudioPassThruRequest() {\n}\n\nvoid PerformAudioPassThruRequest::onTimeOut() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n FinishTTSSpeak();\n CommandRequestImpl::onTimeOut();\n}\n\nbool PerformAudioPassThruRequest::Init() {\n default_timeout_ +=\n (((*message_)[str::msg_params][str::max_duration].asUInt()));\n return true;\n}\n\nvoid PerformAudioPassThruRequest::Run() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n ApplicationSharedPtr app =\n ApplicationManagerImpl::instance()->application(connection_key());\n\n if (!app) {\n LOG4CXX_ERROR(logger_, \"APPLICATION_NOT_REGISTERED\");\n SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);\n return;\n }\n\n if (mobile_api::HMILevel::HMI_NONE == app->hmi_level()) {\n LOG4CXX_ERROR(logger_, \"application isn't activated\");\n SendResponse(false, mobile_apis::Result::REJECTED);\n return;\n }\n\n if (IsWhiteSpaceExist()) {\n LOG4CXX_ERROR(logger_,\n \"Incoming perform audio pass thru has contains \"\n \"\\\\t\\\\n \\\\\\\\t \\\\\\\\n\"\n \" text contains only whitespace in initialPrompt\");\n SendResponse(false, mobile_apis::Result::INVALID_DATA);\n return;\n }\n\n if ((*message_)[str::msg_params].keyExists(str::initial_prompt) &&\n (0 < (*message_)[str::msg_params][str::initial_prompt].length())) {\n \/\/ In case TTS Speak, subscribe on notification\n SendSpeakRequest();\n SendPerformAudioPassThruRequest();\n } else {\n SendPerformAudioPassThruRequest();\n SendRecordStartNotification();\n StartMicrophoneRecording();\n }\n}\n\nvoid PerformAudioPassThruRequest::on_event(const event_engine::Event& event) {\n LOG4CXX_AUTO_TRACE(logger_);\n using namespace helpers;\n\n const smart_objects::SmartObject& message = event.smart_object();\n\n switch (event.id()) {\n case hmi_apis::FunctionID::UI_PerformAudioPassThru: {\n LOG4CXX_INFO(logger_, \"Received UI_PerformAudioPassThru\");\n\n if (!WaitTTSSpeak()) {\n LOG4CXX_AUTO_TRACE(logger_);\n return;\n }\n\n mobile_apis::Result::eType mobile_code =\n GetMobileResultCode(static_cast(\n message[strings::params][hmi_response::code].asUInt()));\n\n \/\/ in case perform audio is started by other request skip stopping\n if (mobile_apis::Result::REJECTED == mobile_code) {\n LOG4CXX_ERROR(logger_, \"Request was rejected\");\n SendResponse(false, mobile_code, NULL, &(message[strings::msg_params]));\n return;\n }\n\n FinishTTSSpeak();\n\n std::string return_info;\n const bool result =\n Compare(\n mobile_code,\n mobile_apis::Result::SUCCESS,\n mobile_apis::Result::RETRY,\n mobile_apis::Result::WARNINGS);\n\n const bool is_result_ok =\n Compare(\n mobile_code,\n mobile_apis::Result::SUCCESS,\n mobile_apis::Result::WARNINGS);\n\n if (is_result_ok &&\n mobile_apis::Result::UNSUPPORTED_RESOURCE == result_tts_speak_) {\n mobile_code = mobile_apis::Result::WARNINGS;\n return_info = \"Unsupported phoneme type sent in a prompt\";\n }\n\n SendResponse(result, mobile_code, return_info.c_str(),\n &(message[strings::msg_params]));\n break;\n }\n case hmi_apis::FunctionID::TTS_Speak: {\n LOG4CXX_INFO(logger_, \"Received TTS_Speak event\");\n result_tts_speak_ = GetMobileResultCode(\n static_cast(\n message[strings::params][hmi_response::code].asUInt()));\n is_active_tts_speak_ = false;\n if (mobile_apis::Result::SUCCESS == result_tts_speak_) {\n SendRecordStartNotification();\n StartMicrophoneRecording();\n\n \/\/ update request timeout to get time for perform audio recording\n ApplicationManagerImpl::instance()->\n updateRequestTimeout(connection_key(),\n correlation_id(),\n default_timeout());\n }\n break;\n }\n case hmi_apis::FunctionID::TTS_OnResetTimeout: {\n LOG4CXX_INFO(logger_, \"Received TTS_OnResetTimeout event\");\n\n ApplicationManagerImpl::instance()->updateRequestTimeout(\n connection_key(), correlation_id(), default_timeout());\n break;\n }\n default: {\n LOG4CXX_ERROR(logger_, \"Received unknown event\" << event.id());\n return;\n }\n }\n}\n\nvoid PerformAudioPassThruRequest::SendSpeakRequest() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n using namespace hmi_apis;\n using namespace smart_objects;\n\n SmartObject msg_params = smart_objects::SmartObject(SmartType_Map);\n\n if ((*message_)[str::msg_params].keyExists(str::initial_prompt) &&\n (0 < (*message_)[str::msg_params][str::initial_prompt].length())) {\n for (uint32_t i = 0;\n i < (*message_)[str::msg_params][str::initial_prompt].length();\n ++i) {\n msg_params[hmi_request::tts_chunks][i][str::text] =\n (*message_)[str::msg_params][str::initial_prompt][i][str::text];\n msg_params[hmi_request::tts_chunks][i][str::type] =\n (*message_)[str::msg_params][str::initial_prompt][i][str::type];\n }\n \/\/ app_id\n msg_params[strings::app_id] = connection_key();\n msg_params[hmi_request::speak_type] = Common_MethodName::AUDIO_PASS_THRU;\n is_active_tts_speak_ = true;\n SendHMIRequest(FunctionID::TTS_Speak, &msg_params, true);\n }\n}\n\nvoid PerformAudioPassThruRequest::SendPerformAudioPassThruRequest() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n smart_objects::SmartObject msg_params = smart_objects::SmartObject(\n smart_objects::SmartType_Map);\n\n msg_params[str::app_id] = connection_key();\n\n msg_params[hmi_request::max_duration] =\n (*message_)[str::msg_params][str::max_duration];\n\n msg_params[hmi_request::audio_pass_display_texts] =\n smart_objects::SmartObject(smart_objects::SmartType_Array);\n\n if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text1)) {\n msg_params[hmi_request::audio_pass_display_texts]\n [0][hmi_request::field_name] = static_cast\n (hmi_apis::Common_TextFieldName::audioPassThruDisplayText1);\n msg_params[hmi_request::audio_pass_display_texts]\n [0][hmi_request::field_text] =\n (*message_)[str::msg_params][str::audio_pass_display_text1];\n }\n\n if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text2)) {\n msg_params[hmi_request::audio_pass_display_texts]\n [1][hmi_request::field_name] = static_cast\n (hmi_apis::Common_TextFieldName::audioPassThruDisplayText2);\n msg_params[hmi_request::audio_pass_display_texts]\n [1][hmi_request::field_text] =\n (*message_)[str::msg_params][str::audio_pass_display_text2];\n }\n\n if ((*message_)[str::msg_params].keyExists(str::mute_audio)) {\n msg_params[str::mute_audio] =\n (*message_)[str::msg_params][str::mute_audio].asBool();\n } else {\n \/\/ If omitted, the value is set to true\n msg_params[str::mute_audio] = true;\n }\n\n SendHMIRequest(hmi_apis::FunctionID::UI_PerformAudioPassThru,\n &msg_params, true);\n}\n\nvoid PerformAudioPassThruRequest::SendRecordStartNotification() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n smart_objects::SmartObject msg_params = smart_objects::SmartObject(\n smart_objects::SmartType_Map);\n msg_params[strings::app_id] = connection_key();\n\n CreateHMINotification(hmi_apis::FunctionID::UI_OnRecordStart, msg_params);\n}\n\nvoid PerformAudioPassThruRequest::StartMicrophoneRecording() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n ApplicationManagerImpl::instance()->begin_audio_pass_thru();\n\n ApplicationManagerImpl::instance()->StartAudioPassThruThread(\n connection_key(), correlation_id(),\n (*message_)[str::msg_params][str::max_duration].asInt(),\n (*message_)[str::msg_params][str::sampling_rate].asInt(),\n (*message_)[str::msg_params][str::bits_per_sample].asInt(),\n (*message_)[str::msg_params][str::audio_type].asInt());\n}\n\nbool PerformAudioPassThruRequest::IsWhiteSpaceExist() {\n LOG4CXX_AUTO_TRACE(logger_);\n const char* str = NULL;\n\n if ((*message_)[strings::msg_params].keyExists(strings::initial_prompt)) {\n const smart_objects::SmartArray* ip_array =\n (*message_)[strings::msg_params][strings::initial_prompt].asArray();\n\n smart_objects::SmartArray::const_iterator it_ip = ip_array->begin();\n smart_objects::SmartArray::const_iterator it_ip_end = ip_array->end();\n\n for (; it_ip != it_ip_end; ++it_ip) {\n str = (*it_ip)[strings::text].asCharArray();\n if (strlen(str) && !CheckSyntax(str)) {\n LOG4CXX_ERROR(logger_, \"Invalid initial_prompt syntax check failed\");\n return true;\n }\n }\n }\n\n if ((*message_)[strings::msg_params].\n keyExists(strings::audio_pass_display_text1)) {\n\n str = (*message_)[strings::msg_params]\n [strings::audio_pass_display_text1].asCharArray();\n if (!CheckSyntax(str)) {\n LOG4CXX_ERROR(logger_,\n \"Invalid audio_pass_display_text1 value syntax check failed\");\n return true;\n }\n }\n\n if ((*message_)[strings::msg_params].\n keyExists(strings::audio_pass_display_text2)) {\n\n str = (*message_)[strings::msg_params]\n [strings::audio_pass_display_text2].asCharArray();\n if (!CheckSyntax(str)) {\n LOG4CXX_ERROR(logger_,\n \"Invalid audio_pass_display_text2 value syntax check failed\");\n return true;\n }\n }\n return false;\n}\n\nvoid PerformAudioPassThruRequest::FinishTTSSpeak() {\n LOG4CXX_AUTO_TRACE(logger_);\n if (ApplicationManagerImpl::instance()->end_audio_pass_thru()) {\n LOG4CXX_DEBUG(logger_, \"Stop AudioPassThru.\");\n ApplicationManagerImpl::instance()->\n StopAudioPassThru(connection_key());\n }\n if (!is_active_tts_speak_) {\n LOG4CXX_DEBUG(logger_, \"TTS Speak is inactive.\");\n return;\n }\n is_active_tts_speak_ = false;\n SendHMIRequest(hmi_apis::FunctionID::TTS_StopSpeaking, NULL);\n}\n\nbool PerformAudioPassThruRequest::WaitTTSSpeak() {\n LOG4CXX_AUTO_TRACE(logger_);\n uint64_t default_timeout_msec =\n profile::Profile::instance()->default_timeout();\n const TimevalStruct start_time = date_time::DateTime::getCurrentTime();\n\n \/\/ Waiting for TTS_Speak\n while (is_active_tts_speak_) {\n uint64_t difference_between_start_current_time\n = date_time::DateTime::calculateTimeSpan(start_time);\n \/\/ Send GENERIC_ERROR after default timeout\n if (difference_between_start_current_time > default_timeout_msec) {\n LOG4CXX_WARN(logger_, \"Expired timeout for TTS.Speak response\");\n \/\/ Don't use onTimeOut(), becouse default_timeout_ is bigger than\n \/\/ Default time in *.ini file\n FinishTTSSpeak();\n SendResponse(false, mobile_apis::Result::eType::GENERIC_ERROR,\n \"Expired timeout for TTS.Speak response\");\n return false;\n }\n }\n return true;\n}\n\n} \/\/ namespace commands\n\n} \/\/ namespace application_manager\n<|endoftext|>"} {"text":"\/*==================================================\n \n Flexbar - flexible barcode and adapter removal\n \n Version 3.0.2\n \n uses SeqAn library release 2.2.0\n and TBB library 4.0 or later\n \n \n Developer: Johannes Roehr\n \n Former contributors: Matthias Dodt\n Benjamin Menkuec\n Sebastian Roskosch\n \n \n https:\/\/github.com\/seqan\/flexbar\n \n===================================================*\/\n\n#include \"Flexbar.h\"\n\n\nint main(int argc, const char* argv[]){\n\t\n\tusing namespace std;\n\tusing namespace seqan;\n\t\n\tconst string version = \"3.0.2\";\n\tconst string date = \"May 2017\";\n\t\n\tArgumentParser parser(\"flexbar\");\n\t\n\tdefineOptions(parser, version, date);\n\tparseCmdLine(parser, version, argc, argv);\n\t\n\tOptions o;\n\t\n\tinitOptions(o, parser);\n\tloadOptions(o, parser);\n\t\n\tstartComputation(o);\n\t\n\treturn 0;\n}\nFlexbar 3.0.3 release\/*==================================================\n \n Flexbar - flexible barcode and adapter removal\n \n Version 3.0.3\n \n uses SeqAn library release 2.2.0\n and TBB library 4.0 or later\n \n \n Developer: Johannes Roehr\n \n Former contributors: Matthias Dodt\n Benjamin Menkuec\n Sebastian Roskosch\n \n \n https:\/\/github.com\/seqan\/flexbar\n \n===================================================*\/\n\n#include \"Flexbar.h\"\n\n\nint main(int argc, const char* argv[]){\n\t\n\tusing namespace std;\n\tusing namespace seqan;\n\t\n\tconst string version = \"3.0.3\";\n\tconst string date = \"May 2017\";\n\t\n\tArgumentParser parser(\"flexbar\");\n\t\n\tdefineOptions(parser, version, date);\n\tparseCmdLine(parser, version, argc, argv);\n\t\n\tOptions o;\n\t\n\tinitOptions(o, parser);\n\tloadOptions(o, parser);\n\t\n\tstartComputation(o);\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/**\n * \\file\n *\n * \\brief Implements a way to build and deal with a backend\n *\n * \\copyright BSD License (see doc\/COPYING or http:\/\/www.libelektra.org)\n *\n *\/\n\n#include \n\nusing namespace std;\n\nnamespace kdb\n{\n\nnamespace tools\n{\n\nnamespace merging\n{\n\n\/**\n * @brief Determines if two keys are equal based on their GetString() values.\n * Returns true if they are equal. False if they are not.\n *\/\nbool ThreeWayMerge::keyDataEqual(const Key& k1, const Key& k2)\n{\n\tif (!k1 && k2) return false;\n\tif (k1 && !k2) return false;\n\tif (k1.getString () != k2.getString ())\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool ThreeWayMerge::keyMetaEqual(Key& k1, Key& k2)\n{\n\tk1.rewindMeta ();\n\tKey currentMeta;\n\twhile ((currentMeta = k1.nextMeta ()))\n\t{\n\t\tstring metaName = currentMeta.getName ();\n\t\tif (!k2.hasMeta (metaName)) return false;\n\t\tif (currentMeta.getString () != k2.getMeta (metaName)) return false;\n\t}\n\n\tk2.rewindMeta ();\n\twhile ((currentMeta = k2.nextMeta ()))\n\t{\n\t\tstring metaName = currentMeta.getName ();\n\t\tif (!k1.hasMeta (metaName)) return false;\n\t\tif (currentMeta.getString () != k1.getMeta (metaName)) return false;\n\t}\n\n\treturn true;\n}\n\nstring ThreeWayMerge::rebasePath(const Key& key, const Key& oldParent,\n\t\tconst Key& newParent)\n{\n\tstring oldPath = key.getFullName ();\n\tstring relativePath = oldPath.substr (oldParent.getFullName ().length (),\n\t\t\toldPath.length ());\n\tstring newPath = newParent.getFullName () + relativePath;\n\n\treturn newPath;\n}\n\nKey ThreeWayMerge::rebaseKey(const Key& key, const Key& oldParent,\n\t\tconst Key& newParent)\n{\n\tKey result = key.dup ();\n\tresult.setName (rebasePath (key, oldParent, newParent));\n\treturn result;\n}\n\n\/\/ TODO: compare metakeys\nvoid ThreeWayMerge::automaticMerge(const MergeTask& task,\n\t\tMergeResult& mergeResult, bool reverseConflictMeta = false)\n{\n\tKey our;\n\tcursor_t savedCursor = task.ours.getCursor ();\n\ttask.ours.rewind ();\n\n\twhile ((our = task.ours.next ()))\n\t{\n\t\tstring theirLookup = rebasePath (our, task.ourParent, task.theirParent);\n\t\tKey theirLookupResult = task.theirs.lookup (theirLookup);\n\t\tKey mergeKey = rebaseKey (our, task.ourParent, task.mergeRoot);\n\n\t\tif (keyDataEqual (our, theirLookupResult))\n\t\t{\n\t\t\t\/\/ keydata matches, see if metakeys match\n\t\t\tif (keyMetaEqual (our, theirLookupResult))\n\t\t\t{\n\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ metakeys are different\n\t\t\t\tmergeResult.addConflict (mergeKey, META, META);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstring baseLookup = rebasePath (our, task.ourParent,\n\t\t\t\t\ttask.baseParent);\n\t\t\tKey baseLookupResult = task.base.lookup (baseLookup);\n\n\t\t\t\/\/ check if the keys was newly added in ours\n\t\t\tif (baseLookupResult)\n\t\t\t{\n\t\t\t\t\/\/ the key exists in base, check if the key still exists in theirs\n\t\t\t\tif (theirLookupResult)\n\t\t\t\t{\n\t\t\t\t\t\/\/ check if only they modified it\n\t\t\t\t\tif (!keyDataEqual (our, baseLookupResult)\n\t\t\t\t\t\t\t&& keyDataEqual (theirLookupResult,\n\t\t\t\t\t\t\t\t\tbaseLookupResult))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was only modified in theirs, take their version\n\t\t\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ check if both modified it\n\t\t\t\t\t\tif (!keyDataEqual (our, baseLookupResult)\n\t\t\t\t\t\t\t\t&& !keyDataEqual (theirLookupResult,\n\t\t\t\t\t\t\t\t\t\tbaseLookupResult))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ the key was modified on both sides\n\t\t\t\t\t\t\tmergeResult.addConflict (mergeKey, MODIFY, MODIFY);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ the key does not exist in theirs anymore, check if ours has modified it\n\t\t\t\t\tif (keyDataEqual (our, baseLookupResult))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was deleted in theirs, and not modified in ours\n\t\t\t\t\t\tmergeResult.removeMergeKey (mergeKey);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was deleted in theirs, but modified in ours\n\t\t\t\t\t\tif (!reverseConflictMeta)\n\t\t\t\t\t\t\tmergeResult.addConflict (mergeKey, MODIFY, DELETE);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmergeResult.addConflict (mergeKey, DELETE, MODIFY);\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ the key does not exist in base, check if the key was added in theirs\n\t\t\t\tif (theirLookupResult)\n\t\t\t\t{\n\t\t\t\t\t\/\/ check if the key was added with the same value in theirs\n\t\t\t\t\tif (keyDataEqual (mergeKey, theirLookupResult))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was added on both sides with the same value\n\t\t\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was added on both sides with different values\n\t\t\t\t\t\tmergeResult.addConflict (mergeKey, ADD, ADD);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ the key was only added to ours\n\t\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttask.ours.setCursor (savedCursor);\n}\n\n\/**\n * Returns a keyset that is the result of a merge on two keysets (ours and theirs) using a base keyset as a refernece (a three-way merge). \n * If the merge function is unscuessful an empty KeySet will be returned. \n * This function is inteded as a full version for the kdb merge command or for the C++ API. \n * It works by taking in three keysets, their parent keys and a parent key for where to store the merged KeySet.\n **\/\nMergeResult ThreeWayMerge::mergeKeySet(const MergeTask& task)\n{\n\n\tMergeResult result;\n\tautomaticMerge (task, result);\n\tautomaticMerge (task.reverse (), result, true);\n\treturn result;\n}\n\n\/**\n *\n * Returns a keyset that is the result of a merge on two keysets (ours and theirs) using a base keyset as a refernece (a three-way merge).\n * If the merge function is unscuessful an empty KeySet will be returned.\n * This function is inteded as a basic version for the C++ API. It takes in three keysets and a parent key for where to store the merged keys.\n * It works by finidng the parent key for each keyset and then calling the more complex function above.\n **\/\nMergeResult ThreeWayMerge::mergeKeySet(const KeySet& base, const KeySet& ours,\n\t\tconst KeySet& theirs, Key& mergeRoot)\n{\n\tKey ourkey = ours.head ().dup ();\n\tKey theirkey = theirs.head ().dup ();\n\tKey basekey = base.head ().dup ();\n\n\tMergeResult merged = mergeKeySet (\n\t\t\tMergeTask (BaseMergeKeys (base, basekey),\n\t\t\t\t\tOurMergeKeys (ours, ourkey),\n\t\t\t\t\tTheirMergeKeys (theirs, theirkey), mergeRoot));\n\n\treturn merged;\n}\n\n}\n}\n}\nWrote comments for the ThreeWayMerge functions\/**\n * \\file\n *\n * \\brief Implements a way to build and deal with a backend\n *\n * \\copyright BSD License (see doc\/COPYING or http:\/\/www.libelektra.org)\n *\n *\/\n\n#include \n\nusing namespace std;\n\nnamespace kdb\n{\n\nnamespace tools\n{\n\nnamespace merging\n{\n\n\/**\n * Determines if two keys are equal based on their string value\n * If one of the two keys is null, false is returned\n *\n * @param k1 the first key to be compared\n * @param k2 the second key to be compared\n * @return true if both keys are not null and have an\n * equal string value, false otherwise\n *\/\nbool ThreeWayMerge::keyDataEqual(const Key& k1, const Key& k2)\n{\n\tif (!k1 && k2) return false;\n\tif (k1 && !k2) return false;\n\tif (k1.getString () != k2.getString ())\n\t{\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n\/**\n * Determines if two keys have equal metadata\n *\n *\n * @param k1 the first key whose metadata should be compared\n * @param k2 the second key whose metadata should be compared\n * @return true if the keys have equal metadata, false otherwise\n *\/\nbool ThreeWayMerge::keyMetaEqual(Key& k1, Key& k2)\n{\n\tk1.rewindMeta ();\n\tKey currentMeta;\n\twhile ((currentMeta = k1.nextMeta ()))\n\t{\n\t\tstring metaName = currentMeta.getName ();\n\t\tif (!k2.hasMeta (metaName)) return false;\n\t\tif (currentMeta.getString () != k2.getMeta (metaName)) return false;\n\t}\n\n\tk2.rewindMeta ();\n\twhile ((currentMeta = k2.nextMeta ()))\n\t{\n\t\tstring metaName = currentMeta.getName ();\n\t\tif (!k1.hasMeta (metaName)) return false;\n\t\tif (currentMeta.getString () != k1.getMeta (metaName)) return false;\n\t}\n\n\treturn true;\n}\n\n\/**\n * Rebases the relative path of the passed key from the old parent\n * to the new parent and returns the new path.\n *\n * For example a key \/user\/example\/config\/key1 with the oldparent\n * \/user\/example and the new parent \/user\/newexample\/newpath would\n * result in \/user\/newexample\/newpath\/config\/key1\n *\n * @param key the key whose path should be rebased\n * @param oldParent the old parent of the key\n * @param newParent the new parent of the key\n * @return the rebased path\n *\/\nstring ThreeWayMerge::rebasePath(const Key& key, const Key& oldParent,\n\t\tconst Key& newParent)\n{\n\tstring oldPath = key.getFullName ();\n\tstring relativePath = oldPath.substr (oldParent.getFullName ().length (),\n\t\t\toldPath.length ());\n\tstring newPath = newParent.getFullName () + relativePath;\n\n\treturn newPath;\n}\n\n\/**\n * Rebases the supplied key from the old parent to the new parent.\n *\n * @see ThreeWayMerge::rebasePath\n * @param key the key to be rebased\n * @param oldParent the old parent of the key\n * @param newParent the new parent of the key\n * @return a rebased copy of the supplied key\n *\/\nKey ThreeWayMerge::rebaseKey(const Key& key, const Key& oldParent,\n\t\tconst Key& newParent)\n{\n\tKey result = key.dup ();\n\tresult.setName (rebasePath (key, oldParent, newParent));\n\treturn result;\n}\n\n\/\/ TODO: compare metakeys\nvoid ThreeWayMerge::automaticMerge(const MergeTask& task,\n\t\tMergeResult& mergeResult, bool reverseConflictMeta = false)\n{\n\tKey our;\n\tcursor_t savedCursor = task.ours.getCursor ();\n\ttask.ours.rewind ();\n\n\twhile ((our = task.ours.next ()))\n\t{\n\t\tstring theirLookup = rebasePath (our, task.ourParent, task.theirParent);\n\t\tKey theirLookupResult = task.theirs.lookup (theirLookup);\n\t\tKey mergeKey = rebaseKey (our, task.ourParent, task.mergeRoot);\n\n\t\tif (keyDataEqual (our, theirLookupResult))\n\t\t{\n\t\t\t\/\/ keydata matches, see if metakeys match\n\t\t\tif (keyMetaEqual (our, theirLookupResult))\n\t\t\t{\n\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ metakeys are different\n\t\t\t\tmergeResult.addConflict (mergeKey, META, META);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstring baseLookup = rebasePath (our, task.ourParent,\n\t\t\t\t\ttask.baseParent);\n\t\t\tKey baseLookupResult = task.base.lookup (baseLookup);\n\n\t\t\t\/\/ check if the keys was newly added in ours\n\t\t\tif (baseLookupResult)\n\t\t\t{\n\t\t\t\t\/\/ the key exists in base, check if the key still exists in theirs\n\t\t\t\tif (theirLookupResult)\n\t\t\t\t{\n\t\t\t\t\t\/\/ check if only they modified it\n\t\t\t\t\tif (!keyDataEqual (our, baseLookupResult)\n\t\t\t\t\t\t\t&& keyDataEqual (theirLookupResult,\n\t\t\t\t\t\t\t\t\tbaseLookupResult))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was only modified in theirs, take their version\n\t\t\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ check if both modified it\n\t\t\t\t\t\tif (!keyDataEqual (our, baseLookupResult)\n\t\t\t\t\t\t\t\t&& !keyDataEqual (theirLookupResult,\n\t\t\t\t\t\t\t\t\t\tbaseLookupResult))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ the key was modified on both sides\n\t\t\t\t\t\t\tmergeResult.addConflict (mergeKey, MODIFY, MODIFY);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ the key does not exist in theirs anymore, check if ours has modified it\n\t\t\t\t\tif (keyDataEqual (our, baseLookupResult))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was deleted in theirs, and not modified in ours\n\t\t\t\t\t\tmergeResult.removeMergeKey (mergeKey);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was deleted in theirs, but modified in ours\n\t\t\t\t\t\tif (!reverseConflictMeta)\n\t\t\t\t\t\t\tmergeResult.addConflict (mergeKey, MODIFY, DELETE);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmergeResult.addConflict (mergeKey, DELETE, MODIFY);\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ the key does not exist in base, check if the key was added in theirs\n\t\t\t\tif (theirLookupResult)\n\t\t\t\t{\n\t\t\t\t\t\/\/ check if the key was added with the same value in theirs\n\t\t\t\t\tif (keyDataEqual (mergeKey, theirLookupResult))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was added on both sides with the same value\n\t\t\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ the key was added on both sides with different values\n\t\t\t\t\t\tmergeResult.addConflict (mergeKey, ADD, ADD);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ the key was only added to ours\n\t\t\t\t\tmergeResult.addMergeKey (mergeKey);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttask.ours.setCursor (savedCursor);\n}\n\n\/**\n * Performs a threeway merge according to the supplied MergeTask. All merged keys will\n * be below the given mergeParent in the MergeTask. Found conflicts will be\n * reported in the MergeResult. Conflicts are below the mergeParent as well and\n * are not part of the mergedKeys.\n *\n * @see MergeTask\n * @see MergeResult\n *\n * @param task a MergeTask describing the intended merge oparation\n * @return a MergeResult that contains the merged keys as well as all found conflicts.\n *\n **\/\nMergeResult ThreeWayMerge::mergeKeySet(const MergeTask& task)\n{\n\n\tMergeResult result;\n\tautomaticMerge (task, result);\n\tautomaticMerge (task.reverse (), result, true);\n\treturn result;\n}\n\n\n\/**\n * Performs a threeway merge based on the supplied KeySets. The result is the same\n * as for ThreeWayMerge::mergeKeySet(const MergeTask&). The first key (i.e. the shortest)\n * in each of the supplied KeySets is considered to be the corresponding parentKey.\n * This means that the parent key of each KeySet MUST be part of the KeySet.\n *\n * @see ThreeWayMerge::mergeKeySet(const MergeTask&)\n *\n * @param base the KeySet containing the base keys and the base parentKey\n * @param ours the KeySet containing our keys and our parentKey\n * @param theirs the KeySet containing their keys and their parentKey\n * @param meregRoot the parentKey for the merged keys\n * @return a MergeResult that contains the merged keys as well as all found conflicts.\n *\/\nMergeResult ThreeWayMerge::mergeKeySet(const KeySet& base, const KeySet& ours,\n\t\tconst KeySet& theirs, Key& mergeRoot)\n{\n\tKey ourkey = ours.head ().dup ();\n\tKey theirkey = theirs.head ().dup ();\n\tKey basekey = base.head ().dup ();\n\n\tMergeResult merged = mergeKeySet (\n\t\t\tMergeTask (BaseMergeKeys (base, basekey),\n\t\t\t\t\tOurMergeKeys (ours, ourkey),\n\t\t\t\t\tTheirMergeKeys (theirs, theirkey), mergeRoot));\n\n\treturn merged;\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"#ifndef ITER_ACCUMULATE_H_\n#define ITER_ACCUMULATE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of Accumulator and accumulate\n template \n class Accumulator;\n\n template \n Accumulator accumulate(\n Container&&, AccumulateFunc);\n\n template \n Accumulator, AccumulateFunc> accumulate(\n std::initializer_list, AccumulateFunc);\n\n template \n class Accumulator {\n private:\n Container container;\n AccumulateFunc accumulate_func;\n\n friend Accumulator accumulate(\n Container&&, AccumulateFunc);\n\n template \n friend Accumulator, AF> accumulate(\n std::initializer_list, AF);\n \n \/\/ AccumVal must be default constructible\n using AccumVal =\n typename std::remove_reference<\n typename std::result_of,\n iterator_deref)>::type>::type;\n static_assert(\n std::is_default_constructible::value,\n \"Cannot accumulate a non-default constructible type\");\n\n Accumulator(Container&& container, AccumulateFunc accumulate_func)\n : container(std::forward(container)),\n accumulate_func(accumulate_func)\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 AccumulateFunc accumulate_func;\n AccumVal acc_val;\n public:\n Iterator (iterator_type iter,\n iterator_type end,\n AccumulateFunc accumulate_func)\n : sub_iter{iter},\n sub_end{end},\n accumulate_func(accumulate_func),\n \/\/ only get first value if not an end iterator\n acc_val(!(iter != end) ? AccumVal{} : *iter)\n { } \n\n const AccumVal& operator*() const {\n return this->acc_val;\n }\n\n Iterator& operator++() { \n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->acc_val = accumulate_func(\n this->acc_val, *this->sub_iter);\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->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->accumulate_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->accumulate_func};\n }\n\n };\n\n \/\/ Helper function to instantiate an Accumulator\n template \n Accumulator accumulate(\n Container&& container,\n AccumulateFunc accumulate_func)\n {\n return {std::forward(container), accumulate_func};\n }\n\n template \n auto accumulate(Container&& container) -> \n decltype(accumulate(std::forward(container),\n std::plus>::type>{}))\n {\n return accumulate(std::forward(container),\n std::plus>::type>{});\n }\n\n template \n Accumulator, AccumulateFunc> accumulate(\n std::initializer_list il,\n AccumulateFunc accumulate_func)\n {\n return {std::move(il), accumulate_func};\n }\n\n template \n auto accumulate(std::initializer_list il) ->\n decltype(accumulate(std::move(il), std::plus{}))\n {\n return accumulate(std::move(il), std::plus{});\n }\n\n}\n\n#endif\nuses c++14 type aliases#ifndef ITER_ACCUMULATE_H_\n#define ITER_ACCUMULATE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of Accumulator and accumulate\n template \n class Accumulator;\n\n template \n Accumulator accumulate(\n Container&&, AccumulateFunc);\n\n template \n Accumulator, AccumulateFunc> accumulate(\n std::initializer_list, AccumulateFunc);\n\n template \n class Accumulator {\n private:\n Container container;\n AccumulateFunc accumulate_func;\n\n friend Accumulator accumulate(\n Container&&, AccumulateFunc);\n\n template \n friend Accumulator, AF> accumulate(\n std::initializer_list, AF);\n \n \/\/ AccumVal must be default constructible\n using AccumVal =\n std::remove_reference_t<\n std::result_of_t,\n iterator_deref)>>;\n static_assert(\n std::is_default_constructible::value,\n \"Cannot accumulate a non-default constructible type\");\n\n Accumulator(Container&& container, AccumulateFunc accumulate_func)\n : container(std::forward(container)),\n accumulate_func(accumulate_func)\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 AccumulateFunc accumulate_func;\n AccumVal acc_val;\n public:\n Iterator (iterator_type iter,\n iterator_type end,\n AccumulateFunc accumulate_func)\n : sub_iter{iter},\n sub_end{end},\n accumulate_func(accumulate_func),\n \/\/ only get first value if not an end iterator\n acc_val(!(iter != end) ? AccumVal{} : *iter)\n { } \n\n const AccumVal& operator*() const {\n return this->acc_val;\n }\n\n Iterator& operator++() { \n ++this->sub_iter;\n if (this->sub_iter != this->sub_end) {\n this->acc_val = accumulate_func(\n this->acc_val, *this->sub_iter);\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->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->accumulate_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->accumulate_func};\n }\n\n };\n\n \/\/ Helper function to instantiate an Accumulator\n template \n Accumulator accumulate(\n Container&& container,\n AccumulateFunc accumulate_func)\n {\n return {std::forward(container), accumulate_func};\n }\n\n template \n auto accumulate(Container&& container) -> \n decltype(accumulate(std::forward(container),\n std::plus>>{}))\n {\n return accumulate(std::forward(container),\n std::plus>>{});\n }\n\n template \n Accumulator, AccumulateFunc> accumulate(\n std::initializer_list il,\n AccumulateFunc accumulate_func)\n {\n return {std::move(il), accumulate_func};\n }\n\n template \n auto accumulate(std::initializer_list il) ->\n decltype(accumulate(std::move(il), std::plus{}))\n {\n return accumulate(std::move(il), std::plus{});\n }\n\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"writer\/CoutWriter.hpp\"\n#include \"fmi\/ValueInfo.hpp\"\n\nnamespace Writer\n{\n\n CoutWriter::CoutWriter(const Initialization::WriterPlan & in)\n : IWriter(in), _lineEndingSign('\\n'), _separator(',')\n {\n LOGGER_WRITE(\"Using CoutWriter\", Util::LC_LOADER, Util::LL_INFO);\n\n }\n\n CoutWriter::~CoutWriter()\n {\n deinitialize();\n }\n\n void CoutWriter::initialize()\n {\n IWriter::initialize();\n if (std::cout.fail())\n throw runtime_error(\"Cannot create and open result file.\");\n }\n\n void CoutWriter::deinitialize()\n {\n IWriter::deinitialize();\n }\n\n void CoutWriter::appendTimeHeader()\n {\n assert(isInitialized());\n std::cout << \"time\";\n }\n\n void CoutWriter::appendTime(double time)\n {\n assert(isInitialized());\n std::cout << _lineEndingSign << std::endl << time;\n }\n\n void CoutWriter::appendHeader(const string_type& fmuName, const FMI::ValueInfo& variables)\n {\n assert(isInitialized());\n for(string_type value : variables.getAllValueNames())\n {\n Util::StringHelper::replaceAll(value, \",\", \"_\");\n std::cout << _separator << fmuName << \".\" << value;\n }\n }\n\n void CoutWriter::appendResults(const string_type& fmuName, const FMI::ValueCollection& values)\n {\n assert(isInitialized());\n for(real_type value : values.getValues())\n std::cout << _separator << to_string(value);\n for(int_type value : values.getValues())\n std::cout << _separator << to_string(value);\n for(bool_type value : values.getValues())\n std::cout << _separator << to_string(value);\n for(string_type value : values.getValues())\n std::cout << _separator << \"\\\"\" << value << \"\\\"\";\n }\n\n void CoutWriter::flushResults()\n {\n assert(isInitialized());\n std::cout.flush();\n }\n\n} \/* namespace DataAccess *\/\nCosmetic changes#include \"writer\/CoutWriter.hpp\"\n#include \"fmi\/ValueInfo.hpp\"\n\nnamespace Writer\n{\n\n CoutWriter::CoutWriter(const Initialization::WriterPlan & in)\n : IWriter(in),\n _lineEndingSign('\\n'),\n _separator(',')\n {\n LOGGER_WRITE(\"Using CoutWriter\", Util::LC_LOADER, Util::LL_INFO);\n\n }\n\n CoutWriter::~CoutWriter()\n {\n deinitialize();\n }\n\n void CoutWriter::initialize()\n {\n IWriter::initialize();\n if (std::cout.fail())\n throw runtime_error(\"Cannot create and open result file.\");\n }\n\n void CoutWriter::deinitialize()\n {\n IWriter::deinitialize();\n }\n\n void CoutWriter::appendTimeHeader()\n {\n assert(isInitialized());\n std::cout << \"time\";\n }\n\n void CoutWriter::appendTime(double time)\n {\n assert(isInitialized());\n std::cout << _lineEndingSign << std::endl << time;\n }\n\n void CoutWriter::appendHeader(const string_type& fmuName, const FMI::ValueInfo& variables)\n {\n assert(isInitialized());\n for (string_type value : variables.getAllValueNames())\n {\n Util::StringHelper::replaceAll(value, \",\", \"_\");\n std::cout << _separator << fmuName << \".\" << value;\n }\n }\n\n void CoutWriter::appendResults(const string_type& fmuName, const FMI::ValueCollection& values)\n {\n assert(isInitialized());\n for (real_type value : values.getValues())\n std::cout << _separator << to_string(value);\n for (int_type value : values.getValues())\n std::cout << _separator << to_string(value);\n for (bool_type value : values.getValues())\n std::cout << _separator << to_string(value);\n for (string_type value : values.getValues())\n std::cout << _separator << \"\\\"\" << value << \"\\\"\";\n }\n\n void CoutWriter::flushResults()\n {\n assert(isInitialized());\n std::cout.flush();\n }\n\n} \/* namespace DataAccess *\/\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 \"analyzer.h\"\n\n#include \"ir\/ir.h\"\n#include \"frontends\/p4\/fromv1.0\/v1model.h\"\n#include \"frontends\/p4\/typeMap.h\"\n#include \"frontends\/common\/resolveReferences\/referenceMap.h\"\n#include \"frontends\/p4\/methodInstance.h\"\n#include \"frontends\/p4\/tableApply.h\"\n\nnamespace FPGA {\n\ncstring nameFromAnnotation(const IR::Annotations* annotations,\n cstring defaultValue) {\n CHECK_NULL(annotations); CHECK_NULL(defaultValue);\n auto anno = annotations->getSingle(IR::Annotation::nameAnnotation);\n if (anno != nullptr) {\n CHECK_NULL(anno->expr);\n auto str = anno->expr->to();\n CHECK_NULL(str);\n return str->value;\n }\n return defaultValue;\n}\n\nunsigned CFG::Node::crtId = 0;\n\nvoid CFG::EdgeSet::dbprint(std::ostream& out) const {\n for (auto s : edges)\n out << \" \" << s;\n}\n\nvoid CFG::Edge::dbprint(std::ostream& out) const {\n out << endpoint->name;\n switch (type) {\n case EdgeType::True:\n out << \"(true)\";\n break;\n case EdgeType::False:\n out << \"(false)\";\n break;\n case EdgeType::Label:\n out << \"(\" << label << \")\";\n break;\n default:\n break;\n }\n}\n\nvoid CFG::Node::dbprint(std::ostream& out) const\n{ out << name << \" =>\" << successors; }\n\nvoid CFG::dbprint(std::ostream& out, CFG::Node* node, std::set &done) const {\n if (done.find(node) != done.end())\n return;\n for (auto p : node->predecessors.edges)\n dbprint(out, p->endpoint, done);\n out << std::endl << node;\n done.emplace(node);\n}\n\nvoid CFG::dbprint(std::ostream& out) const {\n out << \"CFG for \" << container;\n std::set done;\n for (auto n : allNodes)\n dbprint(out, n, done);\n}\n\nvoid CFG::Node::computeSuccessors() {\n for (auto e : predecessors.edges)\n e->getNode()->successors.emplace(e->clone(this));\n}\n\nnamespace {\n\/\/ This visitor \"converts\" IR::Node* into EdgeSets\n\/\/ Since we cannot return EdgeSets, we place them in the 'after' map.\nclass CFGBuilder : public Inspector {\n CFG* cfg;\n const CFG::EdgeSet* current; \/\/ predecessors of current node\n std::map after; \/\/ successors of each statement\n const P4::ReferenceMap* refMap;\n const P4::TypeMap* typeMap;\n\n void setAfter(const IR::Statement* statement, const CFG::EdgeSet* value) {\n LOG1(\"After \" << statement << \" \" << value);\n CHECK_NULL(statement);\n if (value == nullptr) {\n \/\/ This can happen when an error is signaled\n \/\/ one cause is assignmentStatement\n return;\n }\n after.emplace(statement, value);\n current = value;\n }\n\n const CFG::EdgeSet* get(const IR::Statement* statement) {\n return ::get(after, statement);\n }\n bool preorder(const IR::Statement* statement) override {\n \/\/::error(\"%1%: not supported in control block on this architecture\", statement);\n return false;\n }\n bool preorder(const IR::ReturnStatement* statement) override {\n if (current != nullptr) {\n cfg->exitPoint->addPredecessors(current);\n }\n setAfter(statement, new CFG::EdgeSet()); \/\/ empty successor set\n return false;\n }\n bool preorder(const IR::ExitStatement* statement) override {\n if (current != nullptr) {\n cfg->exitPoint->addPredecessors(current);\n }\n setAfter(statement, new CFG::EdgeSet()); \/\/ empty successor set\n return false;\n }\n bool preorder(const IR::EmptyStatement* statement) override {\n \/\/ unchanged 'current'\n setAfter(statement, current);\n return false;\n }\n bool preorder(const IR::MethodCallStatement* statement) override {\n auto instance = P4::MethodInstance::resolve(statement->methodCall, refMap, typeMap);\n if (!instance->is())\n return false;\n auto am = instance->to();\n if (!am->object->is()) {\n ::error(\"%1%: apply method must be on a table\", statement);\n return false;\n }\n auto tc = am->object->to();\n LOG1(\"table << \" << tc);\n auto node = cfg->makeNode(tc, statement->methodCall);\n if (current != nullptr) {\n node->addPredecessors(current);\n }\n setAfter(statement, new CFG::EdgeSet(new CFG::Edge(node)));\n return false;\n }\n bool preorder(const IR::IfStatement* statement) override {\n \/\/ We only allow expressions of the form t.apply().hit currently.\n \/\/ If the expression is more complex it should have been\n \/\/ simplified by prior passes.\n auto tc = P4::TableApplySolver::isHit(statement->condition, refMap, typeMap);\n CFG::Node* node;\n if (tc != nullptr) {\n \/\/ hit-miss case.\n LOG1(\"if << \" << tc);\n node = cfg->makeNode(tc, statement->condition);\n } else {\n node = cfg->makeNode(statement);\n }\n\n if (current != nullptr) {\n node->addPredecessors(current);\n }\n \/\/ If branch\n current = new CFG::EdgeSet(new CFG::Edge(node, true));\n visit(statement->ifTrue);\n auto ifTrue = get(statement->ifTrue);\n if (ifTrue == nullptr)\n return false;\n auto result = new CFG::EdgeSet(ifTrue);\n\n \/\/ Else branch\n if (statement->ifFalse != nullptr) {\n current = new CFG::EdgeSet(new CFG::Edge(node, false));\n visit(statement->ifFalse);\n auto ifFalse = get(statement->ifFalse);\n if (ifFalse != nullptr) {\n result->mergeWith(ifFalse);\n }\n } else {\n \/\/ no else branch\n result->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, false)));\n }\n setAfter(statement, result);\n return false;\n }\n bool preorder(const IR::BlockStatement* statement) override {\n for (auto s : *statement->components) {\n \/\/ NOTE: ignore AssignmentStatement, insert it to 'after' map will\n \/\/ break cfg.\n if (s->is())\n continue;\n auto stat = s->to();\n if (stat == nullptr) continue;\n visit(stat);\n current = get(stat);\n }\n setAfter(statement, current);\n return false;\n }\n bool preorder(const IR::SwitchStatement* statement) override {\n auto tc = P4::TableApplySolver::isActionRun(statement->expression, refMap, typeMap);\n BUG_CHECK(tc != nullptr, \"%1%: unexpected switch statement expression\",\n statement->expression);\n LOG1(\"switch << \" << tc);\n auto node = cfg->makeNode(tc, statement->expression);\n if (current != nullptr) {\n node->addPredecessors(current);\n }\n auto result = new CFG::EdgeSet(new CFG::Edge(node)); \/\/ In case no label matches\n auto labels = new CFG::EdgeSet();\n for (auto sw : statement->cases) {\n cstring label;\n if (sw->label->is()) {\n label = \"default\";\n } else {\n auto pe = sw->label->to();\n CHECK_NULL(pe);\n label = pe->path->name.name;\n }\n labels->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, label)));\n if (sw->statement != nullptr) {\n current = labels;\n visit(sw->statement);\n labels = new CFG::EdgeSet();\n } \/\/ else we accumulate edges\n if (current != nullptr) {\n result->mergeWith(current);\n }\n }\n setAfter(statement, result);\n return false;\n }\n\n public:\n CFGBuilder(CFG* cfg, const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) :\n cfg(cfg), current(nullptr), refMap(refMap), typeMap(typeMap) {}\n const CFG::EdgeSet* run(const IR::Statement* startNode, const CFG::EdgeSet* predecessors) {\n CHECK_NULL(startNode); CHECK_NULL(predecessors);\n current = predecessors;\n LOG1(\"start \" << startNode->node_type_name());\n LOG1(\"pred \" << predecessors);\n startNode->apply(*this);\n return current;\n }\n};\n} \/\/ end anonymous namespace\n\nvoid CFG::build(const IR::P4Control* cc,\n const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) {\n container = cc;\n entryPoint = makeNode(\"entry\");\n exitPoint = makeNode(\"exit\");\n\n CFGBuilder builder(this, refMap, typeMap);\n auto startValue = new CFG::EdgeSet(new CFG::Edge(entryPoint));\n auto last = builder.run(cc->body, startValue);\n LOG1(\"Before exit \" << last);\n if (last != nullptr) {\n \/\/ nullptr can happen when there is an error\n exitPoint->addPredecessors(last);\n computeSuccessors();\n }\n}\n\nnamespace {\nclass DiscoverStructure : public Inspector {\n ProgramParts* structure;\n\n public:\n explicit DiscoverStructure(ProgramParts* structure) : structure(structure) {}\n\n void postorder(const IR::ParameterList* paramList) override {\n bool inAction = findContext() != nullptr;\n unsigned index = 0;\n for (auto p : *paramList->getEnumerator()) {\n structure->index.emplace(p, index);\n if (!inAction)\n structure->nonActionParameters.emplace(p);\n index++;\n }\n }\n void postorder(const IR::P4Action* action) override {\n auto control = findContext();\n structure->actions.emplace(action, control);\n }\n void postorder(const IR::Declaration_Variable* decl) override {\n structure->variables.push_back(decl);\n }\n};\n} \/\/ namespace\n\nvoid ProgramParts::analyze(IR::ToplevelBlock* toplevel) {\n DiscoverStructure disc(this);\n toplevel->getProgram()->apply(disc);\n}\n\n} \/\/ namespace FPGA\nmake sure annotated name does not have '.'\/*\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#include \"analyzer.h\"\n\n#include \"ir\/ir.h\"\n#include \"frontends\/p4\/fromv1.0\/v1model.h\"\n#include \"frontends\/p4\/typeMap.h\"\n#include \"frontends\/common\/resolveReferences\/referenceMap.h\"\n#include \"frontends\/p4\/methodInstance.h\"\n#include \"frontends\/p4\/tableApply.h\"\n\nnamespace FPGA {\n\ncstring nameFromAnnotation(const IR::Annotations* annotations,\n cstring defaultValue) {\n CHECK_NULL(annotations); CHECK_NULL(defaultValue);\n auto anno = annotations->getSingle(IR::Annotation::nameAnnotation);\n if (anno != nullptr) {\n CHECK_NULL(anno->expr);\n auto str = anno->expr->to();\n CHECK_NULL(str);\n \/\/ NOTE: replace '.' with '_' to make bsc happy\n std::string name(str->value);\n std::replace(name.begin(), name.end(), '.', '_');\n return name.c_str();\n }\n return defaultValue;\n}\n\nunsigned CFG::Node::crtId = 0;\n\nvoid CFG::EdgeSet::dbprint(std::ostream& out) const {\n for (auto s : edges)\n out << \" \" << s;\n}\n\nvoid CFG::Edge::dbprint(std::ostream& out) const {\n out << endpoint->name;\n switch (type) {\n case EdgeType::True:\n out << \"(true)\";\n break;\n case EdgeType::False:\n out << \"(false)\";\n break;\n case EdgeType::Label:\n out << \"(\" << label << \")\";\n break;\n default:\n break;\n }\n}\n\nvoid CFG::Node::dbprint(std::ostream& out) const\n{ out << name << \" =>\" << successors; }\n\nvoid CFG::dbprint(std::ostream& out, CFG::Node* node, std::set &done) const {\n if (done.find(node) != done.end())\n return;\n for (auto p : node->predecessors.edges)\n dbprint(out, p->endpoint, done);\n out << std::endl << node;\n done.emplace(node);\n}\n\nvoid CFG::dbprint(std::ostream& out) const {\n out << \"CFG for \" << container;\n std::set done;\n for (auto n : allNodes)\n dbprint(out, n, done);\n}\n\nvoid CFG::Node::computeSuccessors() {\n for (auto e : predecessors.edges)\n e->getNode()->successors.emplace(e->clone(this));\n}\n\nnamespace {\n\/\/ This visitor \"converts\" IR::Node* into EdgeSets\n\/\/ Since we cannot return EdgeSets, we place them in the 'after' map.\nclass CFGBuilder : public Inspector {\n CFG* cfg;\n const CFG::EdgeSet* current; \/\/ predecessors of current node\n std::map after; \/\/ successors of each statement\n const P4::ReferenceMap* refMap;\n const P4::TypeMap* typeMap;\n\n void setAfter(const IR::Statement* statement, const CFG::EdgeSet* value) {\n LOG1(\"After \" << statement << \" \" << value);\n CHECK_NULL(statement);\n if (value == nullptr) {\n \/\/ This can happen when an error is signaled\n \/\/ one cause is assignmentStatement\n return;\n }\n after.emplace(statement, value);\n current = value;\n }\n\n const CFG::EdgeSet* get(const IR::Statement* statement) {\n return ::get(after, statement);\n }\n bool preorder(const IR::Statement* statement) override {\n \/\/::error(\"%1%: not supported in control block on this architecture\", statement);\n return false;\n }\n bool preorder(const IR::ReturnStatement* statement) override {\n if (current != nullptr) {\n cfg->exitPoint->addPredecessors(current);\n }\n setAfter(statement, new CFG::EdgeSet()); \/\/ empty successor set\n return false;\n }\n bool preorder(const IR::ExitStatement* statement) override {\n if (current != nullptr) {\n cfg->exitPoint->addPredecessors(current);\n }\n setAfter(statement, new CFG::EdgeSet()); \/\/ empty successor set\n return false;\n }\n bool preorder(const IR::EmptyStatement* statement) override {\n \/\/ unchanged 'current'\n setAfter(statement, current);\n return false;\n }\n bool preorder(const IR::MethodCallStatement* statement) override {\n auto instance = P4::MethodInstance::resolve(statement->methodCall, refMap, typeMap);\n if (!instance->is())\n return false;\n auto am = instance->to();\n if (!am->object->is()) {\n ::error(\"%1%: apply method must be on a table\", statement);\n return false;\n }\n auto tc = am->object->to();\n LOG1(\"table << \" << tc);\n auto node = cfg->makeNode(tc, statement->methodCall);\n if (current != nullptr) {\n node->addPredecessors(current);\n }\n setAfter(statement, new CFG::EdgeSet(new CFG::Edge(node)));\n return false;\n }\n bool preorder(const IR::IfStatement* statement) override {\n \/\/ We only allow expressions of the form t.apply().hit currently.\n \/\/ If the expression is more complex it should have been\n \/\/ simplified by prior passes.\n auto tc = P4::TableApplySolver::isHit(statement->condition, refMap, typeMap);\n CFG::Node* node;\n if (tc != nullptr) {\n \/\/ hit-miss case.\n LOG1(\"if << \" << tc);\n node = cfg->makeNode(tc, statement->condition);\n } else {\n node = cfg->makeNode(statement);\n }\n\n if (current != nullptr) {\n node->addPredecessors(current);\n }\n \/\/ If branch\n current = new CFG::EdgeSet(new CFG::Edge(node, true));\n visit(statement->ifTrue);\n auto ifTrue = get(statement->ifTrue);\n if (ifTrue == nullptr)\n return false;\n auto result = new CFG::EdgeSet(ifTrue);\n\n \/\/ Else branch\n if (statement->ifFalse != nullptr) {\n current = new CFG::EdgeSet(new CFG::Edge(node, false));\n visit(statement->ifFalse);\n auto ifFalse = get(statement->ifFalse);\n if (ifFalse != nullptr) {\n result->mergeWith(ifFalse);\n }\n } else {\n \/\/ no else branch\n result->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, false)));\n }\n setAfter(statement, result);\n return false;\n }\n bool preorder(const IR::BlockStatement* statement) override {\n for (auto s : *statement->components) {\n \/\/ NOTE: ignore AssignmentStatement, insert it to 'after' map will\n \/\/ break cfg.\n if (s->is())\n continue;\n auto stat = s->to();\n if (stat == nullptr) continue;\n visit(stat);\n current = get(stat);\n }\n setAfter(statement, current);\n return false;\n }\n bool preorder(const IR::SwitchStatement* statement) override {\n auto tc = P4::TableApplySolver::isActionRun(statement->expression, refMap, typeMap);\n BUG_CHECK(tc != nullptr, \"%1%: unexpected switch statement expression\",\n statement->expression);\n LOG1(\"switch << \" << tc);\n auto node = cfg->makeNode(tc, statement->expression);\n if (current != nullptr) {\n node->addPredecessors(current);\n }\n auto result = new CFG::EdgeSet(new CFG::Edge(node)); \/\/ In case no label matches\n auto labels = new CFG::EdgeSet();\n for (auto sw : statement->cases) {\n cstring label;\n if (sw->label->is()) {\n label = \"default\";\n } else {\n auto pe = sw->label->to();\n CHECK_NULL(pe);\n label = pe->path->name.name;\n }\n labels->mergeWith(new CFG::EdgeSet(new CFG::Edge(node, label)));\n if (sw->statement != nullptr) {\n current = labels;\n visit(sw->statement);\n labels = new CFG::EdgeSet();\n } \/\/ else we accumulate edges\n if (current != nullptr) {\n result->mergeWith(current);\n }\n }\n setAfter(statement, result);\n return false;\n }\n\n public:\n CFGBuilder(CFG* cfg, const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) :\n cfg(cfg), current(nullptr), refMap(refMap), typeMap(typeMap) {}\n const CFG::EdgeSet* run(const IR::Statement* startNode, const CFG::EdgeSet* predecessors) {\n CHECK_NULL(startNode); CHECK_NULL(predecessors);\n current = predecessors;\n LOG1(\"start \" << startNode->node_type_name());\n LOG1(\"pred \" << predecessors);\n startNode->apply(*this);\n return current;\n }\n};\n} \/\/ end anonymous namespace\n\nvoid CFG::build(const IR::P4Control* cc,\n const P4::ReferenceMap* refMap, const P4::TypeMap* typeMap) {\n container = cc;\n entryPoint = makeNode(\"entry\");\n exitPoint = makeNode(\"exit\");\n\n CFGBuilder builder(this, refMap, typeMap);\n auto startValue = new CFG::EdgeSet(new CFG::Edge(entryPoint));\n auto last = builder.run(cc->body, startValue);\n LOG1(\"Before exit \" << last);\n if (last != nullptr) {\n \/\/ nullptr can happen when there is an error\n exitPoint->addPredecessors(last);\n computeSuccessors();\n }\n}\n\nnamespace {\nclass DiscoverStructure : public Inspector {\n ProgramParts* structure;\n\n public:\n explicit DiscoverStructure(ProgramParts* structure) : structure(structure) {}\n\n void postorder(const IR::ParameterList* paramList) override {\n bool inAction = findContext() != nullptr;\n unsigned index = 0;\n for (auto p : *paramList->getEnumerator()) {\n structure->index.emplace(p, index);\n if (!inAction)\n structure->nonActionParameters.emplace(p);\n index++;\n }\n }\n void postorder(const IR::P4Action* action) override {\n auto control = findContext();\n structure->actions.emplace(action, control);\n }\n void postorder(const IR::Declaration_Variable* decl) override {\n structure->variables.push_back(decl);\n }\n};\n} \/\/ namespace\n\nvoid ProgramParts::analyze(IR::ToplevelBlock* toplevel) {\n DiscoverStructure disc(this);\n toplevel->getProgram()->apply(disc);\n}\n\n} \/\/ namespace FPGA\n<|endoftext|>"} {"text":"\/\/===-------- IncludeInserter.cpp - clang-tidy ----------------------------===\/\/\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 \"IncludeInserter.h\"\n\nnamespace clang {\nnamespace tidy {\n\nclass IncludeInserterCallback : public PPCallbacks {\npublic:\n explicit IncludeInserterCallback(IncludeInserter *IncludeInserter)\n : IncludeInserter(IncludeInserter) {}\n \/\/ Implements PPCallbacks::InclusionDerective(). Records the names and source\n \/\/ locations of the inclusions in the main source file being processed.\n void InclusionDirective(SourceLocation HashLocation,\n const Token & \/*include_token*\/,\n StringRef FileNameRef, bool IsAngled,\n CharSourceRange FileNameRange,\n const FileEntry * \/*IncludedFile*\/,\n StringRef \/*SearchPath*\/, StringRef \/*RelativePath*\/,\n const Module * \/*ImportedModule*\/) override {\n IncludeInserter->AddInclude(FileNameRef, IsAngled, HashLocation,\n FileNameRange.getEnd());\n }\n\nprivate:\n IncludeInserter *IncludeInserter;\n};\n\nIncludeInserter::IncludeInserter(const SourceManager &SourceMgr,\n const LangOptions &LangOpts,\n IncludeSorter::IncludeStyle Style)\n : SourceMgr(SourceMgr), LangOpts(LangOpts), Style(Style) {}\n\nIncludeInserter::~IncludeInserter() {}\n\nstd::unique_ptr IncludeInserter::CreatePPCallbacks() {\n return llvm::make_unique(this);\n}\n\nllvm::Optional\nIncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header,\n bool IsAngled) {\n \/\/ We assume the same Header will never be included both angled and not\n \/\/ angled.\n if (!InsertedHeaders.insert(std::make_pair(FileID, std::set()))\n .second) {\n return llvm::None;\n }\n if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {\n return llvm::None;\n }\n return IncludeSorterByFile[FileID]->CreateIncludeInsertion(Header, IsAngled);\n}\n\nvoid IncludeInserter::AddInclude(StringRef file_name, bool IsAngled,\n SourceLocation HashLocation,\n SourceLocation end_location) {\n FileID FileID = SourceMgr.getFileID(HashLocation);\n if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {\n IncludeSorterByFile.insert(std::make_pair(\n FileID, llvm::make_unique(\n &SourceMgr, &LangOpts, FileID,\n SourceMgr.getFilename(HashLocation), Style)));\n }\n IncludeSorterByFile[FileID]->AddInclude(file_name, IsAngled, HashLocation,\n end_location);\n}\n\n} \/\/ namespace tidy\n} \/\/ namespace clang\nFix shadowing of type with variable.\/\/===-------- IncludeInserter.cpp - clang-tidy ----------------------------===\/\/\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 \"IncludeInserter.h\"\n\nnamespace clang {\nnamespace tidy {\n\nclass IncludeInserterCallback : public PPCallbacks {\npublic:\n explicit IncludeInserterCallback(IncludeInserter *Inserter)\n : Inserter(Inserter) {}\n \/\/ Implements PPCallbacks::InclusionDerective(). Records the names and source\n \/\/ locations of the inclusions in the main source file being processed.\n void InclusionDirective(SourceLocation HashLocation,\n const Token & \/*include_token*\/,\n StringRef FileNameRef, bool IsAngled,\n CharSourceRange FileNameRange,\n const FileEntry * \/*IncludedFile*\/,\n StringRef \/*SearchPath*\/, StringRef \/*RelativePath*\/,\n const Module * \/*ImportedModule*\/) override {\n Inserter->AddInclude(FileNameRef, IsAngled, HashLocation,\n FileNameRange.getEnd());\n }\n\nprivate:\n IncludeInserter *Inserter;\n};\n\nIncludeInserter::IncludeInserter(const SourceManager &SourceMgr,\n const LangOptions &LangOpts,\n IncludeSorter::IncludeStyle Style)\n : SourceMgr(SourceMgr), LangOpts(LangOpts), Style(Style) {}\n\nIncludeInserter::~IncludeInserter() {}\n\nstd::unique_ptr IncludeInserter::CreatePPCallbacks() {\n return llvm::make_unique(this);\n}\n\nllvm::Optional\nIncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header,\n bool IsAngled) {\n \/\/ We assume the same Header will never be included both angled and not\n \/\/ angled.\n if (!InsertedHeaders.insert(std::make_pair(FileID, std::set()))\n .second) {\n return llvm::None;\n }\n if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {\n return llvm::None;\n }\n return IncludeSorterByFile[FileID]->CreateIncludeInsertion(Header, IsAngled);\n}\n\nvoid IncludeInserter::AddInclude(StringRef file_name, bool IsAngled,\n SourceLocation HashLocation,\n SourceLocation end_location) {\n FileID FileID = SourceMgr.getFileID(HashLocation);\n if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) {\n IncludeSorterByFile.insert(std::make_pair(\n FileID, llvm::make_unique(\n &SourceMgr, &LangOpts, FileID,\n SourceMgr.getFilename(HashLocation), Style)));\n }\n IncludeSorterByFile[FileID]->AddInclude(file_name, IsAngled, HashLocation,\n end_location);\n}\n\n} \/\/ namespace tidy\n} \/\/ namespace clang\n<|endoftext|>"} {"text":"\/**\n * @author Ryan Huang \n * @organization University of California, San Diego\n * \n * Sample test of Tachyon C\/C++ APIs\n *\n *\/\n\n#include \"Tachyon.h\"\n#include \"Util.h\"\n\n#include \n#include \n#include \n\nusing namespace tachyon;\n\nconst char * program_name;\n\nconst char *masterUri;\nconst char *filePath;\n\nconst char *writef = \"\/hello.txt\";\n\nvoid usage()\n{\n fprintf(stderr, \"\\n\\tUsage: %s masterUri testFilePath\\n\\n\", program_name);\n}\n\nvoid testGetFile(jTachyonClient client, const char *fpath)\n{\n jTachyonFile file = client->getFile(fpath);\n if (file == NULL) {\n die(\"fail to get tachyon file: %s\", fpath);\n }\n int fid = client->getFileId(fpath);\n if (fid < 0) {\n die(\"fail to get file id for %s\", fpath);\n }\n long size = file->length();\n if (size < 0) {\n die(\"fail to get tachyon file size\");\n }\n printf(\"got tachyon file, size: %ld, id: %d\\n\", size, fid);\n if (file->isFile() == true) {\n printf(\"Is a regular file\\n\");\n } else {\n printf(\"Not a regular file\\n\");\n }\n \n char * rpath = file->getPath();\n if (rpath == NULL) {\n die(\"fail to get tachyon file path\");\n }\n\n printf(\"===================================\\n\");\n printf(\" content for : %s \\n\", rpath);\n printf(\"===================================\\n\");\n free(rpath);\n\n jInStream istream = file->getInStream(NO_CACHE);\n if (istream == NULL) {\n die(\"fail to get tachyon file instream\");\n }\n\n char buf[512];\n int rdSz = istream->read(buf, 511);\n while (rdSz > 0) {\n if (rdSz >= 512) {\n printf(\"impossible read size\\n\");\n break;\n }\n buf[rdSz] = '\\0';\n printf(\"%s\", buf);\n rdSz = istream->read(buf, 511);\n }\n istream->close(); \/\/ close istream\n printf(\"\\n\");\n printf(\"===================================\\n\");\n}\n\nvoid testMkdir(jTachyonClient client, const char *path)\n{\n bool ok = client->mkdir(path);\n if (!ok) {\n die(\"fail to create tachyon dir %s\", path);\n }\n printf(\"created tachyon dir %s\\n\", path);\n}\n\nvoid testCreateFile(jTachyonClient client, const char *path)\n{\n char *rpath;\n int fid = client->createFile(path);\n if (fid < 0) {\n die(\"fail to create tachyon file %s\", path);\n }\n printf(\"created tachyon file fid:%d\\n\", fid);\n jTachyonFile nfile = client->getFile(fid);\n if (nfile == NULL) {\n die(\"fail to get the created file\");\n }\n rpath = nfile->getPath();\n if (rpath == NULL) {\n die(\"fail to get tachyon file path\");\n }\n printf(\"the created tachyon file has path: %s\\n\", rpath);\n free(rpath);\n}\n\nvoid testWriteFile(jTachyonClient client, const char *path)\n{\n jTachyonFile nfile = client->getFile(path);\n char content[] = \"hello, tachyon!!\\n\";\n jOutStream ostream = nfile->getOutStream(MUST_CACHE);\n if (ostream == NULL) {\n die(\"fail to get outstream\");\n }\n ostream->write(content, strlen(content));\n ostream->close();\n\n jInStream istream = nfile->getInStream(CACHE);\n char buf[32];\n int rdSz = istream->read(buf, 31);\n buf[rdSz] = '\\0';\n printf(\"Content of the created file:\\n\");\n printf(\"%s\\n\", buf);\n istream->close(); \/\/ close istream\n}\n\nvoid testDeleteFile(jTachyonClient client, const char *path, bool recursive)\n{\n bool ok = client->deletePath(path, recursive);\n if (!ok) {\n die(\"fail to delete path %s\", path);\n }\n printf(\"successfully deleted path %s\\n\", path);\n}\n\nint main(int argc, char*argv[])\n{\n program_name = argv[0];\n if (argc != 3) {\n usage();\n exit(1);\n }\n masterUri = argv[1];\n filePath = argv[2];\n\n jTachyonClient client = TachyonClient::createClient(masterUri);\n if (client == NULL) {\n die(\"fail to create tachyon client\");\n }\n char * fullFilePath = fullTachyonPath(masterUri, filePath);\n testGetFile(client, fullFilePath);\n testCreateFile(client, writef);\n testWriteFile(client, writef);\n testDeleteFile(client, writef, false);\n testMkdir(client, \"\/kvstore\");\n testDeleteFile(client, \"\/kvstore\", true);\n return 0;\n}\n\n\/* vim: set ts=4 sw=4 : *\/\nrelease tachyon objects in test\/**\n * @author Ryan Huang \n * @organization University of California, San Diego\n * \n * Sample test of Tachyon C\/C++ APIs\n *\n *\/\n\n#include \"Tachyon.h\"\n#include \"Util.h\"\n\n#include \n#include \n#include \n\nusing namespace tachyon;\n\nconst char * program_name;\n\nconst char *masterUri;\nconst char *filePath;\n\nconst char *writef = \"\/hello.txt\";\n\nvoid usage()\n{\n fprintf(stderr, \"\\n\\tUsage: %s masterUri testFilePath\\n\\n\", program_name);\n}\n\nvoid testGetFile(jTachyonClient client, const char *fpath)\n{\n jTachyonFile nfile = client->getFile(fpath);\n if (nfile == NULL) {\n die(\"fail to get tachyon file: %s\", fpath);\n }\n int fid = client->getFileId(fpath);\n if (fid < 0) {\n die(\"fail to get file id for %s\", fpath);\n }\n long size = nfile->length();\n if (size < 0) {\n die(\"fail to get tachyon file size\");\n }\n printf(\"got tachyon file, size: %ld, id: %d\\n\", size, fid);\n if (nfile->isFile() == true) {\n printf(\"Is a regular file\\n\");\n } else {\n printf(\"Not a regular file\\n\");\n }\n \n char * rpath = nfile->getPath();\n if (rpath == NULL) {\n die(\"fail to get tachyon file path\");\n }\n\n printf(\"===================================\\n\");\n printf(\" content for : %s \\n\", rpath);\n printf(\"===================================\\n\");\n free(rpath);\n\n jInStream istream = nfile->getInStream(NO_CACHE);\n if (istream == NULL) {\n die(\"fail to get tachyon file instream\");\n }\n\n char buf[512];\n int rdSz = istream->read(buf, 511);\n while (rdSz > 0) {\n if (rdSz >= 512) {\n printf(\"impossible read size\\n\");\n break;\n }\n buf[rdSz] = '\\0';\n printf(\"%s\", buf);\n rdSz = istream->read(buf, 511);\n }\n istream->close(); \/\/ close istream\n printf(\"\\n\");\n printf(\"===================================\\n\");\n delete istream;\n delete nfile;\n}\n\nvoid testMkdir(jTachyonClient client, const char *path)\n{\n bool ok = client->mkdir(path);\n if (!ok) {\n die(\"fail to create tachyon dir %s\", path);\n }\n printf(\"created tachyon dir %s\\n\", path);\n}\n\nvoid testCreateFile(jTachyonClient client, const char *path)\n{\n char *rpath;\n int fid = client->createFile(path);\n if (fid < 0) {\n die(\"fail to create tachyon file %s\", path);\n }\n printf(\"created tachyon file fid:%d\\n\", fid);\n jTachyonFile nfile = client->getFile(fid);\n if (nfile == NULL) {\n die(\"fail to get the created file\");\n }\n rpath = nfile->getPath();\n if (rpath == NULL) {\n die(\"fail to get tachyon file path\");\n }\n printf(\"the created tachyon file has path: %s\\n\", rpath);\n free(rpath);\n delete nfile;\n}\n\nvoid testWriteFile(jTachyonClient client, const char *path)\n{\n jTachyonFile nfile = client->getFile(path);\n char content[] = \"hello, tachyon!!\\n\";\n jOutStream ostream = nfile->getOutStream(MUST_CACHE);\n if (ostream == NULL) {\n die(\"fail to get outstream\");\n }\n ostream->write(content, strlen(content));\n ostream->close();\n delete ostream; \/\/ release the jobject\n\n jInStream istream = nfile->getInStream(CACHE);\n char buf[32];\n int rdSz = istream->read(buf, 31);\n buf[rdSz] = '\\0';\n printf(\"Content of the created file:\\n\");\n printf(\"%s\\n\", buf);\n istream->close(); \/\/ close istream\n delete istream; \/\/ release the jobject\n delete nfile;\n}\n\nvoid testDeleteFile(jTachyonClient client, const char *path, bool recursive)\n{\n bool ok = client->deletePath(path, recursive);\n if (!ok) {\n die(\"fail to delete path %s\", path);\n }\n printf(\"successfully deleted path %s\\n\", path);\n}\n\nint main(int argc, char*argv[])\n{\n program_name = argv[0];\n if (argc != 3) {\n usage();\n exit(1);\n }\n masterUri = argv[1];\n filePath = argv[2];\n\n jTachyonClient client = TachyonClient::createClient(masterUri);\n if (client == NULL) {\n die(\"fail to create tachyon client\");\n }\n char * fullFilePath = fullTachyonPath(masterUri, filePath);\n testGetFile(client, fullFilePath);\n testCreateFile(client, writef);\n testWriteFile(client, writef);\n testDeleteFile(client, writef, false);\n testMkdir(client, \"\/kvstore\");\n testDeleteFile(client, \"\/kvstore\", true);\n delete client;\n return 0;\n}\n\n\/* vim: set ts=4 sw=4 : *\/\n<|endoftext|>"} {"text":"#include \"Common.h\"\r\n#include \"Install.h\"\r\n#include \"PathUtil.h\"\r\n\/\/ Maybe: not ideal, decouple this via SetAppDirName() instead of APP_DIR_NAME\r\n#include \"ve8.h\"\r\n\r\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb773569(v=vs.85).aspx\r\n\/\/ TODO: on win8 use PathCchCanonicalize or PathCchCanonicalizeEx\r\nvoid NormalizePathInPlace(WCHAR *src, size_t srcCchSize) {\r\n \/\/ TODO: make it work even if srcCchSize is < MAX_PATH\r\n CrashIf(srcCchSize < MAX_PATH);\r\n WCHAR buf[MAX_PATH];\r\n BOOL ok = PathCanonicalizeW(buf, src);\r\n if (!ok) {\r\n return;\r\n }\r\n memcpy(src, buf, sizeof(buf));\r\n}\r\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms683197(v=vs.85).aspx\r\nstatic std::string GetExePath() {\r\n WCHAR buf[1024*4];\r\n \/\/ it's full path, not name\r\n DWORD bufCchSize = dimof(buf);\r\n DWORD ret = GetModuleFileNameW(NULL, buf, bufCchSize);\n CrashIf(ret == 0);\n \/\/ on XP it returns bufCchSize if buffer too small\n CrashIf(ret == bufCchSize);\n \/\/ post XP error is indicated by GetLastError()\n CrashIfLastError();\n NormalizePathInPlace(buf, dimof(buf));\n return WstrToUtf8Str(buf);\r\n}\r\n\r\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb762181(v=vs.85).aspx\r\nstatic std::string GetKnownFolderPathXp(int nFolder) {\r\n WCHAR buf[MAX_PATH];\r\n \/\/ TODO: on Vista+ use SHGetSpecialFolderPath, SHGetFolderPath is deprecated\r\n HRESULT hr = SHGetFolderPath(NULL, nFolder, NULL, SHGFP_TYPE_DEFAULT, buf);\r\n CrashIf(hr != S_OK);\r\n return WstrToUtf8Str(buf);\r\n}\r\n\r\n\/\/ TODO: make it GetLocalAppDir(const char *add1 = NULL, const char *add2 = NULL, const char *add3 = NULL)\r\n\/\/ so that GetInstallationBaseDir() is just return GetLocalAppDir(\"velociraptor8\")\r\nstd::string GetLocalAppDir() {\r\n return GetKnownFolderPathXp(CSIDL_LOCAL_APPDATA);\r\n}\r\n\r\nstd::string GetInstallationBaseDir() {\r\n auto path = GetLocalAppDir();\r\n path::Join(path, APP_DIR_NAME);\r\n return path;\r\n}\r\n\r\nstd::string GetInstallationBinDir() {\r\n auto path = GetInstallationBaseDir();\r\n path::Join(path, \"bin\");\r\n return path;\r\n}\r\n\r\n\/\/ we consider the program installed if the exe is in the installation\r\n\/\/ directory\r\nbool IsRunningInstalled() {\r\n auto exePath = GetExePath();\r\n auto binDir = GetInstallationBinDir();\r\n \/\/ Maybe: compare for equality?\r\n auto pos = exePath.find(binDir);\r\n return pos == 0;\r\n}\r\n\r\nbool IsRunnignPortable() {\r\n return !IsRunningInstalled();\r\n}\r\nnewlines#include \"Common.h\"\r\n#include \"Install.h\"\r\n#include \"PathUtil.h\"\r\n\/\/ Maybe: not ideal, decouple this via SetAppDirName() instead of APP_DIR_NAME\r\n#include \"ve8.h\"\r\n\r\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb773569(v=vs.85).aspx\r\n\/\/ TODO: on win8 use PathCchCanonicalize or PathCchCanonicalizeEx\r\nvoid NormalizePathInPlace(WCHAR *src, size_t srcCchSize) {\r\n \/\/ TODO: make it work even if srcCchSize is < MAX_PATH\r\n CrashIf(srcCchSize < MAX_PATH);\r\n WCHAR buf[MAX_PATH];\r\n BOOL ok = PathCanonicalizeW(buf, src);\r\n if (!ok) {\r\n return;\r\n }\r\n memcpy(src, buf, sizeof(buf));\r\n}\r\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms683197(v=vs.85).aspx\r\nstatic std::string GetExePath() {\r\n WCHAR buf[1024*4];\r\n \/\/ it's full path, not name\r\n DWORD bufCchSize = dimof(buf);\r\n DWORD ret = GetModuleFileNameW(NULL, buf, bufCchSize);\r\n CrashIf(ret == 0);\r\n \/\/ on XP it returns bufCchSize if buffer too small\r\n CrashIf(ret == bufCchSize);\r\n \/\/ post XP error is indicated by GetLastError()\r\n CrashIfLastError();\r\n NormalizePathInPlace(buf, dimof(buf));\r\n return WstrToUtf8Str(buf);\r\n}\r\n\r\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb762181(v=vs.85).aspx\r\nstatic std::string GetKnownFolderPathXp(int nFolder) {\r\n WCHAR buf[MAX_PATH];\r\n \/\/ TODO: on Vista+ use SHGetSpecialFolderPath, SHGetFolderPath is deprecated\r\n HRESULT hr = SHGetFolderPath(NULL, nFolder, NULL, SHGFP_TYPE_DEFAULT, buf);\r\n CrashIf(hr != S_OK);\r\n return WstrToUtf8Str(buf);\r\n}\r\n\r\n\/\/ TODO: make it GetLocalAppDir(const char *add1 = NULL, const char *add2 = NULL, const char *add3 = NULL)\r\n\/\/ so that GetInstallationBaseDir() is just return GetLocalAppDir(\"velociraptor8\")\r\nstd::string GetLocalAppDir() {\r\n return GetKnownFolderPathXp(CSIDL_LOCAL_APPDATA);\r\n}\r\n\r\nstd::string GetInstallationBaseDir() {\r\n auto path = GetLocalAppDir();\r\n path::Join(path, APP_DIR_NAME);\r\n return path;\r\n}\r\n\r\nstd::string GetInstallationBinDir() {\r\n auto path = GetInstallationBaseDir();\r\n path::Join(path, \"bin\");\r\n return path;\r\n}\r\n\r\n\/\/ we consider the program installed if the exe is in the installation\r\n\/\/ directory\r\nbool IsRunningInstalled() {\r\n auto exePath = GetExePath();\r\n auto binDir = GetInstallationBinDir();\r\n \/\/ Maybe: compare for equality?\r\n auto pos = exePath.find(binDir);\r\n return pos == 0;\r\n}\r\n\r\nbool IsRunnignPortable() {\r\n return !IsRunningInstalled();\r\n}\r\n<|endoftext|>"} {"text":"remove unused const<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: unomodel.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2001-09-13 08:24:44 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef UNOMODEL_HXX\n#define UNOMODEL_HXX\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include \n#endif\n#ifndef _SFX_SFXBASEMODEL_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_PROPERTYSETHELPER_HXX_\n#include \n#endif\n\nclass SmFormat;\n\n\/\/-----------------------------------------------------------------------------\nclass SmModel : public SfxBaseModel,\n public comphelper::PropertySetHelper,\n public com::sun::star::lang::XServiceInfo,\n public com::sun::star::lang::XUnoTunnel\n{\nprotected:\n virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException );\n virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException );\npublic:\n SmModel( SfxObjectShell *pObjSh = 0 );\n virtual ~SmModel() throw ();\n\n \/\/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( )\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL release( )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);\n\n static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();\n\n \/\/XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/XServiceInfo\n virtual rtl::OUString SAL_CALL getImplementationName(void)\n throw( ::com::sun::star::uno::RuntimeException );\n virtual BOOL SAL_CALL supportsService(const rtl::OUString& ServiceName)\n throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void)\n throw( ::com::sun::star::uno::RuntimeException );\n\n inline ::rtl::OUString SmModel::getImplementationName_Static() throw( );\n};\n\ninline ::rtl::OUString SmModel::getImplementationName_Static() throw( )\n{\n return rtl::OUString::createFromAscii(\"math.SmModel\");\n}\n\n#endif\n#92924#: exception specifications\/*************************************************************************\n *\n * $RCSfile: unomodel.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2001-10-18 12:10:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef UNOMODEL_HXX\n#define UNOMODEL_HXX\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_\n#include \n#endif\n#ifndef _SFX_SFXBASEMODEL_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_PROPERTYSETHELPER_HXX_\n#include \n#endif\n\nclass SmFormat;\n\n\/\/-----------------------------------------------------------------------------\nclass SmModel : public SfxBaseModel,\n public comphelper::PropertySetHelper,\n public com::sun::star::lang::XServiceInfo,\n public com::sun::star::lang::XUnoTunnel\n{\nprotected:\n virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException );\n virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue )\n throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException );\npublic:\n SmModel( SfxObjectShell *pObjSh = 0 );\n virtual ~SmModel() throw ();\n\n \/\/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 \/\/XTypeProvider\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException);\n\n static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId();\n\n \/\/XUnoTunnel\n virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/XServiceInfo\n virtual rtl::OUString SAL_CALL getImplementationName(void)\n throw( ::com::sun::star::uno::RuntimeException );\n virtual BOOL SAL_CALL supportsService(const rtl::OUString& ServiceName)\n throw( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void)\n throw( ::com::sun::star::uno::RuntimeException );\n\n inline ::rtl::OUString SmModel::getImplementationName_Static() throw( );\n};\n\ninline ::rtl::OUString SmModel::getImplementationName_Static() throw( )\n{\n return rtl::OUString::createFromAscii(\"math.SmModel\");\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file LexBaan.cxx\n ** Lexer for Baan.\n ** Based heavily on LexCPP.cxx\n **\/\n\/\/ Copyright 2001- by Vamsi Potluru & Praveen Ambekar \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\ninline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '$' || ch == ':');\n}\n\ninline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\nstatic void ColouriseBaanDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],\n Accessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\tWordList &keywords2 = *keywordlists[1];\n\tbool stylingWithinPreprocessor = styler.GetPropertyInt(\"styling.within.preprocessor\");\n\n\tif (initStyle == SCE_BAAN_STRINGEOL)\t\/\/ Does not leak onto next line\n\t\tinitStyle = SCE_BAAN_DEFAULT;\n\n\tint visibleChars = 0;\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward()) {\n\n\t\tif (sc.state == SCE_BAAN_OPERATOR) {\n\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t} else if (sc.state == SCE_BAAN_NUMBER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_IDENTIFIER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_BAAN_WORD);\n\t\t\t\t} else if (keywords2.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_BAAN_WORD2);\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_PREPROCESSOR) {\n\t\t\tif (stylingWithinPreprocessor) {\n\t\t\t\tif (IsASpace(sc.ch)) {\n\t\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (sc.atLineEnd && (sc.chNext != '^')) {\n\t\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_COMMENT) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_COMMENTDOC) {\n\t\t\tif (sc.MatchIgnoreCase(\"enddllusage\")) {\n\t\t\t\tfor (unsigned int i = 0; i < 10; i++){\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tsc.ForwardSetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_STRING) {\n\t\t\tif (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_BAAN_DEFAULT);\n\t\t\t} else if ((sc.atLineEnd) && (sc.chNext != '^')) {\n\t\t\t\tsc.ChangeState(SCE_BAAN_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_C_DEFAULT);\n\t\t\t\tvisibleChars = 0;\n\t\t\t}\n\t\t}\n\n\t\tif (sc.state == SCE_BAAN_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_BAAN_NUMBER);\n\t\t\t} else if (sc.MatchIgnoreCase(\"dllusage\")){\n\t\t\t\t\tsc.SetState(SCE_BAAN_COMMENTDOC);\n\t\t\t\t\tdo {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t} while ((!sc.atLineEnd) && sc.More());\n\t\t\t} else if (IsAWordStart(sc.ch)) {\n\t\t\t\t\tsc.SetState(SCE_BAAN_IDENTIFIER);\n\t\t\t} else if (sc.Match('|')){\n\t\t\t\t\tsc.SetState(SCE_BAAN_COMMENT);\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.SetState(SCE_BAAN_STRING);\n\t\t\t} else if (sc.ch == '#' && visibleChars == 0) {\n\t\t\t\t\/\/ Preprocessor commands are alone on their line\n\t\t\t\tsc.SetState(SCE_BAAN_PREPROCESSOR);\n\t\t\t\t\/\/ Skip whitespace between # and preprocessor word\n\t\t\t\tdo {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t} while (IsASpace(sc.ch) && sc.More());\n\t\t\t} else if (isoperator(static_cast(sc.ch))) {\n\t\t\t\tsc.SetState(SCE_BAAN_OPERATOR);\n\t\t\t}\n\t\t}\n\t\tif (sc.atLineEnd) {\n\t\t\t\/\/ Reset states to begining of colourise so no surprises\n\t\t\t\/\/ if different sets of lines lexed.\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!IsASpace(sc.ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void FoldBaanDoc(unsigned int startPos, int length, int initStyle, WordList *[],\n Accessor &styler) {\n\tbool foldComment = styler.GetPropertyInt(\"fold.comment\");\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1);\n\tunsigned int endPos = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tint styleNext = styler.StyleAt(startPos);\n\tint style = initStyle;\n\tfor (unsigned int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint stylePrev = style;\n\t\tstyle = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (foldComment &&\n\t\t\t(style == SCE_BAAN_COMMENT || style == SCE_BAAN_COMMENTDOC)) {\n\t\t\tif (style != stylePrev) {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if ((style != styleNext) && !atEOL) {\n\t\t\t\t\/\/ Comments don't end at end of line and the next character may be unstyled.\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\t\tif (style == SCE_BAAN_OPERATOR) {\n\t\t\tif (ch == '{') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == '}') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0 && foldCompact)\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0))\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch))\n\t\t\tvisibleChars++;\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nLexerModule lmBAAN(SCLEX_BAAN, ColouriseBaanDoc, \"baan\", FoldBaanDoc);\nChanged lexer name to mathc KeyWords.cxx.\/\/ Scintilla source code edit control\n\/** @file LexBaan.cxx\n ** Lexer for Baan.\n ** Based heavily on LexCPP.cxx\n **\/\n\/\/ Copyright 2001- by Vamsi Potluru & Praveen Ambekar \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\ninline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '$' || ch == ':');\n}\n\ninline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\nstatic void ColouriseBaanDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],\n Accessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\tWordList &keywords2 = *keywordlists[1];\n\tbool stylingWithinPreprocessor = styler.GetPropertyInt(\"styling.within.preprocessor\");\n\n\tif (initStyle == SCE_BAAN_STRINGEOL)\t\/\/ Does not leak onto next line\n\t\tinitStyle = SCE_BAAN_DEFAULT;\n\n\tint visibleChars = 0;\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\n\tfor (; sc.More(); sc.Forward()) {\n\n\t\tif (sc.state == SCE_BAAN_OPERATOR) {\n\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t} else if (sc.state == SCE_BAAN_NUMBER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_IDENTIFIER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_BAAN_WORD);\n\t\t\t\t} else if (keywords2.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_BAAN_WORD2);\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_PREPROCESSOR) {\n\t\t\tif (stylingWithinPreprocessor) {\n\t\t\t\tif (IsASpace(sc.ch)) {\n\t\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (sc.atLineEnd && (sc.chNext != '^')) {\n\t\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_COMMENT) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_COMMENTDOC) {\n\t\t\tif (sc.MatchIgnoreCase(\"enddllusage\")) {\n\t\t\t\tfor (unsigned int i = 0; i < 10; i++){\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tsc.ForwardSetState(SCE_BAAN_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_BAAN_STRING) {\n\t\t\tif (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_BAAN_DEFAULT);\n\t\t\t} else if ((sc.atLineEnd) && (sc.chNext != '^')) {\n\t\t\t\tsc.ChangeState(SCE_BAAN_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_C_DEFAULT);\n\t\t\t\tvisibleChars = 0;\n\t\t\t}\n\t\t}\n\n\t\tif (sc.state == SCE_BAAN_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_BAAN_NUMBER);\n\t\t\t} else if (sc.MatchIgnoreCase(\"dllusage\")){\n\t\t\t\t\tsc.SetState(SCE_BAAN_COMMENTDOC);\n\t\t\t\t\tdo {\n\t\t\t\t\t\tsc.Forward();\n\t\t\t\t\t} while ((!sc.atLineEnd) && sc.More());\n\t\t\t} else if (IsAWordStart(sc.ch)) {\n\t\t\t\t\tsc.SetState(SCE_BAAN_IDENTIFIER);\n\t\t\t} else if (sc.Match('|')){\n\t\t\t\t\tsc.SetState(SCE_BAAN_COMMENT);\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.SetState(SCE_BAAN_STRING);\n\t\t\t} else if (sc.ch == '#' && visibleChars == 0) {\n\t\t\t\t\/\/ Preprocessor commands are alone on their line\n\t\t\t\tsc.SetState(SCE_BAAN_PREPROCESSOR);\n\t\t\t\t\/\/ Skip whitespace between # and preprocessor word\n\t\t\t\tdo {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t} while (IsASpace(sc.ch) && sc.More());\n\t\t\t} else if (isoperator(static_cast(sc.ch))) {\n\t\t\t\tsc.SetState(SCE_BAAN_OPERATOR);\n\t\t\t}\n\t\t}\n\t\tif (sc.atLineEnd) {\n\t\t\t\/\/ Reset states to begining of colourise so no surprises\n\t\t\t\/\/ if different sets of lines lexed.\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!IsASpace(sc.ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void FoldBaanDoc(unsigned int startPos, int length, int initStyle, WordList *[],\n Accessor &styler) {\n\tbool foldComment = styler.GetPropertyInt(\"fold.comment\");\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1);\n\tunsigned int endPos = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tint styleNext = styler.StyleAt(startPos);\n\tint style = initStyle;\n\tfor (unsigned int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint stylePrev = style;\n\t\tstyle = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (foldComment &&\n\t\t\t(style == SCE_BAAN_COMMENT || style == SCE_BAAN_COMMENTDOC)) {\n\t\t\tif (style != stylePrev) {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if ((style != styleNext) && !atEOL) {\n\t\t\t\t\/\/ Comments don't end at end of line and the next character may be unstyled.\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\t\tif (style == SCE_BAAN_OPERATOR) {\n\t\t\tif (ch == '{') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == '}') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0 && foldCompact)\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0))\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch))\n\t\t\tvisibleChars++;\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nLexerModule lmBaan(SCLEX_BAAN, ColouriseBaanDoc, \"baan\", FoldBaanDoc);\n<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file LexYAML.cxx\n ** Lexer for YAML.\n **\/\n\/\/ Copyright 2003- by Sean O'Dell \n\/\/ Release under the same license as Scintilla\/SciTE.\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\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic const char * const yamlWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic inline bool AtEOL(Accessor &styler, unsigned int i) {\n\treturn (styler[i] == '\\n') ||\n\t\t((styler[i] == '\\r') && (styler.SafeGetCharAt(i + 1) != '\\n'));\n}\n\nstatic unsigned int SpaceCount(char* lineBuffer) {\n\tif (lineBuffer == NULL)\n\t\treturn 0;\n\n\tchar* headBuffer = lineBuffer;\n\n\twhile (*headBuffer == ' ')\n\t\theadBuffer++;\n\n\treturn headBuffer - lineBuffer;\n}\n\n#define YAML_STATE_BITSIZE 16\n#define YAML_STATE_MASK\t\t\t(0xFFFF0000)\n#define YAML_STATE_DOCUMENT\t\t(1 << YAML_STATE_BITSIZE)\n#define YAML_STATE_VALUE\t\t\t(2 << YAML_STATE_BITSIZE)\n#define YAML_STATE_COMMENT\t\t(3 << YAML_STATE_BITSIZE)\n#define YAML_STATE_TEXT_PARENT\t(4 << YAML_STATE_BITSIZE)\n#define YAML_STATE_TEXT\t\t\t(5 << YAML_STATE_BITSIZE)\n\nstatic void ColouriseYAMLLine(\n\tchar *lineBuffer,\n\tunsigned int currentLine,\n\tunsigned int lengthLine,\n\tunsigned int startLine,\n\tunsigned int endPos,\n\tWordList &keywords,\n\tAccessor &styler) {\n\n\tunsigned int i = 0;\n\tbool bInQuotes = false;\n\tunsigned int indentAmount = SpaceCount(lineBuffer);\n\n\tif (currentLine > 0) {\n\t\tint parentLineState = styler.GetLineState(currentLine - 1);\n\n\t\tif ((parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT || (parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT_PARENT) {\n\t\t\tunsigned int parentIndentAmount = parentLineState&(~YAML_STATE_MASK);\n\t\t\tif (indentAmount > parentIndentAmount) {\n\t\t\t\tstyler.SetLineState(currentLine, YAML_STATE_TEXT | parentIndentAmount);\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_TEXT);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tstyler.SetLineState(currentLine, 0);\n\tif (strncmp(lineBuffer, \"---\", 3) == 0) {\t\/\/ Document marker\n\t\tstyler.SetLineState(currentLine, YAML_STATE_DOCUMENT);\n\t\tstyler.ColourTo(endPos, SCE_YAML_DOCUMENT);\n\t\treturn;\n\t}\n\t\/\/ Skip initial spaces\n\twhile ((i < lengthLine) && lineBuffer[i] == ' ') { \/\/ YAML always uses space, never TABS or anything else\n\t\ti++;\n\t}\n\tif (lineBuffer[i] == '\\t') { \/\/ if we skipped all spaces, and we are NOT inside a text block, this is wrong\n\t\tstyler.ColourTo(endPos, SCE_YAML_ERROR);\n\t\treturn;\n\t}\n\tif (lineBuffer[i] == '#') {\t\/\/ Comment\n\t\tstyler.SetLineState(currentLine, YAML_STATE_COMMENT);\n\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\treturn;\n\t}\n\twhile (i < lengthLine) {\n\t\tif (lineBuffer[i] == '\\'' || lineBuffer[i] == '\\\"') {\n\t\t\tbInQuotes = !bInQuotes;\n\t\t} else if (lineBuffer[i] == ':' && !bInQuotes) {\n\t\t\tstyler.ColourTo(startLine + i - 1, SCE_YAML_IDENTIFIER);\n\t\t\tstyler.ColourTo(startLine + i, SCE_YAML_OPERATOR);\n\t\t\t\/\/ Non-folding scalar\n\t\t\ti++;\n\t\t\twhile ((i < lengthLine) && isspacechar(lineBuffer[i]))\n\t\t\t\ti++;\n\t\t\tunsigned int endValue = lengthLine - 1;\n\t\t\twhile ((endValue >= i) && isspacechar(lineBuffer[endValue]))\n\t\t\t\tendValue--;\n\t\t\tlineBuffer[endValue + 1] = '\\0';\n\t\t\tif (lineBuffer[i] == '|' || lineBuffer[i] == '>') {\n\t\t\t\ti++;\n\t\t\t\tif (lineBuffer[i] == '+' || lineBuffer[i] == '-')\n\t\t\t\t\ti++;\n\t\t\t\twhile ((i < lengthLine) && isspacechar(lineBuffer[i]))\n\t\t\t\t\ti++;\n\t\t\t\tif (lineBuffer[i] == '\\0') {\n\t\t\t\t\tstyler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount);\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (lineBuffer[i] == '#') {\n\t\t\t\t\tstyler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount);\n\t\t\t\t\tstyler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT);\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_ERROR);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (lineBuffer[i] == '#') {\n\t\t\t\tstyler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT);\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstyler.SetLineState(currentLine, YAML_STATE_VALUE);\n\t\t\tif (lineBuffer[i] == '&' || lineBuffer[i] == '*') {\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_REFERENCE);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (keywords.InList(&lineBuffer[i])) { \/\/ Convertible value (true\/false, etc.)\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_KEYWORD);\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tunsigned int i2 = i;\n\t\t\t\twhile ((i < lengthLine) && lineBuffer[i]) {\n\t\t\t\t\tif (!(isascii(lineBuffer[i]) && isdigit(lineBuffer[i])) && lineBuffer[i] != '-' && lineBuffer[i] != '.' && lineBuffer[i] != ',') {\n\t\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tif (i > i2) {\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_NUMBER);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak; \/\/ shouldn't get here, but just in case, the rest of the line is coloured the default\n\t\t}\n\t\ti++;\n\t}\n\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n}\n\nstatic void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) {\n\tchar lineBuffer[1024];\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tunsigned int linePos = 0;\n\tunsigned int startLine = startPos;\n\tunsigned int endPos = startPos + length;\n\tunsigned int maxPos = styler.Length();\n\tunsigned int lineCurrent = styler.GetLine(startPos);\n\n\tfor (unsigned int i = startPos; i < maxPos && i < endPos; i++) {\n\t\tlineBuffer[linePos++] = styler[i];\n\t\tif (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {\n\t\t\t\/\/ End of line (or of line buffer) met, colourise it\n\t\t\tlineBuffer[linePos] = '\\0';\n\t\t\tColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, i, *keywordLists[0], styler);\n\t\t\tlinePos = 0;\n\t\t\tstartLine = i + 1;\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n\tif (linePos > 0) {\t\/\/ Last line does not have ending characters\n\t\tColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, startPos + length - 1, *keywordLists[0], styler);\n\t}\n}\n\nstatic bool IsCommentLine(int line, Accessor &styler) {\n\tint pos = styler.LineStart(line);\n\tif (styler[pos] == '#')\n\t\treturn true;\n\treturn false;\n}\n\nstatic void FoldYAMLDoc(unsigned int startPos, int length, int \/*initStyle - unused*\/,\n WordList *[], Accessor &styler) {\n\tconst int maxPos = startPos + length;\n\tconst int maxLines = styler.GetLine(maxPos - 1); \/\/ Requested last line\n\tconst int docLines = styler.GetLine(styler.Length() - 1); \/\/ Available last line\n\tconst bool foldComment = styler.GetPropertyInt(\"fold.comment.yaml\") != 0;\n\n\t\/\/ Backtrack to previous non-blank line so we can determine indent level\n\t\/\/ for any white space lines\n\t\/\/ and so we can fix any preceding fold level (which is why we go back\n\t\/\/ at least one line in all cases)\n\tint spaceFlags = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);\n\twhile (lineCurrent > 0) {\n\t\tlineCurrent--;\n\t\tindentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);\n\t\tif (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) &&\n\t\t (!IsCommentLine(lineCurrent, styler)))\n\t\t\tbreak;\n\t}\n\tint indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;\n\n\t\/\/ Set up initial loop state\n\tint prevComment = 0;\n\tif (lineCurrent >= 1)\n\t\tprevComment = foldComment && IsCommentLine(lineCurrent - 1, styler);\n\n\t\/\/ Process all characters to end of requested range\n\t\/\/ or comment that hangs over the end of the range. Cap processing in all cases\n\t\/\/ to end of document (in case of unclosed comment at end).\n\twhile ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevComment)) {\n\n\t\t\/\/ Gather info\n\t\tint lev = indentCurrent;\n\t\tint lineNext = lineCurrent + 1;\n\t\tint indentNext = indentCurrent;\n\t\tif (lineNext <= docLines) {\n\t\t\t\/\/ Information about next line is only available if not at end of document\n\t\t\tindentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);\n\t}\n\t\tconst int comment = foldComment && IsCommentLine(lineCurrent, styler);\n\t\tconst int comment_start = (comment && !prevComment && (lineNext <= docLines) &&\n\t\t IsCommentLine(lineNext, styler) && (lev > SC_FOLDLEVELBASE));\n\t\tconst int comment_continue = (comment && prevComment);\n\t\tif (!comment)\n\t\t\tindentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;\n\t\tif (indentNext & SC_FOLDLEVELWHITEFLAG)\n\t\t\tindentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel;\n\n\t\tif (comment_start) {\n\t\t\t\/\/ Place fold point at start of a block of comments\n\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t} else if (comment_continue) {\n\t\t\t\/\/ Add level to rest of lines in the block\n\t\t\tlev = lev + 1;\n\t\t}\n\n\t\t\/\/ Skip past any blank lines for next indent level info; we skip also\n\t\t\/\/ comments (all comments, not just those starting in column 0)\n\t\t\/\/ which effectively folds them into surrounding code rather\n\t\t\/\/ than screwing up folding.\n\n\t\twhile ((lineNext < docLines) &&\n\t\t ((indentNext & SC_FOLDLEVELWHITEFLAG) ||\n\t\t (lineNext <= docLines && IsCommentLine(lineNext, styler)))) {\n\n\t\t\tlineNext++;\n\t\t\tindentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);\n\t\t}\n\n\t\tconst int levelAfterComments = indentNext & SC_FOLDLEVELNUMBERMASK;\n\t\tconst int levelBeforeComments = Platform::Maximum(indentCurrentLevel,levelAfterComments);\n\n\t\t\/\/ Now set all the indent levels on the lines we skipped\n\t\t\/\/ Do this from end to start. Once we encounter one line\n\t\t\/\/ which is indented more than the line after the end of\n\t\t\/\/ the comment-block, use the level of the block before\n\n\t\tint skipLine = lineNext;\n\t\tint skipLevel = levelAfterComments;\n\n\t\twhile (--skipLine > lineCurrent) {\n\t\t\tint skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, NULL);\n\n\t\t\tif ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments)\n\t\t\t\tskipLevel = levelBeforeComments;\n\n\t\t\tint whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG;\n\n\t\t\tstyler.SetLevel(skipLine, skipLevel | whiteFlag);\n\t\t}\n\n\t\t\/\/ Set fold header on non-comment line\n\t\tif (!comment && !(indentCurrent & SC_FOLDLEVELWHITEFLAG) ) {\n\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t}\n\n\t\t\/\/ Keep track of block comment state of previous line\n\t\tprevComment = comment_start || comment_continue;\n\n\t\t\/\/ Set fold level for this line and move to next line\n\t\tstyler.SetLevel(lineCurrent, lev);\n\t\tindentCurrent = indentNext;\n\t\tlineCurrent = lineNext;\n\t}\n\n\t\/\/ NOTE: Cannot set level of last line here because indentCurrent doesn't have\n\t\/\/ header flag set; the loop above is crafted to take care of this case!\n\t\/\/styler.SetLevel(lineCurrent, indentCurrent);\n}\n\nLexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, \"yaml\", FoldYAMLDoc, yamlWordListDesc);\nUpdate from Sean O'Dell changes the license text to be the same as other code.\/\/ Scintilla source code edit control\n\/** @file LexYAML.cxx\n ** Lexer for YAML.\n **\/\n\/\/ Copyright 2003- by Sean O'Dell \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\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nstatic const char * const yamlWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic inline bool AtEOL(Accessor &styler, unsigned int i) {\n\treturn (styler[i] == '\\n') ||\n\t\t((styler[i] == '\\r') && (styler.SafeGetCharAt(i + 1) != '\\n'));\n}\n\nstatic unsigned int SpaceCount(char* lineBuffer) {\n\tif (lineBuffer == NULL)\n\t\treturn 0;\n\n\tchar* headBuffer = lineBuffer;\n\n\twhile (*headBuffer == ' ')\n\t\theadBuffer++;\n\n\treturn headBuffer - lineBuffer;\n}\n\n#define YAML_STATE_BITSIZE 16\n#define YAML_STATE_MASK\t\t\t(0xFFFF0000)\n#define YAML_STATE_DOCUMENT\t\t(1 << YAML_STATE_BITSIZE)\n#define YAML_STATE_VALUE\t\t\t(2 << YAML_STATE_BITSIZE)\n#define YAML_STATE_COMMENT\t\t(3 << YAML_STATE_BITSIZE)\n#define YAML_STATE_TEXT_PARENT\t(4 << YAML_STATE_BITSIZE)\n#define YAML_STATE_TEXT\t\t\t(5 << YAML_STATE_BITSIZE)\n\nstatic void ColouriseYAMLLine(\n\tchar *lineBuffer,\n\tunsigned int currentLine,\n\tunsigned int lengthLine,\n\tunsigned int startLine,\n\tunsigned int endPos,\n\tWordList &keywords,\n\tAccessor &styler) {\n\n\tunsigned int i = 0;\n\tbool bInQuotes = false;\n\tunsigned int indentAmount = SpaceCount(lineBuffer);\n\n\tif (currentLine > 0) {\n\t\tint parentLineState = styler.GetLineState(currentLine - 1);\n\n\t\tif ((parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT || (parentLineState&YAML_STATE_MASK) == YAML_STATE_TEXT_PARENT) {\n\t\t\tunsigned int parentIndentAmount = parentLineState&(~YAML_STATE_MASK);\n\t\t\tif (indentAmount > parentIndentAmount) {\n\t\t\t\tstyler.SetLineState(currentLine, YAML_STATE_TEXT | parentIndentAmount);\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_TEXT);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tstyler.SetLineState(currentLine, 0);\n\tif (strncmp(lineBuffer, \"---\", 3) == 0) {\t\/\/ Document marker\n\t\tstyler.SetLineState(currentLine, YAML_STATE_DOCUMENT);\n\t\tstyler.ColourTo(endPos, SCE_YAML_DOCUMENT);\n\t\treturn;\n\t}\n\t\/\/ Skip initial spaces\n\twhile ((i < lengthLine) && lineBuffer[i] == ' ') { \/\/ YAML always uses space, never TABS or anything else\n\t\ti++;\n\t}\n\tif (lineBuffer[i] == '\\t') { \/\/ if we skipped all spaces, and we are NOT inside a text block, this is wrong\n\t\tstyler.ColourTo(endPos, SCE_YAML_ERROR);\n\t\treturn;\n\t}\n\tif (lineBuffer[i] == '#') {\t\/\/ Comment\n\t\tstyler.SetLineState(currentLine, YAML_STATE_COMMENT);\n\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\treturn;\n\t}\n\twhile (i < lengthLine) {\n\t\tif (lineBuffer[i] == '\\'' || lineBuffer[i] == '\\\"') {\n\t\t\tbInQuotes = !bInQuotes;\n\t\t} else if (lineBuffer[i] == ':' && !bInQuotes) {\n\t\t\tstyler.ColourTo(startLine + i - 1, SCE_YAML_IDENTIFIER);\n\t\t\tstyler.ColourTo(startLine + i, SCE_YAML_OPERATOR);\n\t\t\t\/\/ Non-folding scalar\n\t\t\ti++;\n\t\t\twhile ((i < lengthLine) && isspacechar(lineBuffer[i]))\n\t\t\t\ti++;\n\t\t\tunsigned int endValue = lengthLine - 1;\n\t\t\twhile ((endValue >= i) && isspacechar(lineBuffer[endValue]))\n\t\t\t\tendValue--;\n\t\t\tlineBuffer[endValue + 1] = '\\0';\n\t\t\tif (lineBuffer[i] == '|' || lineBuffer[i] == '>') {\n\t\t\t\ti++;\n\t\t\t\tif (lineBuffer[i] == '+' || lineBuffer[i] == '-')\n\t\t\t\t\ti++;\n\t\t\t\twhile ((i < lengthLine) && isspacechar(lineBuffer[i]))\n\t\t\t\t\ti++;\n\t\t\t\tif (lineBuffer[i] == '\\0') {\n\t\t\t\t\tstyler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount);\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (lineBuffer[i] == '#') {\n\t\t\t\t\tstyler.SetLineState(currentLine, YAML_STATE_TEXT_PARENT | indentAmount);\n\t\t\t\t\tstyler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT);\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\t\t\t\treturn;\n\t\t\t\t} else {\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_ERROR);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (lineBuffer[i] == '#') {\n\t\t\t\tstyler.ColourTo(startLine + i - 1, SCE_YAML_DEFAULT);\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tstyler.SetLineState(currentLine, YAML_STATE_VALUE);\n\t\t\tif (lineBuffer[i] == '&' || lineBuffer[i] == '*') {\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_REFERENCE);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (keywords.InList(&lineBuffer[i])) { \/\/ Convertible value (true\/false, etc.)\n\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_KEYWORD);\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tunsigned int i2 = i;\n\t\t\t\twhile ((i < lengthLine) && lineBuffer[i]) {\n\t\t\t\t\tif (!(isascii(lineBuffer[i]) && isdigit(lineBuffer[i])) && lineBuffer[i] != '-' && lineBuffer[i] != '.' && lineBuffer[i] != ',') {\n\t\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tif (i > i2) {\n\t\t\t\t\tstyler.ColourTo(endPos, SCE_YAML_NUMBER);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak; \/\/ shouldn't get here, but just in case, the rest of the line is coloured the default\n\t\t}\n\t\ti++;\n\t}\n\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n}\n\nstatic void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) {\n\tchar lineBuffer[1024];\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tunsigned int linePos = 0;\n\tunsigned int startLine = startPos;\n\tunsigned int endPos = startPos + length;\n\tunsigned int maxPos = styler.Length();\n\tunsigned int lineCurrent = styler.GetLine(startPos);\n\n\tfor (unsigned int i = startPos; i < maxPos && i < endPos; i++) {\n\t\tlineBuffer[linePos++] = styler[i];\n\t\tif (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {\n\t\t\t\/\/ End of line (or of line buffer) met, colourise it\n\t\t\tlineBuffer[linePos] = '\\0';\n\t\t\tColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, i, *keywordLists[0], styler);\n\t\t\tlinePos = 0;\n\t\t\tstartLine = i + 1;\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n\tif (linePos > 0) {\t\/\/ Last line does not have ending characters\n\t\tColouriseYAMLLine(lineBuffer, lineCurrent, linePos, startLine, startPos + length - 1, *keywordLists[0], styler);\n\t}\n}\n\nstatic bool IsCommentLine(int line, Accessor &styler) {\n\tint pos = styler.LineStart(line);\n\tif (styler[pos] == '#')\n\t\treturn true;\n\treturn false;\n}\n\nstatic void FoldYAMLDoc(unsigned int startPos, int length, int \/*initStyle - unused*\/,\n WordList *[], Accessor &styler) {\n\tconst int maxPos = startPos + length;\n\tconst int maxLines = styler.GetLine(maxPos - 1); \/\/ Requested last line\n\tconst int docLines = styler.GetLine(styler.Length() - 1); \/\/ Available last line\n\tconst bool foldComment = styler.GetPropertyInt(\"fold.comment.yaml\") != 0;\n\n\t\/\/ Backtrack to previous non-blank line so we can determine indent level\n\t\/\/ for any white space lines\n\t\/\/ and so we can fix any preceding fold level (which is why we go back\n\t\/\/ at least one line in all cases)\n\tint spaceFlags = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);\n\twhile (lineCurrent > 0) {\n\t\tlineCurrent--;\n\t\tindentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, NULL);\n\t\tif (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) &&\n\t\t (!IsCommentLine(lineCurrent, styler)))\n\t\t\tbreak;\n\t}\n\tint indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;\n\n\t\/\/ Set up initial loop state\n\tint prevComment = 0;\n\tif (lineCurrent >= 1)\n\t\tprevComment = foldComment && IsCommentLine(lineCurrent - 1, styler);\n\n\t\/\/ Process all characters to end of requested range\n\t\/\/ or comment that hangs over the end of the range. Cap processing in all cases\n\t\/\/ to end of document (in case of unclosed comment at end).\n\twhile ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevComment)) {\n\n\t\t\/\/ Gather info\n\t\tint lev = indentCurrent;\n\t\tint lineNext = lineCurrent + 1;\n\t\tint indentNext = indentCurrent;\n\t\tif (lineNext <= docLines) {\n\t\t\t\/\/ Information about next line is only available if not at end of document\n\t\t\tindentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);\n\t}\n\t\tconst int comment = foldComment && IsCommentLine(lineCurrent, styler);\n\t\tconst int comment_start = (comment && !prevComment && (lineNext <= docLines) &&\n\t\t IsCommentLine(lineNext, styler) && (lev > SC_FOLDLEVELBASE));\n\t\tconst int comment_continue = (comment && prevComment);\n\t\tif (!comment)\n\t\t\tindentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;\n\t\tif (indentNext & SC_FOLDLEVELWHITEFLAG)\n\t\t\tindentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel;\n\n\t\tif (comment_start) {\n\t\t\t\/\/ Place fold point at start of a block of comments\n\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t} else if (comment_continue) {\n\t\t\t\/\/ Add level to rest of lines in the block\n\t\t\tlev = lev + 1;\n\t\t}\n\n\t\t\/\/ Skip past any blank lines for next indent level info; we skip also\n\t\t\/\/ comments (all comments, not just those starting in column 0)\n\t\t\/\/ which effectively folds them into surrounding code rather\n\t\t\/\/ than screwing up folding.\n\n\t\twhile ((lineNext < docLines) &&\n\t\t ((indentNext & SC_FOLDLEVELWHITEFLAG) ||\n\t\t (lineNext <= docLines && IsCommentLine(lineNext, styler)))) {\n\n\t\t\tlineNext++;\n\t\t\tindentNext = styler.IndentAmount(lineNext, &spaceFlags, NULL);\n\t\t}\n\n\t\tconst int levelAfterComments = indentNext & SC_FOLDLEVELNUMBERMASK;\n\t\tconst int levelBeforeComments = Platform::Maximum(indentCurrentLevel,levelAfterComments);\n\n\t\t\/\/ Now set all the indent levels on the lines we skipped\n\t\t\/\/ Do this from end to start. Once we encounter one line\n\t\t\/\/ which is indented more than the line after the end of\n\t\t\/\/ the comment-block, use the level of the block before\n\n\t\tint skipLine = lineNext;\n\t\tint skipLevel = levelAfterComments;\n\n\t\twhile (--skipLine > lineCurrent) {\n\t\t\tint skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, NULL);\n\n\t\t\tif ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments)\n\t\t\t\tskipLevel = levelBeforeComments;\n\n\t\t\tint whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG;\n\n\t\t\tstyler.SetLevel(skipLine, skipLevel | whiteFlag);\n\t\t}\n\n\t\t\/\/ Set fold header on non-comment line\n\t\tif (!comment && !(indentCurrent & SC_FOLDLEVELWHITEFLAG) ) {\n\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t}\n\n\t\t\/\/ Keep track of block comment state of previous line\n\t\tprevComment = comment_start || comment_continue;\n\n\t\t\/\/ Set fold level for this line and move to next line\n\t\tstyler.SetLevel(lineCurrent, lev);\n\t\tindentCurrent = indentNext;\n\t\tlineCurrent = lineNext;\n\t}\n\n\t\/\/ NOTE: Cannot set level of last line here because indentCurrent doesn't have\n\t\/\/ header flag set; the loop above is crafted to take care of this case!\n\t\/\/styler.SetLevel(lineCurrent, indentCurrent);\n}\n\nLexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, \"yaml\", FoldYAMLDoc, yamlWordListDesc);\n<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file LexYAML.cxx\n ** Lexer for YAML.\n **\/\n\/\/ Copyright 2003- by Sean O'Dell \n\/\/ Release under the same license as Scintilla\/SciTE.\n\n#include \n#include \n#include \n#include \n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic const char * const yamlWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic inline bool AtEOL(Accessor &styler, unsigned int i) {\n\treturn (styler[i] == '\\n') ||\n\t\t((styler[i] == '\\r') && (styler.SafeGetCharAt(i + 1) != '\\n'));\n}\n\nstatic void ColouriseYAMLLine(\n char *lineBuffer,\n unsigned int lengthLine,\n unsigned int startLine,\n unsigned int endPos,\n WordList &keywords,\n Accessor &styler) {\n\n\tunsigned int i = 0;\n\tbool bInQuotes = false;\n\tunsigned int startValue, endValue, valueLen;\n\tchar scalar[256];\n\tif (lineBuffer[0] == '#') {\t\/\/ Comment\n\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\treturn;\n\t}\n\tif (strncmp(lineBuffer, \"---\", 3) == 0) {\t\/\/ Document marker\n\t\tstyler.ColourTo(endPos, SCE_YAML_DOCUMENT);\n\t\treturn;\n\t}\n\t\/\/ Skip initial spaces\n\twhile ((i < lengthLine) && isspacechar(lineBuffer[i])) {\n\t\ti++;\n\t}\n\twhile (i < lengthLine) {\n\t\tif (lineBuffer[i] == '\\'' || lineBuffer[i] == '\\\"') {\n\t\t\tbInQuotes = !bInQuotes;\n\t\t} else if (lineBuffer[i] == ':' && !bInQuotes) {\n\t\t\tstyler.ColourTo(startLine + i, SCE_YAML_IDENTIFIER);\n\t\t\t\/\/ Non-folding scalar\n\t\t\tstartValue = i + 1;\n\t\t\twhile ((startValue < lengthLine) && isspacechar(lineBuffer[startValue])) {\n\t\t\t\tstartValue++;\n\t\t\t}\n\t\t\tendValue = lengthLine - 1;\n\t\t\twhile ((endValue >= startValue) && isspacechar(lineBuffer[endValue])) {\n\t\t\t\tendValue--;\n\t\t\t}\n\t\t\tvalueLen = endValue - startValue + 1;\n\t\t\tif (endValue < startValue || valueLen > sizeof(scalar)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tstrncpy(scalar, &lineBuffer[startValue], valueLen);\n\t\t\tscalar[valueLen] = '\\0';\n\t\t\tif (scalar[0] == '&' || scalar[0] == '*') {\n\t\t\t\tstyler.ColourTo(startLine + endValue, SCE_YAML_REFERENCE);\n\t\t\t}\n\t\t\telse if (keywords.InList(scalar)) { \/\/ Convertible value (true\/false, etc.)\n\t\t\t\tstyler.ColourTo(startLine + endValue, SCE_YAML_KEYWORD);\n\t\t\t} else {\n\t\t\t\tstartValue = 0;\n\t\t\t\twhile (startValue < valueLen) {\n\t\t\t\t\tif (!isdigit(scalar[startValue]) && scalar[startValue] != '-' && scalar[startValue] != '.' && scalar[startValue] != ',') {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tstartValue++;\n\t\t\t\t}\n\t\t\t\tif (startValue >= valueLen) {\n\t\t\t\t\tstyler.ColourTo(startLine + endValue, SCE_YAML_NUMBER);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak; \/\/ the rest of the line is coloured the default\n\t\t}\n\t\ti++;\n\t}\n\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n}\n\nstatic void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) {\n\tchar lineBuffer[1024];\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tunsigned int linePos = 0;\n\tunsigned int startLine = startPos;\n\tfor (unsigned int i = startPos; i < startPos + length; i++) {\n\t\tlineBuffer[linePos++] = styler[i];\n\t\tif (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {\n\t\t\t\/\/ End of line (or of line buffer) met, colourise it\n\t\t\tlineBuffer[linePos] = '\\0';\n\t\t\tColouriseYAMLLine(lineBuffer, linePos, startLine, i, *keywordLists[0], styler);\n\t\t\tlinePos = 0;\n\t\t\tstartLine = i + 1;\n\t\t}\n\t}\n\tif (linePos > 0) {\t\/\/ Last line does not have ending characters\n\t\tColouriseYAMLLine(lineBuffer, linePos, startLine, startPos + length - 1, *keywordLists[0], styler);\n\t}\n}\n\nstatic int IdentifierLevelYAMLLine(\n char *lineBuffer,\n unsigned int lengthLine) {\n\n\tunsigned int i = 0;\n\tbool bInQuotes = false;\n\tint level;\n\tif (lineBuffer[0] == '#') {\t\/\/ Comment\n\t\treturn 0xFFFFFFFF;\n\t}\n\tif (strncmp(lineBuffer, \"---\", 3) == 0) {\t\/\/ Document marker\n\t\treturn 0;\n\t}\n\t\/\/ Count initial spaces and '-' character\n\twhile ((i < lengthLine) && (isspacechar(lineBuffer[i]) || lineBuffer[i] == '-')) {\n\t\ti++;\n\t}\n\tlevel = i;\n\twhile (i < lengthLine) {\n\t\tif (lineBuffer[i] == '\\'' || lineBuffer[i] == '\\\"') {\n\t\t\tbInQuotes = !bInQuotes;\n\t\t} else if (lineBuffer[i] == ':' && !bInQuotes) {\n\t\t\treturn level;\n\t\t}\n\t\ti++;\n\t}\n\treturn -level; \/\/ Scalar\n}\n\nstatic void FoldYAMLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {\n\tchar lineBuffer[1024];\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tunsigned int linePos = 0;\n\tint currentLevel;\n\tint lastLevel = 0xFFFFFFFF;\n\tunsigned int lineCurrent = 0;\n\tfor (unsigned int i = startPos; i < startPos + length; i++) {\n\t\tlineBuffer[linePos++] = styler[i];\n\t\tif (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {\n\t\t\t\/\/ End of line (or of line buffer) met, colourise it\n\t\t\tlineBuffer[linePos] = '\\0';\n\t\t\tcurrentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos);\n\t \t\tif (currentLevel != static_cast(0xFFFFFFFF)) {\n\t\t\t\tif (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) { \/\/ indented higher than last, and last was an identifier line\n\t\t\t\t\tstyler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG);\n\t\t\t\t}\n\t\t\t\tlastLevel = currentLevel;\n\t\t\t}\n\t\t\tlinePos = 0;\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n\tif (linePos > 0) {\t\/\/ Last line does not have ending characters\n\t\tcurrentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos);\n\t\tif (currentLevel != static_cast(0xFFFFFFFF)) {\n\t\t\tif (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) {\n\t\t\t\tstyler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG);\n\t\t\t}\n\t\t}\n\t}\n}\n\nLexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, \"yaml\", FoldYAMLDoc, yamlWordListDesc);\nAdded Platform.h as it includes compile pragmas to avoid unwanted warnings.\/\/ Scintilla source code edit control\n\/** @file LexYAML.cxx\n ** Lexer for YAML.\n **\/\n\/\/ Copyright 2003- by Sean O'Dell \n\/\/ Release under the same license as Scintilla\/SciTE.\n\n#include \n#include \n#include \n#include \n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic const char * const yamlWordListDesc[] = {\n\t\"Keywords\",\n\t0\n};\n\nstatic inline bool AtEOL(Accessor &styler, unsigned int i) {\n\treturn (styler[i] == '\\n') ||\n\t\t((styler[i] == '\\r') && (styler.SafeGetCharAt(i + 1) != '\\n'));\n}\n\nstatic void ColouriseYAMLLine(\n char *lineBuffer,\n unsigned int lengthLine,\n unsigned int startLine,\n unsigned int endPos,\n WordList &keywords,\n Accessor &styler) {\n\n\tunsigned int i = 0;\n\tbool bInQuotes = false;\n\tunsigned int startValue, endValue, valueLen;\n\tchar scalar[256];\n\tif (lineBuffer[0] == '#') {\t\/\/ Comment\n\t\tstyler.ColourTo(endPos, SCE_YAML_COMMENT);\n\t\treturn;\n\t}\n\tif (strncmp(lineBuffer, \"---\", 3) == 0) {\t\/\/ Document marker\n\t\tstyler.ColourTo(endPos, SCE_YAML_DOCUMENT);\n\t\treturn;\n\t}\n\t\/\/ Skip initial spaces\n\twhile ((i < lengthLine) && isspacechar(lineBuffer[i])) {\n\t\ti++;\n\t}\n\twhile (i < lengthLine) {\n\t\tif (lineBuffer[i] == '\\'' || lineBuffer[i] == '\\\"') {\n\t\t\tbInQuotes = !bInQuotes;\n\t\t} else if (lineBuffer[i] == ':' && !bInQuotes) {\n\t\t\tstyler.ColourTo(startLine + i, SCE_YAML_IDENTIFIER);\n\t\t\t\/\/ Non-folding scalar\n\t\t\tstartValue = i + 1;\n\t\t\twhile ((startValue < lengthLine) && isspacechar(lineBuffer[startValue])) {\n\t\t\t\tstartValue++;\n\t\t\t}\n\t\t\tendValue = lengthLine - 1;\n\t\t\twhile ((endValue >= startValue) && isspacechar(lineBuffer[endValue])) {\n\t\t\t\tendValue--;\n\t\t\t}\n\t\t\tvalueLen = endValue - startValue + 1;\n\t\t\tif (endValue < startValue || valueLen > sizeof(scalar)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tstrncpy(scalar, &lineBuffer[startValue], valueLen);\n\t\t\tscalar[valueLen] = '\\0';\n\t\t\tif (scalar[0] == '&' || scalar[0] == '*') {\n\t\t\t\tstyler.ColourTo(startLine + endValue, SCE_YAML_REFERENCE);\n\t\t\t}\n\t\t\telse if (keywords.InList(scalar)) { \/\/ Convertible value (true\/false, etc.)\n\t\t\t\tstyler.ColourTo(startLine + endValue, SCE_YAML_KEYWORD);\n\t\t\t} else {\n\t\t\t\tstartValue = 0;\n\t\t\t\twhile (startValue < valueLen) {\n\t\t\t\t\tif (!isdigit(scalar[startValue]) && scalar[startValue] != '-' && scalar[startValue] != '.' && scalar[startValue] != ',') {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tstartValue++;\n\t\t\t\t}\n\t\t\t\tif (startValue >= valueLen) {\n\t\t\t\t\tstyler.ColourTo(startLine + endValue, SCE_YAML_NUMBER);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak; \/\/ the rest of the line is coloured the default\n\t\t}\n\t\ti++;\n\t}\n\tstyler.ColourTo(endPos, SCE_YAML_DEFAULT);\n}\n\nstatic void ColouriseYAMLDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) {\n\tchar lineBuffer[1024];\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tunsigned int linePos = 0;\n\tunsigned int startLine = startPos;\n\tfor (unsigned int i = startPos; i < startPos + length; i++) {\n\t\tlineBuffer[linePos++] = styler[i];\n\t\tif (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {\n\t\t\t\/\/ End of line (or of line buffer) met, colourise it\n\t\t\tlineBuffer[linePos] = '\\0';\n\t\t\tColouriseYAMLLine(lineBuffer, linePos, startLine, i, *keywordLists[0], styler);\n\t\t\tlinePos = 0;\n\t\t\tstartLine = i + 1;\n\t\t}\n\t}\n\tif (linePos > 0) {\t\/\/ Last line does not have ending characters\n\t\tColouriseYAMLLine(lineBuffer, linePos, startLine, startPos + length - 1, *keywordLists[0], styler);\n\t}\n}\n\nstatic int IdentifierLevelYAMLLine(\n char *lineBuffer,\n unsigned int lengthLine) {\n\n\tunsigned int i = 0;\n\tbool bInQuotes = false;\n\tint level;\n\tif (lineBuffer[0] == '#') {\t\/\/ Comment\n\t\treturn 0xFFFFFFFF;\n\t}\n\tif (strncmp(lineBuffer, \"---\", 3) == 0) {\t\/\/ Document marker\n\t\treturn 0;\n\t}\n\t\/\/ Count initial spaces and '-' character\n\twhile ((i < lengthLine) && (isspacechar(lineBuffer[i]) || lineBuffer[i] == '-')) {\n\t\ti++;\n\t}\n\tlevel = i;\n\twhile (i < lengthLine) {\n\t\tif (lineBuffer[i] == '\\'' || lineBuffer[i] == '\\\"') {\n\t\t\tbInQuotes = !bInQuotes;\n\t\t} else if (lineBuffer[i] == ':' && !bInQuotes) {\n\t\t\treturn level;\n\t\t}\n\t\ti++;\n\t}\n\treturn -level; \/\/ Scalar\n}\n\nstatic void FoldYAMLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {\n\tchar lineBuffer[1024];\n\tstyler.StartAt(startPos);\n\tstyler.StartSegment(startPos);\n\tunsigned int linePos = 0;\n\tint currentLevel;\n\tint lastLevel = 0xFFFFFFFF;\n\tunsigned int lineCurrent = 0;\n\tfor (unsigned int i = startPos; i < startPos + length; i++) {\n\t\tlineBuffer[linePos++] = styler[i];\n\t\tif (AtEOL(styler, i) || (linePos >= sizeof(lineBuffer) - 1)) {\n\t\t\t\/\/ End of line (or of line buffer) met, colourise it\n\t\t\tlineBuffer[linePos] = '\\0';\n\t\t\tcurrentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos);\n\t \t\tif (currentLevel != static_cast(0xFFFFFFFF)) {\n\t\t\t\tif (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) { \/\/ indented higher than last, and last was an identifier line\n\t\t\t\t\tstyler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG);\n\t\t\t\t}\n\t\t\t\tlastLevel = currentLevel;\n\t\t\t}\n\t\t\tlinePos = 0;\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n\tif (linePos > 0) {\t\/\/ Last line does not have ending characters\n\t\tcurrentLevel = IdentifierLevelYAMLLine(lineBuffer, linePos);\n\t\tif (currentLevel != static_cast(0xFFFFFFFF)) {\n\t\t\tif (abs(currentLevel) > abs(lastLevel) && lastLevel >= 0) {\n\t\t\t\tstyler.SetLevel(lineCurrent - 1, SC_FOLDLEVELHEADERFLAG);\n\t\t\t}\n\t\t}\n\t}\n}\n\nLexerModule lmYAML(SCLEX_YAML, ColouriseYAMLDoc, \"yaml\", FoldYAMLDoc, yamlWordListDesc);\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * Copyright (C) 2020 The Symbiflow Authors\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 \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\n\nPRIVATE_NAMESPACE_BEGIN\n\n\nvoid register_in_tcl_interpreter(const std::string& command) {\n\tTcl_Interp* interp = yosys_get_tcl_interp();\n\tstd::string tcl_script = stringf(\"proc %s args { return [yosys %s {*}$args] }\", command.c_str(), command.c_str());\n\tTcl_Eval(interp, tcl_script.c_str());\n}\n\nstruct GetParam : public Pass {\n\tGetParam() : Pass(\"getparam\", \"get parameter on object\") {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() override\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" getparam name selection\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Get the given parameter on the selected object. \\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design* design) override\n\t{\n\t\tif (args.size() == 1) {\n\t\t\tlog_error(\"Incorrect number of arguments\");\n\t\t}\n\n\t\tstd::string param(args.at(1));\n\t\tstd::string value;\n\t\textra_args(args, 2, design);\n\n\t\tfor (auto module : design->selected_modules()) {\n\t\t\tfor (auto cell : module->selected_cells()) {\n\t\t\t\tauto params = cell->parameters;\n\t\t\t\tauto it = params.find(RTLIL::IdString(RTLIL::escape_id(param)));\n\t\t\t\tif (it != params.end()) {\n\t\t\t\t\tauto param_obj = it->second;\n\t\t\t\t\tif (param_obj.flags & RTLIL::CONST_FLAG_STRING) {\n\t\t\t\t\t\tvalue = param_obj.decode_string();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalue = std::to_string(param_obj.as_int());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tchar* tcl_param = Tcl_Alloc(value.size() + 1);\n\t\tstrcpy(tcl_param, value.c_str());\n\t\tTcl_Interp *interp = yosys_get_tcl_interp();\n\t\tTcl_SetResult(interp, tcl_param, TCL_DYNAMIC);\n\t}\n\n} GetParam;\n\nPRIVATE_NAMESPACE_END\nParams plugin: Move IdString outside of loop\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * Copyright (C) 2020 The Symbiflow Authors\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 \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\n\nPRIVATE_NAMESPACE_BEGIN\n\n\nvoid register_in_tcl_interpreter(const std::string& command) {\n\tTcl_Interp* interp = yosys_get_tcl_interp();\n\tstd::string tcl_script = stringf(\"proc %s args { return [yosys %s {*}$args] }\", command.c_str(), command.c_str());\n\tTcl_Eval(interp, tcl_script.c_str());\n}\n\nstruct GetParam : public Pass {\n\tGetParam() : Pass(\"getparam\", \"get parameter on object\") {\n\t\tregister_in_tcl_interpreter(pass_name);\n\t}\n\n\tvoid help() override\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" getparam name selection\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"Get the given parameter on the selected object. \\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design* design) override\n\t{\n\t\tif (args.size() == 1) {\n\t\t\tlog_error(\"Incorrect number of arguments\");\n\t\t}\n\n\t\tauto param = RTLIL::IdString(RTLIL::escape_id(args.at(1)));\n\t\tstd::string value;\n\t\textra_args(args, 2, design);\n\n\t\tfor (auto module : design->selected_modules()) {\n\t\t\tfor (auto cell : module->selected_cells()) {\n\t\t\t\tauto params = cell->parameters;\n\t\t\t\tauto it = params.find(param);\n\t\t\t\tif (it != params.end()) {\n\t\t\t\t\tauto param_obj = it->second;\n\t\t\t\t\tif (param_obj.flags & RTLIL::CONST_FLAG_STRING) {\n\t\t\t\t\t\tvalue = param_obj.decode_string();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalue = std::to_string(param_obj.as_int());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tchar* tcl_param = Tcl_Alloc(value.size() + 1);\n\t\tstrcpy(tcl_param, value.c_str());\n\t\tTcl_Interp *interp = yosys_get_tcl_interp();\n\t\tTcl_SetResult(interp, tcl_param, TCL_DYNAMIC);\n\t}\n\n} GetParam;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"#include \n\nnamespace MetaOpt {\nnamespace Python {\n\n\nnamespace py = pybind11;\n\nvoid init_swarm(py::module &m);\nvoid init_functions(py::module &m);\n\nPYBIND11_PLUGIN(pymetaopt) {\n py::module m(\"pymetaopt\", \"Meta optimization library\");\n init_swarm(m);\n init_functions(m);\n return m.ptr();\n}\n}\n}\nUpdate python lib name#include \n\nnamespace MetaOpt {\nnamespace Python {\n\n\nnamespace py = pybind11;\n\nvoid init_swarm(py::module &m);\nvoid init_functions(py::module &m);\n\nPYBIND11_PLUGIN(pyoptima) {\n py::module m(\"pyoptima\", \"Meta heuristic optimization library\");\n init_swarm(m);\n init_functions(m);\n return m.ptr();\n}\n}\n}\n<|endoftext|>"} {"text":"#include \"askpassphrasedialog.h\"\n#include \"ui_askpassphrasedialog.h\"\n\n#include \"guiconstants.h\"\n#include \"walletmodel.h\"\n\n#include \n#include \n#include \n\nAskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AskPassphraseDialog),\n mode(mode),\n model(0),\n fCapsLock(false)\n{\n ui->setupUi(this);\n ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);\n\n \/\/ Setup Caps Lock detection.\n ui->passEdit1->installEventFilter(this);\n ui->passEdit2->installEventFilter(this);\n ui->passEdit3->installEventFilter(this);\n\n switch(mode)\n {\n case Encrypt: \/\/ Ask passphrase x2\n ui->passLabel1->hide();\n ui->passEdit1->hide();\n ui->warningLabel->setText(tr(\"Enter the new passphrase to the wallet.Please use a passphrase of 10 or more random characters<\/b>, or eight or more words<\/b>.\"));\n setWindowTitle(tr(\"Encrypt wallet\"));\n break;\n case Unlock: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to unlock the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Unlock wallet\"));\n break;\n case Decrypt: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to decrypt the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Decrypt wallet\"));\n break;\n case ChangePass: \/\/ Ask old passphrase + new passphrase x2\n setWindowTitle(tr(\"Change passphrase\"));\n ui->warningLabel->setText(tr(\"Enter the old and new passphrase to the wallet.\"));\n break;\n }\n\n textChanged();\n connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n}\n\nAskPassphraseDialog::~AskPassphraseDialog()\n{\n \/\/ Attempt to overwrite text so that they do not linger around in memory\n ui->passEdit1->setText(QString(\" \").repeated(ui->passEdit1->text().size()));\n ui->passEdit2->setText(QString(\" \").repeated(ui->passEdit2->text().size()));\n ui->passEdit3->setText(QString(\" \").repeated(ui->passEdit3->text().size()));\n delete ui;\n}\n\nvoid AskPassphraseDialog::setModel(WalletModel *model)\n{\n this->model = model;\n}\n\nvoid AskPassphraseDialog::accept()\n{\n SecureString oldpass, newpass1, newpass2;\n if(!model)\n return;\n oldpass.reserve(MAX_PASSPHRASE_SIZE);\n newpass1.reserve(MAX_PASSPHRASE_SIZE);\n newpass2.reserve(MAX_PASSPHRASE_SIZE);\n \/\/ TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)\n \/\/ Alternately, find a way to make this input mlock()'d to begin with.\n oldpass.assign(ui->passEdit1->text().toStdString().c_str());\n newpass1.assign(ui->passEdit2->text().toStdString().c_str());\n newpass2.assign(ui->passEdit3->text().toStdString().c_str());\n\n switch(mode)\n {\n case Encrypt: {\n if(newpass1.empty() || newpass2.empty())\n {\n \/\/ Cannot encrypt with empty passphrase\n break;\n }\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm wallet encryption\"),\n tr(\"Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR BITCOINS<\/b>!\") + \"

\" + tr(\"Are you sure you wish to encrypt your wallet?\"),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n if(retval == QMessageBox::Yes)\n {\n if(newpass1 == newpass2)\n {\n if(model->setWalletEncrypted(true, newpass1))\n {\n QMessageBox::warning(this, tr(\"Wallet encrypted\"),\n \"\" +\n tr(\"Bitcoin will close now to finish the encryption process. \"\n \"Remember that encrypting your wallet cannot fully protect \"\n \"your bitcoins from being stolen by malware infecting your computer.\") +\n \"

\" +\n tr(\"IMPORTANT: Any previous backups you have made of your wallet file \"\n \"should be replaced with the newly generated, encrypted wallet file. \"\n \"For security reasons, previous backups of the unencrypted wallet file \"\n \"will become useless as soon as you start using the new, encrypted wallet.\") +\n \"<\/b><\/qt>\");\n QApplication::quit();\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"Wallet encryption failed due to an internal error. Your wallet was not encrypted.\"));\n }\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n }\n else\n {\n QDialog::reject(); \/\/ Cancelled\n }\n } break;\n case Unlock:\n if(!model->setWalletLocked(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case Decrypt:\n if(!model->setWalletEncrypted(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet decryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case ChangePass:\n if(newpass1 == newpass2)\n {\n if(model->changePassphrase(oldpass, newpass1))\n {\n QMessageBox::information(this, tr(\"Wallet encrypted\"),\n tr(\"Wallet passphrase was successfully changed.\"));\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n break;\n }\n}\n\nvoid AskPassphraseDialog::textChanged()\n{\n \/\/ Validate input, set Ok button to enabled when acceptable\n bool acceptable = false;\n switch(mode)\n {\n case Encrypt: \/\/ New passphrase x2\n acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n case Unlock: \/\/ Old passphrase x1\n case Decrypt:\n acceptable = !ui->passEdit1->text().isEmpty();\n break;\n case ChangePass: \/\/ Old passphrase x1, new passphrase x2\n acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n }\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);\n}\n\nbool AskPassphraseDialog::event(QEvent *event)\n{\n \/\/ Detect Caps Lock key press.\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n if (ke->key() == Qt::Key_CapsLock) {\n fCapsLock = !fCapsLock;\n }\n if (fCapsLock) {\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else {\n ui->capsLabel->clear();\n }\n }\n return QWidget::event(event);\n}\n\nbool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)\n{\n \/* Detect Caps Lock.\n * There is no good OS-independent way to check a key state in Qt, but we\n * can detect Caps Lock by checking for the following condition:\n * Shift key is down and the result is a lower case character, or\n * Shift key is not down and the result is an upper case character.\n *\/\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n QString str = ke->text();\n if (str.length() != 0) {\n const QChar *psz = str.unicode();\n bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;\n if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {\n fCapsLock = true;\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else if (psz->isLetter()) {\n fCapsLock = false;\n ui->capsLabel->clear();\n }\n }\n }\n return QDialog::eventFilter(object, event);\n}\nqt: Improve capslock detection on non-us keyboards (issue #1855)#include \"askpassphrasedialog.h\"\n#include \"ui_askpassphrasedialog.h\"\n\n#include \"guiconstants.h\"\n#include \"walletmodel.h\"\n\n#include \n#include \n#include \n\nAskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AskPassphraseDialog),\n mode(mode),\n model(0),\n fCapsLock(false)\n{\n ui->setupUi(this);\n ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);\n\n \/\/ Setup Caps Lock detection.\n ui->passEdit1->installEventFilter(this);\n ui->passEdit2->installEventFilter(this);\n ui->passEdit3->installEventFilter(this);\n\n switch(mode)\n {\n case Encrypt: \/\/ Ask passphrase x2\n ui->passLabel1->hide();\n ui->passEdit1->hide();\n ui->warningLabel->setText(tr(\"Enter the new passphrase to the wallet.Please use a passphrase of 10 or more random characters<\/b>, or eight or more words<\/b>.\"));\n setWindowTitle(tr(\"Encrypt wallet\"));\n break;\n case Unlock: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to unlock the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Unlock wallet\"));\n break;\n case Decrypt: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to decrypt the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Decrypt wallet\"));\n break;\n case ChangePass: \/\/ Ask old passphrase + new passphrase x2\n setWindowTitle(tr(\"Change passphrase\"));\n ui->warningLabel->setText(tr(\"Enter the old and new passphrase to the wallet.\"));\n break;\n }\n\n textChanged();\n connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n}\n\nAskPassphraseDialog::~AskPassphraseDialog()\n{\n \/\/ Attempt to overwrite text so that they do not linger around in memory\n ui->passEdit1->setText(QString(\" \").repeated(ui->passEdit1->text().size()));\n ui->passEdit2->setText(QString(\" \").repeated(ui->passEdit2->text().size()));\n ui->passEdit3->setText(QString(\" \").repeated(ui->passEdit3->text().size()));\n delete ui;\n}\n\nvoid AskPassphraseDialog::setModel(WalletModel *model)\n{\n this->model = model;\n}\n\nvoid AskPassphraseDialog::accept()\n{\n SecureString oldpass, newpass1, newpass2;\n if(!model)\n return;\n oldpass.reserve(MAX_PASSPHRASE_SIZE);\n newpass1.reserve(MAX_PASSPHRASE_SIZE);\n newpass2.reserve(MAX_PASSPHRASE_SIZE);\n \/\/ TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)\n \/\/ Alternately, find a way to make this input mlock()'d to begin with.\n oldpass.assign(ui->passEdit1->text().toStdString().c_str());\n newpass1.assign(ui->passEdit2->text().toStdString().c_str());\n newpass2.assign(ui->passEdit3->text().toStdString().c_str());\n\n switch(mode)\n {\n case Encrypt: {\n if(newpass1.empty() || newpass2.empty())\n {\n \/\/ Cannot encrypt with empty passphrase\n break;\n }\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm wallet encryption\"),\n tr(\"Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR BITCOINS<\/b>!\") + \"

\" + tr(\"Are you sure you wish to encrypt your wallet?\"),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n if(retval == QMessageBox::Yes)\n {\n if(newpass1 == newpass2)\n {\n if(model->setWalletEncrypted(true, newpass1))\n {\n QMessageBox::warning(this, tr(\"Wallet encrypted\"),\n \"\" +\n tr(\"Bitcoin will close now to finish the encryption process. \"\n \"Remember that encrypting your wallet cannot fully protect \"\n \"your bitcoins from being stolen by malware infecting your computer.\") +\n \"

\" +\n tr(\"IMPORTANT: Any previous backups you have made of your wallet file \"\n \"should be replaced with the newly generated, encrypted wallet file. \"\n \"For security reasons, previous backups of the unencrypted wallet file \"\n \"will become useless as soon as you start using the new, encrypted wallet.\") +\n \"<\/b><\/qt>\");\n QApplication::quit();\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"Wallet encryption failed due to an internal error. Your wallet was not encrypted.\"));\n }\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n }\n else\n {\n QDialog::reject(); \/\/ Cancelled\n }\n } break;\n case Unlock:\n if(!model->setWalletLocked(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case Decrypt:\n if(!model->setWalletEncrypted(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet decryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case ChangePass:\n if(newpass1 == newpass2)\n {\n if(model->changePassphrase(oldpass, newpass1))\n {\n QMessageBox::information(this, tr(\"Wallet encrypted\"),\n tr(\"Wallet passphrase was successfully changed.\"));\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n break;\n }\n}\n\nvoid AskPassphraseDialog::textChanged()\n{\n \/\/ Validate input, set Ok button to enabled when acceptable\n bool acceptable = false;\n switch(mode)\n {\n case Encrypt: \/\/ New passphrase x2\n acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n case Unlock: \/\/ Old passphrase x1\n case Decrypt:\n acceptable = !ui->passEdit1->text().isEmpty();\n break;\n case ChangePass: \/\/ Old passphrase x1, new passphrase x2\n acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n }\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);\n}\n\nbool AskPassphraseDialog::event(QEvent *event)\n{\n \/\/ Detect Caps Lock key press.\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n if (ke->key() == Qt::Key_CapsLock) {\n fCapsLock = !fCapsLock;\n }\n if (fCapsLock) {\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else {\n ui->capsLabel->clear();\n }\n }\n return QWidget::event(event);\n}\n\nbool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)\n{\n \/* Detect Caps Lock.\n * There is no good OS-independent way to check a key state in Qt, but we\n * can detect Caps Lock by checking for the following condition:\n * Shift key is down and the result is a lower case character, or\n * Shift key is not down and the result is an upper case character.\n *\/\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n QString str = ke->text();\n if (str.length() != 0) {\n const QChar *psz = str.unicode();\n bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;\n if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {\n fCapsLock = true;\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else if (psz->isLetter()) {\n fCapsLock = false;\n ui->capsLabel->clear();\n }\n }\n }\n return QDialog::eventFilter(object, event);\n}\n<|endoftext|>"} {"text":"\n\/\/ Copyright (c) 2008-2009, Regents of the University of Colorado.\n\/\/ This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and\n\/\/ NNC07CB47C.\n\n\n#include \"node.h\"\n\n\nNode::Node(QString name, QWidget* parent) : \n QWidget(parent)\n{\n this->name = name;\n\n QRegExp streamRX(\".*\\\\..*\\\\..*\\\\:.*\"); \/\/ matches *.*.*:*\n QRegExp nodeRX(\".*\\\\..*\\\\..*\"); \/\/ matches *.*.*\n QRegExp habRX(\".*\\\\..*\"); \/\/ matches *.*\n\n if ( streamRX.exactMatch(name) ) {\n id = name.section('.', 2, 2).section(':', 1, 1);\n bionetType = STREAM;\n\n bionet_stream_t* stream = bionet_cache_lookup_stream(\n qPrintable(name.section('.', 0, 0)),\n qPrintable(name.section('.', 1, 1)),\n qPrintable(name.section('.', 2, 2).section(':', 0, 0)),\n qPrintable(id));\n\n if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_CONSUMER)\n endpointType = CONSUMER;\n else if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_PRODUCER)\n endpointType = PRODUCER;\n else \n endpointType = NEITHER;\n\n bionetPtr = (void*)stream;\n\n } else if ( nodeRX.exactMatch(name) ) {\n\n bionet_node_t* node = bionet_cache_lookup_node(\n qPrintable(name.section('.', 0, 0)),\n qPrintable(name.section('.', 1, 1)),\n qPrintable(name.section('.', 2, 2)));\n bionetPtr = (void*)node;\n\n id = name.section('.',2,2);\n bionetType = NODE;\n endpointType = NEITHER;\n\n } else if ( habRX.exactMatch(name) ) {\n\n bionet_hab_t* hab = bionet_cache_lookup_hab(\n qPrintable(name.section('.', 0, 0)),\n qPrintable(name.section('.', 1, 1)));\n bionetPtr = (void*)hab;\n\n id = name;\n bionetType = HAB;\n endpointType = NEITHER;\n\n } else if ( name.isEmpty() ) {\n id = QString();\n bionetType = ROOT;\n endpointType = NEITHER;\n }\n\n children = new QList;\n\n \/*\n path = new QPainterPath(QPoint(0,0));\n path->addEllipse(area);\n path->addText(area, Qt::AlignHCenter, Qt::AlignVCenter, id);\n *\/\n}\n\n\nNode::~Node() {\n while ( !children->isEmpty() ) {\n Node* child = children->takeFirst();\n delete child;\n }\n delete children;\n}\n\n\n\nvoid Node::addChild(Node* child) {\n children->append(child);\n}\n\n\nvoid Node::addChildWithoutArea(Node* child) {\n children->append(child);\n}\n\n\nbool Node::removeChild(QString id) {\n int size = children->size();\n\n for (int i = 0; i < size; i++ ) {\n Node* child = children->at(i);\n if (child->getId() == id) {\n Node* child = children->takeAt(i);\n delete child;\n return true;\n }\n }\n\n return false;\n}\n\n\nNode* Node::find(QString fullname) {\n if (this->name == fullname)\n return this;\n\n foreach (Node* node, *children) {\n Node* leaf = node->find(fullname);\n if (leaf != NULL)\n return leaf;\n }\n\n return NULL;\n}\n\n\nNode* Node::find(QPoint point) {\n\n if (area.contains(point))\n return this;\n\n foreach (Node* node, *children) {\n Node *leaf = node->find(point);\n if (leaf != NULL)\n return leaf;\n }\n\n return NULL;\n}\n\n\nNode* Node::find(QRect rect) {\n\n if (area.intersects(rect))\n return this;\n\n foreach (Node* node, *children) {\n Node *leaf = node->find(rect);\n if (leaf != NULL)\n return leaf;\n }\n\n return NULL;\n}\n\n\nvoid Node::setArea(QRect newArea) {\n this->area = newArea;\n \/\/cout << \"this->area = \" << area.x() << \", \" << area.y() << endl;\n}\nfixing 3 possible uninitialized variables\n\/\/ Copyright (c) 2008-2009, Regents of the University of Colorado.\n\/\/ This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and\n\/\/ NNC07CB47C.\n\n\n#include \"node.h\"\n\n\nNode::Node(QString name, QWidget* parent) : \n QWidget(parent)\n{\n this->name = name;\n\n QRegExp streamRX(\".*\\\\..*\\\\..*\\\\:.*\"); \/\/ matches *.*.*:*\n QRegExp nodeRX(\".*\\\\..*\\\\..*\"); \/\/ matches *.*.*\n QRegExp habRX(\".*\\\\..*\"); \/\/ matches *.*\n\n bionetPtr = NULL;\n bionetType = ROOT;\n endpointType = NEITHER;\n\n if ( streamRX.exactMatch(name) ) {\n id = name.section('.', 2, 2).section(':', 1, 1);\n bionetType = STREAM;\n\n bionet_stream_t* stream = bionet_cache_lookup_stream(\n qPrintable(name.section('.', 0, 0)),\n qPrintable(name.section('.', 1, 1)),\n qPrintable(name.section('.', 2, 2).section(':', 0, 0)),\n qPrintable(id));\n\n if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_CONSUMER)\n endpointType = CONSUMER;\n else if (bionet_stream_get_direction(stream) == BIONET_STREAM_DIRECTION_PRODUCER)\n endpointType = PRODUCER;\n else \n endpointType = NEITHER;\n\n bionetPtr = (void*)stream;\n\n } else if ( nodeRX.exactMatch(name) ) {\n\n bionet_node_t* node = bionet_cache_lookup_node(\n qPrintable(name.section('.', 0, 0)),\n qPrintable(name.section('.', 1, 1)),\n qPrintable(name.section('.', 2, 2)));\n bionetPtr = (void*)node;\n\n id = name.section('.',2,2);\n bionetType = NODE;\n endpointType = NEITHER;\n\n } else if ( habRX.exactMatch(name) ) {\n\n bionet_hab_t* hab = bionet_cache_lookup_hab(\n qPrintable(name.section('.', 0, 0)),\n qPrintable(name.section('.', 1, 1)));\n bionetPtr = (void*)hab;\n\n id = name;\n bionetType = HAB;\n endpointType = NEITHER;\n\n } else if ( name.isEmpty() ) {\n id = QString();\n bionetType = ROOT;\n endpointType = NEITHER;\n }\n\n children = new QList;\n\n \/*\n path = new QPainterPath(QPoint(0,0));\n path->addEllipse(area);\n path->addText(area, Qt::AlignHCenter, Qt::AlignVCenter, id);\n *\/\n}\n\n\nNode::~Node() {\n while ( !children->isEmpty() ) {\n Node* child = children->takeFirst();\n delete child;\n }\n delete children;\n}\n\n\n\nvoid Node::addChild(Node* child) {\n children->append(child);\n}\n\n\nvoid Node::addChildWithoutArea(Node* child) {\n children->append(child);\n}\n\n\nbool Node::removeChild(QString id) {\n int size = children->size();\n\n for (int i = 0; i < size; i++ ) {\n Node* child = children->at(i);\n if (child->getId() == id) {\n Node* child = children->takeAt(i);\n delete child;\n return true;\n }\n }\n\n return false;\n}\n\n\nNode* Node::find(QString fullname) {\n if (this->name == fullname)\n return this;\n\n foreach (Node* node, *children) {\n Node* leaf = node->find(fullname);\n if (leaf != NULL)\n return leaf;\n }\n\n return NULL;\n}\n\n\nNode* Node::find(QPoint point) {\n\n if (area.contains(point))\n return this;\n\n foreach (Node* node, *children) {\n Node *leaf = node->find(point);\n if (leaf != NULL)\n return leaf;\n }\n\n return NULL;\n}\n\n\nNode* Node::find(QRect rect) {\n\n if (area.intersects(rect))\n return this;\n\n foreach (Node* node, *children) {\n Node *leaf = node->find(rect);\n if (leaf != NULL)\n return leaf;\n }\n\n return NULL;\n}\n\n\nvoid Node::setArea(QRect newArea) {\n this->area = newArea;\n \/\/cout << \"this->area = \" << area.x() << \", \" << area.y() << endl;\n}\n<|endoftext|>"} {"text":"#include \"recvfileprogressdialog.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n\n\/**\n * Returns a list of requested files\n *\/\nQList RecvFileProgressDialog::parsePayloadFileList(QByteArray payload)\n{\n QList recvFiles;\n QList headers = payload.split(QOM_FILELIST_SEPARATOR);\n foreach(QByteArray header, headers)\n {\n RecvFileInfo info;\n QList tokens = header.split(':');\n qDebug() << \"Tokens:\" << tokens;\n if(tokens.size() < 5)\n continue;\n info.fileID = tokens[0].toInt();\n info.fileName = tokens[1];\n info.size = tokens[2].toInt(0, 16);\n info.mtime = tokens[3].toInt(0, 16);\n info.type = tokens[4].toInt(0, 16);\n qDebug() << \"Parsed ID:\"<errorString();\n reject();\n}\n\nvoid RecvFileProgressDialog::accept()\n{\n qDebug() << \"$$$$$ Socket disconnected\";\n QProgressDialog::accept();\n}\n\nvoid RecvFileProgressDialog::startReceiving()\n{\n m_socket = new QTcpSocket(this);\n m_socket->abort();\n m_socket->connectToHost(m_msg.sender()->addressString(), UDP_PORT);\n \n connect(m_socket, SIGNAL(readyRead()), this, SLOT(readRequest()));\n connect(m_socket, SIGNAL(connected()), this, SLOT(requestFiles()));\n connect(m_socket, SIGNAL(disconnected()), this, SLOT(accept()));\n connect(m_socket, SIGNAL(disconnected()), m_socket, SLOT(deleteLater()));\n connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError)));\n}\n\nvoid RecvFileProgressDialog::requestFiles()\n{\n while(!m_fileHeaders.isEmpty())\n {\n if(m_waitingForData > 0)\n {\n qDebug() << \"Waiting for\"<< m_waitingForData;\n QTimer::singleShot(1000, this, SLOT(requestFiles()));\n break;\n }\n startReceiving();\n RecvFileInfo info = m_fileHeaders.takeFirst();\n m_requestType = info.type;\n \n QByteArray payload = QByteArray::number(m_msg.packetNo(), 16);\n payload += \":\";\n payload += QByteArray::number(info.fileID, 16);\n qDebug() << \"Writing request for file data\"<makeMessage(QOM_GETFILEDATA, payload).toAscii());\n }\n else if(m_requestType == QOM_FILE_DIR)\n {\n writeBlock(messenger()->makeMessage(QOM_GETDIRFILES, payload).toAscii());\n }\n }\n}\n\nvoid RecvFileProgressDialog::informUser()\n{\n QString message(m_msg.sender()->name());\n message.append(tr(\" has sent the following files\\n\\n\"));\n \n qint64 totalSize = 0;\n \n foreach(RecvFileInfo info, m_fileHeaders)\n {\n message.append(info.fileName);\n message.append(\" (\");\n if(info.type == QOM_FILE_REGULAR)\n {\n message.append(QString::number(info.size));\n totalSize += info.size;\n message.append(\" bytes)\\n\");\n }\n else if(info.type == QOM_FILE_DIR)\n {\n message.append(\"Directory, unknown size)\\n\");\n }\n }\n \n message.append(tr(\"\\nTotal Size: \"));\n if(totalSize > 1024*1024)\n {\n message.append(QString::number(totalSize \/ (1024*1024) ));\n message.append(\"Mb\");\n }\n else if( totalSize > 1024 )\n {\n message.append(QString::number(totalSize \/ 1024));\n message.append(\"Kb\");\n }\n else\n {\n message.append(QString::number(totalSize));\n message.append(\"bytes\");\n }\n \n QString msg = m_msg.payload().left(m_msg.payload().indexOf(\"\\a\"));\n if(!msg.isEmpty())\n message.append(\"\\n\\nMessage: \" + msg);\n \n message.append(tr(\"\\n\\nDo you want to accept the files?\"));\n if(QMessageBox::No == QMessageBox::question(NULL, \n tr(\"Receiving files\"), \n message, \n QMessageBox::Yes | QMessageBox::No,\n QMessageBox::Yes)) \/\/ last is default button\n reject();\n else\n m_saveDir = QFileDialog::getExistingDirectory(this, tr(\"Save To\"));\n \n if(!m_saveDir.isEmpty())\n {\n qDebug() << m_saveDir;\n }\n}\n\n\/\/ TODO: share with sending dialog?\nbool RecvFileProgressDialog::writeBlock(QByteArray b)\n{\n int bytesToWrite = b.size();\n int bytesWritten = 0;\n do\n {\n qDebug() << \"Writing\" << b << \"to socket\";\n bytesWritten = m_socket->write(b);\n if(bytesWritten == -1)\n return false;\n b.remove(0, bytesWritten);\n bytesToWrite -= bytesWritten;\n } while(bytesToWrite > 0);\n return true;\n}\n\n\/**\n* Instead of actually reading the data\n* it notifies seperate functions depending\n* on what we are reading, which read as required\n*\/\nvoid RecvFileProgressDialog::readRequest()\n{\n\/\/ QByteArray data;\n\/\/ while(m_socket->bytesAvailable())\n\/\/ {\n\/\/ data += m_socket->read(1024);\n\/\/ \/\/qDebug() << \"Reading\";\n\/\/ }\n\/\/ qDebug() << \":: readRequest data size\" << data.size();\n\/\/ qDebug() << data << \"\\n\\n\";\n if(m_requestType == QOM_FILE_REGULAR)\n requestWriteToFile();\n else if(m_requestType == QOM_FILE_DIR)\n requestWriteToDirectory();\n}\n\nvoid RecvFileProgressDialog::requestWriteToFile()\n{\n QByteArray data = m_socket->readAll();\n writeToFile(data);\n}\n\n\/**\n * Attempts to read headers individually\n * and then read the file as required\n *\/\nvoid RecvFileProgressDialog::requestWriteToDirectory()\n{\n while(m_socket->bytesAvailable())\n {\n if(m_inHeader)\n {\n m_header += m_socket->read(1);\n \/\/qDebug() << m_header;\n QByteArray drop; \/\/ TODO: ideally not required\n RecvFileInfo info = parseDirectoryHeader(m_header, &drop);\n \n if(info.fileID >= 0)\n {\n qDebug() << \"# Header parsed successfully\";\n qDebug() << info.fileName << info.size << info.type;\n \/\/ we got a valid header, process it\n m_inHeader = false;\n m_header.clear();\n \n if(info.type == QOM_FILE_REGULAR)\n {\n qDebug() << \"Now writing new file\" << info.fileName;\n if(!openFile(m_dir->absoluteFilePath(info.fileName)))\n return ;\n m_waitingForData = info.size;\n m_currentSize = info.size;\n }\n else if(info.type == QOM_FILE_DIR)\n {\n qDebug() << \"Creating directory\" << info.fileName;\n bool made = false;\n if(m_dir == NULL)\n made = makeDirectory(m_saveDir + QDir::separator() + info.fileName);\n else\n made = makeDirectory(m_dir->absoluteFilePath(info.fileName));\n if(!made)\n return;\n m_inHeader = true;\n continue;\n }\n else if(info.type == QOM_FILE_RETPARENT)\n {\n qDebug() << \"Going up\";\n m_dir->cdUp();\n if(m_dir->absolutePath() == m_saveDir)\n accept();\n m_inHeader = true;\n continue;\n }\n else\n {\n QMessageBox::critical(this, tr(\"Receive failed\"), tr(\"Bad header! Could not understand file type %1\").arg(info.type));\n reject();\n }\n }\n }\n \/\/ write to file whatever we get\n if(!m_inHeader)\n { \n QByteArray fileData = m_socket->read(m_waitingForData);\n writeToFile(fileData);\n if(m_waitingForData == 0)\n {\n m_inHeader = true;\n }\n }\n }\n \n}\n\nbool RecvFileProgressDialog::openFile(const QString& fileName)\n{\n m_currentFile = new QFile(fileName);\n if(m_currentFile->exists())\n {\n if(QMessageBox::No == QMessageBox::question(this, tr(\"Replace file\"), tr(\"File %1 exists, overwrite?\").arg(fileName),\n QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))\n {\n m_waitingForData = 0;\n return false;\n }\n }\n if(!m_currentFile->open(QIODevice::Truncate | QIODevice::WriteOnly))\n {\n qWarning() << \"Cannot open\" << fileName << \"for writing\";\n m_currentFile->close();\n m_waitingForData = 0;\n return false;\n }\n qDebug() << fileName << \"Opened with truncate\";\n return true;\n}\n\n\/*\n * TODO: i know, the remainder thing is a bad hack.\n *\/\nbool RecvFileProgressDialog::writeToFile(QByteArray& b, QByteArray* remainder)\n{\n if(m_currentFile == NULL)\n return false;\n while(b.size() > 0)\n {\n if(m_waitingForData < b.size())\n {\n qDebug() << \"Excess data, setting remainder\";\n if(remainder != NULL)\n {\n *remainder = b.right(b.size() - m_waitingForData);\n }\n b = b.left(m_waitingForData);\n }\n int written = m_currentFile->write(b);\n \/\/qDebug() << \"Wrote\" << written << \"bytes to\" << m_currentFile->fileName();\n if(written == -1)\n {\n qWarning() << \"Write error\" << m_currentFile->errorString();\n m_currentFile->close();\n return false;\n }\n m_waitingForData -= written;\n qDebug() << \"Wrote\" << written << \"bytes\" << \"Left\" << m_waitingForData;\n b.remove(0, written);\n }\n \n setLabelText(tr(\"Receiving %1\").arg(m_currentFile->fileName()));\n setValue((float)(m_currentSize-m_waitingForData)\/m_currentSize * 100.0);\n if(m_waitingForData <= 0)\n {\n qDebug() << \"Finished writing\" << m_currentFile->fileName();\n m_currentFile->close();\n }\n return true;\n}\n\nbool RecvFileProgressDialog::makeDirectory(const QString& path)\n{\n qDebug() << \"makeDirectory\" << path;\n if(m_dir != NULL)\n {\n delete m_dir;\n m_dir = NULL;\n }\n m_dir = new QDir(path);\n if(!m_dir->exists() && !m_dir->mkdir(path))\n {\n \/\/ TODO: convert to QMessageBox\n qWarning() << \"Could not create directory\" << m_dir->absolutePath() ;\n return false;\n }\n return true;\n}\n\nbool RecvFileProgressDialog::writeToDirectory(QByteArray& b)\n{\n m_header += b;\n \/\/qDebug() << \"At the beginning of writeToDirectory\" << m_header;\n QByteArray leftover;\n RecvFileInfo info = parseDirectoryHeader(m_header, &leftover);\n if(m_waitingForData != 0 && m_header.isEmpty())\n {\n qDebug() << \"Need to flush\";\n exit(5);\n }\n \n \/\/info is filled, only leftover is valuable\n if(info.fileID >= 0)\n {\n m_inHeader = false;\n m_header = leftover;\n \/\/qDebug() << \"! Leftover\" << leftover;\n \n if(info.type == QOM_FILE_REGULAR)\n {\n qDebug() << \"Now writing new file\" << info.fileName;\n if(!openFile(m_dir->absoluteFilePath(info.fileName)))\n return false;\n m_waitingForData = info.size;\n m_currentSize = info.size;\n \n QByteArray moreLeftover;\n \n \/\/ leftover can't immediately have another header\n \/\/ any headers it has now are in moreLeftover\n if(!writeToFile(leftover, &moreLeftover))\n return false;\n \/\/qDebug() << \"!moreLeftover\" << moreLeftover;\n qDebug() << \"line 306:\" << m_waitingForData;\n if(m_waitingForData == 0)\n {\n m_inHeader = true;\n m_header = moreLeftover;\n }\n else\n {\n m_inHeader = false;\n m_header.clear();\n }\n }\n else if(info.type == QOM_FILE_DIR)\n {\n qDebug() << \"Creating new directory\" << info.fileName;\n bool made = false;\n if(m_dir == NULL)\n made = makeDirectory(m_saveDir + QDir::separator() + info.fileName);\n else\n made = makeDirectory(m_dir->absoluteFilePath(info.fileName));\n if(!made)\n return false;\n m_inHeader = true;\n \/\/m_header.clear();\n }\n else if(info.type == QOM_FILE_RETPARENT)\n {\n qDebug() << \"Going up\";\n m_dir->cdUp();\n m_inHeader = true;\n }\n \/\/qDebug() << \"After all processing of header, in header?\" << m_inHeader<<\"\\n\";\n }\n \n if(!m_inHeader)\n {\n qDebug() << \"> In file\";\n QByteArray leftover;\n writeToFile(m_header, &leftover);\n qDebug() << \"line 337:\" << m_waitingForData ;\n if(m_waitingForData == 0)\n {\n m_header = leftover;\n m_inHeader = true;\n }\n else\n {\n m_header.clear();\n m_inHeader = false;\n }\n }\n qDebug() << \" << Returning from writeToDirectory\";\n return true;\n}\n\n\/**\n * Tries to parse a header if it can\n * if it can, fills in RecvFileInfo correctly\n * Otherwise sets RecvFileInfo.fileID to -1, other fields are kept default\n * If any data is left over after parsing header, it is stored in remainder.\n *\/\nRecvFileInfo RecvFileProgressDialog::parseDirectoryHeader(const QByteArray& a, QByteArray* remainder)\n{\n bool bad = false;\n RecvFileInfo ret;\n \n if(a.contains(\":\"))\n {\n QList tokens = a.split(':');\n int headerSize = tokens[0].toInt(0, 16);\n \/\/qDebug() << \"Header size:\"<toLongLong to accomodate large files#include \"recvfileprogressdialog.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n\n\/**\n * Returns a list of requested files\n *\/\nQList RecvFileProgressDialog::parsePayloadFileList(QByteArray payload)\n{\n QList recvFiles;\n QList headers = payload.split(QOM_FILELIST_SEPARATOR);\n foreach(QByteArray header, headers)\n {\n RecvFileInfo info;\n QList tokens = header.split(':');\n qDebug() << \"Tokens:\" << tokens;\n if(tokens.size() < 5)\n continue;\n info.fileID = tokens[0].toInt();\n info.fileName = tokens[1];\n info.size = tokens[2].toLongLong(0, 16);\n info.mtime = tokens[3].toInt(0, 16);\n info.type = tokens[4].toInt(0, 16);\n qDebug() << \"Parsed ID:\"<errorString();\n reject();\n}\n\nvoid RecvFileProgressDialog::accept()\n{\n qDebug() << \"$$$$$ Socket disconnected\";\n QProgressDialog::accept();\n}\n\nvoid RecvFileProgressDialog::startReceiving()\n{\n m_socket = new QTcpSocket(this);\n m_socket->abort();\n m_socket->connectToHost(m_msg.sender()->addressString(), UDP_PORT);\n \n connect(m_socket, SIGNAL(readyRead()), this, SLOT(readRequest()));\n connect(m_socket, SIGNAL(connected()), this, SLOT(requestFiles()));\n connect(m_socket, SIGNAL(disconnected()), this, SLOT(accept()));\n connect(m_socket, SIGNAL(disconnected()), m_socket, SLOT(deleteLater()));\n connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError)));\n}\n\nvoid RecvFileProgressDialog::requestFiles()\n{\n while(!m_fileHeaders.isEmpty())\n {\n if(m_waitingForData > 0)\n {\n qDebug() << \"Waiting for\"<< m_waitingForData;\n QTimer::singleShot(1000, this, SLOT(requestFiles()));\n break;\n }\n startReceiving();\n RecvFileInfo info = m_fileHeaders.takeFirst();\n m_requestType = info.type;\n \n QByteArray payload = QByteArray::number(m_msg.packetNo(), 16);\n payload += \":\";\n payload += QByteArray::number(info.fileID, 16);\n qDebug() << \"Writing request for file data\"<makeMessage(QOM_GETFILEDATA, payload).toAscii());\n }\n else if(m_requestType == QOM_FILE_DIR)\n {\n writeBlock(messenger()->makeMessage(QOM_GETDIRFILES, payload).toAscii());\n }\n }\n}\n\nvoid RecvFileProgressDialog::informUser()\n{\n QString message(m_msg.sender()->name());\n message.append(tr(\" has sent the following files\\n\\n\"));\n \n qint64 totalSize = 0;\n \n foreach(RecvFileInfo info, m_fileHeaders)\n {\n message.append(info.fileName);\n message.append(\" (\");\n if(info.type == QOM_FILE_REGULAR)\n {\n message.append(QString::number(info.size));\n totalSize += info.size;\n message.append(\" bytes)\\n\");\n }\n else if(info.type == QOM_FILE_DIR)\n {\n message.append(\"Directory, unknown size)\\n\");\n }\n }\n \n message.append(tr(\"\\nTotal Size: \"));\n if(totalSize > 1024*1024)\n {\n message.append(QString::number(totalSize \/ (1024*1024) ));\n message.append(\"Mb\");\n }\n else if( totalSize > 1024 )\n {\n message.append(QString::number(totalSize \/ 1024));\n message.append(\"Kb\");\n }\n else\n {\n message.append(QString::number(totalSize));\n message.append(\"bytes\");\n }\n \n QString msg = m_msg.payload().left(m_msg.payload().indexOf(\"\\a\"));\n if(!msg.isEmpty())\n message.append(\"\\n\\nMessage: \" + msg);\n \n message.append(tr(\"\\n\\nDo you want to accept the files?\"));\n if(QMessageBox::No == QMessageBox::question(NULL, \n tr(\"Receiving files\"), \n message, \n QMessageBox::Yes | QMessageBox::No,\n QMessageBox::Yes)) \/\/ last is default button\n reject();\n else\n m_saveDir = QFileDialog::getExistingDirectory(this, tr(\"Save To\"));\n \n if(!m_saveDir.isEmpty())\n {\n qDebug() << m_saveDir;\n }\n}\n\n\/\/ TODO: share with sending dialog?\nbool RecvFileProgressDialog::writeBlock(QByteArray b)\n{\n int bytesToWrite = b.size();\n int bytesWritten = 0;\n do\n {\n qDebug() << \"Writing\" << b << \"to socket\";\n bytesWritten = m_socket->write(b);\n if(bytesWritten == -1)\n return false;\n b.remove(0, bytesWritten);\n bytesToWrite -= bytesWritten;\n } while(bytesToWrite > 0);\n return true;\n}\n\n\/**\n* Instead of actually reading the data\n* it notifies seperate functions depending\n* on what we are reading, which read as required\n*\/\nvoid RecvFileProgressDialog::readRequest()\n{\n\/\/ QByteArray data;\n\/\/ while(m_socket->bytesAvailable())\n\/\/ {\n\/\/ data += m_socket->read(1024);\n\/\/ \/\/qDebug() << \"Reading\";\n\/\/ }\n\/\/ qDebug() << \":: readRequest data size\" << data.size();\n\/\/ qDebug() << data << \"\\n\\n\";\n if(m_requestType == QOM_FILE_REGULAR)\n requestWriteToFile();\n else if(m_requestType == QOM_FILE_DIR)\n requestWriteToDirectory();\n}\n\nvoid RecvFileProgressDialog::requestWriteToFile()\n{\n QByteArray data = m_socket->readAll();\n writeToFile(data);\n}\n\n\/**\n * Attempts to read headers individually\n * and then read the file as required\n *\/\nvoid RecvFileProgressDialog::requestWriteToDirectory()\n{\n while(m_socket->bytesAvailable())\n {\n if(m_inHeader)\n {\n m_header += m_socket->read(1);\n \/\/qDebug() << m_header;\n QByteArray drop; \/\/ TODO: ideally not required\n RecvFileInfo info = parseDirectoryHeader(m_header, &drop);\n \n if(info.fileID >= 0)\n {\n qDebug() << \"# Header parsed successfully\";\n qDebug() << info.fileName << info.size << info.type;\n \/\/ we got a valid header, process it\n m_inHeader = false;\n m_header.clear();\n \n if(info.type == QOM_FILE_REGULAR)\n {\n qDebug() << \"Now writing new file\" << info.fileName;\n if(!openFile(m_dir->absoluteFilePath(info.fileName)))\n return ;\n m_waitingForData = info.size;\n m_currentSize = info.size;\n }\n else if(info.type == QOM_FILE_DIR)\n {\n qDebug() << \"Creating directory\" << info.fileName;\n bool made = false;\n if(m_dir == NULL)\n made = makeDirectory(m_saveDir + QDir::separator() + info.fileName);\n else\n made = makeDirectory(m_dir->absoluteFilePath(info.fileName));\n if(!made)\n return;\n m_inHeader = true;\n continue;\n }\n else if(info.type == QOM_FILE_RETPARENT)\n {\n qDebug() << \"Going up\";\n m_dir->cdUp();\n if(m_dir->absolutePath() == m_saveDir)\n accept();\n m_inHeader = true;\n continue;\n }\n else\n {\n QMessageBox::critical(this, tr(\"Receive failed\"), tr(\"Bad header! Could not understand file type %1\").arg(info.type));\n reject();\n }\n }\n }\n \/\/ write to file whatever we get\n if(!m_inHeader)\n { \n QByteArray fileData = m_socket->read(m_waitingForData);\n writeToFile(fileData);\n if(m_waitingForData == 0)\n {\n m_inHeader = true;\n }\n }\n }\n \n}\n\nbool RecvFileProgressDialog::openFile(const QString& fileName)\n{\n m_currentFile = new QFile(fileName);\n if(m_currentFile->exists())\n {\n if(QMessageBox::No == QMessageBox::question(this, tr(\"Replace file\"), tr(\"File %1 exists, overwrite?\").arg(fileName),\n QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))\n {\n m_waitingForData = 0;\n return false;\n }\n }\n if(!m_currentFile->open(QIODevice::Truncate | QIODevice::WriteOnly))\n {\n qWarning() << \"Cannot open\" << fileName << \"for writing\";\n m_currentFile->close();\n m_waitingForData = 0;\n return false;\n }\n qDebug() << fileName << \"Opened with truncate\";\n return true;\n}\n\n\/*\n * TODO: i know, the remainder thing is a bad hack.\n *\/\nbool RecvFileProgressDialog::writeToFile(QByteArray& b, QByteArray* remainder)\n{\n if(m_currentFile == NULL)\n return false;\n while(b.size() > 0)\n {\n if(m_waitingForData < b.size())\n {\n qDebug() << \"Excess data, setting remainder\";\n if(remainder != NULL)\n {\n *remainder = b.right(b.size() - m_waitingForData);\n }\n b = b.left(m_waitingForData);\n }\n int written = m_currentFile->write(b);\n \/\/qDebug() << \"Wrote\" << written << \"bytes to\" << m_currentFile->fileName();\n if(written == -1)\n {\n qWarning() << \"Write error\" << m_currentFile->errorString();\n m_currentFile->close();\n return false;\n }\n m_waitingForData -= written;\n qDebug() << \"Wrote\" << written << \"bytes\" << \"Left\" << m_waitingForData;\n b.remove(0, written);\n }\n \n setLabelText(tr(\"Receiving %1\").arg(m_currentFile->fileName()));\n setValue((float)(m_currentSize-m_waitingForData)\/m_currentSize * 100.0);\n if(m_waitingForData <= 0)\n {\n qDebug() << \"Finished writing\" << m_currentFile->fileName();\n m_currentFile->close();\n }\n return true;\n}\n\nbool RecvFileProgressDialog::makeDirectory(const QString& path)\n{\n qDebug() << \"makeDirectory\" << path;\n if(m_dir != NULL)\n {\n delete m_dir;\n m_dir = NULL;\n }\n m_dir = new QDir(path);\n if(!m_dir->exists() && !m_dir->mkdir(path))\n {\n \/\/ TODO: convert to QMessageBox\n qWarning() << \"Could not create directory\" << m_dir->absolutePath() ;\n return false;\n }\n return true;\n}\n\nbool RecvFileProgressDialog::writeToDirectory(QByteArray& b)\n{\n m_header += b;\n \/\/qDebug() << \"At the beginning of writeToDirectory\" << m_header;\n QByteArray leftover;\n RecvFileInfo info = parseDirectoryHeader(m_header, &leftover);\n if(m_waitingForData != 0 && m_header.isEmpty())\n {\n qDebug() << \"Need to flush\";\n exit(5);\n }\n \n \/\/info is filled, only leftover is valuable\n if(info.fileID >= 0)\n {\n m_inHeader = false;\n m_header = leftover;\n \/\/qDebug() << \"! Leftover\" << leftover;\n \n if(info.type == QOM_FILE_REGULAR)\n {\n qDebug() << \"Now writing new file\" << info.fileName;\n if(!openFile(m_dir->absoluteFilePath(info.fileName)))\n return false;\n m_waitingForData = info.size;\n m_currentSize = info.size;\n \n QByteArray moreLeftover;\n \n \/\/ leftover can't immediately have another header\n \/\/ any headers it has now are in moreLeftover\n if(!writeToFile(leftover, &moreLeftover))\n return false;\n \/\/qDebug() << \"!moreLeftover\" << moreLeftover;\n qDebug() << \"line 306:\" << m_waitingForData;\n if(m_waitingForData == 0)\n {\n m_inHeader = true;\n m_header = moreLeftover;\n }\n else\n {\n m_inHeader = false;\n m_header.clear();\n }\n }\n else if(info.type == QOM_FILE_DIR)\n {\n qDebug() << \"Creating new directory\" << info.fileName;\n bool made = false;\n if(m_dir == NULL)\n made = makeDirectory(m_saveDir + QDir::separator() + info.fileName);\n else\n made = makeDirectory(m_dir->absoluteFilePath(info.fileName));\n if(!made)\n return false;\n m_inHeader = true;\n \/\/m_header.clear();\n }\n else if(info.type == QOM_FILE_RETPARENT)\n {\n qDebug() << \"Going up\";\n m_dir->cdUp();\n m_inHeader = true;\n }\n \/\/qDebug() << \"After all processing of header, in header?\" << m_inHeader<<\"\\n\";\n }\n \n if(!m_inHeader)\n {\n qDebug() << \"> In file\";\n QByteArray leftover;\n writeToFile(m_header, &leftover);\n qDebug() << \"line 337:\" << m_waitingForData ;\n if(m_waitingForData == 0)\n {\n m_header = leftover;\n m_inHeader = true;\n }\n else\n {\n m_header.clear();\n m_inHeader = false;\n }\n }\n qDebug() << \" << Returning from writeToDirectory\";\n return true;\n}\n\n\/**\n * Tries to parse a header if it can\n * if it can, fills in RecvFileInfo correctly\n * Otherwise sets RecvFileInfo.fileID to -1, other fields are kept default\n * If any data is left over after parsing header, it is stored in remainder.\n *\/\nRecvFileInfo RecvFileProgressDialog::parseDirectoryHeader(const QByteArray& a, QByteArray* remainder)\n{\n bool bad = false;\n RecvFileInfo ret;\n \n if(a.contains(\":\"))\n {\n QList tokens = a.split(':');\n int headerSize = tokens[0].toInt(0, 16);\n \/\/qDebug() << \"Header size:\"<"} {"text":"\/* This file is part of the KDE project\n Copyright (C) 2006-2007 Matthias Kretz \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) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), Nokia Corporation\n (or its successors, if any) and the KDE Free Qt Foundation, which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public \n License along with this library. If not, see .\n\n*\/\n\n#include \"effectwidget.h\"\n#include \"effectwidget_p.h\"\n\n#include \n#include \n\n#include \"effect.h\"\n#include \"effectparameter.h\"\n#include \"phonondefs_p.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef min\n#undef min\n#endif\n#ifdef max\n#undef max\n#endif\nstatic const qreal DEFAULT_MIN = std::numeric_limits::min();\nstatic const qreal DEFAULT_MAX = std::numeric_limits::max();\nstatic const int DEFAULT_MIN_INT = std::numeric_limits::min();\nstatic const int DEFAULT_MAX_INT = std::numeric_limits::max();\nstatic const int SLIDER_RANGE = 8;\nstatic const int TICKINTERVAL = 4;\n\n\nQT_BEGIN_NAMESPACE\n\n#ifndef QT_NO_PHONON_EFFECTWIDGET\n\nnamespace Phonon\n{\n\nEffectWidget::EffectWidget(Effect *effect, QWidget *parent)\n : QWidget(parent),\n k_ptr(new EffectWidgetPrivate(effect))\n{\n K_D(EffectWidget);\n d->q_ptr = this;\n d->autogenerateUi();\n}\n\nEffectWidget::~EffectWidget()\n{\n delete k_ptr;\n}\n\n\/*\nEffectWidget::EffectWidget(EffectWidgetPrivate &dd, QWidget *parent)\n : QWidget(parent)\n , k_ptr(&dd)\n{\n K_D(EffectWidget);\n d->q_ptr = this;\n d->autogenerateUi();\n}\n*\/\n\nEffectWidgetPrivate::EffectWidgetPrivate(Effect *e)\n : effect(e)\n{\n \/\/TODO: look up whether there is a specialized widget for this effect. This\n \/\/could be a DSO or a Designer ui file found via KTrader.\n \/\/\n \/\/if no specialized widget is available:\n}\n\nvoid EffectWidgetPrivate::autogenerateUi()\n{\n Q_Q(EffectWidget);\n QVBoxLayout *mainLayout = new QVBoxLayout(q);\n mainLayout->setMargin(0);\n foreach (const EffectParameter ¶, effect->parameters()) {\n QVariant value = effect->parameterValue(para);\n QHBoxLayout *pLayout = new QHBoxLayout;\n mainLayout->addLayout(pLayout);\n\n QLabel *label = new QLabel(q);\n pLayout->addWidget(label);\n label->setText(para.name());\n#ifndef QT_NO_TOOLTIP\n label->setToolTip(para.description());\n#endif\n\n QWidget *control = 0;\n switch (para.type()) {\n case QVariant::String:\n {\n QComboBox *cb = new QComboBox(q);\n control = cb;\n if (value.type() == QVariant::Int) {\n \/\/value just defines the item index\n foreach (const QVariant &item, para.possibleValues()) {\n cb->addItem(item.toString());\n }\n cb->setCurrentIndex(value.toInt());\n QObject::connect(cb, SIGNAL(currentIndexChanged(int)), q, SLOT(_k_setIntParameter(int)));\n } else {\n foreach (const QVariant &item, para.possibleValues()) {\n cb->addItem(item.toString());\n if (item == value) {\n cb->setCurrentIndex(cb->count() - 1);\n }\n }\n QObject::connect(cb, SIGNAL(currentIndexChanged(QString)), q, SLOT(_k_setStringParameter(QString)));\n }\n }\n break;\n case QVariant::Bool:\n {\n QCheckBox *cb = new QCheckBox(q);\n control = cb;\n cb->setChecked(value.toBool());\n QObject::connect(cb, SIGNAL(toggled(bool)), q, SLOT(_k_setToggleParameter(bool)));\n }\n break;\n case QVariant::Int:\n {\n QSpinBox *sb = new QSpinBox(q);\n control = sb;\n bool minValueOk = false;\n bool maxValueOk = false;\n const int minValue = para.minimumValue().toInt(&minValueOk);\n const int maxValue = para.minimumValue().toInt(&maxValueOk);\n\n sb->setRange(minValueOk ? minValue : DEFAULT_MIN_INT, maxValueOk ? maxValue : DEFAULT_MAX_INT);\n sb->setValue(value.toInt());\n QObject::connect(sb, SIGNAL(valueChanged(int)), q, SLOT(_k_setIntParameter(int)));\n }\n break;\n case QVariant::Double:\n {\n const double minValue = (para.minimumValue().type() == QVariant::Double ?\n para.minimumValue().toDouble() : DEFAULT_MIN);\n const double maxValue = (para.maximumValue().type() == QVariant::Double ?\n para.maximumValue().toDouble() : DEFAULT_MAX);\n\n if (minValue == -1. && maxValue == 1.) {\n \/\/Special case values between -1 and 1.0 to use a slider for improved usability\n QSlider *slider = new QSlider(Qt::Horizontal, q);\n slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE);\n slider->setValue(int(SLIDER_RANGE * value.toDouble()));\n slider->setTickPosition(QSlider::TicksBelow);\n slider->setTickInterval(TICKINTERVAL);\n QObject::connect(slider, SIGNAL(valueChanged(int)), q, SLOT(_k_setSliderParameter(int)));\n } else {\n double step = 0.1;\n if (qAbs(maxValue - minValue) > 50)\n step = 1.0;\n QDoubleSpinBox *sb = new QDoubleSpinBox(q);\n control = sb;\n sb->setRange(minValue, maxValue);\n sb->setValue(value.toDouble());\n sb->setSingleStep(step);\n QObject::connect(sb, SIGNAL(valueChanged(double)), q,\n SLOT(_k_setDoubleParameter(double)));\n }\n }\n break;\n default:\n break;\n }\n\n#ifndef QT_NO_TOOLTIP\n control->setToolTip(para.description());\n#endif\n if (control) {\n#ifndef QT_NO_SHORTCUT\n label->setBuddy(control);\n#endif\n pLayout->addWidget(control);\n parameterForObject.insert(control, para);\n }\n }\n}\n\nvoid EffectWidgetPrivate::_k_setToggleParameter(bool checked)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], checked);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setIntParameter(int value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], value);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setDoubleParameter(double value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], value);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setStringParameter(const QString &value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], value);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setSliderParameter(int value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], double(value) \/ double(SLIDER_RANGE));\n }\n}\n\n\n} \/\/ namespace Phonon\n\n\n#endif \/\/ QT_NO_PHONON_EFFECTWIDGET\n\nQT_END_NAMESPACE\n\n#include \"moc_effectwidget.cpp\"\n\n\/\/ vim: sw=4 ts=4\nFix a crash in Phonon::EffectWidget\/* This file is part of the KDE project\n Copyright (C) 2006-2007 Matthias Kretz \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) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), Nokia Corporation\n (or its successors, if any) and the KDE Free Qt Foundation, which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public \n License along with this library. If not, see .\n\n*\/\n\n#include \"effectwidget.h\"\n#include \"effectwidget_p.h\"\n\n#include \n#include \n\n#include \"effect.h\"\n#include \"effectparameter.h\"\n#include \"phonondefs_p.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef min\n#undef min\n#endif\n#ifdef max\n#undef max\n#endif\nstatic const qreal DEFAULT_MIN = std::numeric_limits::min();\nstatic const qreal DEFAULT_MAX = std::numeric_limits::max();\nstatic const int DEFAULT_MIN_INT = std::numeric_limits::min();\nstatic const int DEFAULT_MAX_INT = std::numeric_limits::max();\nstatic const int SLIDER_RANGE = 8;\nstatic const int TICKINTERVAL = 4;\n\n\nQT_BEGIN_NAMESPACE\n\n#ifndef QT_NO_PHONON_EFFECTWIDGET\n\nnamespace Phonon\n{\n\nEffectWidget::EffectWidget(Effect *effect, QWidget *parent)\n : QWidget(parent),\n k_ptr(new EffectWidgetPrivate(effect))\n{\n K_D(EffectWidget);\n d->q_ptr = this;\n d->autogenerateUi();\n}\n\nEffectWidget::~EffectWidget()\n{\n delete k_ptr;\n}\n\n\/*\nEffectWidget::EffectWidget(EffectWidgetPrivate &dd, QWidget *parent)\n : QWidget(parent)\n , k_ptr(&dd)\n{\n K_D(EffectWidget);\n d->q_ptr = this;\n d->autogenerateUi();\n}\n*\/\n\nEffectWidgetPrivate::EffectWidgetPrivate(Effect *e)\n : effect(e)\n{\n \/\/TODO: look up whether there is a specialized widget for this effect. This\n \/\/could be a DSO or a Designer ui file found via KTrader.\n \/\/\n \/\/if no specialized widget is available:\n}\n\nvoid EffectWidgetPrivate::autogenerateUi()\n{\n Q_Q(EffectWidget);\n QVBoxLayout *mainLayout = new QVBoxLayout(q);\n mainLayout->setMargin(0);\n foreach (const EffectParameter ¶, effect->parameters()) {\n QVariant value = effect->parameterValue(para);\n QHBoxLayout *pLayout = new QHBoxLayout;\n mainLayout->addLayout(pLayout);\n\n QLabel *label = new QLabel(q);\n pLayout->addWidget(label);\n label->setText(para.name());\n#ifndef QT_NO_TOOLTIP\n label->setToolTip(para.description());\n#endif\n\n QWidget *control = 0;\n switch (para.type()) {\n case QVariant::String:\n {\n QComboBox *cb = new QComboBox(q);\n control = cb;\n if (value.type() == QVariant::Int) {\n \/\/value just defines the item index\n foreach (const QVariant &item, para.possibleValues()) {\n cb->addItem(item.toString());\n }\n cb->setCurrentIndex(value.toInt());\n QObject::connect(cb, SIGNAL(currentIndexChanged(int)), q, SLOT(_k_setIntParameter(int)));\n } else {\n foreach (const QVariant &item, para.possibleValues()) {\n cb->addItem(item.toString());\n if (item == value) {\n cb->setCurrentIndex(cb->count() - 1);\n }\n }\n QObject::connect(cb, SIGNAL(currentIndexChanged(QString)), q, SLOT(_k_setStringParameter(QString)));\n }\n }\n break;\n case QVariant::Bool:\n {\n QCheckBox *cb = new QCheckBox(q);\n control = cb;\n cb->setChecked(value.toBool());\n QObject::connect(cb, SIGNAL(toggled(bool)), q, SLOT(_k_setToggleParameter(bool)));\n }\n break;\n case QVariant::Int:\n {\n QSpinBox *sb = new QSpinBox(q);\n control = sb;\n bool minValueOk = false;\n bool maxValueOk = false;\n const int minValue = para.minimumValue().toInt(&minValueOk);\n const int maxValue = para.minimumValue().toInt(&maxValueOk);\n\n sb->setRange(minValueOk ? minValue : DEFAULT_MIN_INT, maxValueOk ? maxValue : DEFAULT_MAX_INT);\n sb->setValue(value.toInt());\n QObject::connect(sb, SIGNAL(valueChanged(int)), q, SLOT(_k_setIntParameter(int)));\n }\n break;\n case QVariant::Double:\n {\n const double minValue = (para.minimumValue().type() == QVariant::Double ?\n para.minimumValue().toDouble() : DEFAULT_MIN);\n const double maxValue = (para.maximumValue().type() == QVariant::Double ?\n para.maximumValue().toDouble() : DEFAULT_MAX);\n\n if (minValue == -1. && maxValue == 1.) {\n \/\/Special case values between -1 and 1.0 to use a slider for improved usability\n QSlider *slider = new QSlider(Qt::Horizontal, q);\n control = slider;\n slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE);\n slider->setValue(int(SLIDER_RANGE * value.toDouble()));\n slider->setTickPosition(QSlider::TicksBelow);\n slider->setTickInterval(TICKINTERVAL);\n QObject::connect(slider, SIGNAL(valueChanged(int)), q, SLOT(_k_setSliderParameter(int)));\n } else {\n double step = 0.1;\n if (qAbs(maxValue - minValue) > 50)\n step = 1.0;\n QDoubleSpinBox *sb = new QDoubleSpinBox(q);\n control = sb;\n sb->setRange(minValue, maxValue);\n sb->setValue(value.toDouble());\n sb->setSingleStep(step);\n QObject::connect(sb, SIGNAL(valueChanged(double)), q,\n SLOT(_k_setDoubleParameter(double)));\n }\n }\n break;\n default:\n break;\n }\n\n if (control) {\n#ifndef QT_NO_TOOLTIP\n control->setToolTip(para.description());\n#endif\n#ifndef QT_NO_SHORTCUT\n label->setBuddy(control);\n#endif\n pLayout->addWidget(control);\n parameterForObject.insert(control, para);\n }\n }\n}\n\nvoid EffectWidgetPrivate::_k_setToggleParameter(bool checked)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], checked);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setIntParameter(int value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], value);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setDoubleParameter(double value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], value);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setStringParameter(const QString &value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], value);\n }\n}\n\nvoid EffectWidgetPrivate::_k_setSliderParameter(int value)\n{\n Q_Q(EffectWidget);\n if (parameterForObject.contains(q->sender())) {\n effect->setParameterValue(parameterForObject[q->sender()], double(value) \/ double(SLIDER_RANGE));\n }\n}\n\n\n} \/\/ namespace Phonon\n\n\n#endif \/\/ QT_NO_PHONON_EFFECTWIDGET\n\nQT_END_NAMESPACE\n\n#include \"moc_effectwidget.cpp\"\n\n\/\/ vim: sw=4 ts=4\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"SuperComponent.hpp\"\n#include \n\nnamespace Component {\n \/\/\/ %Component handling a camera lens.\n class Lens : public SuperComponent {\n public:\n \/\/\/ Create new lens.\n \/**\n * @param entity Pointer to which entity this component corresponds.\n *\/\n Lens(Entity* entity);\n \n \/\/\/ Save the component.\n \/**\n * @return JSON value to be stored on disk.\n *\/\n Json::Value Save() const override;\n \n \/\/\/ Load component from JSON node.\n \/**\n * @param node JSON node to load from.\n *\/\n void Load(const Json::Value& node) override;\n\n \/\/\/ Get the projection matrix.\n \/**\n * @param screenSize Screen size in pixels.\n * @return The projection matrix.\n *\/\n glm::mat4 GetProjection(const glm::vec2& screenSize) const;\n \n \/\/\/ Field of view, in degrees.\n \/**\n * Default: 45.0\n *\/\n float fieldOfView = 45.f;\n \n \/\/\/ Near plane.\n \/**\n * Default: 0.5\n *\/\n float zNear = 0.5f;\n \n \/\/\/ Far plane.\n \/**\n * Default: 100.0\n *\/\n float zFar = 100.f;\n };\n}\nFix GLM include#pragma once\n\n#include \"SuperComponent.hpp\"\n#include \n\nnamespace Component {\n \/\/\/ %Component handling a camera lens.\n class Lens : public SuperComponent {\n public:\n \/\/\/ Create new lens.\n \/**\n * @param entity Pointer to which entity this component corresponds.\n *\/\n Lens(Entity* entity);\n \n \/\/\/ Save the component.\n \/**\n * @return JSON value to be stored on disk.\n *\/\n Json::Value Save() const override;\n \n \/\/\/ Load component from JSON node.\n \/**\n * @param node JSON node to load from.\n *\/\n void Load(const Json::Value& node) override;\n\n \/\/\/ Get the projection matrix.\n \/**\n * @param screenSize Screen size in pixels.\n * @return The projection matrix.\n *\/\n glm::mat4 GetProjection(const glm::vec2& screenSize) const;\n \n \/\/\/ Field of view, in degrees.\n \/**\n * Default: 45.0\n *\/\n float fieldOfView = 45.f;\n \n \/\/\/ Near plane.\n \/**\n * Default: 0.5\n *\/\n float zNear = 0.5f;\n \n \/\/\/ Far plane.\n \/**\n * Default: 100.0\n *\/\n float zFar = 100.f;\n };\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2011-2014, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * 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 THE COPYRIGHT HOLDER 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 ON\n * 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#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n\/* details namespace is here to hide implementation details to header end user. It\n * is NOT intended to be used outside. *\/\nnamespace details\n{\n\n\/** Helper class to limit instantiation of templates *\/\ntemplate\nstruct ConvertionAllowed;\n\n\/* List of allowed types for conversion *\/\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\n\ntemplate\nstatic inline bool convertTo(const std::string &str, T &result)\n{\n \/* Check that conversion to that type is allowed.\n * If this fails, this means that this template was not intended to be used\n * with this type, thus that the result is undefined. *\/\n ConvertionAllowed();\n\n if (str.find_first_of(std::string(\"\\r\\n\\t\\v \")) != std::string::npos) {\n return false;\n }\n\n \/* Check for a '-' in string. If type is unsigned and a - is found, the\n * parsing fails. This is made necessary because \"-1\" is read as 65535 for\n * uint16_t, for example *\/\n if (str.find(\"-\") != std::string::npos\n && !std::numeric_limits::is_signed) {\n return false;\n }\n\n std::stringstream ss(str);\n\n \/* Sadly, the stream conversion does not handle hexadecimal format, thus\n * check is done manually *\/\n if (str.substr(0, 2) == \"0x\") {\n if (std::numeric_limits::is_integer) {\n ss >> std::hex >> result;\n }\n else {\n \/* Conversion undefined for non integers *\/\n return false;\n }\n } else {\n ss >> result;\n }\n\n return ss.eof() && !ss.fail() && !ss.bad();\n}\n} \/\/ namespace details\n\n\/**\n * Convert a string to a given type.\n *\n * This template function read the value of the type T in the given string.\n * The function does not allow to have white spaces around the value to parse\n * and tries to parse the whole string, which means that if some bytes were not\n * read in the string, the function fails.\n * Hexadecimal representation (ie numbers starting with 0x) is supported only\n * for integral types conversions.\n * Result may be modified, even in case of failure.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate\nstatic inline bool convertTo(const std::string &str, T &result)\n{\n return details::convertTo(str, result);\n}\n\n\/**\n * Specialization for float of convertTo template function.\n *\n * This function follows the same paradigm than it's generic version and is\n * based on it but makes furthers checks on the returned value.\n *\n * The specific implementation is made necessary because the stlport conversion\n * from string to float behaves differently than GNU STL: overflow produce\n * +\/-Infinity rather than an error.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, float &result)\n{\n if (!details::convertTo(str, result)) {\n return false;\n }\n\n if (!std::isfinite(result)) {\n return false;\n }\n\n return true;\n}\n\n\/**\n * Specialization for double of convertTo template function.\n *\n * This function follows the same paradigm than it's generic version and is\n * based on it but makes furthers checks on the returned value.\n *\n * The specific implementation is made necessary because the stlport conversion\n * from string to double behaves differently than GNU STL: overflow produce\n * +\/-Infinity rather than an error.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, double &result)\n{\n if (!details::convertTo(str, result)) {\n return false;\n }\n\n if (!std::isfinite(result)) {\n return false;\n }\n\n return true;\n}\n\n\/**\n * Specialization for boolean of convertTo template function.\n *\n * This function follows the same paradigm than it's generic version.\n * This function accepts to parse boolean as \"0\/1\" or \"false\/true\" or\n * \"FALSE\/TRUE\".\n * The specific implementation is made necessary because the behaviour of\n * string streams when parsing boolean values is not sufficient to fit our\n * requirements. Indeed, parsing \"true\" will correctly parse the value, but the\n * end of stream is not reached which makes the ss.eof() fails in the generic\n * implementation.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, bool &result)\n{\n if (str == \"0\" || str == \"FALSE\" || str == \"false\") {\n result = false;\n return true;\n }\n\n if (str == \"1\" || str == \"TRUE\" || str == \"true\") {\n result = true;\n return true;\n }\n\n return false;\n}\nDefine special case for convertTo() and convertTo()\/*\n * Copyright (c) 2011-2014, Intel Corporation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * 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 THE COPYRIGHT HOLDER 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 ON\n * 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#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n\/* details namespace is here to hide implementation details to header end user. It\n * is NOT intended to be used outside. *\/\nnamespace details\n{\n\n\/** Helper class to limit instantiation of templates *\/\ntemplate\nstruct ConvertionAllowed;\ntemplate\nstruct ConvertionAllowedVia;\n\n\/* List of allowed types for conversion *\/\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\ntemplate<> struct ConvertionAllowed {};\n\n\/* Allow chars and unsigned chars to be converted via integers *\/\ntemplate<> struct ConvertionAllowedVia {};\ntemplate<> struct ConvertionAllowedVia {};\n\ntemplate\nstatic inline bool convertTo(const std::string &str, T &result)\n{\n \/* Check that conversion to that type is allowed.\n * If this fails, this means that this template was not intended to be used\n * with this type, thus that the result is undefined. *\/\n ConvertionAllowed();\n\n if (str.find_first_of(std::string(\"\\r\\n\\t\\v \")) != std::string::npos) {\n return false;\n }\n\n \/* Check for a '-' in string. If type is unsigned and a - is found, the\n * parsing fails. This is made necessary because \"-1\" is read as 65535 for\n * uint16_t, for example *\/\n if (str.find(\"-\") != std::string::npos\n && !std::numeric_limits::is_signed) {\n return false;\n }\n\n std::stringstream ss(str);\n\n \/* Sadly, the stream conversion does not handle hexadecimal format, thus\n * check is done manually *\/\n if (str.substr(0, 2) == \"0x\") {\n if (std::numeric_limits::is_integer) {\n ss >> std::hex >> result;\n }\n else {\n \/* Conversion undefined for non integers *\/\n return false;\n }\n } else {\n ss >> result;\n }\n\n return ss.eof() && !ss.fail() && !ss.bad();\n}\n\ntemplate\nstatic inline bool convertToVia(const std::string &str, T &result)\n{\n \/* Check that conversion to that type is allowed.\n * If this fails, this means that this template was not intended to be used\n * with this type, thus that the result is undefined. *\/\n ConvertionAllowedVia();\n\n \/* We want to override the behaviour of convertTo with that of\n * convertTo and then safely cast the result into a T. *\/\n Via res;\n\n if (!convertTo(str, res)) {\n return false;\n }\n\n if ((res > std::numeric_limits::max())\n or (res < std::numeric_limits::min())) {\n return false;\n }\n\n result = static_cast(res);\n return true;\n}\n} \/\/ namespace details\n\n\/**\n * Convert a string to a given type.\n *\n * This template function read the value of the type T in the given string.\n * The function does not allow to have white spaces around the value to parse\n * and tries to parse the whole string, which means that if some bytes were not\n * read in the string, the function fails.\n * Hexadecimal representation (ie numbers starting with 0x) is supported only\n * for integral types conversions.\n * Result may be modified, even in case of failure.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate\nstatic inline bool convertTo(const std::string &str, T &result)\n{\n return details::convertTo(str, result);\n}\n\n\/** Specialization for uint8_t of convertTo template function.\n *\n * This function follows the same paradigm than it's generic version.\n *\n * The generic version was converting int8 as it was a character\n * (uint8_t is an alias to unsigned char on most compiler).\n * Thus converting \"1\" would return 49 ie '1'.\n * As convertTo is thought as an _numerical_ convertion tool\n * (contrary to boost::lexical_cast for example),\n * forbid considering the input as a character and consider uint8_t\n * (aka unsigned char) as a number exclusively.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, uint8_t &result)\n{\n return details::convertToVia(str, result);\n}\n\n\/** Specialization for int8_t of convertTo template function.\n *\n * @see convertTo\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, int8_t &result)\n{\n return details::convertToVia(str, result);\n}\n\n\/**\n * Specialization for float of convertTo template function.\n *\n * This function follows the same paradigm than it's generic version and is\n * based on it but makes furthers checks on the returned value.\n *\n * The specific implementation is made necessary because the stlport conversion\n * from string to float behaves differently than GNU STL: overflow produce\n * +\/-Infinity rather than an error.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, float &result)\n{\n if (!details::convertTo(str, result)) {\n return false;\n }\n\n if (!std::isfinite(result)) {\n return false;\n }\n\n return true;\n}\n\n\/**\n * Specialization for double of convertTo template function.\n *\n * This function follows the same paradigm than it's generic version and is\n * based on it but makes furthers checks on the returned value.\n *\n * The specific implementation is made necessary because the stlport conversion\n * from string to double behaves differently than GNU STL: overflow produce\n * +\/-Infinity rather than an error.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, double &result)\n{\n if (!details::convertTo(str, result)) {\n return false;\n }\n\n if (!std::isfinite(result)) {\n return false;\n }\n\n return true;\n}\n\n\/**\n * Specialization for boolean of convertTo template function.\n *\n * This function follows the same paradigm than it's generic version.\n * This function accepts to parse boolean as \"0\/1\" or \"false\/true\" or\n * \"FALSE\/TRUE\".\n * The specific implementation is made necessary because the behaviour of\n * string streams when parsing boolean values is not sufficient to fit our\n * requirements. Indeed, parsing \"true\" will correctly parse the value, but the\n * end of stream is not reached which makes the ss.eof() fails in the generic\n * implementation.\n *\n * @param[in] str the string to parse.\n * @param[out] result reference to object where to store the result.\n *\n * @return true if conversion was successful, false otherwise.\n *\/\ntemplate<>\ninline bool convertTo(const std::string &str, bool &result)\n{\n if (str == \"0\" || str == \"FALSE\" || str == \"false\") {\n result = false;\n return true;\n }\n\n if (str == \"1\" || str == \"TRUE\" || str == \"true\") {\n result = true;\n return true;\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \"numerics\/frequency_analysis.hpp\"\n\n#include \n#include \n#include \n\n#include \"base\/tags.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/hilbert.hpp\"\n#include \"numerics\/poisson_series_basis.hpp\"\n#include \"numerics\/root_finders.hpp\"\n#include \"numerics\/unbounded_arrays.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace frequency_analysis {\nnamespace internal_frequency_analysis {\n\nusing base::uninitialized;\nusing geometry::Hilbert;\nusing geometry::Vector;\nusing quantities::Inverse;\nusing quantities::IsFinite;\nusing quantities::Sqrt;\nusing quantities::Square;\nusing quantities::SquareRoot;\n\ntemplate class Evaluator>\nAngularFrequency PreciseMode(\n Interval const& fft_mode,\n Function const& function,\n PoissonSeries const& weight) {\n auto const weighted_function = weight * function;\n auto const weighted_function_spectrum = weighted_function.FourierTransform();\n\n auto power =\n [&weighted_function_spectrum](AngularFrequency const& ω) {\n return weighted_function_spectrum(ω).Norm²();\n };\n\n return Brent(power,\n fft_mode.min,\n fft_mode.max,\n std::greater<>());\n}\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nProjection(Function const& function,\n AngularFrequency const& ω,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n std::optional optional_ω = ω;\n\n \/\/ A calculator that returns optional_ω once and then stops.\n auto angular_frequency_calculator = [&optional_ω](auto const& residual) {\n auto const result = optional_ω;\n optional_ω = std::nullopt;\n return result;\n };\n\n return IncrementalProjection(\n function,\n angular_frequency_calculator,\n weight,\n t_min, t_max);\n}\n\n#define DO_THE_LOGGING 0\n#define USE_CGS 1\n#define USE_INTEGRATE 0\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nIncrementalProjection(Function const& function,\n AngularFrequencyCalculator const& calculator,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n using Value = std::invoke_result_t;\n using Norm = typename Hilbert::NormType;\n using Normalized = typename Hilbert::NormalizedType;\n using Series = PoissonSeries;\n\n \/\/ This code follows [Kud07], section 2. Our indices start at 0, unlike those\n \/\/ of Кудрявцев which start at 1.\n\n Instant const& t0 = weight.origin();\n\n std::optional ω = calculator(function);\n CHECK(ω.has_value());\n\n std::vector basis;\n \/\/ The Poisson series basis[k] belongs to the subspace basis_subspaces[k];\n \/\/ this remains true after orthonormalization, i.e., q[k] belongs to the\n \/\/ subspace basis_subspaces[k] below.\n std::vector basis_subspaces;\n\n int basis_size;\n \/\/ TODO(phl): This is replicated below.\n if (ω.value() == AngularFrequency{}) {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(t0);\n basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n } else {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(ω.value(), t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(\n ω.value(), t0);\n basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n }\n\n \/\/ This is logically Q in the QR decomposition of basis.\n std::vector> q;\n\n auto const& a₀ = basis[0];\n auto const r₀₀ = a₀.Norm(weight, t_min, t_max);\n CHECK(IsFinite(r₀₀)) << a₀;\n q.push_back(a₀ \/ r₀₀);\n\n auto const A₀ = InnerProduct(function, q[0], weight, t_min, t_max);\n\n Series F = A₀ * q[0];\n auto f = function - F;\n\n int m_begin = 1;\n for (;;) {\n for (int m = m_begin; m < basis_size; ++m) {\n auto const& aₘ = basis[m];\n\n \/\/ k -> m\n std::optional previous_q̂ₘ;\n Series q̂ₘ = aₘ;\n std::vector rₘ(m);\n \/\/ Loop on p.\n do {\n std::vector sᵖₘ;\n for (int i = 0; i < m; ++i) {\n sᵖₘ.push_back(InnerProduct(q[i], q̂ₘ, weight, t_min, t_max));\n }\n previous_q̂ₘ = q̂ₘ;\n for (int i = 0; i < m; ++i) {\n q̂ₘ -= sᵖₘ[i] * q[i];\n }\n for (int i = 0; i < m; ++i) {\n rₘ[i] += sᵖₘ[i];\n }\n \/\/LOG(ERROR) << \"m: \" << m << \" q̂ₘ: \" << q̂ₘ.Norm(weight, t_min, t_max)\n \/\/ << \" previous q̂ₘ: \"\n \/\/ << previous_q̂ₘ.value().Norm(\n \/\/ weight, t_min, t_max);\n } while (q̂ₘ.Norm(weight, t_min, t_max) <\n 0.5 * previous_q̂ₘ.value().Norm(weight, t_min, t_max));\n auto const rₘₘ = q̂ₘ.Norm(weight, t_min, t_max);\n q.push_back(q̂ₘ \/ rₘₘ);\n\n#if 0\n auto const r₀ₘ = InnerProduct(q[0], aₘ, weight, t_min, t_max);\n Series Σrᵢₘqᵢ = r₀ₘ * q[0];\n for (int i = 1; i < m; ++i) {\n auto const rᵢₘ = InnerProduct(q[i], aₘ, weight, t_min, t_max);\n Σrᵢₘqᵢ += rᵢₘ * q[i];\n }\n\n auto const qʹₘ = aₘ - Σrᵢₘqᵢ;\n auto rₘₘ = qʹₘ.Norm(weight, t_min, t_max);\n q.push_back(qʹₘ \/ rₘₘ);\n#endif\n DCHECK_EQ(m + 1, q.size());\n\n Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);\n\n auto const Aₘqₘ = Aₘ * q[m];\n f -= Aₘqₘ;\n F += Aₘqₘ;\n }\n\n ω = calculator(f);\n if (!ω.has_value()) {\n return F;\n }\n\n int ω_basis_size;\n if (ω.value() == AngularFrequency{}) {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(t0);\n ω_basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n } else {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(ω.value(), t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(\n ω.value(), t0);\n ω_basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n }\n m_begin = basis_size;\n basis_size += ω_basis_size;\n }\n}\n\n} \/\/ namespace internal_frequency_analysis\n} \/\/ namespace frequency_analysis\n} \/\/ namespace numerics\n} \/\/ namespace principia\nSome code simplification.\n#pragma once\n\n#include \"numerics\/frequency_analysis.hpp\"\n\n#include \n#include \n#include \n\n#include \"base\/tags.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/hilbert.hpp\"\n#include \"numerics\/poisson_series_basis.hpp\"\n#include \"numerics\/root_finders.hpp\"\n#include \"numerics\/unbounded_arrays.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace frequency_analysis {\nnamespace internal_frequency_analysis {\n\nusing base::uninitialized;\nusing geometry::Hilbert;\nusing geometry::Vector;\nusing quantities::Inverse;\nusing quantities::IsFinite;\nusing quantities::Sqrt;\nusing quantities::Square;\nusing quantities::SquareRoot;\n\ntemplate class Evaluator>\nAngularFrequency PreciseMode(\n Interval const& fft_mode,\n Function const& function,\n PoissonSeries const& weight) {\n auto const weighted_function = weight * function;\n auto const weighted_function_spectrum = weighted_function.FourierTransform();\n\n auto power =\n [&weighted_function_spectrum](AngularFrequency const& ω) {\n return weighted_function_spectrum(ω).Norm²();\n };\n\n return Brent(power,\n fft_mode.min,\n fft_mode.max,\n std::greater<>());\n}\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nProjection(Function const& function,\n AngularFrequency const& ω,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n std::optional optional_ω = ω;\n\n \/\/ A calculator that returns optional_ω once and then stops.\n auto angular_frequency_calculator = [&optional_ω](auto const& residual) {\n auto const result = optional_ω;\n optional_ω = std::nullopt;\n return result;\n };\n\n return IncrementalProjection(\n function,\n angular_frequency_calculator,\n weight,\n t_min, t_max);\n}\n\n#define DO_THE_LOGGING 0\n#define USE_CGS 1\n#define USE_INTEGRATE 0\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nIncrementalProjection(Function const& function,\n AngularFrequencyCalculator const& calculator,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n using Value = std::invoke_result_t;\n using Norm = typename Hilbert::NormType;\n using Normalized = typename Hilbert::NormalizedType;\n using Series = PoissonSeries;\n\n \/\/ This code follows [Kud07], section 2. Our indices start at 0, unlike those\n \/\/ of Кудрявцев which start at 1.\n\n Instant const& t0 = weight.origin();\n\n std::optional ω = calculator(function);\n CHECK(ω.has_value());\n\n std::vector basis;\n \/\/ The Poisson series basis[k] belongs to the subspace basis_subspaces[k];\n \/\/ this remains true after orthonormalization, i.e., q[k] belongs to the\n \/\/ subspace basis_subspaces[k] below.\n std::vector basis_subspaces;\n\n int basis_size;\n \/\/ TODO(phl): This is replicated below.\n if (ω.value() == AngularFrequency{}) {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(t0);\n basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n } else {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(ω.value(), t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(\n ω.value(), t0);\n basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n }\n\n \/\/ This is logically Q in the QR decomposition of basis.\n std::vector> q;\n\n auto const& a₀ = basis[0];\n auto const r₀₀ = a₀.Norm(weight, t_min, t_max);\n CHECK(IsFinite(r₀₀)) << a₀;\n q.push_back(a₀ \/ r₀₀);\n\n auto const A₀ = InnerProduct(function, q[0], weight, t_min, t_max);\n\n Series F = A₀ * q[0];\n auto f = function - F;\n\n int m_begin = 1;\n for (;;) {\n for (int m = m_begin; m < basis_size; ++m) {\n auto const& aₘ = basis[m];\n\n \/\/ k -> m\n Series q̂ₘ = aₘ;\n Series previous_q̂ₘ = q̂ₘ;\n std::vector rₘ(m);\n \/\/ Loop on p.\n do {\n previous_q̂ₘ = q̂ₘ;\n std::vector sᵖₘ;\n for (int i = 0; i < m; ++i) {\n if (!PoissonSeriesSubspace::orthogonal(basis_subspaces[i],\n basis_subspaces[m])) {\n auto const sᵖₘ =\n InnerProduct(q[i], previous_q̂ₘ, weight, t_min, t_max);\n q̂ₘ -= sᵖₘ * q[i];\n }\n }\n \/\/LOG(ERROR) << \"m: \" << m << \" q̂ₘ: \" << q̂ₘ.Norm(weight, t_min, t_max)\n \/\/ << \" previous q̂ₘ: \"\n \/\/ << previous_q̂ₘ.value().Norm(\n \/\/ weight, t_min, t_max);\n } while (q̂ₘ.Norm(weight, t_min, t_max) <\n 0.5 * previous_q̂ₘ.Norm(weight, t_min, t_max));\n auto const rₘₘ = q̂ₘ.Norm(weight, t_min, t_max);\n q.push_back(q̂ₘ \/ rₘₘ);\n\n#if 0\n auto const r₀ₘ = InnerProduct(q[0], aₘ, weight, t_min, t_max);\n Series Σrᵢₘqᵢ = r₀ₘ * q[0];\n for (int i = 1; i < m; ++i) {\n auto const rᵢₘ = InnerProduct(q[i], aₘ, weight, t_min, t_max);\n Σrᵢₘqᵢ += rᵢₘ * q[i];\n }\n\n auto const qʹₘ = aₘ - Σrᵢₘqᵢ;\n auto rₘₘ = qʹₘ.Norm(weight, t_min, t_max);\n q.push_back(qʹₘ \/ rₘₘ);\n#endif\n DCHECK_EQ(m + 1, q.size());\n\n Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);\n\n auto const Aₘqₘ = Aₘ * q[m];\n f -= Aₘqₘ;\n F += Aₘqₘ;\n }\n\n ω = calculator(f);\n if (!ω.has_value()) {\n return F;\n }\n\n int ω_basis_size;\n if (ω.value() == AngularFrequency{}) {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(t0);\n ω_basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n } else {\n auto const ω_basis =\n PoissonSeriesBasisGenerator::Basis(ω.value(), t0);\n auto const ω_basis_subspaces =\n PoissonSeriesBasisGenerator::Subspaces(\n ω.value(), t0);\n ω_basis_size = std::tuple_size_v;\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n }\n m_begin = basis_size;\n basis_size += ω_basis_size;\n }\n}\n\n} \/\/ namespace internal_frequency_analysis\n} \/\/ namespace frequency_analysis\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \"numerics\/frequency_analysis.hpp\"\n\n#include \n#include \n#include \n\n#include \"base\/status.hpp\"\n#include \"base\/tags.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/hilbert.hpp\"\n#include \"numerics\/poisson_series_basis.hpp\"\n#include \"numerics\/root_finders.hpp\"\n#include \"numerics\/unbounded_arrays.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace frequency_analysis {\nnamespace internal_frequency_analysis {\n\nusing base::Error;\nusing base::Status;\nusing base::uninitialized;\nusing geometry::Hilbert;\nusing geometry::Vector;\nusing quantities::Inverse;\nusing quantities::IsFinite;\nusing quantities::Sqrt;\nusing quantities::Square;\nusing quantities::SquareRoot;\n\n\/\/ Appends basis elements for |ω| to |basis| and |basis_subspaces|. Returns the\n\/\/ number of elements that were appended.\ntemplate\nint MakeBasis(std::optional const& ω,\n Instant const& t_min,\n Instant const& t_max,\n std::vector& basis,\n std::vector& basis_subspaces) {\n if (ω.value() == AngularFrequency{}) {\n using Generator =\n PoissonSeriesBasisGenerator;\n auto const ω_basis = Generator::Basis(t_min, t_max);\n auto const ω_basis_subspaces = Generator::Subspaces();\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n return std::tuple_size_v;\n } else {\n using Generator = PoissonSeriesBasisGenerator;\n auto const ω_basis = Generator::Basis(ω.value(), t_min, t_max);\n auto const ω_basis_subspaces = Generator::Subspaces(ω.value());\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n return std::tuple_size_v;\n }\n}\n\n\/\/TODO(phl):comment\ntemplate class Evaluator>\nStatus GramSchmidtStep(\n Function const& aₘ,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max,\n std::vector const& basis_subspaces,\n std::vector const& q,\n BasisSeries& qₘ,\n std::vector& rₘ) {\n \/\/ This code follows Björk, Numerics of Gram-Schmidt Orthogonalization,\n \/\/ Algorithm 6.1. It processes one column of q and r at a time.\n\n static constexpr double α = 0.5;\n int const m = q.size();\n rₘ.resize(m + 1, 0.0);\n\n Function q̂ₘ = aₘ;\n\n \/\/ Formal integration works for a single basis element.\n double q̂ₘ_norm =\n Sqrt((PointwiseInnerProduct(q̂ₘ, q̂ₘ) * weight).Integrate(t_min, t_max) \/\n (t_max - t_min));\n\n \/\/ Loop on p.\n Function previous_q̂ₘ = q̂ₘ;\n double previous_q̂ₘ_norm;\n do {\n previous_q̂ₘ = q̂ₘ;\n previous_q̂ₘ_norm = q̂ₘ_norm;\n for (int i = 0; i < m; ++i) {\n if (!PoissonSeriesSubspace::orthogonal(basis_subspaces[i],\n basis_subspaces[m])) {\n double const sᵖₘ =\n InnerProduct(q[i], previous_q̂ₘ, weight, t_min, t_max);\n q̂ₘ -= sᵖₘ * q[i];\n rₘ[i] += sᵖₘ;\n }\n }\n q̂ₘ_norm = q̂ₘ.Norm(weight, t_min, t_max);\n\n if (!IsFinite(q̂ₘ_norm)) {\n return Status(Error::OUT_OF_RANGE, u8\"Unable to compute q̂ₘ_norm\");\n }\n } while (q̂ₘ_norm < α * previous_q̂ₘ_norm);\n\n \/\/ Fill the result.\n qₘ = q̂ₘ \/ q̂ₘ_norm;\n rₘ[m] = q̂ₘ_norm;\n\n return Status::OK;\n}\n\ntemplate class Evaluator>\nAngularFrequency PreciseMode(\n Interval const& fft_mode,\n Function const& function,\n PoissonSeries const& weight) {\n auto const weighted_function = weight * function;\n auto const weighted_function_spectrum = weighted_function.FourierTransform();\n\n auto power =\n [&weighted_function_spectrum](AngularFrequency const& ω) {\n return weighted_function_spectrum(ω).Norm²();\n };\n\n return Brent(power,\n fft_mode.min,\n fft_mode.max,\n std::greater<>());\n}\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nProjection(Function const& function,\n AngularFrequency const& ω,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n std::optional optional_ω = ω;\n\n \/\/ A calculator that returns optional_ω once and then stops.\n auto angular_frequency_calculator = [&optional_ω](auto const& residual) {\n auto const result = optional_ω;\n optional_ω = std::nullopt;\n return result;\n };\n\n return IncrementalProjection(\n function,\n angular_frequency_calculator,\n weight,\n t_min, t_max);\n}\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nIncrementalProjection(Function const& function,\n AngularFrequencyCalculator const& calculator,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n using Value = std::invoke_result_t;\n using Norm = typename Hilbert::NormType;\n using Normalized = typename Hilbert::NormalizedType;\n using BasisSeries = PoissonSeries;\n using ResultSeries = PoissonSeries;\n\n Instant const& t0 = weight.origin();\n auto const basis_zero = static_cast<\n typename BasisSeries::AperiodicPolynomial>(\n typename PoissonSeries::AperiodicPolynomial(\n {Normalized{}}, t0));\n auto const result_zero =\n static_cast(\n typename PoissonSeries::AperiodicPolynomial(\n {Value{}}, t0));\n\n std::optional ω = calculator(function);\n CHECK(ω.has_value());\n\n std::vector basis;\n \/\/ The Poisson series basis[k] belongs to the subspace basis_subspaces[k];\n \/\/ this remains true after orthonormalization, i.e., q[k] belongs to the\n \/\/ subspace basis_subspaces[k] below.\n std::vector basis_subspaces;\n\n int basis_size = MakeBasis(\n ω, t_min, t_max, basis, basis_subspaces);\n\n \/\/ This is logically Q in the QR decomposition of basis.\n std::vector q;\n\n \/\/ This is logically R in the QR decomposition of basis.\n UnboundedUpperTriangularMatrix r(basis_size); \/\/ Zero-initialized.\n\n ResultSeries F(result_zero, {{}});\n auto f = function - F;\n\n int m_begin = 0;\n for (;;) {\n for (int m = m_begin; m < basis_size; ++m) {\n BasisSeries qₘ(basis_zero, {{}});\n std::vector rₘ;\n\n auto const status = GramSchmidtStep(\n \/*aₘ=*\/basis[m], weight, t_min, t_max, basis_subspaces, q, qₘ, rₘ);\n if (!status.ok()) {\n return F;\n }\n\n q.push_back(qₘ);\n DCHECK_EQ(m + 1, q.size());\n\n Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);\n\n auto const Aₘqₘ = Aₘ * q[m];\n f -= Aₘqₘ;\n F += Aₘqₘ;\n }\n\n ω = calculator(f);\n if (!ω.has_value()) {\n return F;\n }\n\n int const ω_basis_size = MakeBasis(\n ω, t_min, t_max, basis, basis_subspaces);\n m_begin = basis_size;\n basis_size += ω_basis_size;\n r.Extend(basis_size);\n }\n}\n\n} \/\/ namespace internal_frequency_analysis\n} \/\/ namespace frequency_analysis\n} \/\/ namespace numerics\n} \/\/ namespace principia\nFill the QR decomposition.\n#pragma once\n\n#include \"numerics\/frequency_analysis.hpp\"\n\n#include \n#include \n#include \n\n#include \"base\/status.hpp\"\n#include \"base\/tags.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/hilbert.hpp\"\n#include \"numerics\/poisson_series_basis.hpp\"\n#include \"numerics\/root_finders.hpp\"\n#include \"numerics\/unbounded_arrays.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace frequency_analysis {\nnamespace internal_frequency_analysis {\n\nusing base::Error;\nusing base::Status;\nusing base::uninitialized;\nusing geometry::Hilbert;\nusing geometry::Vector;\nusing quantities::Inverse;\nusing quantities::IsFinite;\nusing quantities::Sqrt;\nusing quantities::Square;\nusing quantities::SquareRoot;\n\n\/\/ Appends basis elements for |ω| to |basis| and |basis_subspaces|. Returns the\n\/\/ number of elements that were appended.\ntemplate\nint MakeBasis(std::optional const& ω,\n Instant const& t_min,\n Instant const& t_max,\n std::vector& basis,\n std::vector& basis_subspaces) {\n if (ω.value() == AngularFrequency{}) {\n using Generator =\n PoissonSeriesBasisGenerator;\n auto const ω_basis = Generator::Basis(t_min, t_max);\n auto const ω_basis_subspaces = Generator::Subspaces();\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n return std::tuple_size_v;\n } else {\n using Generator = PoissonSeriesBasisGenerator;\n auto const ω_basis = Generator::Basis(ω.value(), t_min, t_max);\n auto const ω_basis_subspaces = Generator::Subspaces(ω.value());\n std::move(ω_basis.begin(), ω_basis.end(), std::back_inserter(basis));\n std::move(ω_basis_subspaces.begin(),\n ω_basis_subspaces.end(),\n std::back_inserter(basis_subspaces));\n return std::tuple_size_v;\n }\n}\n\n\/\/TODO(phl):comment\ntemplate class Evaluator>\nStatus GramSchmidtStep(\n Function const& aₘ,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max,\n std::vector const& basis_subspaces,\n std::vector const& q,\n BasisSeries& qₘ,\n std::vector& rₘ) {\n \/\/ This code follows Björk, Numerics of Gram-Schmidt Orthogonalization,\n \/\/ Algorithm 6.1. It processes one column of q and r at a time.\n\n static constexpr double α = 0.5;\n int const m = q.size();\n rₘ.resize(m + 1, 0.0);\n\n Function q̂ₘ = aₘ;\n\n \/\/ Formal integration works for a single basis element.\n double q̂ₘ_norm =\n Sqrt((PointwiseInnerProduct(q̂ₘ, q̂ₘ) * weight).Integrate(t_min, t_max) \/\n (t_max - t_min));\n\n \/\/ Loop on p.\n Function previous_q̂ₘ = q̂ₘ;\n double previous_q̂ₘ_norm;\n do {\n previous_q̂ₘ = q̂ₘ;\n previous_q̂ₘ_norm = q̂ₘ_norm;\n for (int i = 0; i < m; ++i) {\n if (!PoissonSeriesSubspace::orthogonal(basis_subspaces[i],\n basis_subspaces[m])) {\n double const sᵖₘ =\n InnerProduct(q[i], previous_q̂ₘ, weight, t_min, t_max);\n q̂ₘ -= sᵖₘ * q[i];\n rₘ[i] += sᵖₘ;\n }\n }\n q̂ₘ_norm = q̂ₘ.Norm(weight, t_min, t_max);\n\n if (!IsFinite(q̂ₘ_norm)) {\n return Status(Error::OUT_OF_RANGE, u8\"Unable to compute q̂ₘ_norm\");\n }\n } while (q̂ₘ_norm < α * previous_q̂ₘ_norm);\n\n \/\/ Fill the result.\n qₘ = q̂ₘ \/ q̂ₘ_norm;\n rₘ[m] = q̂ₘ_norm;\n\n return Status::OK;\n}\n\ntemplate class Evaluator>\nAngularFrequency PreciseMode(\n Interval const& fft_mode,\n Function const& function,\n PoissonSeries const& weight) {\n auto const weighted_function = weight * function;\n auto const weighted_function_spectrum = weighted_function.FourierTransform();\n\n auto power =\n [&weighted_function_spectrum](AngularFrequency const& ω) {\n return weighted_function_spectrum(ω).Norm²();\n };\n\n return Brent(power,\n fft_mode.min,\n fft_mode.max,\n std::greater<>());\n}\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nProjection(Function const& function,\n AngularFrequency const& ω,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n std::optional optional_ω = ω;\n\n \/\/ A calculator that returns optional_ω once and then stops.\n auto angular_frequency_calculator = [&optional_ω](auto const& residual) {\n auto const result = optional_ω;\n optional_ω = std::nullopt;\n return result;\n };\n\n return IncrementalProjection(\n function,\n angular_frequency_calculator,\n weight,\n t_min, t_max);\n}\n\ntemplate class Evaluator>\nPoissonSeries,\n aperiodic_degree, periodic_degree,\n Evaluator>\nIncrementalProjection(Function const& function,\n AngularFrequencyCalculator const& calculator,\n PoissonSeries const& weight,\n Instant const& t_min,\n Instant const& t_max) {\n using Value = std::invoke_result_t;\n using Norm = typename Hilbert::NormType;\n using Normalized = typename Hilbert::NormalizedType;\n using BasisSeries = PoissonSeries;\n using ResultSeries = PoissonSeries;\n\n Instant const& t0 = weight.origin();\n auto const basis_zero = static_cast<\n typename BasisSeries::AperiodicPolynomial>(\n typename PoissonSeries::AperiodicPolynomial(\n {Normalized{}}, t0));\n auto const result_zero =\n static_cast(\n typename PoissonSeries::AperiodicPolynomial(\n {Value{}}, t0));\n\n std::optional ω = calculator(function);\n CHECK(ω.has_value());\n\n std::vector basis;\n \/\/ The Poisson series basis[k] belongs to the subspace basis_subspaces[k];\n \/\/ this remains true after orthonormalization, i.e., q[k] belongs to the\n \/\/ subspace basis_subspaces[k] below.\n std::vector basis_subspaces;\n\n int basis_size = MakeBasis(\n ω, t_min, t_max, basis, basis_subspaces);\n\n \/\/ This is logically Q in the QR decomposition of basis.\n std::vector q;\n\n \/\/ This is logically R in the QR decomposition of basis.\n UnboundedUpperTriangularMatrix r(basis_size, uninitialized);\n\n ResultSeries F(result_zero, {{}});\n auto f = function - F;\n\n int m_begin = 0;\n for (;;) {\n for (int m = m_begin; m < basis_size; ++m) {\n BasisSeries qₘ(basis_zero, {{}});\n std::vector rₘ;\n\n auto const status = GramSchmidtStep(\n \/*aₘ=*\/basis[m], weight, t_min, t_max, basis_subspaces, q, qₘ, rₘ);\n if (!status.ok()) {\n return F;\n }\n\n for (int i = 0; i <=m; ++i) {\n r[i][m] = rₘ[i];\n }\n q.push_back(qₘ);\n DCHECK_EQ(m + 1, q.size());\n\n Norm const Aₘ = InnerProduct(f, q[m], weight, t_min, t_max);\n\n auto const Aₘqₘ = Aₘ * q[m];\n f -= Aₘqₘ;\n F += Aₘqₘ;\n }\n\n ω = calculator(f);\n if (!ω.has_value()) {\n return F;\n }\n\n int const ω_basis_size = MakeBasis(\n ω, t_min, t_max, basis, basis_subspaces);\n m_begin = basis_size;\n basis_size += ω_basis_size;\n r.Extend(basis_size, uninitialized);\n }\n}\n\n} \/\/ namespace internal_frequency_analysis\n} \/\/ namespace frequency_analysis\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"#ifndef PARAMETERHANDLER_HH_INCLUDED\r\n#define PARAMETERHANDLER_HH_INCLUDED\n\n#include \n#include \n#include \r\n\r\n\/**\n * \\brief class processing parameter file\n *\n * \\c ParameterHandler reads a parameter file once and stores all found values internally\n **\/\nclass ParameterHandler\n{\n private:\n typedef std::map< std::string, std::string > MapType;\n MapType parameter_map_;\n bool status_;\n\n public:\n \/** \\ Please doc me!\n *\n **\/\n ParameterHandler( const std::string filename )\n :status_( false )\n {\n ParseParamFile( filename );\n }\n\n ParameterHandler( )\n :status_( false )\n {\n }\n\n \/** \\brief function used for parametrized ctor and two-step creation\n **\/\n bool ParseParamFile( const std::string filename )\n {\n std::ifstream parameter_file( filename.c_str() );\n if( parameter_file.is_open() )\n {\n while( !parameter_file.eof() )\n {\n std :: string line;\n std :: getline( parameter_file, line );\n\n if( line.size() == 0 )\n continue;\n\n if( (line[ 0 ] != '%') && (line[ 0 ] != '#') )\n {\n std::string param_name = line.substr( 0, line.find_first_of(\":\") );\n std::string value = line.substr( line.find_first_of(\":\")+1, line.length() );\n parameter_map_[param_name] = value;\n }\n\n }\n status_ = true;\n parameter_file.close();\n }\n else {\n \/\/LOGERROR\n status_ = false;\n std::cerr << \"ERROR: file \" << filename << \" not found!\\n\";\n }\n return Ok();\n }\n\n \/**\n * \\brief checks, if a parameter is found in the parameterfile\n * \\arg const std::string name name of the parameter to be found\n * \\return returns true, if the parameter is found\n **\/\n bool ParameterExists( const std::string name ) const\n {\n if ( !( status_ ) ) {\n return false;\n }\n else {\n MapType::const_iterator it = parameter_map_.find( name );\n if ( it != parameter_map_.end() ) {\n return true;\n }\n else {\n return false;\n }\n\n }\n }\n\n \/** \\todo Please doc me! *\/\n template < class ReturnType >\n ReturnType GetParameter( const std::string name) const\n {\n if ( !( status_ ) ) {\n return (ReturnType) 0;\n }\n else {\n MapType::const_iterator it = parameter_map_.find( name ) ;\n if ( it != parameter_map_.end() ){\n return Stuff::fromString( it->second );\n }\n else {\n \/\/LogError\n return (ReturnType) 0;\n }\n }\n }\n\n \/** \\todo Please doc me! *\/\n void Print( std::ostream &out ) const\n {\n assert( status_ );\n for (MapType::const_iterator it = parameter_map_.begin(); parameter_map_.end() != it; ++it){\n out << it->first << \":\" << it->second << \"\\n\" ;\n }\n out << std::endl;\n }\n\n \/** \\todo Please doc me! *\/\n bool Ok()\n {\n return status_;\n }\n\n \/** \\todo Please doc me! *\/\n ~ParameterHandler(){}\n\n};\n\n\/\/\/** \\brief global singelton for paramhandler\n\nParameterHandler& params()\n{\n static ParameterHandler param;\n return param;\n}\n\r\n\r\n#endif \/\/ PARAMETERHANDLER_HH_INCLUDED\r\nremove obsolete file<|endoftext|>"} {"text":"#ifndef CLOVER_UTIL_PROFILING_HPP\n#define CLOVER_UTIL_PROFILING_HPP\n\n#include \"build.hpp\"\n#include \"util\/preproc_join.hpp\"\n\n#include \n\n\/\/ No profiling on windows due to odd crashes with mingw 4.8.2\n#define PROFILING_ENABLED (ATOMIC_PTR_READWRITE == true && OS != OS_WINDOWS)\n\nnamespace clover {\nnamespace util {\nnamespace detail {\n\nstruct BlockInfo {\n\tconst char* funcName;\n\tuint32 line;\n\t\/\/\/ Don't assume that labels with same string will point to\n\t\/\/\/ the same memory - depends on compiler optimizations\n\tconst char* label;\n\tuint64 exclusiveMemAllocs;\n\tuint64 inclusiveMemAllocs;\n};\n\nstruct BlockProfiler {\n\tstatic BlockInfo createBlockInfo(\tconst char* func,\n\t\t\t\t\t\t\t\t\t\tuint32 line,\n\t\t\t\t\t\t\t\t\t\tconst char* label);\n\tBlockProfiler(BlockInfo& info);\n\t~BlockProfiler();\n};\n\nstruct StackJoiner {\n\tStackJoiner();\n\t~StackJoiner();\n};\n\nstruct StackDetacher {\n\tStackDetacher();\n\t~StackDetacher();\n};\n\nvoid setSuperThread(std::thread::id super_id);\n\n} \/\/ detail\n\n\/\/\/ Call in main() -- we don't want to see any impl defined pre-main stuff\nvoid tryEnableProfiling();\n\n#if PROFILING_ENABLED\n\/\/\/ Should be called on system memory allocation\nvoid profileSystemMemAlloc();\n#else\nvoid profileSystemMemAlloc() {};\n#endif\n\n} \/\/ util\n} \/\/ clover\n\n#if PROFILING_ENABLED\n\n\/\/\/ Same as PROFILE but with a label\n#define PROFILE_(label)\\\n\tstatic util::detail::BlockInfo JOIN(profiler_block_info_, __LINE__)= \\\n\t\tutil::detail::BlockProfiler::createBlockInfo( \\\n\t\t\t\t__PRETTY_FUNCTION__, \\\n\t\t\t\t__LINE__, \\\n\t\t\t\tlabel); \\\n\tutil::detail::BlockProfiler JOIN(profiler_, __LINE__)(JOIN(profiler_block_info_, __LINE__))\n\n\/\/\/ Marks current block to be profiled\n#define PROFILE()\\\n\tPROFILE_(nullptr)\n\n\/\/\/ Notifies profiler of a super thread\n#define PROFILER_SUPER_THREAD(thread_id)\\\n\tutil::detail::setSuperThread(thread_id)\n\n\/\/\/ Joins callstacks of this and super thread in current scope\n#define PROFILER_STACK_JOIN()\\\n\tutil::detail::StackJoiner JOIN(stack_joiner_, __LINE__)\n\/\/\/ Detaches callstacks of this and super thread in current scope\n#define PROFILER_STACK_DETACH()\\\n\tutil::detail::StackDetacher JOIN(stack_detacher_, __LINE__)\n\n#else\n\n#define PROFILE_(label)\n#define PROFILE()\n#define PROFILER_SUPER_THREAD(thread_id)\n#define PROFILER_STACK_JOIN()\n#define PROFILER_STACK_DETACH()\n\n#endif\n\n#endif \/\/ CLOVER_UTIL_PROFILING_HPP\nProfiling is now working on windows?!#ifndef CLOVER_UTIL_PROFILING_HPP\n#define CLOVER_UTIL_PROFILING_HPP\n\n#include \"build.hpp\"\n#include \"util\/preproc_join.hpp\"\n\n#include \n\n\/\/ No profiling on windows due to odd crashes with mingw 4.8.2\n#define PROFILING_ENABLED (ATOMIC_PTR_READWRITE == true)\n\nnamespace clover {\nnamespace util {\nnamespace detail {\n\nstruct BlockInfo {\n\tconst char* funcName;\n\tuint32 line;\n\t\/\/\/ Don't assume that labels with same string will point to\n\t\/\/\/ the same memory - depends on compiler optimizations\n\tconst char* label;\n\tuint64 exclusiveMemAllocs;\n\tuint64 inclusiveMemAllocs;\n};\n\nstruct BlockProfiler {\n\tstatic BlockInfo createBlockInfo(\tconst char* func,\n\t\t\t\t\t\t\t\t\t\tuint32 line,\n\t\t\t\t\t\t\t\t\t\tconst char* label);\n\tBlockProfiler(BlockInfo& info);\n\t~BlockProfiler();\n};\n\nstruct StackJoiner {\n\tStackJoiner();\n\t~StackJoiner();\n};\n\nstruct StackDetacher {\n\tStackDetacher();\n\t~StackDetacher();\n};\n\nvoid setSuperThread(std::thread::id super_id);\n\n} \/\/ detail\n\n\/\/\/ Call in main() -- we don't want to see any impl defined pre-main stuff\nvoid tryEnableProfiling();\n\n#if PROFILING_ENABLED\n\/\/\/ Should be called on system memory allocation\nvoid profileSystemMemAlloc();\n#else\nvoid profileSystemMemAlloc() {};\n#endif\n\n} \/\/ util\n} \/\/ clover\n\n#if PROFILING_ENABLED\n\n\/\/\/ Same as PROFILE but with a label\n#define PROFILE_(label)\\\n\tstatic util::detail::BlockInfo JOIN(profiler_block_info_, __LINE__)= \\\n\t\tutil::detail::BlockProfiler::createBlockInfo( \\\n\t\t\t\t__PRETTY_FUNCTION__, \\\n\t\t\t\t__LINE__, \\\n\t\t\t\tlabel); \\\n\tutil::detail::BlockProfiler JOIN(profiler_, __LINE__)(JOIN(profiler_block_info_, __LINE__))\n\n\/\/\/ Marks current block to be profiled\n#define PROFILE()\\\n\tPROFILE_(nullptr)\n\n\/\/\/ Notifies profiler of a super thread\n#define PROFILER_SUPER_THREAD(thread_id)\\\n\tutil::detail::setSuperThread(thread_id)\n\n\/\/\/ Joins callstacks of this and super thread in current scope\n#define PROFILER_STACK_JOIN()\\\n\tutil::detail::StackJoiner JOIN(stack_joiner_, __LINE__)\n\/\/\/ Detaches callstacks of this and super thread in current scope\n#define PROFILER_STACK_DETACH()\\\n\tutil::detail::StackDetacher JOIN(stack_detacher_, __LINE__)\n\n#else\n\n#define PROFILE_(label)\n#define PROFILE()\n#define PROFILER_SUPER_THREAD(thread_id)\n#define PROFILER_STACK_JOIN()\n#define PROFILER_STACK_DETACH()\n\n#endif\n\n#endif \/\/ CLOVER_UTIL_PROFILING_HPP\n<|endoftext|>"} {"text":"#include \n\nnamespace Refal2 {\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CProgram\n\nCProgram::CProgram( int numberOfModules ) :\n\tmodulesSize( numberOfModules ),\n\tmodules( new CRuntimeModule[modulesSize] ),\n\temptyFunction( new CEmptyFunction )\n{\n\tassert( modulesSize > 0 );\n\tassert( modules != nullptr );\n}\n\nCProgram::~CProgram()\n{\n\tdelete[] modules;\n}\n\nCRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId )\n{\n\tassert( moduleId >= 0 && moduleId < modulesSize );\n\treturn modules[moduleId];\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CProgramPrintHelper\n\nvoid CProgramPrintHelper::Label( std::ostream& outputStream,\n\tconst TLabel label ) const\n{\n\tconst int labelModuleId = label \/ LabelMask;\n\tif( PrintLabelWithModule() ) {\n\t\toutputStream << labelModuleId << \":\";\n\t}\n\toutputStream << program->Module( labelModuleId ).Functions.\n\t\tGetKey(\tlabel % LabelMask );\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CGlobalFunctionData\n\nclass CGlobalFunctionData {\npublic:\n\tCGlobalFunctionData();\n\n\tbool IsEmbeddedFunction() const;\n\tbool IsPreparatoryFunction() const;\n\tbool IsDefined() const;\n\n\tvoid SetPreparatoryFunction(\n\t\tconst CPreparatoryFunction* const _preparatoryFunction,\n\t\tconst TRuntimeModuleId _runtimeModuleId );\n\tconst CPreparatoryFunction* PreparatoryFunction() const;\n\n\tconst TRuntimeModuleId RuntimeModuleId() const;\n\n\tvoid SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction );\n\tTEmbeddedFunctionPtr EmbeddedFunction() const;\n\n\tCRuntimeFunctionPtr RuntimeFunction( const CProgramPtr& program ) const;\n\nprivate:\n\tconst CPreparatoryFunction* preparatoryFunction;\n\tTEmbeddedFunctionPtr embeddedFunction;\n\tTRuntimeModuleId runtimeModuleId;\n\tmutable CRuntimeFunctionPtr runtimeFunction;\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CGlobalFunctionData\n\nCGlobalFunctionData::CGlobalFunctionData() :\n\tpreparatoryFunction( nullptr ),\n\tembeddedFunction( nullptr ),\n\truntimeModuleId( 0 )\n{\n}\n\nbool CGlobalFunctionData::IsEmbeddedFunction() const\n{\n\treturn ( embeddedFunction != nullptr );\n}\n\nbool CGlobalFunctionData::IsPreparatoryFunction() const\n{\n\treturn ( preparatoryFunction != nullptr );\n}\n\nbool CGlobalFunctionData::IsDefined() const\n{\n\treturn ( IsEmbeddedFunction() || IsPreparatoryFunction() );\n}\n\nvoid CGlobalFunctionData::SetPreparatoryFunction(\n\tconst CPreparatoryFunction* const _preparatoryFunction,\n\tconst TRuntimeModuleId _runtimeModuleId )\n{\n\tassert( !IsDefined() );\n\tassert( _preparatoryFunction != nullptr );\n\tpreparatoryFunction = _preparatoryFunction;\n\truntimeModuleId = _runtimeModuleId;\n}\n\nconst CPreparatoryFunction* CGlobalFunctionData::PreparatoryFunction() const\n{\n\tassert( IsPreparatoryFunction() );\n\treturn preparatoryFunction;\n}\n\nconst TRuntimeModuleId CGlobalFunctionData::RuntimeModuleId() const\n{\n\tassert( IsPreparatoryFunction() );\n\treturn runtimeModuleId;\n}\n\nvoid CGlobalFunctionData::SetEmbeddedFunction(\n\tconst TEmbeddedFunctionPtr _embeddedFunction )\n{\n\tassert( !IsDefined() );\n\tassert( _embeddedFunction != nullptr );\n\tembeddedFunction = _embeddedFunction;\n}\n\nTEmbeddedFunctionPtr CGlobalFunctionData::EmbeddedFunction() const\n{\n\tassert( IsEmbeddedFunction() );\n\treturn embeddedFunction;\n}\n\nCRuntimeFunctionPtr CGlobalFunctionData::RuntimeFunction(\n\tconst CProgramPtr& program ) const\n{\n\tif( !static_cast( runtimeFunction ) ) {\n\t\tif( IsEmbeddedFunction() ) {\n\t\t\truntimeFunction.reset( new CEmbeddedFunction(\n\t\t\t\tembeddedFunction ) );\n\t\t} else {\n\t\t\tassert( IsPreparatoryFunction() );\n\t\t\tif( PreparatoryFunction()->IsEmpty() ) {\n\t\t\t\truntimeFunction = program->EmptyFunction();\n\t\t\t} else {\n\t\t\t\truntimeFunction.reset( new COrdinaryFunction(\n\t\t\t\t\tPreparatoryFunction()->FirstOperation(),\n\t\t\t\t\tRuntimeModuleId() ) );\n\t\t\t}\n\t\t}\n\t}\n\treturn runtimeFunction;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CInternalProgramBuilder\n\nconst char* const ProgramStartFunctionName = \"go\";\n\nclass CInternalProgramBuilder {\npublic:\n\tstatic CProgramPtr Build( CModuleDataVector& modules,\n\t\tCErrorsHelper& errors );\n\nprivate:\n\tCErrorsHelper& errors;\n\tCDictionary globals;\n\tCProgramPtr program;\n\n\tCInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules );\n\n\ttypedef void ( CInternalProgramBuilder::*TProcessFunctionPtr )(\n\t\tCPreparatoryFunction* function,\n\t\tconst TRuntimeModuleId runtimeModuleId );\n\n\tvoid processModules( const CModuleDataVector& modules,\n\t\tconst TProcessFunctionPtr processFunction );\n\n\tvoid collectFunction( CPreparatoryFunction* function,\n\t\t const TRuntimeModuleId runtimeModuleId );\n\tvoid collect( const CModuleDataVector& modules );\n\n\tvoid check();\n\n\tvoid compileFunction( CPreparatoryFunction* function,\n\t\tconst TRuntimeModuleId runtimeModuleId );\n\tvoid compile( const CModuleDataVector& modules );\n\n\tvoid linkFunction( CPreparatoryFunction* function,\n\t\tconst TRuntimeModuleId runtimeModuleId );\n\tvoid link( const CModuleDataVector& modules );\n};\n\n\/\/-----------------------------------------------------------------------------\n\nCInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors,\n\t\tint numberOfModules ) :\n\terrors( _errors ),\n\tprogram( new CProgram( numberOfModules ) )\n{\n\tassert( static_cast( program ) );\n\t\/\/ add standart functions\n\tfor( const CEmbeddedFunctionData* function = EmbeddedFunctionDataTable();\n\t\tfunction->EmbeddedFunction != nullptr; function++ )\n\t{\n\t\tassert( function->ExternalName != nullptr );\n\t\tstd::string externalName = function->ExternalName;\n\t\tassert( !externalName.empty() );\n\t\tconst int globalIndex = globals.AddKey( externalName );\n\t\tCGlobalFunctionData& global = globals.GetData( globalIndex );\n\t\tglobal.SetEmbeddedFunction( function->EmbeddedFunction );\n\t}\n\t\/\/ add `ProgramStartFunctionName`\n\tconst int globalGoIndex = globals.AddKey( ProgramStartFunctionName );\n\tassert( !globals.GetData( globalGoIndex ).IsDefined() );\n}\n\nCProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules,\n\tCErrorsHelper& errors )\n{\n\tassert( !errors.HasErrors() );\n\tassert( !modules.empty() );\n\tCInternalProgramBuilder builder( errors, modules.size() );\n\tbuilder.collect( modules );\n\tif( !errors.HasErrors() ) {\n\t\tbuilder.check();\n\t\tif( !errors.HasErrors() ) {\n\t\t\tbuilder.compile( modules );\n\t\t\tassert( !errors.HasErrors() );\n\t\t\tbuilder.link( modules );\n\t\t\tassert( !errors.HasErrors() );\n\t\t\treturn builder.program;\n\t\t}\n\t}\n\tmodules.clear();\n\treturn nullptr;\n}\n\nvoid CInternalProgramBuilder::processModules( const CModuleDataVector& modules,\n\tconst TProcessFunctionPtr processFunction )\n{\n\tTRuntimeModuleId currentModuleId = 0;\n\tfor( CModuleDataVector::const_iterator module = modules.begin();\n\t\tmodule != modules.end(); ++module )\n\t{\n\t\tconst CPreparatoryFunctions& functions = ( *module )->Functions;\n\t\tfor( int i = 0; i < functions.Size(); i++ ) {\n\t\t\t( this->*processFunction )( functions.GetData( i ).get(),\n\t\t\t\tcurrentModuleId );\n\t\t}\n\t\tcurrentModuleId++;\n\t}\n}\n\nvoid CInternalProgramBuilder::collectFunction( CPreparatoryFunction* function,\n\tconst TRuntimeModuleId runtimeModuleId )\n{\n\tif( !function->IsExternal() && !function->IsEntry() ) {\n\t\treturn;\n\t}\n\n\tconst int globalIndex = globals.AddKey( function->ExternalName() );\n\tif( function->IsEntry() ) {\n\t\tassert( !function->IsExternal() );\n\t\tCGlobalFunctionData& global = globals.GetData( globalIndex );\n\t\tif( global.IsDefined() ) {\n\t\t\tstd::ostringstream stringStream;\n\t\t\tstringStream << \"function with external name `\"\n\t\t\t\t<< function->ExternalNameToken().word\n\t\t\t\t<< \"` already defined in program\";\n\t\t\terrors.RaiseError( ES_LinkError, stringStream.str() );\n\t\t} else {\n\t\t\tglobal.SetPreparatoryFunction( function, runtimeModuleId );\n\t\t}\n\t}\n}\n\nvoid CInternalProgramBuilder::collect( const CModuleDataVector& modules )\n{\n\tprocessModules( modules, &CInternalProgramBuilder::collectFunction );\n}\n\nvoid CInternalProgramBuilder::check()\n{\n\tfor( int globalIndex = 0; globalIndex < globals.Size(); globalIndex++ )\n\t{\n\t\tif( !globals.GetData( globalIndex ).IsDefined() ) {\n\t\t\tstd::ostringstream stringStream;\n\t\t\tstringStream << \"function with external name `\"\n\t\t\t\t<< globals.GetKey( globalIndex ) << \"` was not defined\";\n\t\t\terrors.RaiseError( ES_LinkError, stringStream.str() );\n\t\t}\n\t}\n}\n\nvoid CInternalProgramBuilder::compileFunction( CPreparatoryFunction* function,\n\tconst TRuntimeModuleId \/*runtimeModuleId*\/ )\n{\n\tCFunctionCompiler compiler( program->OperationsHolder() );\n\tif( function->IsOrdinary() ) {\n\t\tDEBUG_PRINT( __FUNCTION__ << \" \" << function->Name() )\n\t\tfunction->Compile( compiler );\n\t}\n}\n\nvoid CInternalProgramBuilder::compile( const CModuleDataVector& modules )\n{\n\tprocessModules( modules, &CInternalProgramBuilder::compileFunction );\n}\n\nvoid CInternalProgramBuilder::linkFunction( CPreparatoryFunction* function,\n\tconst TRuntimeModuleId runtimeModuleId )\n{\n\tCRuntimeFunctions& functions = program->Module( runtimeModuleId ).Functions;\n\tconst int functionKey = functions.AddKey( function->Name() );\n\tCRuntimeFunctionPtr& runtimeFunction = functions.GetData( functionKey );\n\tassert( !static_cast( runtimeFunction ) );\n\n\tswitch( function->GetType() ) {\n\t\tcase PFT_Empty:\n\t\t\truntimeFunction = program->EmptyFunction();\n\t\t\tbreak;\n\t\tcase PFT_Compiled:\n\t\t\truntimeFunction.reset( new COrdinaryFunction(\n\t\t\t\tfunction->FirstOperation(), runtimeModuleId ) );\n\t\t\tbreak;\n\t\tcase PFT_External:\n\t\t{\n\t\t\tconst int globalIndex = globals.FindKey( function->ExternalName() );\n\t\t\tassert( globalIndex != InvalidDictionaryIndex );\n\t\t\tconst CGlobalFunctionData& global = globals.GetData( globalIndex );\n\t\t\truntimeFunction = global.RuntimeFunction( program );\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tassert( false );\n\t\t\tbreak;\n\t}\n}\n\nvoid CInternalProgramBuilder::link( const CModuleDataVector& modules )\n{\n\tconst CGlobalFunctionData& goFunction = globals.GetData( globals.FindKey(\n\t\tProgramStartFunctionName ) );\n\tTOperationAddress goFirstOperation =\n\t\tgoFunction.PreparatoryFunction()->FirstOperation();\n\tTRuntimeModuleId goRuntimeModuleId = goFunction.RuntimeModuleId();\n\t\/\/ link all\n\tprocessModules( modules, &CInternalProgramBuilder::linkFunction );\n\t\/\/ set program start function\n\tconst CRuntimeFunctions& runtimeFunctions =\n\t\tprogram->Module( goRuntimeModuleId ).Functions;\n\tTLabel goLabel = InvalidDictionaryIndex;\n\tfor( int i = 0; i < runtimeFunctions.Size(); i++ ) {\n\t\tif( runtimeFunctions.GetData( i )->IsOrdinary()\n\t\t\t&& static_cast(\n\t\t\t\truntimeFunctions.GetData( i ).get() )->FirstOperation() ==\n\t\t\t\tgoFirstOperation )\n\t\t{\n\t\t\tgoLabel = i;\n\t\t}\n\t}\n\tassert( goLabel != InvalidDictionaryIndex );\n\tprogram->SetProgramStartFunction( goLabel + goRuntimeModuleId * LabelMask );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CProgramBuilder\n\nCProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) :\n\tCFunctionBuilder( errorHandler )\n{\n\tReset();\n}\n\nvoid CProgramBuilder::Reset()\n{\n\tCFunctionBuilder::Reset();\n}\n\nvoid CProgramBuilder::AddModule( CModuleDataPtr& module )\n{\n\tmodules.push_back( CModuleDataPtr( module.release() ) );\n}\n\nCProgramPtr CProgramBuilder::BuildProgram()\n{\n\treturn CInternalProgramBuilder::Build( modules, *this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\n} \/\/ end of namespace Refal2\nbug fixes#include \n\nnamespace Refal2 {\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CProgram\n\nCProgram::CProgram( int numberOfModules ) :\n\tmodulesSize( numberOfModules ),\n\tmodules( new CRuntimeModule[modulesSize] ),\n\temptyFunction( new CEmptyFunction )\n{\n\tassert( modulesSize > 0 );\n\tassert( modules != nullptr );\n}\n\nCProgram::~CProgram()\n{\n\tdelete[] modules;\n}\n\nCRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId )\n{\n\tassert( moduleId >= 0 && moduleId < modulesSize );\n\treturn modules[moduleId];\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CProgramPrintHelper\n\nvoid CProgramPrintHelper::Label( std::ostream& outputStream,\n\tconst TLabel label ) const\n{\n\tconst int labelModuleId = label \/ LabelMask;\n\tif( PrintLabelWithModule() ) {\n\t\toutputStream << labelModuleId << \":\";\n\t}\n\toutputStream << program->Module( labelModuleId ).Functions.\n\t\tGetKey(\tlabel % LabelMask );\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CGlobalFunctionData\n\nclass CGlobalFunctionData {\npublic:\n\tCGlobalFunctionData();\n\n\tbool IsEmbeddedFunction() const;\n\tbool IsPreparatoryFunction() const;\n\tbool IsDefined() const;\n\n\tvoid SetPreparatoryFunction(\n\t\tconst CPreparatoryFunction* const _preparatoryFunction,\n\t\tconst TRuntimeModuleId _runtimeModuleId );\n\tconst CPreparatoryFunction* PreparatoryFunction() const;\n\n\tconst TRuntimeModuleId RuntimeModuleId() const;\n\n\tvoid SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction );\n\tTEmbeddedFunctionPtr EmbeddedFunction() const;\n\n\tCRuntimeFunctionPtr RuntimeFunction( const CProgramPtr& program ) const;\n\nprivate:\n\tconst CPreparatoryFunction* preparatoryFunction;\n\tTEmbeddedFunctionPtr embeddedFunction;\n\tTRuntimeModuleId runtimeModuleId;\n\tmutable CRuntimeFunctionPtr runtimeFunction;\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CGlobalFunctionData\n\nCGlobalFunctionData::CGlobalFunctionData() :\n\tpreparatoryFunction( nullptr ),\n\tembeddedFunction( nullptr ),\n\truntimeModuleId( 0 )\n{\n}\n\nbool CGlobalFunctionData::IsEmbeddedFunction() const\n{\n\treturn ( embeddedFunction != nullptr );\n}\n\nbool CGlobalFunctionData::IsPreparatoryFunction() const\n{\n\treturn ( preparatoryFunction != nullptr );\n}\n\nbool CGlobalFunctionData::IsDefined() const\n{\n\treturn ( IsEmbeddedFunction() || IsPreparatoryFunction() );\n}\n\nvoid CGlobalFunctionData::SetPreparatoryFunction(\n\tconst CPreparatoryFunction* const _preparatoryFunction,\n\tconst TRuntimeModuleId _runtimeModuleId )\n{\n\tassert( !IsDefined() );\n\tassert( _preparatoryFunction != nullptr );\n\tpreparatoryFunction = _preparatoryFunction;\n\truntimeModuleId = _runtimeModuleId;\n}\n\nconst CPreparatoryFunction* CGlobalFunctionData::PreparatoryFunction() const\n{\n\tassert( IsPreparatoryFunction() );\n\treturn preparatoryFunction;\n}\n\nconst TRuntimeModuleId CGlobalFunctionData::RuntimeModuleId() const\n{\n\tassert( IsPreparatoryFunction() );\n\treturn runtimeModuleId;\n}\n\nvoid CGlobalFunctionData::SetEmbeddedFunction(\n\tconst TEmbeddedFunctionPtr _embeddedFunction )\n{\n\tassert( !IsDefined() );\n\tassert( _embeddedFunction != nullptr );\n\tembeddedFunction = _embeddedFunction;\n}\n\nTEmbeddedFunctionPtr CGlobalFunctionData::EmbeddedFunction() const\n{\n\tassert( IsEmbeddedFunction() );\n\treturn embeddedFunction;\n}\n\nCRuntimeFunctionPtr CGlobalFunctionData::RuntimeFunction(\n\tconst CProgramPtr& program ) const\n{\n\tif( !static_cast( runtimeFunction ) ) {\n\t\tif( IsEmbeddedFunction() ) {\n\t\t\truntimeFunction.reset( new CEmbeddedFunction(\n\t\t\t\tembeddedFunction ) );\n\t\t} else {\n\t\t\tassert( IsPreparatoryFunction() );\n\t\t\tif( PreparatoryFunction()->IsEmpty() ) {\n\t\t\t\truntimeFunction = program->EmptyFunction();\n\t\t\t} else {\n\t\t\t\truntimeFunction.reset( new COrdinaryFunction(\n\t\t\t\t\tPreparatoryFunction()->FirstOperation(),\n\t\t\t\t\tRuntimeModuleId() ) );\n\t\t\t}\n\t\t}\n\t}\n\treturn runtimeFunction;\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CInternalProgramBuilder\n\nconst char* const ProgramStartFunctionName = \"go\";\n\nclass CInternalProgramBuilder {\npublic:\n\tstatic CProgramPtr Build( CModuleDataVector& modules,\n\t\tCErrorsHelper& errors );\n\nprivate:\n\tCErrorsHelper& errors;\n\tCDictionary globals;\n\tCProgramPtr program;\n\n\tCInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules );\n\n\ttypedef void ( CInternalProgramBuilder::*TProcessFunctionPtr )(\n\t\tCPreparatoryFunction* function,\n\t\tconst TRuntimeModuleId runtimeModuleId );\n\n\tvoid processModules( const CModuleDataVector& modules,\n\t\tconst TProcessFunctionPtr processFunction );\n\n\tvoid collectFunction( CPreparatoryFunction* function,\n\t\t const TRuntimeModuleId runtimeModuleId );\n\tvoid collect( const CModuleDataVector& modules );\n\n\tvoid check();\n\n\tvoid compileFunction( CPreparatoryFunction* function,\n\t\tconst TRuntimeModuleId runtimeModuleId );\n\tvoid compile( const CModuleDataVector& modules );\n\n\tvoid linkFunction( CPreparatoryFunction* function,\n\t\tconst TRuntimeModuleId runtimeModuleId );\n\tvoid link( const CModuleDataVector& modules );\n};\n\n\/\/-----------------------------------------------------------------------------\n\nCInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors,\n\t\tint numberOfModules ) :\n\terrors( _errors ),\n\tprogram( new CProgram( numberOfModules ) )\n{\n\tassert( static_cast( program ) );\n\t\/\/ add standart functions\n\tfor( const CEmbeddedFunctionData* function = EmbeddedFunctionDataTable();\n\t\tfunction->EmbeddedFunction != nullptr; function++ )\n\t{\n\t\tassert( function->ExternalName != nullptr );\n\t\tstd::string externalName = function->ExternalName;\n\t\tassert( !externalName.empty() );\n\t\tconst int globalIndex = globals.AddKey( externalName );\n\t\tCGlobalFunctionData& global = globals.GetData( globalIndex );\n\t\tglobal.SetEmbeddedFunction( function->EmbeddedFunction );\n\t}\n\t\/\/ add `ProgramStartFunctionName`\n\tconst int globalGoIndex = globals.AddKey( ProgramStartFunctionName );\n\tassert( !globals.GetData( globalGoIndex ).IsDefined() );\n}\n\nCProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules,\n\tCErrorsHelper& errors )\n{\n\tif( !errors.HasErrors() && !modules.empty() ) {\n\t\tCInternalProgramBuilder builder( errors, modules.size() );\n\t\tbuilder.collect( modules );\n\t\tif( !errors.HasErrors() ) {\n\t\t\tbuilder.check();\n\t\t\tif( !errors.HasErrors() ) {\n\t\t\t\tbuilder.compile( modules );\n\t\t\t\tassert( !errors.HasErrors() );\n\t\t\t\tbuilder.link( modules );\n\t\t\t\tassert( !errors.HasErrors() );\n\t\t\t\treturn builder.program;\n\t\t\t}\n\t\t}\n\t}\n\tmodules.clear();\n\treturn nullptr;\n}\n\nvoid CInternalProgramBuilder::processModules( const CModuleDataVector& modules,\n\tconst TProcessFunctionPtr processFunction )\n{\n\tTRuntimeModuleId currentModuleId = 0;\n\tfor( CModuleDataVector::const_iterator module = modules.begin();\n\t\tmodule != modules.end(); ++module )\n\t{\n\t\tconst CPreparatoryFunctions& functions = ( *module )->Functions;\n\t\tfor( int i = 0; i < functions.Size(); i++ ) {\n\t\t\t( this->*processFunction )( functions.GetData( i ).get(),\n\t\t\t\tcurrentModuleId );\n\t\t}\n\t\tcurrentModuleId++;\n\t}\n}\n\nvoid CInternalProgramBuilder::collectFunction( CPreparatoryFunction* function,\n\tconst TRuntimeModuleId runtimeModuleId )\n{\n\tif( !function->IsExternal() && !function->IsEntry() ) {\n\t\treturn;\n\t}\n\n\tconst int globalIndex = globals.AddKey( function->ExternalName() );\n\tif( function->IsEntry() ) {\n\t\tassert( !function->IsExternal() );\n\t\tCGlobalFunctionData& global = globals.GetData( globalIndex );\n\t\tif( global.IsDefined() ) {\n\t\t\tstd::ostringstream stringStream;\n\t\t\tstringStream << \"function with external name `\"\n\t\t\t\t<< function->ExternalNameToken().word\n\t\t\t\t<< \"` already defined in program\";\n\t\t\terrors.RaiseError( ES_LinkError, stringStream.str() );\n\t\t} else {\n\t\t\tglobal.SetPreparatoryFunction( function, runtimeModuleId );\n\t\t}\n\t}\n}\n\nvoid CInternalProgramBuilder::collect( const CModuleDataVector& modules )\n{\n\tprocessModules( modules, &CInternalProgramBuilder::collectFunction );\n}\n\nvoid CInternalProgramBuilder::check()\n{\n\tfor( int globalIndex = 0; globalIndex < globals.Size(); globalIndex++ )\n\t{\n\t\tif( !globals.GetData( globalIndex ).IsDefined() ) {\n\t\t\tstd::ostringstream stringStream;\n\t\t\tstringStream << \"function with external name `\"\n\t\t\t\t<< globals.GetKey( globalIndex ) << \"` was not defined\";\n\t\t\terrors.RaiseError( ES_LinkError, stringStream.str() );\n\t\t}\n\t}\n}\n\nvoid CInternalProgramBuilder::compileFunction( CPreparatoryFunction* function,\n\tconst TRuntimeModuleId \/*runtimeModuleId*\/ )\n{\n\tCFunctionCompiler compiler( program->OperationsHolder() );\n\tif( function->IsOrdinary() ) {\n\t\tDEBUG_PRINT( __FUNCTION__ << \" \" << function->Name() )\n\t\tfunction->Compile( compiler );\n\t}\n}\n\nvoid CInternalProgramBuilder::compile( const CModuleDataVector& modules )\n{\n\tprocessModules( modules, &CInternalProgramBuilder::compileFunction );\n}\n\nvoid CInternalProgramBuilder::linkFunction( CPreparatoryFunction* function,\n\tconst TRuntimeModuleId runtimeModuleId )\n{\n\tCRuntimeFunctions& functions = program->Module( runtimeModuleId ).Functions;\n\tconst int functionKey = functions.AddKey( function->Name() );\n\tCRuntimeFunctionPtr& runtimeFunction = functions.GetData( functionKey );\n\tassert( !static_cast( runtimeFunction ) );\n\n\tswitch( function->GetType() ) {\n\t\tcase PFT_Empty:\n\t\t\truntimeFunction = program->EmptyFunction();\n\t\t\tbreak;\n\t\tcase PFT_Compiled:\n\t\t\truntimeFunction.reset( new COrdinaryFunction(\n\t\t\t\tfunction->FirstOperation(), runtimeModuleId ) );\n\t\t\tbreak;\n\t\tcase PFT_External:\n\t\t{\n\t\t\tconst int globalIndex = globals.FindKey( function->ExternalName() );\n\t\t\tassert( globalIndex != InvalidDictionaryIndex );\n\t\t\tconst CGlobalFunctionData& global = globals.GetData( globalIndex );\n\t\t\truntimeFunction = global.RuntimeFunction( program );\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tassert( false );\n\t\t\tbreak;\n\t}\n}\n\nvoid CInternalProgramBuilder::link( const CModuleDataVector& modules )\n{\n\tconst CGlobalFunctionData& goFunction = globals.GetData( globals.FindKey(\n\t\tProgramStartFunctionName ) );\n\tTOperationAddress goFirstOperation =\n\t\tgoFunction.PreparatoryFunction()->FirstOperation();\n\tTRuntimeModuleId goRuntimeModuleId = goFunction.RuntimeModuleId();\n\t\/\/ link all\n\tprocessModules( modules, &CInternalProgramBuilder::linkFunction );\n\t\/\/ set program start function\n\tconst CRuntimeFunctions& runtimeFunctions =\n\t\tprogram->Module( goRuntimeModuleId ).Functions;\n\tTLabel goLabel = InvalidDictionaryIndex;\n\tfor( int i = 0; i < runtimeFunctions.Size(); i++ ) {\n\t\tif( runtimeFunctions.GetData( i )->IsOrdinary()\n\t\t\t&& static_cast(\n\t\t\t\truntimeFunctions.GetData( i ).get() )->FirstOperation() ==\n\t\t\t\tgoFirstOperation )\n\t\t{\n\t\t\tgoLabel = i;\n\t\t}\n\t}\n\tassert( goLabel != InvalidDictionaryIndex );\n\tprogram->SetProgramStartFunction( goLabel + goRuntimeModuleId * LabelMask );\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/ CProgramBuilder\n\nCProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) :\n\tCFunctionBuilder( errorHandler )\n{\n\tReset();\n}\n\nvoid CProgramBuilder::Reset()\n{\n\tCFunctionBuilder::Reset();\n}\n\nvoid CProgramBuilder::AddModule( CModuleDataPtr& module )\n{\n\tmodules.push_back( CModuleDataPtr( module.release() ) );\n}\n\nCProgramPtr CProgramBuilder::BuildProgram()\n{\n\treturn CInternalProgramBuilder::Build( modules, *this );\n}\n\n\/\/-----------------------------------------------------------------------------\n\n} \/\/ end of namespace Refal2\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"filelib.h\"\n#include \"stringlib.h\"\n#include \"sparse_vector.h\"\n#include \"scorer.h\"\n#include \"viterbi_envelope.h\"\n#include \"inside_outside.h\"\n#include \"error_surface.h\"\n#include \"hg.h\"\n#include \"hg_io.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n po::options_description opts(\"Configuration options\");\n opts.add_options()\n (\"reference,r\",po::value >(), \"[REQD] Reference translation (tokenized text)\")\n (\"source,s\",po::value(), \"Source file (ignored, except for AER)\")\n (\"loss_function,l\",po::value()->default_value(\"ibm_bleu\"), \"Loss function being optimized\")\n (\"input,i\",po::value()->default_value(\"-\"), \"Input file to map (- is STDIN)\")\n (\"help,h\", \"Help\");\n po::options_description dcmdline_options;\n dcmdline_options.add(opts);\n po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n bool flag = false;\n if (!conf->count(\"reference\")) {\n cerr << \"Please specify one or more references using -r \\n\";\n flag = true;\n }\n if (flag || conf->count(\"help\")) {\n cerr << dcmdline_options << endl;\n exit(1);\n }\n}\n\nbool ReadSparseVectorString(const string& s, SparseVector* v) {\n vector fields;\n Tokenize(s, ';', &fields);\n if (fields.empty()) return false;\n for (int i = 0; i < fields.size(); ++i) {\n vector pair(2);\n Tokenize(fields[i], '=', &pair);\n if (pair.size() != 2) {\n cerr << \"Error parsing vector string: \" << fields[i] << endl;\n return false;\n }\n v->set_value(FD::Convert(pair[0]), atof(pair[1].c_str()));\n }\n return true;\n}\n\nint main(int argc, char** argv) {\n po::variables_map conf;\n InitCommandLine(argc, argv, &conf);\n const string loss_function = conf[\"loss_function\"].as();\n ScoreType type = ScoreTypeFromString(loss_function);\n DocScorer ds(type, conf[\"reference\"].as >(), conf[\"source\"].as());\n cerr << \"Loaded \" << ds.size() << \" references for scoring with \" << loss_function << endl;\n Hypergraph hg;\n string last_file;\n ReadFile in_read(conf[\"input\"].as());\n istream &in=*in_read.stream();\n while(in) {\n string line;\n getline(in, line);\n if (line.empty()) continue;\n istringstream is(line);\n int sent_id;\n string file, s_origin, s_axis;\n is >> file >> sent_id >> s_origin >> s_axis;\n SparseVector origin;\n assert(ReadSparseVectorString(s_origin, &origin));\n SparseVector axis;\n assert(ReadSparseVectorString(s_axis, &axis));\n \/\/ cerr << \"File: \" << file << \"\\nAxis: \" << axis << \"\\n X: \" << origin << endl;\n if (last_file != file) {\n last_file = file;\n ReadFile rf(file);\n HypergraphIO::ReadFromJSON(rf.stream(), &hg);\n }\n ViterbiEnvelopeWeightFunction wf(origin, axis);\n ViterbiEnvelope ve = Inside(hg, NULL, wf);\n ErrorSurface es;\n ds[sent_id]->ComputeErrorSurface(ve, &es, type, hg);\n \/\/cerr << \"Viterbi envelope has \" << ve.size() << \" segments\\n\";\n \/\/ cerr << \"Error surface has \" << es.size() << \" segments\\n\";\n string val;\n es.Serialize(&val);\n cout << 'M' << ' ' << s_origin << ' ' << s_axis << '\\t';\n B64::b64encode(val.c_str(), val.size(), &cout);\n cout << endl;\n }\n return 0;\n}\nwhitespace#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"filelib.h\"\n#include \"stringlib.h\"\n#include \"sparse_vector.h\"\n#include \"scorer.h\"\n#include \"viterbi_envelope.h\"\n#include \"inside_outside.h\"\n#include \"error_surface.h\"\n#include \"hg.h\"\n#include \"hg_io.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n po::options_description opts(\"Configuration options\");\n opts.add_options()\n (\"reference,r\",po::value >(), \"[REQD] Reference translation (tokenized text)\")\n (\"source,s\",po::value(), \"Source file (ignored, except for AER)\")\n (\"loss_function,l\",po::value()->default_value(\"ibm_bleu\"), \"Loss function being optimized\")\n (\"input,i\",po::value()->default_value(\"-\"), \"Input file to map (- is STDIN)\")\n (\"help,h\", \"Help\");\n po::options_description dcmdline_options;\n dcmdline_options.add(opts);\n po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n bool flag = false;\n if (!conf->count(\"reference\")) {\n cerr << \"Please specify one or more references using -r \\n\";\n flag = true;\n }\n if (flag || conf->count(\"help\")) {\n cerr << dcmdline_options << endl;\n exit(1);\n }\n}\n\nbool ReadSparseVectorString(const string& s, SparseVector* v) {\n vector fields;\n Tokenize(s, ';', &fields);\n if (fields.empty()) return false;\n for (int i = 0; i < fields.size(); ++i) {\n vector pair(2);\n Tokenize(fields[i], '=', &pair);\n if (pair.size() != 2) {\n cerr << \"Error parsing vector string: \" << fields[i] << endl;\n return false;\n }\n v->set_value(FD::Convert(pair[0]), atof(pair[1].c_str()));\n }\n return true;\n}\n\nint main(int argc, char** argv) {\n po::variables_map conf;\n InitCommandLine(argc, argv, &conf);\n const string loss_function = conf[\"loss_function\"].as();\n ScoreType type = ScoreTypeFromString(loss_function);\n DocScorer ds(type, conf[\"reference\"].as >(), conf[\"source\"].as());\n cerr << \"Loaded \" << ds.size() << \" references for scoring with \" << loss_function << endl;\n Hypergraph hg;\n string last_file;\n ReadFile in_read(conf[\"input\"].as());\n istream &in=*in_read.stream();\n while(in) {\n string line;\n getline(in, line);\n if (line.empty()) continue;\n istringstream is(line);\n int sent_id;\n string file, s_origin, s_axis;\n is >> file >> sent_id >> s_origin >> s_axis;\n SparseVector origin;\n assert(ReadSparseVectorString(s_origin, &origin));\n SparseVector axis;\n assert(ReadSparseVectorString(s_axis, &axis));\n \/\/ cerr << \"File: \" << file << \"\\nAxis: \" << axis << \"\\n X: \" << origin << endl;\n if (last_file != file) {\n last_file = file;\n ReadFile rf(file);\n HypergraphIO::ReadFromJSON(rf.stream(), &hg);\n }\n ViterbiEnvelopeWeightFunction wf(origin, axis);\n ViterbiEnvelope ve = Inside(hg, NULL, wf);\n ErrorSurface es;\n ds[sent_id]->ComputeErrorSurface(ve, &es, type, hg);\n \/\/cerr << \"Viterbi envelope has \" << ve.size() << \" segments\\n\";\n \/\/ cerr << \"Error surface has \" << es.size() << \" segments\\n\";\n string val;\n es.Serialize(&val);\n cout << 'M' << ' ' << s_origin << ' ' << s_axis << '\\t';\n B64::b64encode(val.c_str(), val.size(), &cout);\n cout << endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Manjeet Dahiya\n *\n * Source:\n * http:\/\/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\n#include \"QXmppUtils.h\"\n#include \"QXmppIq.h\"\n\n#include \n#include \n\n\/\/\/ Constructs a QXmppIq with the specified \\a type.\n\/\/\/\n\/\/\/ \\param type\n\nQXmppIq::QXmppIq(QXmppIq::Type type)\n : QXmppStanza(), m_type(type)\n{\n generateAndSetNextId();\n}\n\n\/\/\/ Returns the IQ's type.\n\/\/\/\n\nQXmppIq::Type QXmppIq::type() const\n{\n return m_type;\n}\n\n\/\/\/ Sets the IQ's type.\n\/\/\/\n\/\/\/ \\param type\n\nvoid QXmppIq::setType(QXmppIq::Type type)\n{\n m_type = type;\n}\n\nvoid QXmppIq::parse(const QDomElement &element)\n{\n QXmppStanza::parse(element);\n setTypeFromStr(element.attribute(\"type\"));\n parseElementFromChild(element);\n}\n\nvoid QXmppIq::parseElementFromChild(const QDomElement &element)\n{\n QXmppElementList extensions;\n QDomElement itemElement = element.firstChildElement();\n while (!itemElement.isNull())\n {\n extensions.append(QXmppElement(itemElement));\n itemElement = itemElement.nextSiblingElement();\n }\n setExtensions(extensions);\n}\n\nvoid QXmppIq::toXml( QXmlStreamWriter *xmlWriter ) const\n{\n xmlWriter->writeStartElement(\"iq\");\n\n helperToXmlAddAttribute(xmlWriter, \"id\", id());\n helperToXmlAddAttribute(xmlWriter, \"to\", to());\n helperToXmlAddAttribute(xmlWriter, \"from\", from());\n if(getTypeStr().isEmpty())\n helperToXmlAddAttribute(xmlWriter, \"type\", \"get\");\n else\n helperToXmlAddAttribute(xmlWriter, \"type\", getTypeStr());\n toXmlElementFromChild(xmlWriter);\n error().toXml(xmlWriter);\n xmlWriter->writeEndElement();\n}\n\nvoid QXmppIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const\n{\n foreach (const QXmppElement &extension, extensions())\n extension.toXml(writer);\n}\n\nQString QXmppIq::getTypeStr() const\n{\n switch(m_type)\n {\n case QXmppIq::Error:\n return \"error\";\n case QXmppIq::Get:\n return \"get\";\n case QXmppIq::Set:\n return \"set\";\n case QXmppIq::Result:\n return \"result\";\n default:\n qWarning(\"QXmppIq::getTypeStr() invalid type %d\", (int)m_type);\n return \"\";\n }\n}\n\nvoid QXmppIq::setTypeFromStr(const QString& str)\n{\n if(str == \"error\")\n {\n setType(QXmppIq::Error);\n return;\n }\n else if(str == \"get\")\n {\n setType(QXmppIq::Get);\n return;\n }\n else if(str == \"set\")\n {\n setType(QXmppIq::Set);\n return;\n }\n else if(str == \"result\")\n {\n setType(QXmppIq::Result);\n return;\n }\n else\n {\n setType(static_cast(-1));\n qWarning(\"QXmppIq::setTypeFromStr() invalid input string type: %s\",\n qPrintable(str));\n return;\n }\n}\n\n\/\/ deprecated\n\nQXmppIq::Type QXmppIq::getType() const\n{\n return m_type;\n}\n\ndoc improvement\/*\n * Copyright (C) 2008-2010 The QXmpp developers\n *\n * Author:\n * Manjeet Dahiya\n *\n * Source:\n * http:\/\/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\n#include \"QXmppUtils.h\"\n#include \"QXmppIq.h\"\n\n#include \n#include \n\n\/\/\/ Constructs a QXmppIq with the specified \\a type.\n\/\/\/\n\/\/\/ \\param type\n\nQXmppIq::QXmppIq(QXmppIq::Type type)\n : QXmppStanza(), m_type(type)\n{\n generateAndSetNextId();\n}\n\n\/\/\/ Returns the IQ's type.\n\/\/\/\n\/\/\/ \\return QXmppIq::Type\n\nQXmppIq::Type QXmppIq::type() const\n{\n return m_type;\n}\n\n\/\/\/ Sets the IQ's type.\n\/\/\/\n\/\/\/ \\param type as QXmppIq::Type\n\nvoid QXmppIq::setType(QXmppIq::Type type)\n{\n m_type = type;\n}\n\nvoid QXmppIq::parse(const QDomElement &element)\n{\n QXmppStanza::parse(element);\n setTypeFromStr(element.attribute(\"type\"));\n parseElementFromChild(element);\n}\n\nvoid QXmppIq::parseElementFromChild(const QDomElement &element)\n{\n QXmppElementList extensions;\n QDomElement itemElement = element.firstChildElement();\n while (!itemElement.isNull())\n {\n extensions.append(QXmppElement(itemElement));\n itemElement = itemElement.nextSiblingElement();\n }\n setExtensions(extensions);\n}\n\nvoid QXmppIq::toXml( QXmlStreamWriter *xmlWriter ) const\n{\n xmlWriter->writeStartElement(\"iq\");\n\n helperToXmlAddAttribute(xmlWriter, \"id\", id());\n helperToXmlAddAttribute(xmlWriter, \"to\", to());\n helperToXmlAddAttribute(xmlWriter, \"from\", from());\n if(getTypeStr().isEmpty())\n helperToXmlAddAttribute(xmlWriter, \"type\", \"get\");\n else\n helperToXmlAddAttribute(xmlWriter, \"type\", getTypeStr());\n toXmlElementFromChild(xmlWriter);\n error().toXml(xmlWriter);\n xmlWriter->writeEndElement();\n}\n\nvoid QXmppIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const\n{\n foreach (const QXmppElement &extension, extensions())\n extension.toXml(writer);\n}\n\nQString QXmppIq::getTypeStr() const\n{\n switch(m_type)\n {\n case QXmppIq::Error:\n return \"error\";\n case QXmppIq::Get:\n return \"get\";\n case QXmppIq::Set:\n return \"set\";\n case QXmppIq::Result:\n return \"result\";\n default:\n qWarning(\"QXmppIq::getTypeStr() invalid type %d\", (int)m_type);\n return \"\";\n }\n}\n\nvoid QXmppIq::setTypeFromStr(const QString& str)\n{\n if(str == \"error\")\n {\n setType(QXmppIq::Error);\n return;\n }\n else if(str == \"get\")\n {\n setType(QXmppIq::Get);\n return;\n }\n else if(str == \"set\")\n {\n setType(QXmppIq::Set);\n return;\n }\n else if(str == \"result\")\n {\n setType(QXmppIq::Result);\n return;\n }\n else\n {\n setType(static_cast(-1));\n qWarning(\"QXmppIq::setTypeFromStr() invalid input string type: %s\",\n qPrintable(str));\n return;\n }\n}\n\n\/\/ deprecated\n\nQXmppIq::Type QXmppIq::getType() const\n{\n return m_type;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Time\/Duration.h\"\n\n#include \"Common.h\"\n#include \"TimeOutException.h\"\n\n#include \"WaitableEvent.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Execution;\n\nusing Stroika::Foundation::Time::Duration;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n * Design notes:\n *\n * o The use of condition variables is non-obvious. I haven't found good documentation, but\n * the best I've found would be\n * https:\/\/computing.llnl.gov\/tutorials\/pthreads\/#ConVarOverview\n *\n * In particular, on the surface, it looks like the mutex locks in Wait() and signal should prevent things\n * form working (deadlock). But they apparently do not cause a deadlock because\n * \"pthread_cond_wait() blocks the calling thread until the specified condition is signalled.\n * This routine should be called while mutex is locked, and it will automatically release the\n * mutex while it waits. After signal is received and thread is awakened, mutex will be\n * automatically locked for use by the thread. The programmer is then responsible for\n * unlocking mutex when the thread is finished with it.\"\n *\n *\/\n\n\/*\n ********************************************************************************\n ****************************** WaitableEvent::WE_ ******************************\n ********************************************************************************\n *\/\nvoid WaitableEvent::WE_::WaitUntil (Time::DurationSecondsType timeoutAt)\n{\n if (WaitUntilQuietly (timeoutAt) == kWaitQuietlyTimeoutResult) {\n\/\/ note - safe use of TimeOutException::kThe because you cannot really wait except when threads are running, so\n\/\/ inside 'main' lifetime\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n \/\/ only thing Throw() helper does is DbgTrace ()- and that can make traces hard to read unless you are debugging a timeout \/event issue\n Throw (TimeOutException::kThe);\n#else\n throw (TimeOutException::kThe);\n#endif\n }\n}\n\nbool WaitableEvent::WE_::WaitUntilQuietly (Time::DurationSecondsType timeoutAt)\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (L\"WaitableEvent::WE_::WaitUntil\", \"timeout = %e\", timeoutAt);\n#endif\n CheckForThreadInterruption ();\n std::unique_lock lock (fConditionVariable.fMutex);\n if (fConditionVariable.wait_until (lock, timeoutAt, [this]() { return fTriggered; })) {\n if (fResetType == eAutoReset) {\n \/\/ cannot call Reset () directly because we (may???) already have the lock mutex? Maybe not cuz of cond variable?\n fTriggered = false; \/\/ autoreset\n }\n return not kWaitQuietlyTimeoutResult;\n }\n else {\n return kWaitQuietlyTimeoutResult;\n }\n}\n\n\/*\n ********************************************************************************\n ********************************** WaitableEvent *******************************\n ********************************************************************************\n *\/\nconstexpr WaitableEvent::ResetType WaitableEvent::eAutoReset;\nconstexpr WaitableEvent::ResetType WaitableEvent::eManualReset;\n\n#if qDebug || qStroika_FeatureSupported_Valgrind\nWaitableEvent::~WaitableEvent ()\n{\n Require (fExtraWaitableEvents_.empty ()); \/\/ Cannot kill a waitable event while its being waited on by others\n \/\/ Stroika_Foundation_Debug_ValgrindDisableHelgrind (fWE_.fConditionVariable.fConditionVariable); \/\/ avoid sporadic (about 1\/3 time) probably spurious helgrind failure - for test Foundation::Execution::Threads -https:\/\/stroika.atlassian.net\/browse\/STK-484\n}\n#endif\n\nvoid WaitableEvent::Set ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"WaitableEvent::Set\");\n#endif\n fWE_.Set ();\n#if qExecution_WaitableEvent_SupportWaitForMultipleObjects\n auto critSec{make_unique_lock (_Stroika_Foundation_Execution_Private_WaitableEvent_ModuleInit_.Actual ().fExtraWaitableEventsMutex_)};\n for (auto i : fExtraWaitableEvents_) {\n i->Set ();\n }\n#endif\n}\nhttps:\/\/stroika.atlassian.net\/browse\/STK-484 possible fix - waitableevent - may need extra mutex lock on read (found with tsan)\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Time\/Duration.h\"\n\n#include \"Common.h\"\n#include \"TimeOutException.h\"\n\n#include \"WaitableEvent.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Execution;\n\nusing Stroika::Foundation::Time::Duration;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n * Design notes:\n *\n * o The use of condition variables is non-obvious. I haven't found good documentation, but\n * the best I've found would be\n * https:\/\/computing.llnl.gov\/tutorials\/pthreads\/#ConVarOverview\n *\n * In particular, on the surface, it looks like the mutex locks in Wait() and signal should prevent things\n * form working (deadlock). But they apparently do not cause a deadlock because\n * \"pthread_cond_wait() blocks the calling thread until the specified condition is signalled.\n * This routine should be called while mutex is locked, and it will automatically release the\n * mutex while it waits. After signal is received and thread is awakened, mutex will be\n * automatically locked for use by the thread. The programmer is then responsible for\n * unlocking mutex when the thread is finished with it.\"\n *\n *\/\n\n\/*\n ********************************************************************************\n ****************************** WaitableEvent::WE_ ******************************\n ********************************************************************************\n *\/\nvoid WaitableEvent::WE_::WaitUntil (Time::DurationSecondsType timeoutAt)\n{\n if (WaitUntilQuietly (timeoutAt) == kWaitQuietlyTimeoutResult) {\n\/\/ note - safe use of TimeOutException::kThe because you cannot really wait except when threads are running, so\n\/\/ inside 'main' lifetime\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n \/\/ only thing Throw() helper does is DbgTrace ()- and that can make traces hard to read unless you are debugging a timeout \/event issue\n Throw (TimeOutException::kThe);\n#else\n throw (TimeOutException::kThe);\n#endif\n }\n}\n\nbool WaitableEvent::WE_::WaitUntilQuietly (Time::DurationSecondsType timeoutAt)\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (L\"WaitableEvent::WE_::WaitUntil\", \"timeout = %e\", timeoutAt);\n#endif\n CheckForThreadInterruption ();\n std::unique_lock lock (fConditionVariable.fMutex);\n if (fConditionVariable.wait_until (lock, timeoutAt, [this]() { return fTriggered; })) {\n if (fResetType == eAutoReset) {\n \/\/ cannot call Reset () directly because we (may???) already have the lock mutex? Maybe not cuz of cond variable?\n fTriggered = false; \/\/ autoreset\n }\n return not kWaitQuietlyTimeoutResult;\n }\n else {\n return kWaitQuietlyTimeoutResult;\n }\n}\n\n\/*\n ********************************************************************************\n ********************************** WaitableEvent *******************************\n ********************************************************************************\n *\/\nconstexpr WaitableEvent::ResetType WaitableEvent::eAutoReset;\nconstexpr WaitableEvent::ResetType WaitableEvent::eManualReset;\n\n#if qDebug || qStroika_FeatureSupported_Valgrind\nWaitableEvent::~WaitableEvent ()\n{\n Require (fExtraWaitableEvents_.empty ()); \/\/ Cannot kill a waitable event while its being waited on by others\n \/\/ Stroika_Foundation_Debug_ValgrindDisableHelgrind (fWE_.fConditionVariable.fConditionVariable); \/\/ avoid sporadic (about 1\/3 time) probably spurious helgrind failure - for test Foundation::Execution::Threads -https:\/\/stroika.atlassian.net\/browse\/STK-484\n}\n#endif\n\nvoid WaitableEvent::Set ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"WaitableEvent::Set\");\n#endif\n fWE_.Set ();\n#if qExecution_WaitableEvent_SupportWaitForMultipleObjects\n auto critSec{make_unique_lock (_Stroika_Foundation_Execution_Private_WaitableEvent_ModuleInit_.Actual ().fExtraWaitableEventsMutex_)};\n for (auto i : fExtraWaitableEvents_) {\n i->Set ();\n }\n#endif\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ This program will take a flow XML and run it in dummy mode.\n\/\/ This means that it will run every node with a dummy function and\n\/\/ exercise the flow with all of its guard acquisitions. \n\/\/ It can be used to test the flow for bottlenecks or other effects.\n\/\/ It may also indicate interesting effects related to choice of runtime.\n\/\/ Limitations:\n\/\/ * guards are reduced to singleton (no () key guards)\n\/\/ * no data is passed since the replacement nodes do not pass inputs or\n\/\/ outputs\n\n#include \"OFlux.h\"\n#include \"flow\/OFluxFlowExerciseFunctions.h\"\n#include \"flow\/OFluxFlow.h\"\n#include \"atomic\/OFluxAtomic.h\"\n#include \"lockfree\/atomic\/OFluxLFAtomicMaps.h\"\n#include \"atomic\/OFluxAtomicHolder.h\"\n#include \"OFluxRunTimeBase.h\"\n#include \"OFluxIOConversion.h\"\n#include \"OFluxEarlyRelease.h\"\n#include \"OFluxLogging.h\"\n#include \n#include \n\n\noflux::shared_ptr theRT;\n\nvoid\ninit_atomic_maps(int) {}\n\noflux::flow::exercise::AtomicSetAbstract * atomic_set = NULL;\noflux::flow::Flow * flow = NULL;\n\nvoid handlesighup(int)\n{\n\tsignal(SIGHUP,handlesighup);\n\tatomic_set->report();\n\toflux::flow::exercise::node_report(flow);\n\ttheRT->log_snapshot();\n}\n\noflux::flow::exercise::AtomicAbstract::P * _atomic_array;\n\nvoid \nex_release_guards()\n{\n\toflux::release_all_guards(theRT.get());\n}\n\nint\nmain(int argc, char * argv[])\n{\n\toflux::flow::exercise::release_guards = ex_release_guards;\n\n\tif(argc <= 1) {\n\t\tstd::cout << \"provide an XML flow file argument\\n\";\n\t\treturn 9;\n\t}\n\tchar * max_nsec_wait_str = getenv(\"EXERCISE_SLEEP\");\n\tif(max_nsec_wait_str) {\n\t\toflux::flow::exercise::max_nsec_wait = atol(max_nsec_wait_str);\n\t}\n\tint init_threads = 0;\n\tchar * init_threads_str = getenv(\"EXERCISE_THREADS\");\n\tif(init_threads_str) {\n\t\tinit_threads = atoi(init_threads_str);\n\t}\n\toflux::RunTimeConfiguration rtc = {\n\t\t 1024*1024 \/\/ stack size\n\t\t, init_threads \/\/ initial threads (ignored really)\n\t\t, 0 \/\/ max threads\n\t\t, 0 \/\/ max detached\n\t\t, 0 \/\/ thread collection threshold\n\t\t, 1000 \/\/ thread collection sample period (every N node execs)\n\t\t, argv[1] \/\/ XML file\n\t\t, NULL \/\/ temporary\n\t\t, \"xml\" \/\/ xml subdir for plugins\n\t\t, \"lib\" \/\/ lib subdir for plugins\n\t\t, NULL\n\t\t, init_atomic_maps\n\t\t};\n\toflux::logging::toStream(std::cout); \n\toflux_log_info(\" exercise::max_nsec_wait is %ld\\n\", oflux::flow::exercise::max_nsec_wait);\n\toflux::EnvironmentVar env(oflux::runtime::Factory::classic);\n\toflux::flow::ExerciseFunctionMaps ffmaps(env.runtime_number == 4);\n\tatomic_set = ffmaps.atomic_set();\n\trtc.flow_maps = &ffmaps;\n\ttheRT.reset(oflux::runtime::Factory::create(env.runtime_number, rtc));\n\tflow = theRT->flow();\n\toflux::flow::exercise::AtomicAbstract::P atomic_array[atomic_set->size()+1];\n\t_atomic_array = &atomic_array[0];\n\tatomic_set->fill(atomic_array);\n\tsignal(SIGHUP,handlesighup);\n\tif(!env.nostart) {\n\t\ttheRT->start();\n\t}\n\ttheRT.reset(); \/\/ force deletion of the runtime\n\t\n\treturn 0;\n}\nmax threads in exercise\/\/\n\/\/ This program will take a flow XML and run it in dummy mode.\n\/\/ This means that it will run every node with a dummy function and\n\/\/ exercise the flow with all of its guard acquisitions. \n\/\/ It can be used to test the flow for bottlenecks or other effects.\n\/\/ It may also indicate interesting effects related to choice of runtime.\n\/\/ Limitations:\n\/\/ * guards are reduced to singleton (no () key guards)\n\/\/ * no data is passed since the replacement nodes do not pass inputs or\n\/\/ outputs\n\n#include \"OFlux.h\"\n#include \"flow\/OFluxFlowExerciseFunctions.h\"\n#include \"flow\/OFluxFlow.h\"\n#include \"atomic\/OFluxAtomic.h\"\n#include \"lockfree\/atomic\/OFluxLFAtomicMaps.h\"\n#include \"atomic\/OFluxAtomicHolder.h\"\n#include \"OFluxRunTimeBase.h\"\n#include \"OFluxIOConversion.h\"\n#include \"OFluxEarlyRelease.h\"\n#include \"OFluxLogging.h\"\n#include \n#include \n\n\noflux::shared_ptr theRT;\n\nvoid\ninit_atomic_maps(int) {}\n\noflux::flow::exercise::AtomicSetAbstract * atomic_set = NULL;\noflux::flow::Flow * flow = NULL;\n\nvoid handlesighup(int)\n{\n\tsignal(SIGHUP,handlesighup);\n\tatomic_set->report();\n\toflux::flow::exercise::node_report(flow);\n\ttheRT->log_snapshot();\n}\n\noflux::flow::exercise::AtomicAbstract::P * _atomic_array;\n\nvoid \nex_release_guards()\n{\n\toflux::release_all_guards(theRT.get());\n}\n\nint\nmain(int argc, char * argv[])\n{\n\toflux::flow::exercise::release_guards = ex_release_guards;\n\n\tif(argc <= 1) {\n\t\tstd::cout << \"provide an XML flow file argument\\n\";\n\t\treturn 9;\n\t}\n\tchar * max_nsec_wait_str = getenv(\"EXERCISE_SLEEP\");\n\tif(max_nsec_wait_str) {\n\t\toflux::flow::exercise::max_nsec_wait = atol(max_nsec_wait_str);\n\t}\n\tint init_threads = 0;\n\tchar * init_threads_str = getenv(\"EXERCISE_THREADS\");\n\tif(init_threads_str) {\n\t\tinit_threads = atoi(init_threads_str);\n\t}\n\toflux::RunTimeConfiguration rtc = {\n\t\t 1024*1024 \/\/ stack size\n\t\t, init_threads \/\/ initial threads (ignored really)\n\t\t, 64 \/\/ max threads\n\t\t, 0 \/\/ max detached\n\t\t, 0 \/\/ thread collection threshold\n\t\t, 1000 \/\/ thread collection sample period (every N node execs)\n\t\t, argv[1] \/\/ XML file\n\t\t, NULL \/\/ temporary\n\t\t, \"xml\" \/\/ xml subdir for plugins\n\t\t, \"lib\" \/\/ lib subdir for plugins\n\t\t, NULL\n\t\t, init_atomic_maps\n\t\t};\n\toflux::logging::toStream(std::cout); \n\toflux_log_info(\" exercise::max_nsec_wait is %ld\\n\", oflux::flow::exercise::max_nsec_wait);\n\toflux::EnvironmentVar env(oflux::runtime::Factory::classic);\n\toflux::flow::ExerciseFunctionMaps ffmaps(env.runtime_number == 4);\n\tatomic_set = ffmaps.atomic_set();\n\trtc.flow_maps = &ffmaps;\n\ttheRT.reset(oflux::runtime::Factory::create(env.runtime_number, rtc));\n\tflow = theRT->flow();\n\toflux::flow::exercise::AtomicAbstract::P atomic_array[atomic_set->size()+1];\n\t_atomic_array = &atomic_array[0];\n\tatomic_set->fill(atomic_array);\n\tsignal(SIGHUP,handlesighup);\n\tif(!env.nostart) {\n\t\ttheRT->start();\n\t}\n\ttheRT.reset(); \/\/ force deletion of the runtime\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/\r\n\/\/ Copyright 2014, 2015 Razer Inc.\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, software\r\n\/\/ 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\r\n#include \"OSVRPrivatePCH.h\"\r\n\r\n#include \"OSVRInterfaceCollection.h\"\r\n#include \"OSVREntryPoint.h\"\r\n\r\nOSVR_ClientContext osvrClientContext(nullptr);\r\n\r\nOSVREntryPoint::OSVREntryPoint()\r\n{\r\n\tosvrClientContext = osvrClientInit(\"OSVR Unreal Engine 4 Plugin\");\r\n\r\n\tInterfaceCollection = MakeShareable(new OSVRInterfaceCollection(\r\n\t\tosvrClientContext\r\n\t\t));\r\n}\r\n\r\nOSVREntryPoint::~OSVREntryPoint()\r\n{\r\n\tInterfaceCollection = nullptr;\r\n\r\n\tosvrClientShutdown(osvrClientContext);\r\n}\r\n\r\nvoid OSVREntryPoint::Tick(float DeltaTime)\r\n{\r\n\tosvrClientUpdate(osvrClientContext);\r\n}\r\n\r\nOSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()\r\n{\r\n\treturn InterfaceCollection.Get();\r\n}\r\nSmall change to the application identifier.\/\/\r\n\/\/ Copyright 2014, 2015 Razer Inc.\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, software\r\n\/\/ 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\r\n#include \"OSVRPrivatePCH.h\"\r\n\r\n#include \"OSVRInterfaceCollection.h\"\r\n#include \"OSVREntryPoint.h\"\r\n\r\nOSVR_ClientContext osvrClientContext(nullptr);\r\n\r\nOSVREntryPoint::OSVREntryPoint()\r\n{\r\n\tosvrClientContext = osvrClientInit(\"com.osvr.unreal.plugin\");\r\n\r\n\tInterfaceCollection = MakeShareable(new OSVRInterfaceCollection(\r\n\t\tosvrClientContext\r\n\t\t));\r\n}\r\n\r\nOSVREntryPoint::~OSVREntryPoint()\r\n{\r\n\tInterfaceCollection = nullptr;\r\n\r\n\tosvrClientShutdown(osvrClientContext);\r\n}\r\n\r\nvoid OSVREntryPoint::Tick(float DeltaTime)\r\n{\r\n\tosvrClientUpdate(osvrClientContext);\r\n}\r\n\r\nOSVRInterfaceCollection* OSVREntryPoint::GetInterfaceCollection()\r\n{\r\n\treturn InterfaceCollection.Get();\r\n}\r\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 \"sdd\/sdd.hh\"\n#include \"sdd\/tools\/size.hh\"\n#include \"sdd\/tools\/nodes.hh\"\n#include \"sdd\/tools\/arcs.hh\"\n#include \"sdd\/tools\/sequences.hh\"\n#include \"sdd\/tools\/dot\/sdd.hh\"\n\nusing namespace std;\n\nstatic bool finish = false;\n\nvoid\nhandler(int s)\n{\n finish = true;\n}\n\nstruct conf\n : public sdd::flat_set_default_configuration\n{\n using Identifier = unsigned int;\n using Values = sdd::values::flat_set;\n};\nusing SDD = sdd::SDD;\nusing values_type = conf::Values;\n\nint\nmain (int argc, const char** argv)\n{\n const auto subsize = 100;\n if (argc == 0)\n {\n cerr << \"sdd-stream \" << endl;\n return 1;\n }\n\n struct sigaction sigIntHandler;\n sigIntHandler.sa_handler = handler;\n sigemptyset (&sigIntHandler.sa_mask);\n sigIntHandler.sa_flags = 0;\n sigaction (SIGINT, &sigIntHandler, NULL);\n\n size_t max_length = stoi (argv [1]);\n\n vector collections;\n collections.reserve (subsize);\n\n conf c;\n c.final_cleanup = false; \/\/ don't cleanup memory on manager scope exit.\n c.hom_cache_size = 2; \/\/ we don't use homomorphisms.\n c.hom_unique_table_size = 2; \/\/ we don't use homomorphisms.\n\/\/ c.sdd_intersection_cache_size = 16000000;\n\/\/ c.sdd_sum_cache_size = 16000000;\n\/\/ c.sdd_difference_cache_size = 16000000;\n\/\/ c.sdd_unique_table_size = 10000000;\n auto manager = sdd::init(c);\n\n \/\/ \/\/ Construct the SDD order: we need one level per letter.\n \/\/ vector v (max_length);\n \/\/ iota (v.begin(), v.end(), 0);\n sdd::order_builder ob;\n const sdd::order order {sdd::order_builder ()};\n\n set characters;\n\n size_t inserted = 0;\n size_t dropped = 0;\n size_t total = 0;\n size_t sum_inserted = 0;\n string line;\n line.reserve (80);\n string sequence;\n sequence.reserve (max_length);\n cout << \"\\033[s\" << flush;\n while (getline (cin, line))\n {\n if (line [0] == '>')\n { \/\/ starting a new sequence:\n total += 1;\n if (sequence.size () != 0)\n {\n if (sequence.size () <= max_length)\n {\n SDD word = SDD(0, SDD::eol::flat, sdd::one());\n for (auto i = 0u; i < sequence.size(); ++i)\n {\n characters.insert (sequence[sequence.size() - i - 1]);\n word = SDD(0, {sequence[sequence.size() - i - 1]}, word);\n }\n collections.emplace_back(word);\n inserted += 1;\n sum_inserted += sequence.size();\n }\n else\n dropped += 1;\n sequence.clear ();\n }\n if (finish)\n break;\n }\n else\n sequence += line;\n if (collections.size () == subsize)\n {\n const auto result = sdd::sum ( collections.cbegin()\n , collections.cend() );\n collections.clear ();\n collections.push_back (result);\n }\n if (total % 200 == 0)\n cout << \"\\033[u\"\n << \"inserted: \" << inserted\n << \" \/ \"\n << \"dropped: \" << dropped\n << \" \/ \"\n << \"total: \" << total\n << flush;\n }\n if (sequence.size () <= max_length)\n {\n SDD word = SDD(0, SDD::eol::flat, sdd::one());\n for (auto i = 0u; i < line.size(); ++i)\n {\n word = SDD(0, {line[line.size() - i - 1]}, word);\n }\n collections.emplace_back(word);\n inserted += 1;\n sum_inserted += sequence.size();\n }\n else\n dropped += 1;\n cout << \"\\033[u\"\n << \"inserted: \" << inserted\n << \" \/ \"\n << \"dropped: \" << dropped\n << \" \/ \"\n << \"total: \" << total\n << endl;\n const auto result = sdd::sum ( collections.cbegin()\n , collections.cend() );\n\n cout << \"# Characters: \" << characters.size() << endl;\n cout << \"# Words: \" << result.size() << endl;\n const auto nodes = sdd::tools::nodes(result).first;\n cout << \"# Nodes: \" << nodes << endl;\n const auto size = sdd::tools::size(result);\n cout << \"Size: \" << ceil(static_cast(size) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n cout << \"Average node size: \" << (size \/ nodes) << \" bytes\" << endl;\n\n auto frequency = sdd::tools::arcs(result);\n auto sequences = sdd::tools::sequences(result);\n\n \/\/ BUG here!\n size_t nb = 0;\n for (auto& p : sequences)\n {\n\/\/ cout << \" == \" << p.first << \" => \" << p.second << endl;\n nb += p.first * p.second;\n }\n cout << \"!!!!! nb: \" << nb << \" =?= \" << frequency[1].first << endl;\n\n size_t max_children = 0;\n for (auto& p : frequency)\n {\n max_children = max_children < p.first\n ? p.first\n : max_children;\n }\n size_t expected = 0;\n size_t bitfield_size = ceil(static_cast(characters.size())\/8);\n size_t base_size = bitfield_size + 4 + 8 + 1;\n cout << \"Bit field size: \" << bitfield_size << \" bytes\" << endl;\n cout << \"Base node size: \" << base_size << \" bytes\" << endl;\n const size_t average_length = 100;\n const size_t bitsize = ceil(log2(characters.size()));\n cout << \"Bitsize: \" << bitsize << endl;\n for (size_t i = 0; i <= max_children; ++i)\n {\n if (frequency[i].first == 0)\n continue;\n cout << left << setw(3) << i\n << \" => \"\n << left << setw(10) << frequency[i].first\n << right\n << endl;\n size_t subresult = 0;\n size_t subsize = 0;\n if (i == 1)\n {\n size_t subcount = 0;\n for (const auto& p : sequences)\n {\n size_t size = base_size + 8 + ceil(static_cast(bitsize)* p.first \/ 8);\n size += size % 8 == 0\n ? 0\n : 8 - (size % 8);\n\n size *= p.second;\n subresult += size;\n subsize += p.second;\n subcount += p.second * p.first;\n \/*\n cout << \" For Length: \" << p.first\n << endl\n << \" # Sequences: \" << p.second\n << endl\n << \" String size: \" << ceil((static_cast(bitsize) * p.first) \/ 8)\n << \" bytes\"\n << endl\n << \" Size: \" << size\n << \" bytes\"\n << endl\n << \" Average size: \" << (size \/ p.second)\n << \" bytes\"\n << endl;\n *\/\n }\n subresult += (base_size + 8 + ceil(static_cast(bitsize) \/ 8)) * (frequency[1].first - subcount);\n cout << \" Subcount: \" << subcount << endl;\n cout << \" Frequency: \" << frequency[i].first << endl;\n size_t average = 150;\n size_t should_size =\n (base_size + 8 + ceil(static_cast(bitsize)*average \/ 8))\n * frequency[i].first \/ average;\n cout << \" Sould be: \"\n << should_size\n << \" bytes\"\n << endl;\n }\n else\n {\n size_t size = base_size + i * 8;\n size += size % 8 == 0\n ? 0\n : 8 - (size % 8);\n subresult = size * frequency[i].first;\n subsize = frequency[i].first;\n }\n cout << \" Total: \" << subresult << \" bytes\"\n << endl\n << \" Average: \" << (subresult \/ subsize) << \" bytes\"\n << endl;\n expected += subresult;\n }\n cout << \"Expected size: \" << ceil(static_cast(expected) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n cout << \"Original size: \" << ceil(static_cast(sum_inserted) \/ 1024 \/ 1024)\n << \" Mbytes\"\n << endl\n << \"Binary size: \" << (sum_inserted * bitsize \/ 8 \/ 1024 \/ 1024 + 1)\n << \" Mbytes\"\n << endl;\n\n if (nodes <= 5000)\n {\n ofstream of (\"machin.dot\");\n of << sdd::tools::dot (result, order);\n }\n\n return 0;\n}\nAdd min-length argument.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"sdd\/sdd.hh\"\n#include \"sdd\/tools\/size.hh\"\n#include \"sdd\/tools\/nodes.hh\"\n#include \"sdd\/tools\/arcs.hh\"\n#include \"sdd\/tools\/sequences.hh\"\n#include \"sdd\/tools\/dot\/sdd.hh\"\n\nusing namespace std;\n\nstatic bool finish = false;\n\nvoid\nhandler(int s)\n{\n finish = true;\n}\n\nstruct conf\n : public sdd::flat_set_default_configuration\n{\n using Identifier = unsigned int;\n using Values = sdd::values::flat_set;\n};\nusing SDD = sdd::SDD;\nusing values_type = conf::Values;\n\nint\nmain (int argc, const char** argv)\n{\n const auto subsize = 100;\n if (argc == 0)\n {\n cerr << \"sdd-stream \" << endl;\n return 1;\n }\n\n struct sigaction sigIntHandler;\n sigIntHandler.sa_handler = handler;\n sigemptyset (&sigIntHandler.sa_mask);\n sigIntHandler.sa_flags = 0;\n sigaction (SIGINT, &sigIntHandler, NULL);\n\n size_t min_length = stoi (argv [1]);\n size_t max_length = stoi (argv [2]);\n\n vector collections;\n collections.reserve (subsize);\n\n conf c;\n c.final_cleanup = false; \/\/ don't cleanup memory on manager scope exit.\n c.hom_cache_size = 2; \/\/ we don't use homomorphisms.\n c.hom_unique_table_size = 2; \/\/ we don't use homomorphisms.\n\/\/ c.sdd_intersection_cache_size = 16000000;\n\/\/ c.sdd_sum_cache_size = 16000000;\n\/\/ c.sdd_difference_cache_size = 16000000;\n\/\/ c.sdd_unique_table_size = 10000000;\n auto manager = sdd::init(c);\n\n \/\/ \/\/ Construct the SDD order: we need one level per letter.\n \/\/ vector v (max_length);\n \/\/ iota (v.begin(), v.end(), 0);\n sdd::order_builder ob;\n const sdd::order order {sdd::order_builder ()};\n\n set characters;\n\n size_t inserted = 0;\n size_t dropped = 0;\n size_t total = 0;\n size_t sum_inserted = 0;\n string line;\n line.reserve (80);\n string sequence;\n sequence.reserve (max_length);\n cout << \"\\033[s\" << flush;\n while (getline (cin, line))\n {\n if (line [0] == '>')\n { \/\/ starting a new sequence:\n total += 1;\n if (sequence.size () != 0)\n {\n if ((sequence.size() >= min_length) && (sequence.size () <= max_length))\n {\n SDD word = SDD(0, SDD::eol::flat, sdd::one());\n for (auto i = 0u; i < sequence.size(); ++i)\n {\n characters.insert (sequence[sequence.size() - i - 1]);\n word = SDD(0, {sequence[sequence.size() - i - 1]}, word);\n }\n collections.emplace_back(word);\n inserted += 1;\n sum_inserted += sequence.size();\n }\n else\n dropped += 1;\n sequence.clear ();\n }\n if (finish)\n break;\n }\n else\n sequence += line;\n if (collections.size () == subsize)\n {\n const auto result = sdd::sum ( collections.cbegin()\n , collections.cend() );\n collections.clear ();\n collections.push_back (result);\n }\n if (total % 200 == 0)\n cout << \"\\033[u\"\n << \"inserted: \" << inserted\n << \" \/ \"\n << \"dropped: \" << dropped\n << \" \/ \"\n << \"total: \" << total\n << flush;\n }\n if ((sequence.size() >= min_length) && (sequence.size () <= max_length))\n {\n SDD word = SDD(0, SDD::eol::flat, sdd::one());\n for (auto i = 0u; i < line.size(); ++i)\n {\n word = SDD(0, {line[line.size() - i - 1]}, word);\n }\n collections.emplace_back(word);\n inserted += 1;\n sum_inserted += sequence.size();\n }\n else\n dropped += 1;\n cout << \"\\033[u\"\n << \"inserted: \" << inserted\n << \" \/ \"\n << \"dropped: \" << dropped\n << \" \/ \"\n << \"total: \" << total\n << endl;\n const auto result = sdd::sum ( collections.cbegin()\n , collections.cend() );\n\n cout << \"# Characters: \" << characters.size() << endl;\n cout << \"# Words: \" << result.size() << endl;\n const auto nodes = sdd::tools::nodes(result).first;\n cout << \"# Nodes: \" << nodes << endl;\n const auto size = sdd::tools::size(result);\n cout << \"Size: \" << ceil(static_cast(size) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n cout << \"Average node size: \" << (size \/ nodes) << \" bytes\" << endl;\n\n auto frequency = sdd::tools::arcs(result);\n auto sequences = sdd::tools::sequences(result);\n\n \/\/ BUG here!\n size_t nb = 0;\n for (auto& p : sequences)\n {\n\/\/ cout << \" == \" << p.first << \" => \" << p.second << endl;\n nb += p.first * p.second;\n }\n cout << \"!!!!! nb: \" << nb << \" =?= \" << frequency[1].first << endl;\n\n size_t max_children = 0;\n for (auto& p : frequency)\n {\n max_children = max_children < p.first\n ? p.first\n : max_children;\n }\n size_t expected = 0;\n size_t bitfield_size = ceil(static_cast(characters.size())\/8);\n size_t base_size = bitfield_size + 4 + 8 + 1;\n cout << \"Bit field size: \" << bitfield_size << \" bytes\" << endl;\n cout << \"Base node size: \" << base_size << \" bytes\" << endl;\n const size_t average_length = 100;\n const size_t bitsize = ceil(log2(characters.size()));\n cout << \"Bitsize: \" << bitsize << endl;\n for (size_t i = 0; i <= max_children; ++i)\n {\n if (frequency[i].first == 0)\n continue;\n cout << left << setw(3) << i\n << \" => \"\n << left << setw(10) << frequency[i].first\n << right\n << endl;\n size_t subresult = 0;\n size_t subsize = 0;\n if (i == 1)\n {\n size_t subcount = 0;\n for (const auto& p : sequences)\n {\n size_t size = base_size + 8 + ceil(static_cast(bitsize)* p.first \/ 8);\n size += size % 8 == 0\n ? 0\n : 8 - (size % 8);\n\n size *= p.second;\n subresult += size;\n subsize += p.second;\n subcount += p.second * p.first;\n \/*\n cout << \" For Length: \" << p.first\n << endl\n << \" # Sequences: \" << p.second\n << endl\n << \" String size: \" << ceil((static_cast(bitsize) * p.first) \/ 8)\n << \" bytes\"\n << endl\n << \" Size: \" << size\n << \" bytes\"\n << endl\n << \" Average size: \" << (size \/ p.second)\n << \" bytes\"\n << endl;\n *\/\n }\n subresult += (base_size + 8 + ceil(static_cast(bitsize) \/ 8)) * (frequency[1].first - subcount);\n cout << \" Subcount: \" << subcount << endl;\n cout << \" Frequency: \" << frequency[i].first << endl;\n size_t average = 150;\n size_t should_size =\n (base_size + 8 + ceil(static_cast(bitsize)*average \/ 8))\n * frequency[i].first \/ average;\n cout << \" Sould be: \"\n << should_size\n << \" bytes\"\n << endl;\n }\n else\n {\n size_t size = base_size + i * 8;\n size += size % 8 == 0\n ? 0\n : 8 - (size % 8);\n subresult = size * frequency[i].first;\n subsize = frequency[i].first;\n }\n cout << \" Total: \" << subresult << \" bytes\"\n << endl\n << \" Average: \" << (subresult \/ subsize) << \" bytes\"\n << endl;\n expected += subresult;\n }\n cout << \"Expected size: \" << ceil(static_cast(expected) \/ 1024 \/ 1024) << \" Mbytes\" << endl;\n cout << \"Original size: \" << ceil(static_cast(sum_inserted) \/ 1024 \/ 1024)\n << \" Mbytes\"\n << endl\n << \"Binary size: \" << (sum_inserted * bitsize \/ 8 \/ 1024 \/ 1024 + 1)\n << \" Mbytes\"\n << endl;\n\n if (nodes <= 5000)\n {\n ofstream of (\"machin.dot\");\n of << sdd::tools::dot (result, order);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#ifndef POSEIDON_SOCKET_ABSTRACT_SOCKET_\n#define POSEIDON_SOCKET_ABSTRACT_SOCKET_\n\n#include \"..\/fwd.hpp\"\n#include \"enums.hpp\"\n#include \"socket_address.hpp\"\n\nnamespace poseidon {\n\nclass Abstract_Socket\n : public ::asteria::Rcfwd\n {\n friend Network_Driver;\n\n protected:\n unique_FD m_fd;\n atomic_relaxed m_resident = { false }; \/\/ don't delete if orphaned\n\n \/\/ These are used by network driver.\n uint64_t m_epoll_data = UINT64_MAX;\n uint32_t m_epoll_events = UINT32_MAX;\n\n \/\/ This the local address. It is initialized upon the first request.\n mutable once_flag m_local_addr_once;\n mutable Socket_Address m_local_addr;\n\n \/\/ These are I\/O components.\n mutable simple_mutex m_io_mutex;\n Connection_State m_connection_state = connection_state_empty;\n linear_buffer m_rqueue;\n linear_buffer m_wqueue;\n\n protected:\n \/\/ Adopts a foreign or accepted socket.\n explicit\n Abstract_Socket(unique_FD&& fd);\n\n \/\/ Creates a new non-blocking socket.\n explicit\n Abstract_Socket(::sa_family_t family, int type, int protocol = 0);\n\n protected:\n \/\/ The network driver notifies incoming data via this callback.\n \/\/ `lock` shall lock `*this` after the call if locking is supported.\n \/\/ Please mind thread safety, as this function is called by the network thread.\n virtual\n IO_Result\n do_socket_on_poll_read(simple_mutex::unique_lock& lock)\n = 0;\n\n \/\/ This function shall return the number of bytes that are pending for writing.\n \/\/ `lock` shall lock `*this` after the call if locking is supported.\n virtual\n size_t\n do_write_queue_size(simple_mutex::unique_lock& lock) const\n = 0;\n\n \/\/ The network driver notifies possibility of outgoing data via this callback.\n \/\/ `lock` shall lock `*this` after the call if locking is supported.\n \/\/ Please mind thread safety, as this function is called by the network thread.\n virtual\n IO_Result\n do_socket_on_poll_write(simple_mutex::unique_lock& lock)\n = 0;\n\n \/\/ The network driver notifies closure via this callback.\n \/\/ `err` is zero for graceful shutdown.\n \/\/ Please mind thread safety, as this function is called by the network thread.\n virtual\n void\n do_socket_on_poll_close(int err)\n = 0;\n\n public:\n ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Socket);\n\n \/\/ Prevents this socket from being deleted if network driver holds its last\n \/\/ reference.\n bool\n set_resident(bool value = true) noexcept\n { return this->m_resident.exchange(value); }\n\n \/\/ Returns the stream descriptor.\n \/\/ This is used to query and adjust stream flags. You shall not perform I\/O\n \/\/ operations on it.\n ROCKET_PURE\n int\n get_fd() const noexcept\n { return this->m_fd; }\n\n \/\/ Causes abnormal termination of this stream.\n \/\/ Any data that have not been delivered to the other peer are discarded.\n \/\/ The other peer is likely to see a 'connection reset by peer' error.\n void\n kill() noexcept;\n\n \/\/ Gets the (bound) address of the local peer.\n const Socket_Address&\n get_local_address() const;\n };\n\n} \/\/ namespace poseidon\n\n#endif\nabstract_socket: Make private data private\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#ifndef POSEIDON_SOCKET_ABSTRACT_SOCKET_\n#define POSEIDON_SOCKET_ABSTRACT_SOCKET_\n\n#include \"..\/fwd.hpp\"\n#include \"enums.hpp\"\n#include \"socket_address.hpp\"\n\nnamespace poseidon {\n\nclass Abstract_Socket\n : public ::asteria::Rcfwd\n {\n friend Network_Driver;\n\n private:\n unique_FD m_fd;\n atomic_relaxed m_resident = { false }; \/\/ don't delete if orphaned\n\n \/\/ These are used by network driver.\n uint64_t m_epoll_data = UINT64_MAX;\n uint32_t m_epoll_events = UINT32_MAX;\n\n \/\/ This the local address. It is initialized upon the first request.\n mutable once_flag m_local_addr_once;\n mutable Socket_Address m_local_addr;\n\n protected:\n \/\/ These are I\/O components.\n mutable simple_mutex m_io_mutex;\n Connection_State m_connection_state = connection_state_empty;\n linear_buffer m_rqueue;\n linear_buffer m_wqueue;\n\n protected:\n \/\/ Adopts a foreign or accepted socket.\n explicit\n Abstract_Socket(unique_FD&& fd);\n\n \/\/ Creates a new non-blocking socket.\n explicit\n Abstract_Socket(::sa_family_t family, int type, int protocol = 0);\n\n protected:\n \/\/ The network driver notifies incoming data via this callback.\n \/\/ `lock` shall lock `*this` after the call if locking is supported.\n \/\/ Please mind thread safety, as this function is called by the network thread.\n virtual\n IO_Result\n do_socket_on_poll_read(simple_mutex::unique_lock& lock)\n = 0;\n\n \/\/ This function shall return the number of bytes that are pending for writing.\n \/\/ `lock` shall lock `*this` after the call if locking is supported.\n virtual\n size_t\n do_write_queue_size(simple_mutex::unique_lock& lock) const\n = 0;\n\n \/\/ The network driver notifies possibility of outgoing data via this callback.\n \/\/ `lock` shall lock `*this` after the call if locking is supported.\n \/\/ Please mind thread safety, as this function is called by the network thread.\n virtual\n IO_Result\n do_socket_on_poll_write(simple_mutex::unique_lock& lock)\n = 0;\n\n \/\/ The network driver notifies closure via this callback.\n \/\/ `err` is zero for graceful shutdown.\n \/\/ Please mind thread safety, as this function is called by the network thread.\n virtual\n void\n do_socket_on_poll_close(int err)\n = 0;\n\n public:\n ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Socket);\n\n \/\/ Prevents this socket from being deleted if network driver holds its last\n \/\/ reference.\n bool\n set_resident(bool value = true) noexcept\n { return this->m_resident.exchange(value); }\n\n \/\/ Returns the stream descriptor.\n \/\/ This is used to query and adjust stream flags. You shall not perform I\/O\n \/\/ operations on it.\n ROCKET_PURE\n int\n get_fd() const noexcept\n { return this->m_fd; }\n\n \/\/ Causes abnormal termination of this stream.\n \/\/ Any data that have not been delivered to the other peer are discarded.\n \/\/ The other peer is likely to see a 'connection reset by peer' error.\n void\n kill() noexcept;\n\n \/\/ Gets the (bound) address of the local peer.\n const Socket_Address&\n get_local_address() const;\n };\n\n} \/\/ namespace poseidon\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2011-2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fnordmetric {\nnamespace query {\n\nvoid eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() == rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() == rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __eq_symbol(\"eq\", &eqExpr);\n\nvoid andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() && rhs->getBool());\n return;\n }\n }\n\n assert(0);\n}\n\nstatic SymbolTableEntry __and_symbol(\"and\", &andExpr);\n\nvoid orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() || rhs->getBool());\n return;\n }\n }\n\n assert(0);\n}\n\nstatic SymbolTableEntry __or_symbol(\"or\", &orExpr);\n\nvoid negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 1);\n SValue* val = argv;\n\n switch(val->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(val->getInteger() * -1);\n return;\n case SValue::T_FLOAT:\n *out = SValue(val->getFloat() * -1.0f);\n return;\n case SValue::T_BOOL:\n *out = SValue(!val->getBool());\n return;\n default:\n break;\n }\n\n assert(0);\n}\n\nstatic SymbolTableEntry __neg_symbol(\"neg\", &negExpr);\n\nvoid ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() < rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() < rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n assert(0);\n}\n\nstatic SymbolTableEntry __lt_symbol(\"lt\", <Expr);\n\nvoid gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() > rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() > rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n assert(0); \/\/ FIXPAUL\n}\n\nstatic SymbolTableEntry __gt_symbol(\"gt\", >Expr);\n\n}\n}\nboolean expressions...\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2011-2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fnordmetric {\nnamespace query {\n\nvoid eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() == rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() == rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n *out = SValue(*lhs == *rhs);\n}\n\nstatic SymbolTableEntry __eq_symbol(\"eq\", &eqExpr);\n\nvoid andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() && rhs->getBool());\n return;\n }\n }\n\n RAISE(util::RuntimeException, \"can't AND %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __and_symbol(\"and\", &andExpr);\n\nvoid orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() || rhs->getBool());\n return;\n }\n }\n\n RAISE(util::RuntimeException, \"can't OR %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __or_symbol(\"or\", &orExpr);\n\nvoid negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 1);\n SValue* val = argv;\n\n switch(val->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(val->getInteger() * -1);\n return;\n case SValue::T_FLOAT:\n *out = SValue(val->getFloat() * -1.0f);\n return;\n case SValue::T_BOOL:\n *out = SValue(!val->getBool());\n return;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't negate %s\",\n val->getTypeName());\n}\n\nstatic SymbolTableEntry __neg_symbol(\"neg\", &negExpr);\n\nvoid ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() < rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() < rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __lt_symbol(\"lt\", <Expr);\n\nvoid gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n assert(argc == 2);\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() > rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() > rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __gt_symbol(\"gt\", >Expr);\n\n}\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2011-2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fnordmetric {\nnamespace query {\n\nvoid eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for eq. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() == rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n if (lhs->getType() == SValue::T_STRING ||\n rhs->getType() == SValue::T_STRING) {\n *out = SValue(lhs->toString() == rhs->toString());\n return;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __eq_symbol(\"eq\", &eqExpr);\n\nvoid andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for and. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() && rhs->getBool());\n return;\n }\n }\n\n RAISE(util::RuntimeException, \"can't AND %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __and_symbol(\"and\", &andExpr);\n\nvoid orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for or. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() || rhs->getBool());\n return;\n }\n }\n\n RAISE(util::RuntimeException, \"can't OR %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __or_symbol(\"or\", &orExpr);\n\nvoid negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 1) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for neg. expected: 1, got: %i\", argc);\n }\n\n SValue* val = argv;\n\n switch(val->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(val->getInteger() * -1);\n return;\n case SValue::T_FLOAT:\n *out = SValue(val->getFloat() * -1.0f);\n return;\n case SValue::T_BOOL:\n *out = SValue(!val->getBool());\n return;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't negate %s\",\n val->getTypeName());\n}\n\nstatic SymbolTableEntry __neg_symbol(\"neg\", &negExpr);\n\nvoid ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for lt. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() < rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() < rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __lt_symbol(\"lt\", <Expr);\n\nvoid gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for gt. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_INTEGER:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() > rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getInteger() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->getType()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getFloat() > rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't ompare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __gt_symbol(\"gt\", >Expr);\n\n}\n}\nnumeric conversion in lt\/gt expressions\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2011-2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace fnordmetric {\nnamespace query {\n\nvoid eqExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for eq. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() == rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() == rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n if (lhs->getType() == SValue::T_STRING ||\n rhs->getType() == SValue::T_STRING) {\n *out = SValue(lhs->toString() == rhs->toString());\n return;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __eq_symbol(\"eq\", &eqExpr);\n\nvoid andExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for and. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() && rhs->getBool());\n return;\n }\n }\n\n RAISE(util::RuntimeException, \"can't AND %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __and_symbol(\"and\", &andExpr);\n\nvoid orExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for or. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->getType()) {\n case SValue::T_BOOL:\n switch(rhs->getType()) {\n case SValue::T_BOOL:\n *out = SValue(lhs->getBool() || rhs->getBool());\n return;\n }\n }\n\n RAISE(util::RuntimeException, \"can't OR %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __or_symbol(\"or\", &orExpr);\n\nvoid negExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 1) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for neg. expected: 1, got: %i\", argc);\n }\n\n SValue* val = argv;\n\n switch(val->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n *out = SValue(val->getInteger() * -1);\n return;\n case SValue::T_FLOAT:\n *out = SValue(val->getFloat() * -1.0f);\n return;\n case SValue::T_BOOL:\n *out = SValue(!val->getBool());\n return;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't negate %s\",\n val->getTypeName());\n}\n\nstatic SymbolTableEntry __neg_symbol(\"neg\", &negExpr);\n\nvoid ltExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for lt. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() < rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() < rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __lt_symbol(\"lt\", <Expr);\n\nvoid gtExpr(void* scratchpad, int argc, SValue* argv, SValue* out) {\n if (argc != 2) {\n RAISE(\n util::RuntimeException,\n \"wrong number of arguments for gt. expected: 2, got: %i\", argc);\n }\n\n SValue* lhs = argv;\n SValue* rhs = argv + 1;\n\n switch(lhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n *out = SValue(lhs->getInteger() > rhs->getInteger());\n return;\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n case SValue::T_FLOAT:\n switch(rhs->testTypeWithNumericConversion()) {\n case SValue::T_INTEGER:\n case SValue::T_FLOAT:\n *out = SValue(lhs->getFloat() > rhs->getFloat());\n return;\n default:\n break;\n }\n break;\n default:\n break;\n }\n\n RAISE(util::RuntimeException, \"can't compare %s with %s\",\n lhs->getTypeName(),\n rhs->getTypeName());\n}\n\nstatic SymbolTableEntry __gt_symbol(\"gt\", >Expr);\n\n}\n}\n<|endoftext|>"} {"text":"\n#include \"util\/zorba.h\"\n#include \"store\/naive\/qname_pool.h\"\n\nnamespace xqp\n{\n\nQNamePool* QNameImpl::theQNamePool = NULL;\n\/\/const xqp_unsignedLong QNamePool::MAX_CACHE_SIZE = 65536;\nconst float QNamePool::DEFAULT_LOAD_FACTOR = 0.6;\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ QNamePool \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nQNamePool::QNamePool(xqp_unsignedLong size) \n :\n theCache(new QNameImpl[size]),\n theCacheSize(size),\n theFirstFree(1),\n theNumFree(size - 1),\n theNumQNames(0),\n theHashTabSize(2 * size),\n theLoadFactor(DEFAULT_LOAD_FACTOR)\n{\n \/\/ Put all the preallocated slots in the free list of the cahce.\n for (xqp_unsignedLong i = 1; i < size - 1; i++)\n {\n theCache[i].theNextFree = i + 1;\n theCache[i].thePrevFree = i - 1;\n theCache[i].thePosition = i;\n }\n theCache[size-1].theNextFree = 0;\n theCache[size-1].thePrevFree = size - 2;\n theCache[size-1].thePosition = size - 1;\n\n \/\/ Allocate the hash table. Its initial size is double the size of theCache,\n \/\/ plus an inital 32 overflow entries.\n theHashTab.resize(theHashTabSize + 32);\n\n \/\/ Format the overflow area of theHashTab as a list of free entries\n HashEntry* lastentry = &theHashTab[theHashTabSize + 31];\n for (HashEntry* entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)\n entry->theNext = entry + 1;\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nQNamePool::~QNamePool() \n{\n#if 0\n xqp_unsignedLong n = theOverflow.size();\n for (xqp_unsignedLong i = 0; i < n; i++)\n {\n if (theOverflow[i] != NULL)\n delete theOverflow[i];\n }\n#else\n xqp_unsignedLong n = theHashTab.size();\n for (xqp_unsignedLong i = 0; i < n; i++)\n {\n if (theHashTab[i].theQName != NULL && theHashTab[i].theQName->isOverflow())\n ::delete theHashTab[i].theQName;\n }\n#endif\n\n if (theCache != NULL)\n {\n delete [] theCache;\n theCache = NULL;\n }\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nQNameImpl* QNamePool::insert(\n const char* ns,\n const char* pre,\n const char* ln)\n{\n QNameImpl* qn;\n\n HashEntry* entry = hash(ns, pre, ln);\n\n \/\/ If the qname is already in the pool, return a ptr to its containing slot.\n \/\/ If the slot is in the free list of the cache, it is first removed from\n \/\/ that list. \n if (entry->theQName != NULL)\n {\n qn = entry->theQName;\n\n if (qn->isInCache())\n {\n if (qn->theNextFree != 0)\n theCache[qn->theNextFree].thePrevFree = qn->thePrevFree;\n\n if (qn->thePrevFree != 0)\n {\n theCache[qn->thePrevFree].theNextFree = qn->theNextFree;\n }\n else if (theFirstFree == qn->thePosition)\n {\n theFirstFree = qn->theNextFree;\n }\n\n qn->theNextFree = qn->thePrevFree = 0;\n theNumFree--;\n }\n\n return qn;\n }\n\n \/\/ The qname is not in the pool.\n \/\/ Use the 1st slot from the free list of the cache to store the new qname.\n \/\/ The qname was is currently in that slot is removed from the cache.\n if (theFirstFree != 0)\n {\n qn = &theCache[theFirstFree];\n entry->theQName = qn;\n\n theFirstFree = qn->theNextFree;\n theCache[theFirstFree].thePrevFree = 0;\n\n if (!qn->theLocal.empty())\n unhash(qn->theNamespace.c_str(), qn->thePrefix.c_str(), qn->theLocal.c_str());\n\n qn->theNextFree = qn->thePrevFree = 0;\n qn->theNamespace = ns;\n qn->thePrefix = pre;\n qn->theLocal = ln;\n\n theNumFree--;\n\n return qn;\n }\n\n \/\/ The cache was full, so allocate a QNameItem from the heap.\n qn = new QNameImpl(ns, pre, ln);\n \/\/theOverflow.push_back(qn);\n entry->theQName = qn;\n return qn;\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid QNamePool::remove(QNameImpl* qn)\n{\n if (qn->get_refCount() > 0)\n return;\n\n if (qn->isInCache())\n {\n qn->theNextFree = theFirstFree;\n theCache[theFirstFree].thePrevFree = qn->thePosition;\n theFirstFree = qn->thePosition;\n theNumFree++;\n }\n else\n {\n \/\/ If all the pointers to QNameItems were smart pointers, we could leave\n \/\/ qn in the pool, and let the pool garbage-collect it later (if it still\n \/\/ unused). If however QNameItems may be referenced by regular pointers as\n \/\/ well, then qn must be removed from the pool and really deleted\n unhash(qn->getNamespace().c_str(),\n qn->getPrefix().c_str(),\n qn->getLocalName().c_str());\n\n \/\/std::vector::iterator it;\n \/\/it = theOverflow.begin() + qn->thePosition;\n \/\/theOverflow.erase(it);\n\n ::delete qn;\n }\n}\n\n\n\/*******************************************************************************\n Check if the given qname is already in the pool, and if so, return its hash\n entry. If not, allocate a new hash entry for it, and return it to the caller.\n********************************************************************************\/\nQNamePool::HashEntry*\nQNamePool::hash(const char* ns, const char* pre, const char* ln)\n{\n xqp_unsignedLong len;\n HashEntry* entry;\n HashEntry* lastentry;\n\n \/\/ Get ptr to the 1st entry of the hash bucket corresponding to the given qname\n xqp_unsignedLong hval = hashfun::h32(pre, hashfun::h32(ln, hashfun::h32(ns))) % theHashTabSize;\n entry = &theHashTab[ hval % theHashTabSize];\n\n \/\/ If the hash bucket is empty, its 1st entry is used to store the new qname.\n if (entry->isFree())\n {\n theNumQNames++;\n return entry;\n }\n\n \/\/ Search the hash bucket looking for the given qname.\n while (entry != NULL)\n {\n QNameImpl* qn = entry->theQName;\n\n len = qn->theLocal.bytes();\n if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)\n {\n lastentry = entry;\n entry = entry->theNext;\n continue;\n }\n\n len = qn->theNamespace.bytes();\n if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)\n {\n lastentry = entry;\n entry = entry->theNext;\n continue;\n }\n \n len = qn->thePrefix.bytes();\n if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)\n {\n lastentry = entry;\n entry = entry->theNext;\n continue;\n }\n\n return entry;\n }\n\n \/\/ The qname was not found.\n\n \/\/ Double the size of hash table if it is more than 60% full. \n if (theNumQNames > theHashTabSize * theLoadFactor)\n resizeHashTab();\n\n \/\/ Get an entry from the free list in the overflow section of the hash teble\n \/\/ If no free entry exists, a new entry is appended into the hash table. \n if (theHashTab[theHashTabSize].theNext == 0)\n {\n theHashTab.push_back(HashEntry());\n entry = &theHashTab[theHashTab.size() - 1];\n lastentry->theNext = entry;\n }\n else\n {\n entry = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = entry->theNext;\n lastentry->theNext = entry;\n entry->theNext = NULL;\n }\n\n theNumQNames++;\n\n return entry;\n}\n\n\n\/*******************************************************************************\n Remove the given qname from the hash table, if it is found there.\n********************************************************************************\/\nvoid QNamePool::unhash(const char* ns, const char* pre, const char* ln)\n{\n xqp_unsignedLong len;\n HashEntry* entry;\n HashEntry* preventry = NULL;\n\n \/\/ Get ptr to the 1st entry of the hash bucket corresponding to the given qname\n xqp_unsignedLong hval = hashfun::h32(pre, hashfun::h32(ln, hashfun::h32(ns))) % theHashTabSize;\n entry = &theHashTab[ hval % theHashTabSize];\n\n \/\/ If the hash bucket is empty, the qname is not in the hash table.\n if (entry->isFree())\n return;\n\n \/\/ Search the hash bucket looking for the given qname.\n while (entry != NULL)\n {\n QNameImpl* qn = entry->theQName;\n\n len = qn->theLocal.bytes();\n if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)\n {\n preventry = entry;\n entry = entry->theNext;\n continue;\n }\n\n len = qn->theNamespace.bytes();\n if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)\n {\n preventry = entry;\n entry = entry->theNext;\n continue;\n }\n \n len = qn->thePrefix.bytes();\n if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)\n {\n preventry = entry;\n entry = entry->theNext;\n continue;\n }\n\n \/\/ Found the qname in the current entry. Must remove the entry from the\n \/\/ hash bucket and add it to the free list.\n if (preventry != NULL)\n {\n preventry->theNext = entry->theNext;\n entry->theQName = NULL;\n entry->theNext = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = entry;\n }\n else if (entry->theNext != NULL)\n {\n HashEntry* nextentry = entry->theNext;\n *entry = *nextentry;\n nextentry->theQName = NULL;\n nextentry->theNext = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = nextentry;\n }\n else\n {\n entry->theQName = NULL;\n }\n\n theNumQNames--;\n\n return;\n }\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid QNamePool::resizeHashTab()\n{\n HashEntry* entry;\n HashEntry* lastentry;\n\n \/\/ Make a copy of theHashTab, and then resize it to double theHashTabSize\n std::vector oldTab = theHashTab;\n xqp_unsignedLong oldsize = oldTab.size();\n\n theHashTabSize <<= 1;\n\n theHashTab.clear();\n theHashTab.resize(theHashTabSize + 32);\n\n \/\/ Format the overflow area of theHashTab as a list of free entries\n lastentry = &theHashTab[theHashTabSize + 31];\n for (entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)\n entry->theNext = entry + 1;\n \n \/\/ Now rehash every entry\n for (xqp_unsignedLong i = 0; i < oldsize; i++)\n {\n QNameImpl* qn = oldTab[i].theQName;\n\n xqp_unsignedLong h = hashfun::h32(qn->thePrefix.c_str(),\n hashfun::h32(qn->theLocal.c_str(),\n hashfun::h32(qn->theNamespace.c_str())));\n entry = &theHashTab[h % theHashTabSize];\n\n if (!entry->isFree())\n {\n \/\/ Go to the last entry of the current bucket\n HashEntry* lastentry = entry;\n while (lastentry->theNext != NULL)\n lastentry = lastentry->theNext;\n\n \/\/ Get an entry from the free list in the overflow section of the hash\n \/\/ table. If no free entry exists, a new entry is appended into the table.\n if (theHashTab[theHashTabSize].theNext == 0)\n {\n theHashTab.push_back(HashEntry());\n entry = &theHashTab[theHashTab.size() - 1];\n lastentry->theNext = entry;\n }\n else\n {\n entry = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = entry->theNext;\n lastentry->theNext = entry;\n entry->theNext = NULL;\n }\n }\n\n entry->theQName = qn;\n }\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ QNameItem \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nQNameImpl::QNameImpl(\n const xqp_string& ns,\n const xqp_string& pre,\n const xqp_string& local)\n :\n theNamespace(ns),\n thePrefix (pre),\n theLocal(local),\n theNextFree(0),\n thePrevFree(0)\n{\n}\n\n\nQNameImpl::QNameImpl(\n const char* ns,\n const char* pre,\n const char* local)\n :\n theNamespace(ns),\n thePrefix (pre),\n theLocal(local),\n theNextFree(0),\n thePrevFree(0)\n{\n}\n\n\nvoid QNameImpl::setQNamePool(QNamePool* p)\n{\n theQNamePool = p;\n}\n\n\nvoid QNameImpl::free()\n{\n getQNamePool()->remove(this);\n}\n\n\nqnamekey_t QNameImpl::getQNameKey( ) const\n{\n return Item::createQNameKey(theNamespace, thePrefix, theLocal);\n}\n\n\nItem_t QNameImpl::getAtomizationValue( ) const\n{\n return zorba::getItemFactory()->createQName(theNamespace, thePrefix, theLocal).get_ptr();\n}\n\n\nbool QNameImpl::equals(Item_t item) const\n{\n return (this == item.get_ptr() ||\n (item->getNamespace() == theNamespace &&\n item->getLocalName() == theLocal));\n}\n\n\nItem_t QNameImpl::getEBV( ) const\n{\n ZorbaErrorAlerts::error_alert (\n error_messages::FORG0006_INVALID_ARGUMENT_TYPE,\n\t\t error_messages::RUNTIME_ERROR,\n\t\t NULL,\n\t\t false,\n\t\t \"Effective Boolean Value is not defined for QName!\");\n return NULL;\n}\n\n\nxqp_string QNameImpl::getStringProperty( ) const\n{\n return thePrefix != \"\" ? thePrefix + \":\" + theLocal : theLocal;\n}\n\n\nxqp_string QNameImpl::show() const\n{\n return \"xs:qname(\" + theNamespace + \",\" + thePrefix + \",\" + theLocal + \")\";\n}\n\n}\ntiny (?) optimizations in qnamae pool constructor\/desctructor\n#include \"util\/zorba.h\"\n#include \"store\/naive\/qname_pool.h\"\n\nnamespace xqp\n{\n\nQNamePool* QNameImpl::theQNamePool = NULL;\n\nconst float QNamePool::DEFAULT_LOAD_FACTOR = 0.6;\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ QNamePool \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nQNamePool::QNamePool(xqp_unsignedLong size) \n :\n theCache(new QNameImpl[size]),\n theCacheSize(size),\n theFirstFree(1),\n theNumFree(size - 1),\n theNumQNames(0),\n theHashTabSize(2 * size),\n theLoadFactor(DEFAULT_LOAD_FACTOR)\n{\n \/\/ Put all the preallocated slots in the free list of the cahce.\n QNameImpl* qn = &theCache[1];\n QNameImpl* last = qn + size - 1;\n\n for (xqp_unsignedLong i = 1; qn < last; qn++, i++)\n {\n qn->theNextFree = i + 1;\n qn->thePrevFree = i - 1;\n qn->thePosition = i;\n }\n qn->theNextFree = 0;\n\n \/\/ Allocate the hash table. Its initial size is double the size of theCache,\n \/\/ plus an inital 32 overflow entries.\n theHashTab.resize(theHashTabSize + 32);\n\n \/\/ Format the overflow area of theHashTab as a list of free entries\n HashEntry* lastentry = &theHashTab[theHashTabSize + 31];\n for (HashEntry* entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)\n entry->theNext = entry + 1;\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nQNamePool::~QNamePool() \n{\n#if 0\n xqp_unsignedLong n = theOverflow.size();\n for (xqp_unsignedLong i = 0; i < n; i++)\n {\n if (theOverflow[i] != NULL)\n delete theOverflow[i];\n }\n#else\n xqp_unsignedLong n = theHashTab.size();\n for (xqp_unsignedLong i = 0; i < n; i++)\n {\n if (theHashTab[i].theQName != NULL && theHashTab[i].theQName->isOverflow())\n ::delete theHashTab[i].theQName;\n }\n#endif\n\n if (theCache != NULL)\n {\n delete [] theCache;\n theCache = NULL;\n }\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nQNameImpl* QNamePool::insert(\n const char* ns,\n const char* pre,\n const char* ln)\n{\n QNameImpl* qn;\n\n HashEntry* entry = hash(ns, pre, ln);\n\n \/\/ If the qname is already in the pool, return a ptr to its containing slot.\n \/\/ If the slot is in the free list of the cache, it is first removed from\n \/\/ that list. \n if (entry->theQName != NULL)\n {\n qn = entry->theQName;\n\n if (qn->isInCache())\n {\n if (qn->theNextFree != 0)\n theCache[qn->theNextFree].thePrevFree = qn->thePrevFree;\n\n if (qn->thePrevFree != 0)\n {\n theCache[qn->thePrevFree].theNextFree = qn->theNextFree;\n }\n else if (theFirstFree == qn->thePosition)\n {\n theFirstFree = qn->theNextFree;\n }\n\n qn->theNextFree = qn->thePrevFree = 0;\n theNumFree--;\n }\n\n return qn;\n }\n\n \/\/ The qname is not in the pool.\n \/\/ Use the 1st slot from the free list of the cache to store the new qname.\n \/\/ The qname was is currently in that slot is removed from the cache.\n if (theFirstFree != 0)\n {\n qn = &theCache[theFirstFree];\n entry->theQName = qn;\n\n theFirstFree = qn->theNextFree;\n theCache[theFirstFree].thePrevFree = 0;\n\n if (!qn->theLocal.empty())\n unhash(qn->theNamespace.c_str(), qn->thePrefix.c_str(), qn->theLocal.c_str());\n\n qn->theNextFree = qn->thePrevFree = 0;\n qn->theNamespace = ns;\n qn->thePrefix = pre;\n qn->theLocal = ln;\n\n theNumFree--;\n\n return qn;\n }\n\n \/\/ The cache was full, so allocate a QNameItem from the heap.\n qn = new QNameImpl(ns, pre, ln);\n \/\/theOverflow.push_back(qn);\n entry->theQName = qn;\n return qn;\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid QNamePool::remove(QNameImpl* qn)\n{\n if (qn->get_refCount() > 0)\n return;\n\n if (qn->isInCache())\n {\n qn->theNextFree = theFirstFree;\n theCache[theFirstFree].thePrevFree = qn->thePosition;\n theFirstFree = qn->thePosition;\n theNumFree++;\n }\n else\n {\n \/\/ If all the pointers to QNameItems were smart pointers, we could leave\n \/\/ qn in the pool, and let the pool garbage-collect it later (if it still\n \/\/ unused). If however QNameItems may be referenced by regular pointers as\n \/\/ well, then qn must be removed from the pool and really deleted\n unhash(qn->getNamespace().c_str(),\n qn->getPrefix().c_str(),\n qn->getLocalName().c_str());\n\n \/\/std::vector::iterator it;\n \/\/it = theOverflow.begin() + qn->thePosition;\n \/\/theOverflow.erase(it);\n\n ::delete qn;\n }\n}\n\n\n\/*******************************************************************************\n Check if the given qname is already in the pool, and if so, return its hash\n entry. If not, allocate a new hash entry for it, and return it to the caller.\n********************************************************************************\/\nQNamePool::HashEntry*\nQNamePool::hash(const char* ns, const char* pre, const char* ln)\n{\n xqp_unsignedLong len;\n HashEntry* entry;\n HashEntry* lastentry;\n\n \/\/ Get ptr to the 1st entry of the hash bucket corresponding to the given qname\n xqp_unsignedLong hval = hashfun::h32(pre,\n hashfun::h32(ln,\n hashfun::h32(ns))) % theHashTabSize;\n entry = &theHashTab[ hval % theHashTabSize];\n\n \/\/ If the hash bucket is empty, its 1st entry is used to store the new qname.\n if (entry->isFree())\n {\n theNumQNames++;\n return entry;\n }\n\n \/\/ Search the hash bucket looking for the given qname.\n while (entry != NULL)\n {\n QNameImpl* qn = entry->theQName;\n\n len = qn->theLocal.bytes();\n if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)\n {\n lastentry = entry;\n entry = entry->theNext;\n continue;\n }\n\n len = qn->theNamespace.bytes();\n if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)\n {\n lastentry = entry;\n entry = entry->theNext;\n continue;\n }\n \n len = qn->thePrefix.bytes();\n if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)\n {\n lastentry = entry;\n entry = entry->theNext;\n continue;\n }\n\n return entry;\n }\n\n \/\/ The qname was not found.\n\n \/\/ Double the size of hash table if it is more than 60% full. \n if (theNumQNames > theHashTabSize * theLoadFactor)\n resizeHashTab();\n\n \/\/ Get an entry from the free list in the overflow section of the hash teble\n \/\/ If no free entry exists, a new entry is appended into the hash table. \n if (theHashTab[theHashTabSize].theNext == 0)\n {\n theHashTab.push_back(HashEntry());\n entry = &theHashTab[theHashTab.size() - 1];\n lastentry->theNext = entry;\n }\n else\n {\n entry = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = entry->theNext;\n lastentry->theNext = entry;\n entry->theNext = NULL;\n }\n\n theNumQNames++;\n\n return entry;\n}\n\n\n\/*******************************************************************************\n Remove the given qname from the hash table, if it is found there.\n********************************************************************************\/\nvoid QNamePool::unhash(const char* ns, const char* pre, const char* ln)\n{\n xqp_unsignedLong len;\n HashEntry* entry;\n HashEntry* preventry = NULL;\n\n \/\/ Get ptr to the 1st entry of the hash bucket corresponding to the given qname\n xqp_unsignedLong hval = hashfun::h32(pre,\n hashfun::h32(ln,\n hashfun::h32(ns))) % theHashTabSize;\n entry = &theHashTab[ hval % theHashTabSize];\n\n \/\/ If the hash bucket is empty, the qname is not in the hash table.\n if (entry->isFree())\n return;\n\n \/\/ Search the hash bucket looking for the given qname.\n while (entry != NULL)\n {\n QNameImpl* qn = entry->theQName;\n\n len = qn->theLocal.bytes();\n if (len != strlen(ln) || memcmp(qn->theLocal.c_str(), ln, len) != 0)\n {\n preventry = entry;\n entry = entry->theNext;\n continue;\n }\n\n len = qn->theNamespace.bytes();\n if (len != strlen(ns) || memcmp(qn->theNamespace.c_str(), ns, len) != 0)\n {\n preventry = entry;\n entry = entry->theNext;\n continue;\n }\n \n len = qn->thePrefix.bytes();\n if (len != strlen(pre) || memcmp(qn->thePrefix.c_str(), pre, len) != 0)\n {\n preventry = entry;\n entry = entry->theNext;\n continue;\n }\n\n \/\/ Found the qname in the current entry. Must remove the entry from the\n \/\/ hash bucket and add it to the free list.\n if (preventry != NULL)\n {\n preventry->theNext = entry->theNext;\n entry->theQName = NULL;\n entry->theNext = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = entry;\n }\n else if (entry->theNext != NULL)\n {\n HashEntry* nextentry = entry->theNext;\n *entry = *nextentry;\n nextentry->theQName = NULL;\n nextentry->theNext = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = nextentry;\n }\n else\n {\n entry->theQName = NULL;\n }\n\n theNumQNames--;\n\n return;\n }\n}\n\n\n\/*******************************************************************************\n\n********************************************************************************\/\nvoid QNamePool::resizeHashTab()\n{\n HashEntry* entry;\n HashEntry* lastentry;\n\n \/\/ Make a copy of theHashTab, and then resize it to double theHashTabSize\n std::vector oldTab = theHashTab;\n xqp_unsignedLong oldsize = oldTab.size();\n\n theHashTabSize <<= 1;\n\n theHashTab.clear();\n theHashTab.resize(theHashTabSize + 32);\n\n \/\/ Format the overflow area of theHashTab as a list of free entries\n lastentry = &theHashTab[theHashTabSize + 31];\n for (entry = &theHashTab[theHashTabSize]; entry < lastentry; entry++)\n entry->theNext = entry + 1;\n \n \/\/ Now rehash every entry\n for (xqp_unsignedLong i = 0; i < oldsize; i++)\n {\n QNameImpl* qn = oldTab[i].theQName;\n\n xqp_unsignedLong h = hashfun::h32(qn->thePrefix.c_str(),\n hashfun::h32(qn->theLocal.c_str(),\n hashfun::h32(qn->theNamespace.c_str())));\n entry = &theHashTab[h % theHashTabSize];\n\n if (!entry->isFree())\n {\n \/\/ Go to the last entry of the current bucket\n HashEntry* lastentry = entry;\n while (lastentry->theNext != NULL)\n lastentry = lastentry->theNext;\n\n \/\/ Get an entry from the free list in the overflow section of the hash\n \/\/ table. If no free entry exists, a new entry is appended into the table.\n if (theHashTab[theHashTabSize].theNext == 0)\n {\n theHashTab.push_back(HashEntry());\n entry = &theHashTab[theHashTab.size() - 1];\n lastentry->theNext = entry;\n }\n else\n {\n entry = theHashTab[theHashTabSize].theNext;\n theHashTab[theHashTabSize].theNext = entry->theNext;\n lastentry->theNext = entry;\n entry->theNext = NULL;\n }\n }\n\n entry->theQName = qn;\n }\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ QNameItem \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nQNameImpl::QNameImpl(\n const xqp_string& ns,\n const xqp_string& pre,\n const xqp_string& local)\n :\n theNamespace(ns),\n thePrefix (pre),\n theLocal(local),\n theNextFree(0),\n thePrevFree(0)\n{\n}\n\n\nQNameImpl::QNameImpl(\n const char* ns,\n const char* pre,\n const char* local)\n :\n theNamespace(ns),\n thePrefix (pre),\n theLocal(local),\n theNextFree(0),\n thePrevFree(0)\n{\n}\n\n\nvoid QNameImpl::setQNamePool(QNamePool* p)\n{\n theQNamePool = p;\n}\n\n\nvoid QNameImpl::free()\n{\n getQNamePool()->remove(this);\n}\n\n\nqnamekey_t QNameImpl::getQNameKey( ) const\n{\n return Item::createQNameKey(theNamespace, thePrefix, theLocal);\n}\n\n\nItem_t QNameImpl::getAtomizationValue( ) const\n{\n return zorba::getItemFactory()->createQName(theNamespace, thePrefix, theLocal).get_ptr();\n}\n\n\nbool QNameImpl::equals(Item_t item) const\n{\n return (this == item.get_ptr() ||\n (item->getNamespace() == theNamespace &&\n item->getLocalName() == theLocal));\n}\n\n\nItem_t QNameImpl::getEBV( ) const\n{\n ZorbaErrorAlerts::error_alert (\n error_messages::FORG0006_INVALID_ARGUMENT_TYPE,\n\t\t error_messages::RUNTIME_ERROR,\n\t\t NULL,\n\t\t false,\n\t\t \"Effective Boolean Value is not defined for QName!\");\n return NULL;\n}\n\n\nxqp_string QNameImpl::getStringProperty( ) const\n{\n return thePrefix != \"\" ? thePrefix + \":\" + theLocal : theLocal;\n}\n\n\nxqp_string QNameImpl::show() const\n{\n return \"xs:qname(\" + theNamespace + \",\" + thePrefix + \",\" + theLocal + \")\";\n}\n\n}\n<|endoftext|>"} {"text":"\/**********************************************************\n * Author : Hsin-Yi Chou\n * Email : hchou@cern.ch\n * Last modified : 2015-07-22 16:29\n * Filename : YiProdNtuple.C\n * Description :\n * *******************************************************\/\n#ifndef __YiProdNtuple_C__\n#define __YiProdNtuple_C__\n#include \"YiProdNtuple.h\"\n#include \"YiProdNtuple.tcc\"\n#include \n\nint main(int argc, const char ** argv) {\n\tCOUT(\"\\n**--------------------------**\\n\");\n\tCOUT(\"\\n** YiProdNtuple START **\\n\");\n\tCOUT(\"\\n**--------------------------**\\n\");\n\n google::InitGoogleLogging(argv[0]);\n google::SetStderrLogging(google::GLOG_FATAL);\n\n TrackSys::Sys::SetEnv(\"TRACKSys_MagBox\", \"\/ams_home\/hchou\/AMSData\/magnetic\/AMS02Mag.bin\");\n TrackSys::Sys::SetEnv(\"TRACKSys_MatBox\", \"\/ams_home\/hchou\/AMSData\/material\");\n\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MagBox\", \"\/eos\/ams\/user\/h\/hchou\/ExternalLibs\/DB\/magnetic\/AMS02Mag.bin\");\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MatBox\", \"\/eos\/ams\/user\/h\/hchou\/ExternalLibs\/DB\/material\");\n\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MagBox\", \"\/afs\/cern.ch\/work\/h\/hchou\/public\/DATABASE\/DB\/magnetic\/AMS02Mag.bin\");\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MatBox\", \"\/afs\/cern.ch\/work\/h\/hchou\/public\/DATABASE\/DB\/material\");\n\n\tYiNtuple::setSelectionMode(YiNtuple::NORM);\n\t\/\/YiNtuple::setSelectionMode(YiNtuple::COPY);\n\n\tDataSelection::setOption(DataSelection::LIST, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::RTI, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TRG, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TOF, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::ACC, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TRK, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TRD, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::RICH, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::ECAL, DataSelection::ON);\n\n\tEventBase::setEventVersion(EventBase::B950);\n\n\tCOUT(\"\\n\\n\");\n\tCOUT(\"Usage : YiProdNtuple event_mode file_list group_id group_size (path)\\n\");\n\tCOUT(\" Parameters : \\n\");\n\tCOUT(\" event_mode [ISS BT MC]\\n\");\n\tCOUT(\" file_list\\n\");\n\tCOUT(\" group_id\\n\");\n\tCOUT(\" group_size\\n\");\n\tCOUT(\" (path)\\n\");\n\tCOUT(\"\\n\\n\");\n\n\tif (argc != 5 && argc != 6)\n\t\tMGSys::ShowErrorAndExit(LOCADR(), \"Number of argument is not conform! Exiting ...\");\n\n\tstd::string event_mode = argv[1];\n\tstd::string file_list = argv[2];\n\tLong64_t group_id = atol(argv[3]);\n\tLong64_t group_size = atol(argv[4]);\n\n\tstd::use_facet >(std::locale()).toupper(&event_mode[0], &event_mode[0] + event_mode.size());\n\tif (event_mode == \"ISS\") EventBase::setEventMode(EventBase::ISS);\n\telse if (event_mode == \"BT\") EventBase::setEventMode(EventBase::BT);\n\telse if (event_mode == \"MC\") EventBase::setEventMode(EventBase::MC);\n\telse MGSys::ShowErrorAndExit(LOCADR(), \"Can't find event mode (ISS, BT, MC)! Exiting ...\");\n\n\tstd::string outputFile = \"\";\n\tif (YiNtuple::checkSelectionMode(YiNtuple::NORM))\n\t\toutputFile = STR(\"YiNtuple_%s.%07ld.root\", event_mode.c_str(), group_id);\n\telse if (YiNtuple::checkSelectionMode(YiNtuple::COPY))\n\t\toutputFile = STR(\"YiMirror_%s.%07ld.root\", event_mode.c_str(), group_id);\n\n\tstd::string path = \".\";\n\tif (argc == 6) path = argv[5];\n\n\tbool isMultiTree = false;\n\tYiNtuple * ntuple = new YiNtuple();\n\tntuple->setOutputFile(outputFile, path, isMultiTree);\n\tntuple->readDataFrom(file_list, group_id, group_size);\n\tntuple->loopEventChain();\n\n\tif (ntuple != nullptr) delete ntuple;\n\tntuple = nullptr;\n\n\tCOUT(\"\\n**------------------------**\\n\");\n\tCOUT(\"\\n** YiProdNtuple END **\\n\");\n\tCOUT(\"\\n**------------------------**\\n\");\n\treturn 0;\n}\n#endif \/\/ __YiProdNtuple_C__\nupdate\/**********************************************************\n * Author : Hsin-Yi Chou\n * Email : hchou@cern.ch\n * Last modified : 2015-07-22 16:29\n * Filename : YiProdNtuple.C\n * Description :\n * *******************************************************\/\n#ifndef __YiProdNtuple_C__\n#define __YiProdNtuple_C__\n#include \"YiProdNtuple.h\"\n#include \"YiProdNtuple.tcc\"\n#include \n\nint main(int argc, const char ** argv) {\n\tCOUT(\"\\n**--------------------------**\\n\");\n\tCOUT(\"\\n** YiProdNtuple START **\\n\");\n\tCOUT(\"\\n**--------------------------**\\n\");\n\n google::InitGoogleLogging(argv[0]);\n google::SetStderrLogging(google::GLOG_FATAL);\n\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MagBox\", \"\/ams_home\/hchou\/AMSData\/magnetic\/AMS02Mag.bin\");\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MatBox\", \"\/ams_home\/hchou\/AMSData\/material\");\n\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MagBox\", \"\/eos\/ams\/user\/h\/hchou\/ExternalLibs\/DB\/magnetic\/AMS02Mag.bin\");\n \/\/TrackSys::Sys::SetEnv(\"TRACKSys_MatBox\", \"\/eos\/ams\/user\/h\/hchou\/ExternalLibs\/DB\/material\");\n\n TrackSys::Sys::SetEnv(\"TRACKSys_MagBox\", \"\/afs\/cern.ch\/work\/h\/hchou\/public\/DATABASE\/DB\/magnetic\/AMS02Mag.bin\");\n TrackSys::Sys::SetEnv(\"TRACKSys_MatBox\", \"\/afs\/cern.ch\/work\/h\/hchou\/public\/DATABASE\/DB\/material\");\n\n\tYiNtuple::setSelectionMode(YiNtuple::NORM);\n\t\/\/YiNtuple::setSelectionMode(YiNtuple::COPY);\n\n\tDataSelection::setOption(DataSelection::LIST, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::RTI, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TRG, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TOF, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::ACC, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TRK, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::TRD, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::RICH, DataSelection::ON);\n\tDataSelection::setOption(DataSelection::ECAL, DataSelection::ON);\n\n\tEventBase::setEventVersion(EventBase::B950);\n\n\tCOUT(\"\\n\\n\");\n\tCOUT(\"Usage : YiProdNtuple event_mode file_list group_id group_size (path)\\n\");\n\tCOUT(\" Parameters : \\n\");\n\tCOUT(\" event_mode [ISS BT MC]\\n\");\n\tCOUT(\" file_list\\n\");\n\tCOUT(\" group_id\\n\");\n\tCOUT(\" group_size\\n\");\n\tCOUT(\" (path)\\n\");\n\tCOUT(\"\\n\\n\");\n\n\tif (argc != 5 && argc != 6)\n\t\tMGSys::ShowErrorAndExit(LOCADR(), \"Number of argument is not conform! Exiting ...\");\n\n\tstd::string event_mode = argv[1];\n\tstd::string file_list = argv[2];\n\tLong64_t group_id = atol(argv[3]);\n\tLong64_t group_size = atol(argv[4]);\n\n\tstd::use_facet >(std::locale()).toupper(&event_mode[0], &event_mode[0] + event_mode.size());\n\tif (event_mode == \"ISS\") EventBase::setEventMode(EventBase::ISS);\n\telse if (event_mode == \"BT\") EventBase::setEventMode(EventBase::BT);\n\telse if (event_mode == \"MC\") EventBase::setEventMode(EventBase::MC);\n\telse MGSys::ShowErrorAndExit(LOCADR(), \"Can't find event mode (ISS, BT, MC)! Exiting ...\");\n\n\tstd::string outputFile = \"\";\n\tif (YiNtuple::checkSelectionMode(YiNtuple::NORM))\n\t\toutputFile = STR(\"YiNtuple_%s.%07ld.root\", event_mode.c_str(), group_id);\n\telse if (YiNtuple::checkSelectionMode(YiNtuple::COPY))\n\t\toutputFile = STR(\"YiMirror_%s.%07ld.root\", event_mode.c_str(), group_id);\n\n\tstd::string path = \".\";\n\tif (argc == 6) path = argv[5];\n\n\tbool isMultiTree = false;\n\tYiNtuple * ntuple = new YiNtuple();\n\tntuple->setOutputFile(outputFile, path, isMultiTree);\n\tntuple->readDataFrom(file_list, group_id, group_size);\n\tntuple->loopEventChain();\n\n\tif (ntuple != nullptr) delete ntuple;\n\tntuple = nullptr;\n\n\tCOUT(\"\\n**------------------------**\\n\");\n\tCOUT(\"\\n** YiProdNtuple END **\\n\");\n\tCOUT(\"\\n**------------------------**\\n\");\n\treturn 0;\n}\n#endif \/\/ __YiProdNtuple_C__\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the plugins of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n\n#include \n#include \n\n\nQT_BEGIN_NAMESPACE\n\n\nclass DirectShowPostedEvent\n{\npublic:\n DirectShowPostedEvent(QObject *receiver, QEvent *event)\n : receiver(receiver)\n , event(event)\n , next(0)\n {\n }\n\n ~DirectShowPostedEvent()\n {\n delete event;\n }\n\n QObject *receiver;\n QEvent *event;\n DirectShowPostedEvent *next;\n};\n\nDirectShowEventLoop::DirectShowEventLoop(QObject *parent)\n : QWinEventNotifier(parent)\n , m_postsHead(0)\n , m_postsTail(0)\n , m_eventHandle(::CreateEvent(0, 0, 0, 0))\n , m_waitHandle(::CreateEvent(0, 0, 0, 0))\n{\n setHandle(m_eventHandle);\n setEnabled(true);\n}\n\nDirectShowEventLoop::~DirectShowEventLoop()\n{\n setEnabled(false);\n\n ::CloseHandle(m_eventHandle);\n ::CloseHandle(m_waitHandle);\n\n for (DirectShowPostedEvent *post = m_postsHead; post; post = m_postsHead) {\n m_postsHead = m_postsHead->next;\n\n delete post;\n }\n}\n\nvoid DirectShowEventLoop::wait(QMutex *mutex)\n{\n ::ResetEvent(m_waitHandle);\n\n mutex->unlock();\n\n HANDLE handles[] = { m_eventHandle, m_waitHandle };\n while (::WaitForMultipleObjects(2, handles, false, INFINITE) == WAIT_OBJECT_0)\n processEvents();\n \n mutex->lock();\n}\n\nvoid DirectShowEventLoop::wake()\n{\n ::SetEvent(m_waitHandle);\n}\n\nvoid DirectShowEventLoop::postEvent(QObject *receiver, QEvent *event)\n{\n QMutexLocker locker(&m_mutex);\n\n DirectShowPostedEvent *post = new DirectShowPostedEvent(receiver, event);\n\n if (m_postsTail)\n m_postsTail->next = post;\n else\n m_postsHead = post;\n\n m_postsTail = post;\n\n ::SetEvent(m_eventHandle);\n}\n\nbool DirectShowEventLoop::event(QEvent *event)\n{\n if (event->type() == QEvent::WinEventAct) {\n processEvents();\n\n return true;\n } else {\n return QWinEventNotifier::event(event);\n }\n}\n\nvoid DirectShowEventLoop::processEvents()\n{\n QMutexLocker locker(&m_mutex);\n\n while(m_postsHead) {\n ::ResetEvent(m_eventHandle);\n\n DirectShowPostedEvent *post = m_postsHead;\n m_postsHead = m_postsHead->next;\n\n locker.unlock();\n QCoreApplication::sendEvent(post->receiver, post->event);\n delete post;\n locker.relock();\n }\n\n m_postsTail = 0;\n}\n\nQT_END_NAMESPACE\nFix corruption of Direct Show event queue.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the plugins of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \n\n#include \n#include \n\n\nQT_BEGIN_NAMESPACE\n\n\nclass DirectShowPostedEvent\n{\npublic:\n DirectShowPostedEvent(QObject *receiver, QEvent *event)\n : receiver(receiver)\n , event(event)\n , next(0)\n {\n }\n\n ~DirectShowPostedEvent()\n {\n delete event;\n }\n\n QObject *receiver;\n QEvent *event;\n DirectShowPostedEvent *next;\n};\n\nDirectShowEventLoop::DirectShowEventLoop(QObject *parent)\n : QWinEventNotifier(parent)\n , m_postsHead(0)\n , m_postsTail(0)\n , m_eventHandle(::CreateEvent(0, 0, 0, 0))\n , m_waitHandle(::CreateEvent(0, 0, 0, 0))\n{\n setHandle(m_eventHandle);\n setEnabled(true);\n}\n\nDirectShowEventLoop::~DirectShowEventLoop()\n{\n setEnabled(false);\n\n ::CloseHandle(m_eventHandle);\n ::CloseHandle(m_waitHandle);\n\n for (DirectShowPostedEvent *post = m_postsHead; post; post = m_postsHead) {\n m_postsHead = m_postsHead->next;\n\n delete post;\n }\n}\n\nvoid DirectShowEventLoop::wait(QMutex *mutex)\n{\n ::ResetEvent(m_waitHandle);\n\n mutex->unlock();\n\n HANDLE handles[] = { m_eventHandle, m_waitHandle };\n while (::WaitForMultipleObjects(2, handles, false, INFINITE) == WAIT_OBJECT_0)\n processEvents();\n \n mutex->lock();\n}\n\nvoid DirectShowEventLoop::wake()\n{\n ::SetEvent(m_waitHandle);\n}\n\nvoid DirectShowEventLoop::postEvent(QObject *receiver, QEvent *event)\n{\n QMutexLocker locker(&m_mutex);\n\n DirectShowPostedEvent *post = new DirectShowPostedEvent(receiver, event);\n\n if (m_postsTail)\n m_postsTail->next = post;\n else\n m_postsHead = post;\n\n m_postsTail = post;\n\n ::SetEvent(m_eventHandle);\n}\n\nbool DirectShowEventLoop::event(QEvent *event)\n{\n if (event->type() == QEvent::WinEventAct) {\n processEvents();\n\n return true;\n } else {\n return QWinEventNotifier::event(event);\n }\n}\n\nvoid DirectShowEventLoop::processEvents()\n{\n QMutexLocker locker(&m_mutex);\n\n while(m_postsHead) {\n ::ResetEvent(m_eventHandle);\n\n DirectShowPostedEvent *post = m_postsHead;\n m_postsHead = m_postsHead->next;\n\n if (!m_postsHead)\n m_postsTail = 0;\n\n locker.unlock();\n QCoreApplication::sendEvent(post->receiver, post->event);\n delete post;\n locker.relock();\n }\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#pragma once\n\n#include \"core\/CompileConfig.h\"\n\n#if OUZEL_SUPPORTS_DIRECTSOUND\n\n#include \n\n#include \n#include \"audio\/AudioDevice.hpp\"\n\nnamespace ouzel\n{\n namespace audio\n {\n class AudioDeviceDS: public AudioDevice\n {\n friend Audio;\n public:\n virtual ~AudioDeviceDS();\n\n virtual bool update() override;\n\n IDirectSound8* getDirectSound() const { return directSound; }\n\n protected:\n AudioDeviceDS();\n virtual bool init(bool debugAudio) override;\n\n void run();\n\n IDirectSound8* directSound = nullptr;\n \n IDirectSoundBuffer* primaryBuffer = nullptr;\n IDirectSoundBuffer8* buffer = nullptr;\n\n uint32_t nextBuffer = 0;\n\n bool running = true;\n\n std::vector data;\n\n#if OUZEL_MULTITHREADED\n std::thread audioThread;\n#endif\n };\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\nRemove the declaration of update()\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#pragma once\n\n#include \"core\/CompileConfig.h\"\n\n#if OUZEL_SUPPORTS_DIRECTSOUND\n\n#include \n\n#include \n#include \"audio\/AudioDevice.hpp\"\n\nnamespace ouzel\n{\n namespace audio\n {\n class AudioDeviceDS: public AudioDevice\n {\n friend Audio;\n public:\n virtual ~AudioDeviceDS();\n\n IDirectSound8* getDirectSound() const { return directSound; }\n\n protected:\n AudioDeviceDS();\n virtual bool init(bool debugAudio) override;\n\n void run();\n\n IDirectSound8* directSound = nullptr;\n \n IDirectSoundBuffer* primaryBuffer = nullptr;\n IDirectSoundBuffer8* buffer = nullptr;\n\n uint32_t nextBuffer = 0;\n\n bool running = true;\n\n std::vector data;\n\n#if OUZEL_MULTITHREADED\n std::thread audioThread;\n#endif\n };\n } \/\/ namespace audio\n} \/\/ namespace ouzel\n\n#endif\n<|endoftext|>"} {"text":"\/*\n* (C) 2015 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_HAS_COMPRESSION)\n #include \n#endif\n\nnamespace Botan_Tests {\n\n#if defined(BOTAN_HAS_COMPRESSION)\n\nnamespace {\n\nconst char* text_str =\n \"'Twas brillig, and the slithy toves\"\n \"Did gyre and gimble in the wabe:\"\n \"All mimsy were the borogoves,\"\n \"And the mome raths outgrabe.\"\n\n \"'Beware the Jabberwock, my son!\"\n \"The jaws that bite, the claws that catch!\"\n \"Beware the Jubjub bird, and shun\"\n \"The frumious Bandersnatch!'\"\n\n \"He took his vorpal sword in hand;\"\n \"Long time the manxome foe he sought-\"\n \"So rested he by the Tumtum tree\"\n \"And stood awhile in thought.\"\n\n \"And, as in uffish thought he stood,\"\n \"The Jabberwock, with eyes of flame,\"\n \"Came whiffling through the tulgey wood,\"\n \"And burbled as it came!\"\n\n \"One, two! One, two! And through and through\"\n \"The vorpal blade went snicker-snack!\"\n \"He left it dead, and with its head\"\n \"He went galumphing back.\"\n\n \"'And hast thou slain the Jabberwock?\"\n \"Come to my arms, my beamish boy!\"\n \"O frabjous day! Callooh! Callay!'\"\n \"He chortled in his joy.\"\n\n \"'Twas brillig, and the slithy toves\"\n \"Did gyre and gimble in the wabe:\"\n \"All mimsy were the borogoves,\"\n \"And the mome raths outgrabe.\";\n\nclass Compression_Tests final : public Test\n {\n public:\n std::vector run() override\n {\n std::vector results;\n const size_t text_len = std::strlen(text_str);\n\n for(std::string algo : { \"zlib\", \"deflate\", \"gzip\", \"bz2\", \"lzma\" })\n {\n try\n {\n Test::Result result(algo + \" compression\");\n\n std::unique_ptr c(Botan::make_compressor(algo));\n std::unique_ptr d(Botan::make_decompressor(algo));\n\n if(!c || !d)\n {\n result.note_missing(algo);\n continue;\n }\n\n result.test_ne(\"Not the same name\", c->name(), d->name());\n\n const Botan::secure_vector empty;\n const Botan::secure_vector all_zeros(text_len, 0);\n const Botan::secure_vector random_binary = Test::rng().random_vec(text_len);\n const Botan::secure_vector short_text = { 'f', 'o', 'o', '\\n' };\n\n const uint8_t* textb = reinterpret_cast(text_str);\n const Botan::secure_vector text(textb, textb + text_len);\n\n const size_t c1_e = run_compression(result, 1, *c, *d, empty);\n const size_t c9_e = run_compression(result, 9, *c, *d, empty);\n const size_t c1_z = run_compression(result, 1, *c, *d, all_zeros);\n const size_t c9_z = run_compression(result, 9, *c, *d, all_zeros);\n const size_t c1_r = run_compression(result, 1, *c, *d, random_binary);\n const size_t c9_r = run_compression(result, 9, *c, *d, random_binary);\n const size_t c1_t = run_compression(result, 1, *c, *d, text);\n const size_t c9_t = run_compression(result, 9, *c, *d, text);\n const size_t c1_s = run_compression(result, 1, *c, *d, short_text);\n const size_t c9_s = run_compression(result, 9, *c, *d, short_text);\n\n result.test_gte(\"Empty input L1 compresses to non-empty output\", c1_e, 1);\n result.test_gte(\"Empty input L9 compresses to non-empty output\", c9_e, 1);\n\n result.test_gte(\"Level 9 compresses empty at least as well as level 1\", c1_e, c9_e);\n result.test_gte(\"Level 9 compresses zeros at least as well as level 1\", c1_z, c9_z);\n result.test_gte(\"Level 9 compresses random at least as well as level 1\", c1_r, c9_r);\n result.test_gte(\"Level 9 compresses text at least as well as level 1\", c1_t, c9_t);\n result.test_gte(\"Level 9 compresses short text at least as well as level 1\", c1_s, c9_s);\n\n result.test_lt(\"Zeros compresses much better than text\", c1_z \/ 8, c1_t);\n result.test_lt(\"Text compresses much better than random\", c1_t \/ 2, c1_r);\n\n results.emplace_back(result);\n }\n catch(std::exception& e)\n {\n results.emplace_back(Test::Result::Failure(\"testing \" + algo, e.what()));\n }\n }\n\n return results;\n }\n\n private:\n\n \/\/ Returns # of bytes of compressed message\n size_t run_compression(Test::Result& result,\n size_t level,\n Botan::Compression_Algorithm& c,\n Botan::Decompression_Algorithm& d,\n const Botan::secure_vector& msg)\n {\n Botan::secure_vector compressed(2*msg.size());\n\n for(bool with_flush : { true, false })\n {\n try\n {\n compressed = msg;\n\n c.start(level);\n c.update(compressed, 0, false);\n\n if(with_flush)\n {\n Botan::secure_vector flush_bits;\n c.update(flush_bits, 0, true);\n compressed += flush_bits;\n }\n\n Botan::secure_vector final_bits;\n c.finish(final_bits);\n compressed += final_bits;\n\n Botan::secure_vector decompressed = compressed;\n d.start();\n d.update(decompressed);\n\n Botan::secure_vector final_outputs;\n d.finish(final_outputs);\n\n decompressed += final_outputs;\n\n result.test_eq(\"compression round tripped\", msg, decompressed);\n }\n catch(Botan::Exception& e)\n {\n result.test_failure(e.what());\n }\n }\n\n return compressed.size();\n }\n };\n\nBOTAN_REGISTER_TEST(\"compression\", \"compression\", Compression_Tests);\n\nclass CompressionCreate_Tests final : public Test\n {\n public:\n std::vector run() override\n {\n std::vector results;\n\n for(std::string algo : { \"zlib\", \"deflate\", \"gzip\", \"bz2\", \"lzma\" })\n {\n try\n {\n Test::Result result(algo + \" create compression\");\n\n std::unique_ptr c1(Botan::Compression_Algorithm::create(algo));\n std::unique_ptr d1(Botan::Decompression_Algorithm::create(algo));\n\n if(!c1 || !d1)\n {\n result.note_missing(algo);\n continue;\n }\n result.test_ne(\"Not the same name after create\", c1->name(), d1->name());\n\n std::unique_ptr c2(Botan::Compression_Algorithm::create_or_throw(algo));\n std::unique_ptr d2(Botan::Decompression_Algorithm::create_or_throw(algo));\n\n if(!c2 || !d2)\n {\n result.note_missing(algo);\n continue;\n }\n result.test_ne(\"Not the same name after create_or_throw\", c2->name(), d2->name());\n\n results.emplace_back(result);\n }\n catch(std::exception& e)\n {\n results.emplace_back(Test::Result::Failure(\"testing \" + algo, e.what()));\n }\n }\n\n {\n Test::Result result(\"create invalid compression\");\n result.test_throws(\"lookup error\",\n \"Unavailable Compression bogocompress\",\n [&]() { Botan::Compression_Algorithm::create_or_throw(\"bogocompress\"); });\n result.test_throws(\"lookup error\",\n \"Unavailable Decompression bogocompress\",\n [&]() { Botan::Decompression_Algorithm::create_or_throw(\"bogocompress\"); });\n results.emplace_back(result);\n }\n\n return results;\n }\n };\n\nBOTAN_REGISTER_TEST(\"compression\", \"create_compression\", CompressionCreate_Tests);\n\n}\n\n#endif\n\n}\nTime compression tests\/*\n* (C) 2015 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_HAS_COMPRESSION)\n #include \n#endif\n\nnamespace Botan_Tests {\n\n#if defined(BOTAN_HAS_COMPRESSION)\n\nnamespace {\n\nconst char* text_str =\n \"'Twas brillig, and the slithy toves\"\n \"Did gyre and gimble in the wabe:\"\n \"All mimsy were the borogoves,\"\n \"And the mome raths outgrabe.\"\n\n \"'Beware the Jabberwock, my son!\"\n \"The jaws that bite, the claws that catch!\"\n \"Beware the Jubjub bird, and shun\"\n \"The frumious Bandersnatch!'\"\n\n \"He took his vorpal sword in hand;\"\n \"Long time the manxome foe he sought-\"\n \"So rested he by the Tumtum tree\"\n \"And stood awhile in thought.\"\n\n \"And, as in uffish thought he stood,\"\n \"The Jabberwock, with eyes of flame,\"\n \"Came whiffling through the tulgey wood,\"\n \"And burbled as it came!\"\n\n \"One, two! One, two! And through and through\"\n \"The vorpal blade went snicker-snack!\"\n \"He left it dead, and with its head\"\n \"He went galumphing back.\"\n\n \"'And hast thou slain the Jabberwock?\"\n \"Come to my arms, my beamish boy!\"\n \"O frabjous day! Callooh! Callay!'\"\n \"He chortled in his joy.\"\n\n \"'Twas brillig, and the slithy toves\"\n \"Did gyre and gimble in the wabe:\"\n \"All mimsy were the borogoves,\"\n \"And the mome raths outgrabe.\";\n\nclass Compression_Tests final : public Test\n {\n public:\n std::vector run() override\n {\n std::vector results;\n const size_t text_len = std::strlen(text_str);\n\n for(std::string algo : { \"zlib\", \"deflate\", \"gzip\", \"bz2\", \"lzma\" })\n {\n try\n {\n Test::Result result(algo + \" compression\");\n\n result.start_timer();\n\n std::unique_ptr c(Botan::make_compressor(algo));\n std::unique_ptr d(Botan::make_decompressor(algo));\n\n if(!c || !d)\n {\n result.note_missing(algo);\n continue;\n }\n\n result.test_ne(\"Not the same name\", c->name(), d->name());\n\n const Botan::secure_vector empty;\n const Botan::secure_vector all_zeros(text_len, 0);\n const Botan::secure_vector random_binary = Test::rng().random_vec(text_len);\n const Botan::secure_vector short_text = { 'f', 'o', 'o', '\\n' };\n\n const uint8_t* textb = reinterpret_cast(text_str);\n const Botan::secure_vector text(textb, textb + text_len);\n\n const size_t c1_e = run_compression(result, 1, *c, *d, empty);\n const size_t c9_e = run_compression(result, 9, *c, *d, empty);\n const size_t c1_z = run_compression(result, 1, *c, *d, all_zeros);\n const size_t c9_z = run_compression(result, 9, *c, *d, all_zeros);\n const size_t c1_r = run_compression(result, 1, *c, *d, random_binary);\n const size_t c9_r = run_compression(result, 9, *c, *d, random_binary);\n const size_t c1_t = run_compression(result, 1, *c, *d, text);\n const size_t c9_t = run_compression(result, 9, *c, *d, text);\n const size_t c1_s = run_compression(result, 1, *c, *d, short_text);\n const size_t c9_s = run_compression(result, 9, *c, *d, short_text);\n\n result.test_gte(\"Empty input L1 compresses to non-empty output\", c1_e, 1);\n result.test_gte(\"Empty input L9 compresses to non-empty output\", c9_e, 1);\n\n result.test_gte(\"Level 9 compresses empty at least as well as level 1\", c1_e, c9_e);\n result.test_gte(\"Level 9 compresses zeros at least as well as level 1\", c1_z, c9_z);\n result.test_gte(\"Level 9 compresses random at least as well as level 1\", c1_r, c9_r);\n result.test_gte(\"Level 9 compresses text at least as well as level 1\", c1_t, c9_t);\n result.test_gte(\"Level 9 compresses short text at least as well as level 1\", c1_s, c9_s);\n\n result.test_lt(\"Zeros compresses much better than text\", c1_z \/ 8, c1_t);\n result.test_lt(\"Text compresses much better than random\", c1_t \/ 2, c1_r);\n\n result.end_timer();\n\n results.emplace_back(result);\n }\n catch(std::exception& e)\n {\n results.emplace_back(Test::Result::Failure(\"testing \" + algo, e.what()));\n }\n }\n\n return results;\n }\n\n private:\n\n \/\/ Returns # of bytes of compressed message\n size_t run_compression(Test::Result& result,\n size_t level,\n Botan::Compression_Algorithm& c,\n Botan::Decompression_Algorithm& d,\n const Botan::secure_vector& msg)\n {\n Botan::secure_vector compressed(2*msg.size());\n\n for(bool with_flush : { true, false })\n {\n try\n {\n compressed = msg;\n\n c.start(level);\n c.update(compressed, 0, false);\n\n if(with_flush)\n {\n Botan::secure_vector flush_bits;\n c.update(flush_bits, 0, true);\n compressed += flush_bits;\n }\n\n Botan::secure_vector final_bits;\n c.finish(final_bits);\n compressed += final_bits;\n\n Botan::secure_vector decompressed = compressed;\n d.start();\n d.update(decompressed);\n\n Botan::secure_vector final_outputs;\n d.finish(final_outputs);\n\n decompressed += final_outputs;\n\n result.test_eq(\"compression round tripped\", msg, decompressed);\n }\n catch(Botan::Exception& e)\n {\n result.test_failure(e.what());\n }\n }\n\n return compressed.size();\n }\n };\n\nBOTAN_REGISTER_TEST(\"compression\", \"compression\", Compression_Tests);\n\nclass CompressionCreate_Tests final : public Test\n {\n public:\n std::vector run() override\n {\n std::vector results;\n\n for(std::string algo : { \"zlib\", \"deflate\", \"gzip\", \"bz2\", \"lzma\" })\n {\n try\n {\n Test::Result result(algo + \" create compression\");\n\n std::unique_ptr c1(Botan::Compression_Algorithm::create(algo));\n std::unique_ptr d1(Botan::Decompression_Algorithm::create(algo));\n\n if(!c1 || !d1)\n {\n result.note_missing(algo);\n continue;\n }\n result.test_ne(\"Not the same name after create\", c1->name(), d1->name());\n\n std::unique_ptr c2(Botan::Compression_Algorithm::create_or_throw(algo));\n std::unique_ptr d2(Botan::Decompression_Algorithm::create_or_throw(algo));\n\n if(!c2 || !d2)\n {\n result.note_missing(algo);\n continue;\n }\n result.test_ne(\"Not the same name after create_or_throw\", c2->name(), d2->name());\n\n results.emplace_back(result);\n }\n catch(std::exception& e)\n {\n results.emplace_back(Test::Result::Failure(\"testing \" + algo, e.what()));\n }\n }\n\n {\n Test::Result result(\"create invalid compression\");\n result.test_throws(\"lookup error\",\n \"Unavailable Compression bogocompress\",\n [&]() { Botan::Compression_Algorithm::create_or_throw(\"bogocompress\"); });\n result.test_throws(\"lookup error\",\n \"Unavailable Decompression bogocompress\",\n [&]() { Botan::Decompression_Algorithm::create_or_throw(\"bogocompress\"); });\n results.emplace_back(result);\n }\n\n return results;\n }\n };\n\nBOTAN_REGISTER_TEST(\"compression\", \"create_compression\", CompressionCreate_Tests);\n\n}\n\n#endif\n\n}\n<|endoftext|>"} {"text":"\/*\n * header.cpp\n *\n * Created on: Aug 24, 2015\n * Author: zmij\n *\/\n\n#include \n#include \n#include \n\nnamespace tip {\nnamespace http {\n\nstd::ostream&\noperator << (std::ostream& out, header const& val)\n{\n\tnamespace karma = boost::spirit::karma;\n\ttypedef std::ostream_iterator output_iterator;\n\ttypedef grammar::gen::header_grammar header_grammar;\n\tstd::ostream::sentry s(out);\n\tif (s) {\n\t\toutput_iterator oi(out);\n\t\tkarma::generate(oi, header_grammar(), val);\n\t}\n\treturn out;\n}\n\n\nstd::ostream&\noperator << (std::ostream& out, headers const& val)\n{\n\tnamespace karma = boost::spirit::karma;\n\ttypedef std::ostream_iterator output_iterator;\n\ttypedef grammar::gen::headers_grammar headers_grammar;\n\tstd::ostream::sentry s(out);\n\tif (s) {\n\t\toutput_iterator oi(out);\n\t\tkarma::generate(oi, headers_grammar(), val);\n\t}\n\treturn out;\n}\n\n\nsize_t\ncontent_length(headers const& hdrs)\n{\n\tnamespace qi = boost::spirit::qi;\n\ttypedef std::string::const_iterator string_iterator;\n\tauto p = hdrs.find(ContentLength);\n\tif (p != hdrs.end()) {\n\t\tstring_iterator f = p->second.begin();\n\t\tstring_iterator l = p->second.end();\n\t\tsize_t res;\n\t\tif (qi::parse(f, l, qi::int_parser(), res) && f == l)\n\t\t\treturn res;\n\t\telse\n\t\t\tthrow std::runtime_error(\"Invalid Content-Length header\");\n\t}\n\treturn 0;\n}\n\nbool\nchunked_transfer_encoding(headers const& hdrs)\n{\n\ttypedef std::string::const_iterator string_iterator;\n\tauto p = hdrs.find(TransferEncoding);\n\tif (p != hdrs.end()) {\n\t\treturn p->second == \"chunked\";\n\t}\n\treturn false;\n}\n} \/\/ namespace http\n} \/\/ namespace tip\nPedantic code cleanup\/*\n * header.cpp\n *\n * Created on: Aug 24, 2015\n * Author: zmij\n *\/\n\n#include \n#include \n#include \n\nnamespace tip {\nnamespace http {\n\nstd::ostream&\noperator << (std::ostream& out, header const& val)\n{\n\tnamespace karma = boost::spirit::karma;\n\ttypedef std::ostream_iterator output_iterator;\n\ttypedef grammar::gen::header_grammar header_grammar;\n\tstd::ostream::sentry s(out);\n\tif (s) {\n\t\toutput_iterator oi(out);\n\t\tkarma::generate(oi, header_grammar(), val);\n\t}\n\treturn out;\n}\n\n\nstd::ostream&\noperator << (std::ostream& out, headers const& val)\n{\n\tnamespace karma = boost::spirit::karma;\n\ttypedef std::ostream_iterator output_iterator;\n\ttypedef grammar::gen::headers_grammar headers_grammar;\n\tstd::ostream::sentry s(out);\n\tif (s) {\n\t\toutput_iterator oi(out);\n\t\tkarma::generate(oi, headers_grammar(), val);\n\t}\n\treturn out;\n}\n\n\nsize_t\ncontent_length(headers const& hdrs)\n{\n\tnamespace qi = boost::spirit::qi;\n\ttypedef std::string::const_iterator string_iterator;\n\tauto p = hdrs.find(ContentLength);\n\tif (p != hdrs.end()) {\n\t\tstring_iterator f = p->second.begin();\n\t\tstring_iterator l = p->second.end();\n\t\tsize_t res;\n\t\tif (qi::parse(f, l, qi::int_parser(), res) && f == l)\n\t\t\treturn res;\n\t\telse\n\t\t\tthrow std::runtime_error(\"Invalid Content-Length header\");\n\t}\n\treturn 0;\n}\n\nbool\nchunked_transfer_encoding(headers const& hdrs)\n{\n\tauto p = hdrs.find(TransferEncoding);\n\tif (p != hdrs.end()) {\n\t\treturn p->second == \"chunked\";\n\t}\n\treturn false;\n}\n} \/\/ namespace http\n} \/\/ namespace tip\n<|endoftext|>"} {"text":"\/*\n *\n * StellarLikeBlockchainExplorerAccountSynchronizer.cpp\n * ledger-core\n *\n * Created by Pierre Pollastri on 10\/07\/2019.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \"StellarLikeBlockchainExplorerAccountSynchronizer.hpp\"\n\n#include \n#include \n\n\/**\n * Current version of the synchronization. Please keep this field up to date to ensure that we have proper migration\n * mechanism if the synchronizer needs to save more data in its state in the future (or modify current value). This\n * version allow smooth migration.\n *\/\nstatic const auto SYNCHRONIZATION_ALGORITHM_VERSION = 1;\n\nnamespace ledger {\n namespace core {\n\n StellarLikeBlockchainExplorerAccountSynchronizer::StellarLikeBlockchainExplorerAccountSynchronizer(\n const std::shared_ptr &pool,\n const std::shared_ptr &explorer) :\n DedicatedContext(pool->getDispatcher()->getSerialExecutionContext(\"stellar_like_account_synchronizer\")),\n _explorer(explorer),\n _database(pool->getDatabaseSessionPool()) {\n\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::reset(const std::shared_ptr &account,\n const std::chrono::system_clock::time_point &toDate) {\n account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\")->editor()->clear();\n }\n\n std::shared_ptr> StellarLikeBlockchainExplorerAccountSynchronizer::synchronize(\n const std::shared_ptr &account) {\n if (_notifier != nullptr) {\n return _notifier;\n }\n _notifier = std::make_shared>();\n synchronizeAccount(account);\n return _notifier;\n }\n\n bool StellarLikeBlockchainExplorerAccountSynchronizer::isSynchronizing() const {\n return _notifier != nullptr;\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr &account) {\n auto self = shared_from_this();\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n auto state = preferences\n ->template getObject(\"state\")\n \/\/ provide default state if none exists yet\n .getValueOr(SavedState{});\n\n synchronizeAccount(account, state);\n }\n\n void\n StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr& account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n\n _explorer->getAccount(address)\n .onComplete(account->getContext(), [self, account, state] (const Try>& accountInfo) mutable {\n if (accountInfo.isFailure() && accountInfo.getFailure().getErrorCode() == api::ErrorCode::ACCOUNT_NOT_FOUND) {\n self->endSynchronization(account, state);\n } else if (accountInfo.isFailure()) {\n self->failSynchronization(accountInfo.getFailure());\n } else {\n soci::session sql(self->_database->getPool());\n account->updateAccountInfo(sql, *accountInfo.getValue());\n self->synchronizeTransactions(account, state);\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeTransactions(\n const std::shared_ptr &account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n fmt::print(\"Current paging token: {}\\n\", state.transactionPagingToken.getValueOr(\"no paging token\"));\n _explorer->getTransactions(address, state.transactionPagingToken)\n .onComplete(account->getContext(), [self, account, state] (const Try& txs) mutable {\n if (txs.isFailure()) {\n self->failSynchronization(txs.getFailure());\n } else {\n {\n soci::session sql(self->_database->getPool());\n soci::transaction tr(sql);\n\n for (const auto &tx : txs.getValue()) {\n account->logger()->debug(\"XLM transaction hash: {}, paging_token: {}\", tx->hash, tx->pagingToken);\n auto const flag = account->putTransaction(sql, *tx);\n\n if (::ledger::core::account::isInsertedOperation(flag)) {\n ++state.insertedOperations;\n }\n\n state.lastBlockHeight = std::max(state.lastBlockHeight, tx->ledger);\n }\n tr.commit();\n }\n if (!txs.getValue().empty()) {\n state.transactionPagingToken = txs.getValue().back()->pagingToken;\n fmt::print(\"Paging token for next round: {}\\n\", state.transactionPagingToken.getValueOr(\"no paging token\"));\n {\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n preferences->editor()->putObject(\"state\", state)->commit();\n }\n \n self->synchronizeTransactions(account, state);\n } else {\n self->endSynchronization(account, state);\n }\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::endSynchronization(\n const std::shared_ptr& account,\n const StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n BlockchainExplorerAccountSynchronizationResult result;\n\n soci::session sql(account->getWallet()->getDatabase()->getPool());\n result.lastBlockHeight = BlockDatabaseHelper::getLastBlock(sql,\n account->getWallet()->getCurrency().name)\n .template map([] (const Block& block) {\n return block.height;\n }).getValueOr(0);\n\n result.newOperations = state.insertedOperations;\n\n\n _notifier->success(result);\n _notifier = nullptr;\n }\n\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::failSynchronization(const Exception &ex) {\n _notifier->failure(ex);\n _notifier = nullptr;\n }\n }\n}\nEmit env at the end of batch insertion for XLM\/*\n *\n * StellarLikeBlockchainExplorerAccountSynchronizer.cpp\n * ledger-core\n *\n * Created by Pierre Pollastri on 10\/07\/2019.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \"StellarLikeBlockchainExplorerAccountSynchronizer.hpp\"\n\n#include \n#include \n\n\/**\n * Current version of the synchronization. Please keep this field up to date to ensure that we have proper migration\n * mechanism if the synchronizer needs to save more data in its state in the future (or modify current value). This\n * version allow smooth migration.\n *\/\nstatic const auto SYNCHRONIZATION_ALGORITHM_VERSION = 1;\n\nnamespace ledger {\n namespace core {\n\n StellarLikeBlockchainExplorerAccountSynchronizer::StellarLikeBlockchainExplorerAccountSynchronizer(\n const std::shared_ptr &pool,\n const std::shared_ptr &explorer) :\n DedicatedContext(pool->getDispatcher()->getSerialExecutionContext(\"stellar_like_account_synchronizer\")),\n _explorer(explorer),\n _database(pool->getDatabaseSessionPool()) {\n\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::reset(const std::shared_ptr &account,\n const std::chrono::system_clock::time_point &toDate) {\n account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\")->editor()->clear();\n }\n\n std::shared_ptr> StellarLikeBlockchainExplorerAccountSynchronizer::synchronize(\n const std::shared_ptr &account) {\n if (_notifier != nullptr) {\n return _notifier;\n }\n _notifier = std::make_shared>();\n synchronizeAccount(account);\n return _notifier;\n }\n\n bool StellarLikeBlockchainExplorerAccountSynchronizer::isSynchronizing() const {\n return _notifier != nullptr;\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr &account) {\n auto self = shared_from_this();\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n auto state = preferences\n ->template getObject(\"state\")\n \/\/ provide default state if none exists yet\n .getValueOr(SavedState{});\n\n synchronizeAccount(account, state);\n }\n\n void\n StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeAccount(const std::shared_ptr& account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n\n _explorer->getAccount(address)\n .onComplete(account->getContext(), [self, account, state] (const Try>& accountInfo) mutable {\n if (accountInfo.isFailure() && accountInfo.getFailure().getErrorCode() == api::ErrorCode::ACCOUNT_NOT_FOUND) {\n self->endSynchronization(account, state);\n } else if (accountInfo.isFailure()) {\n self->failSynchronization(accountInfo.getFailure());\n } else {\n soci::session sql(self->_database->getPool());\n account->updateAccountInfo(sql, *accountInfo.getValue());\n self->synchronizeTransactions(account, state);\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::synchronizeTransactions(\n const std::shared_ptr &account,\n StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n auto address = account->getKeychain()->getAddress()->toString();\n auto self = shared_from_this();\n fmt::print(\"Current paging token: {}\\n\", state.transactionPagingToken.getValueOr(\"no paging token\"));\n _explorer->getTransactions(address, state.transactionPagingToken)\n .onComplete(account->getContext(), [self, account, state] (const Try& txs) mutable {\n if (txs.isFailure()) {\n self->failSynchronization(txs.getFailure());\n } else {\n {\n for (const auto &tx : txs.getValue()) {\n soci::session sql(self->_database->getPool());\n soci::transaction tr(sql);\n account->logger()->debug(\"XLM transaction hash: {}, paging_token: {}\", tx->hash, tx->pagingToken);\n auto const flag = account->putTransaction(sql, *tx);\n\n if (::ledger::core::account::isInsertedOperation(flag)) {\n ++state.insertedOperations;\n }\n tr.commit();\n state.lastBlockHeight = std::max(state.lastBlockHeight, tx->ledger);\n }\n }\n account->emitEventsNow();\n if (!txs.getValue().empty()) {\n state.transactionPagingToken = txs.getValue().back()->pagingToken;\n fmt::print(\"Paging token for next round: {}\\n\", state.transactionPagingToken.getValueOr(\"no paging token\"));\n {\n auto preferences = account->getInternalPreferences()->getSubPreferences(\"StellarLikeBlockchainExplorerAccountSynchronizer\");\n preferences->editor()->putObject(\"state\", state)->commit();\n }\n \n self->synchronizeTransactions(account, state);\n } else {\n self->endSynchronization(account, state);\n }\n }\n });\n }\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::endSynchronization(\n const std::shared_ptr& account,\n const StellarLikeBlockchainExplorerAccountSynchronizer::SavedState &state) {\n BlockchainExplorerAccountSynchronizationResult result;\n\n soci::session sql(account->getWallet()->getDatabase()->getPool());\n result.lastBlockHeight = BlockDatabaseHelper::getLastBlock(sql,\n account->getWallet()->getCurrency().name)\n .template map([] (const Block& block) {\n return block.height;\n }).getValueOr(0);\n\n result.newOperations = state.insertedOperations;\n\n\n _notifier->success(result);\n _notifier = nullptr;\n }\n\n\n void StellarLikeBlockchainExplorerAccountSynchronizer::failSynchronization(const Exception &ex) {\n _notifier->failure(ex);\n _notifier = nullptr;\n }\n }\n}\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Copyright (c) 2017 Josef Adamsson\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n\nnamespace inviwo {\n\n\/\/ The Class Identifier has to be globally unique. Use a reverse DNS naming scheme\nconst ProcessorInfo CoordinateReader::processorInfo_{\n \"envision.CoordinateReader\", \/\/ Class identifier\n \"Coordinate Reader\", \/\/ Display name\n \"Crystal\", \/\/ Category\n CodeState::Experimental, \/\/ Code state\n Tags::None, \/\/ Tags\n};\nconst ProcessorInfo CoordinateReader::getProcessorInfo() const {\n return processorInfo_;\n}\n\nCoordinateReader::CoordinateReader()\n : Processor()\n , outport_(\"outport\")\n , inport_(\"inport\")\n\n \/\/ New property for animations\n , timestep_(\"timestep\", \"Time step\", false)\n , path_(\"path\", \"Path\", \"\", InvalidationLevel::InvalidOutput, PropertySemantics::Default) {\n\n addPort(outport_);\n addPort(inport_);\n\n \/\/ New property for animations\n addProperty(timestep_);\n addProperty(path_);\n}\n\nvoid CoordinateReader::process() {\n const auto h5path = hdf5::Path(path_.get());\n const auto data = inport_.getData();\n auto vecptr = std::make_shared>(data->getVectorOfVec3AtPath(h5path));\n outport_.setData(vecptr);\n}\n\n} \/\/ namespace\nNy branch för coordreader\/*********************************************************************************\n *\n * Copyright (c) 2017 Josef Adamsson\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n\nnamespace inviwo {\n\n\/\/ The Class Identifier has to be globally unique. Use a reverse DNS naming scheme\nconst ProcessorInfo CoordinateReader::processorInfo_{\n \"envision.CoordinateReader\", \/\/ Class identifier\n \"Coordinate Reader\", \/\/ Display name\n \"Crystal\", \/\/ Category\n CodeState::Experimental, \/\/ Code state\n Tags::None, \/\/ Tags\n};\nconst ProcessorInfo CoordinateReader::getProcessorInfo() const {\n return processorInfo_;\n}\n\nCoordinateReader::CoordinateReader()\n : Processor()\n , outport_(\"outport\")\n , inport_(\"inport\")\n\n \/\/ New property for animations\n , timestep_(\"timestep\", \"Time step\", false)\n , path_(\"path\", \"Path\", \"\", InvalidationLevel::InvalidOutput, PropertySemantics::Default) {\n\n addPort(outport_);\n addPort(inport_);\n\n \/\/ New property for animations\n addProperty(timestep_);\n addProperty(path_);\n}\n\nvoid CoordinateReader::process() {\n const auto h5path = hdf5::Path(path_.get());\n const auto data = inport_.getData();\n \n\/*\nif ibrion = 0\n timeh5 = h5path.split('\/')\nelse\n\n\n*\/\n\n auto vecptr = std::make_shared>(data->getVectorOfVec3AtPath(h5path));\n outport_.setData(vecptr);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*\n * caosVM_flow.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Sun May 30 2004.\n * Copyright (c) 2004 Alyssa Milburn. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 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 \"caosVM.h\"\n#include \n#include \"openc2e.h\"\n#include \"World.h\" \/\/ enum\n#include \/\/ sqrt\n#include \n#include \"AgentHelpers.h\"\n\n\/**\n DOIF (command) condition (condition)\n %status maybe\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n \n Part of a DOIF\/ELIF\/ELSE\/ENDI block. Jumps to the next part of the block if condition is false, \n otherwise continues executing the script.\n*\/\nvoid caosVM::c_DOIF() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n ELIF (command) condition (condition)\n %pragma variants all\n %status maybe\n %cost c1,c2 0\n \n Part of a DOIF\/ELIF\/ELSE\/ENDI block. If none of the previous DOIF\/ELIF conditions have been true, and condition evaluates to true, then the code in the ELIF block is executed.\n If found outside a DOIF block, it is equivalent to a DOIF. If you take advantage of this behavior, fuzzie is of the opinion that you should be shot.\n*\/\nvoid caosVM::c_ELIF() {\n\t\/\/ handled elsewhere\n}\n\n\n\/**\n ELSE (command)\n %status maybe\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n \n Part of a DOIF\/ELIF\/ELSE\/ENDI block. If ELSE is present, it is jumped to when none of the previous DOIF\/ELIF conditions are true.\n*\/\nvoid caosVM::c_ELSE() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n ENDI (command)\n %status maybe\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n \n The end of a DOIF\/ELIF\/ELSE\/ENDI block.\n*\/\nvoid caosVM::c_ENDI() {\n\t\/\/ TODO: cost in c2e?\n}\n\n\/**\n REPS (command) reps (integer)\n %status maybe\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n\n The start of a REPS...REPE loop. The body of the loop will be executed (reps) times.\n*\/\nvoid caosVM::c_REPS() {\n\t\/\/ Our expression parameter might push on a value that's a pointer\n\t\/\/ (or otherwise not an integer); deal with it\n\t\n\tVM_PARAM_INTEGER(n);\n\tresult.setInt(n+1); \/\/ we'll visit the DECJNZ first to handle 0 etc\n}\n\n\/**\n REPE (command)\n %status maybe\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n\n The end of a REPS...REPE loop.\n*\/\nvoid caosVM::c_REPE() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n LOOP (command)\n %status maybe\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n \n The start of a LOOP...EVER or LOOP...UNTL loop.\n*\/\nvoid caosVM::c_LOOP() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n EVER (command)\n %status maybe\n %pragma variants c1 c2 cv c3\n \n Jumps back to the matching LOOP, no matter what.\n*\/\nvoid caosVM::c_EVER() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n UNTL (command) condition (condition)\n %status maybe\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n \n Jumps back to the matching LOOP unless the condition evaluates to true.\n*\/\nvoid caosVM::c_UNTL() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n GSUB (command) label (label)\n %pragma retc -1\n %status maybe\n %pragma variants c1 c2 cv c3\n \n Jumps to a subroutine defined by SUBR with label (label).\n*\/\nvoid caosVM::c_GSUB() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n SUBR (command) label (label)\n %status maybe\n %pragma variants c1 c2 cv c3\n \n Defines the start of a subroute to be called with GSUB, with label (label).\n If the command is encountered during execution, it acts like a STOP.\n*\/\nvoid caosVM::c_SUBR() {\n\t\/\/ handled elsewhere\n}\n\n\/**\n RETN (command)\n %pragma retc -1\n %status maybe\n %pragma variants c1 c2 cv c3\n \n Returns from a subroutine called with GSUB.\n*\/\nvoid caosVM::c_RETN() {\n\tif (callStack.empty())\n\t\tthrow creaturesException(\"RETN with an empty callstack\");\n\tnip = callStack.back().nip;\n\tcallStack.back().valueStack.swap(valueStack);\n\tcallStack.back().valueStack.clear(); \/\/ just in case\n\tcallStack.pop_back();\n}\n\n\/**\n NEXT (command)\n %status maybe\n %pragma variants all\n %cost c1,c2 0\n\n The end of an ENUM...NEXT loop.\n*\/\nvoid caosVM::c_NEXT() {\n\ttarg = owner;\n}\n\n\/**\n ENUM (command) family (integer) genus (integer) species (integer)\n %status maybe\n %pragma retc -1\n %pragma variants c1 c2 cv c3\n %cost c1,c2 0\n\n Loops through all agents with the given classifier. 0 on any field is a\n wildcard. The loop body is terminated by a NEXT.\n*\/\nvoid caosVM::c_ENUM() {\n\tVM_VERIFY_SIZE(3)\n\tVM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);\n\tVM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);\n\tVM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);\n\n\tcaosVar nullv; nullv.reset();\n\tvalueStack.push_back(nullv);\n\t\n\tfor (std::list >::iterator i\n\t\t\t= world.agents.begin(); i != world.agents.end(); i++) {\n\t\tboost::shared_ptr a = (*i);\n\t\tif (!a) continue;\n\t\tif (species && species != a->species) continue;\n\t\tif (genus && genus != a->genus) continue;\n\t\tif (family && family != a->family) continue;\n\n\t\tcaosVar v; v.setAgent(a);\n\t\tvalueStack.push_back(v);\n\t}\n}\n\n\/**\n ESEE (command) family (integer) genus (integer) species (integer)\n %status maybe\n %pragma retc -1\n %pragma variants c2 cv c3\n \n Simular to ENUM, but iterates through agents visible to OWNR, or visible to TARG in an install script.\n An agent can be seen if it is within the range set by RNGE, and is visible (this includes the PERM value\n of walls that lie between them, and, if the agent is a Creature, it not having the 'invisible' attribute).\n*\/\nvoid caosVM::c_ESEE() {\n\tVM_VERIFY_SIZE(3)\n\tVM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);\n\tVM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);\n\tVM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);\n\n\tAgent *seeing;\n\tif (owner) seeing = owner; else seeing = targ;\n\tvalid_agent(seeing);\n\n\tcaosVar nullv; nullv.reset();\n\tvalueStack.push_back(nullv);\n\n\tstd::vector > agents = getVisibleList(seeing, family, genus, species);\n\tfor (std::vector >::iterator i = agents.begin(); i != agents.end(); i++) {\n\t\tcaosVar v; v.setAgent(*i);\n\t\tvalueStack.push_back(v);\n\t}\n}\n\nbool agentsTouching(Agent *first, Agent *second); \/\/ caosVM_agent.cpp\n\n\/**\n ETCH (command) family (integer) genus (integer) species (integer)\n %pragma retc -1\n %status maybe\n %pragma variants c2 cv c3\n\n Similar to ENUM, but iterates through the agents OWNR is touching, or TARG is touching in an install script.\n*\/\nvoid caosVM::c_ETCH() {\n\tVM_VERIFY_SIZE(3)\n\tVM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);\n\tVM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);\n\tVM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);\n\n\tAgent *touching;\n\tif (owner) touching = owner; else touching = targ;\n\tvalid_agent(touching);\n\t\n\tcaosVar nullv; nullv.reset();\n\tvalueStack.push_back(nullv);\n\t\n\tfor (std::list >::iterator i\n\t\t\t= world.agents.begin(); i != world.agents.end(); i++) {\n\t\tboost::shared_ptr a = (*i);\n\t\tif (!a) continue;\n\t\tif (species && species != a->species) continue;\n\t\tif (genus && genus != a->genus) continue;\n\t\tif (family && family != a->family) continue;\n\t\tif (a.get() == touching) continue;\n\n\t\tif (agentsTouching(a.get(), touching)) {\n\t\t\tcaosVar v; v.setAgent(a);\n\t\t\tvalueStack.push_back(v);\n\t\t}\n\t}\n}\n\n\/**\n EPAS (command) family (integer) genus (integer) species (integer)\n %pragma retc -1\n %status stub\n\n Similar to ENUM, but iterates through the OWNR vehicle's passengers.\n*\/\nvoid caosVM::c_EPAS() {\n\tVM_VERIFY_SIZE(3)\n\tVM_PARAM_INTEGER(species) caos_assert(species >= 0); caos_assert(species <= 65535);\n\tVM_PARAM_INTEGER(genus) caos_assert(genus >= 0); caos_assert(genus <= 255);\n\tVM_PARAM_INTEGER(family) caos_assert(family >= 0); caos_assert(family <= 255);\n\n\t\/\/ TODO: should probably implement this (ESEE)\n\n\tcaosVar nullv; nullv.reset();\n\tvalueStack.push_back(nullv);\n}\n\n\/**\n ECON (command) agent (agent)\n %pragma retc -1\n %status stub\n\n Loops through all the agents in the connective system containing the given agent.\n*\/\nvoid caosVM::c_ECON() {\n\tVM_VERIFY_SIZE(3)\n\tVM_PARAM_VALIDAGENT(agent)\n\n\t\/\/ TODO: should probably implement this (ESEE)\n\n\tcaosVar nullv; nullv.reset();\n\tvalueStack.push_back(nullv);\n}\n\n\/**\n CALL (command) script_no (integer) p1 (any) p2 (any)\n %status maybe\n %pragma variants c2 cv c3\n\n Calls script_no on OWNR, then waits for it to return. The invoked script\n will inherit the caller's INST setting, but any changes it makes to it will\n be reversed once it returns - so eg if you call a script when in INST mode,\n it calls OVER and returns, you'll still be in INST.\n \n Script variables (VAxx) will not be preserved - you'll have to use OVxx\n for any parameters.\n *\/\nvoid caosVM::c_CALL() {\n\tVM_PARAM_VALUE(p2)\n\tVM_PARAM_VALUE(p1)\n\tVM_PARAM_INTEGER(script_no)\n\n\tvalid_agent(owner);\n\tcaos_assert(script_no >= 0 && script_no < 65536);\n\n\tshared_ptr