text
stringlengths
54
60.6k
<commit_before>/** * Copyright (C) 2015 Topology LP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <bonefish/websocket/websocket_transport.hpp> #include <bonefish/messages/wamp_message.hpp> #include <bonefish/messages/wamp_message_type.hpp> #include <bonefish/serialization/expandable_buffer.hpp> #include <bonefish/serialization/wamp_serializer.hpp> #include <bonefish/trace/trace.hpp> #include <iostream> namespace bonefish { websocket_transport::websocket_transport(const std::shared_ptr<wamp_serializer>& serializer, const websocketpp::connection_hdl& handle, const std::shared_ptr<websocketpp::server<websocket_config>>& server) : m_serializer(serializer) , m_handle(handle) , m_server(server) { } bool websocket_transport::send_message(const wamp_message* message) { BONEFISH_TRACE("sending message: %1%", message_type_to_string(message->get_type())); expandable_buffer buffer = m_serializer->serialize(message); m_server->send(m_handle, buffer.data(), buffer.size(), websocketpp::frame::opcode::BINARY); return true; } } // namespace bonefish <commit_msg>[websocket] Send JSON as text rather than binary.<commit_after>/** * Copyright (C) 2015 Topology LP * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <bonefish/websocket/websocket_transport.hpp> #include <bonefish/messages/wamp_message.hpp> #include <bonefish/messages/wamp_message_type.hpp> #include <bonefish/serialization/expandable_buffer.hpp> #include <bonefish/serialization/wamp_serializer.hpp> #include <bonefish/trace/trace.hpp> #include <iostream> namespace bonefish { websocket_transport::websocket_transport(const std::shared_ptr<wamp_serializer>& serializer, const websocketpp::connection_hdl& handle, const std::shared_ptr<websocketpp::server<websocket_config>>& server) : m_serializer(serializer) , m_handle(handle) , m_server(server) { } bool websocket_transport::send_message(const wamp_message* message) { BONEFISH_TRACE("sending message: %1%", message_type_to_string(message->get_type())); expandable_buffer buffer = m_serializer->serialize(message); auto opcode = (m_serializer->get_type() == wamp_serializer_type::JSON) ? websocketpp::frame::opcode::TEXT : websocketpp::frame::opcode::BINARY; m_server->send(m_handle, buffer.data(), buffer.size(), opcode); return true; } } // namespace bonefish <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #ifndef TYPE_TRAITS_H #define TYPE_TRAITS_H #include <types.hpp> #include <enable_if.hpp> namespace std { template <typename T> struct iterator_traits { using value_type = typename T::value_type; ///< The value type of the iterator using reference = typename T::reference; ///< The reference type of the iterator using pointer = typename T::pointer; ///< The pointer type of the iterator using difference_type = typename T::difference_type; ///< The difference type of the iterator }; template <typename T> struct iterator_traits <T*> { using value_type = T; ///< The value type of the iterator using reference = T&; ///< The reference type of the iterator using pointer = T*; ///< The pointer type of the iterator using difference_type = size_t; ///< The difference type of the iterator }; /* remove_reference */ template<typename T> struct remove_reference { using type = T; }; template<typename T> struct remove_reference<T&>{ using type = T; }; template<typename T> struct remove_reference<T&&> { using type = T; }; template<typename T> using remove_reference_t = typename remove_reference<T>::type; /* remove_extent */ template<typename T> struct remove_extent { using type = T; }; template<typename T> struct remove_extent<T[]> { using type = T; }; template<typename T, size_t N> struct remove_extent<T[N]> { using type = T; }; template<typename T> using remove_extent_t = typename remove_extent<T>::type; /* remove_const */ template<typename T> struct remove_const { using type = T; }; template<typename T> struct remove_const<const T> { using type = T; }; template<typename T> using remove_const_t = typename remove_const<T>::type; /* add_const */ template<typename T> struct add_const { using type = const T; }; template<typename T> struct add_const<const T> { using type = T; }; template<typename T> using add_const_t = typename add_const<T>::type; /* remove_volatile */ template<typename T> struct remove_volatile { using type = T; }; template<typename T> struct remove_volatile<volatile T> { using type = T; }; template<typename T> using remove_volatile_t = typename remove_volatile<T>::type; /* remove_cv */ template<typename T> struct remove_cv { using type = typename std::remove_volatile<typename std::remove_const<T>::type>::type; }; template<typename T> using remove_cv_t = typename remove_cv<T>::type; /* conditional */ template<bool B, typename T, typename F> struct conditional { using type = T; }; template<typename T, typename F> struct conditional<false, T, F> { using type = F; }; template<bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type; /* is_trivially_destructible */ template<typename T> struct is_trivially_destructible { static constexpr const bool value = __has_trivial_destructor(T); }; template<> struct is_trivially_destructible<void> { static constexpr const bool value = true; }; /* is_trivially_destructible */ template<typename T> struct has_trivial_assign { static constexpr const bool value = __has_trivial_assign(T); }; /* is_pointer */ /*! * \brief Traits to test if given type is a pointer type */ template <typename T> struct is_pointer { static constexpr const bool value = false; }; /*! * \copdoc is_pointer */ template <typename T> struct is_pointer<T*>{ static constexpr const bool value = true; }; /* is_reference */ /*! * \brief Traits to test if given type is a reference type */ template <typename T> struct is_reference { static constexpr const bool value = false; }; /*! * \copdoc is_reference */ template <typename T> struct is_reference<T&>{ static constexpr const bool value = true; }; /*! * \copdoc is_reference */ template <typename T> struct is_reference<T&&>{ static constexpr const bool value = true; }; /* is_array */ /*! * \brief Traits to test if given type is an array type */ template<typename T> struct is_array { static constexpr const bool value = false; }; /*! * \copdoc is_array */ template<typename T> struct is_array<T[]>{ static constexpr const bool value = true; }; /*! * \copdoc is_array */ template<typename T, size_t N> struct is_array<T[N]>{ static constexpr const bool value = true; }; /* is_function */ template<typename T> struct is_function { static constexpr const bool value = false; }; template<typename Ret, typename... Args> struct is_function<Ret(Args...)> { static constexpr const bool value = true; }; template<typename Ret, typename... Args> struct is_function<Ret(Args......)> { static constexpr const bool value = true; }; /* add_rvalue_reference */ template<typename T, typename Enable = void> struct add_rvalue_reference; template<typename T> struct add_rvalue_reference<T, typename std::enable_if_t<std::is_reference<T>::value>> { using type = T; }; template<typename T> struct add_rvalue_reference<T, typename std::disable_if_t<!std::is_reference<T>::value>> { using type = T&&; }; /* add_pointer */ template<typename T> struct add_pointer { using type = typename std::remove_reference<T>::type*; }; template<typename T> using add_pointer_t = typename add_pointer<T>::type; /* decay */ template<typename T> struct decay { using U = std::remove_reference_t<T>; using type = std::conditional_t< std::is_array<U>::value, std::remove_extent_t<U>*, std::conditional_t< std::is_function<U>::value, std::add_pointer_t<U>, std::remove_cv_t<U>>>; }; /* is_same */ /*! * \brief Traits to test if two types are the same */ template<typename T1, typename T2> struct is_same { static constexpr const bool value = false; }; /*! * \copydoc is_same */ template<typename T1> struct is_same <T1, T1> { static constexpr const bool value = true; }; } //end of namespace std #endif <commit_msg>is_integral traits<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #ifndef TYPE_TRAITS_H #define TYPE_TRAITS_H #include <types.hpp> #include <enable_if.hpp> namespace std { template <typename T> struct iterator_traits { using value_type = typename T::value_type; ///< The value type of the iterator using reference = typename T::reference; ///< The reference type of the iterator using pointer = typename T::pointer; ///< The pointer type of the iterator using difference_type = typename T::difference_type; ///< The difference type of the iterator }; template <typename T> struct iterator_traits <T*> { using value_type = T; ///< The value type of the iterator using reference = T&; ///< The reference type of the iterator using pointer = T*; ///< The pointer type of the iterator using difference_type = size_t; ///< The difference type of the iterator }; /* remove_reference */ template<typename T> struct remove_reference { using type = T; }; template<typename T> struct remove_reference<T&>{ using type = T; }; template<typename T> struct remove_reference<T&&> { using type = T; }; template<typename T> using remove_reference_t = typename remove_reference<T>::type; /* remove_extent */ template<typename T> struct remove_extent { using type = T; }; template<typename T> struct remove_extent<T[]> { using type = T; }; template<typename T, size_t N> struct remove_extent<T[N]> { using type = T; }; template<typename T> using remove_extent_t = typename remove_extent<T>::type; /* remove_const */ template<typename T> struct remove_const { using type = T; }; template<typename T> struct remove_const<const T> { using type = T; }; template<typename T> using remove_const_t = typename remove_const<T>::type; /* add_const */ template<typename T> struct add_const { using type = const T; }; template<typename T> struct add_const<const T> { using type = T; }; template<typename T> using add_const_t = typename add_const<T>::type; /* remove_volatile */ template<typename T> struct remove_volatile { using type = T; }; template<typename T> struct remove_volatile<volatile T> { using type = T; }; template<typename T> using remove_volatile_t = typename remove_volatile<T>::type; /* remove_cv */ template<typename T> struct remove_cv { using type = typename std::remove_volatile<typename std::remove_const<T>::type>::type; }; template<typename T> using remove_cv_t = typename remove_cv<T>::type; /* conditional */ template<bool B, typename T, typename F> struct conditional { using type = T; }; template<typename T, typename F> struct conditional<false, T, F> { using type = F; }; template<bool B, typename T, typename F> using conditional_t = typename std::conditional<B, T, F>::type; /* is_trivially_destructible */ template<typename T> struct is_trivially_destructible { static constexpr const bool value = __has_trivial_destructor(T); }; template<> struct is_trivially_destructible<void> { static constexpr const bool value = true; }; /* is_trivially_destructible */ template<typename T> struct has_trivial_assign { static constexpr const bool value = __has_trivial_assign(T); }; /* is_pointer */ /*! * \brief Traits to test if given type is a pointer type */ template <typename T> struct is_pointer { static constexpr const bool value = false; }; /*! * \copdoc is_pointer */ template <typename T> struct is_pointer<T*>{ static constexpr const bool value = true; }; /* is_reference */ /*! * \brief Traits to test if given type is a reference type */ template <typename T> struct is_reference { static constexpr const bool value = false; }; /*! * \copdoc is_reference */ template <typename T> struct is_reference<T&>{ static constexpr const bool value = true; }; /*! * \copdoc is_reference */ template <typename T> struct is_reference<T&&>{ static constexpr const bool value = true; }; /* is_array */ /*! * \brief Traits to test if given type is an array type */ template<typename T> struct is_array { static constexpr const bool value = false; }; /*! * \copdoc is_array */ template<typename T> struct is_array<T[]>{ static constexpr const bool value = true; }; /*! * \copdoc is_array */ template<typename T, size_t N> struct is_array<T[N]>{ static constexpr const bool value = true; }; /* is_function */ template<typename T> struct is_function { static constexpr const bool value = false; }; template<typename Ret, typename... Args> struct is_function<Ret(Args...)> { static constexpr const bool value = true; }; template<typename Ret, typename... Args> struct is_function<Ret(Args......)> { static constexpr const bool value = true; }; /* add_rvalue_reference */ template<typename T, typename Enable = void> struct add_rvalue_reference; template<typename T> struct add_rvalue_reference<T, typename std::enable_if_t<std::is_reference<T>::value>> { using type = T; }; template<typename T> struct add_rvalue_reference<T, typename std::disable_if_t<!std::is_reference<T>::value>> { using type = T&&; }; /* add_pointer */ template<typename T> struct add_pointer { using type = typename std::remove_reference<T>::type*; }; template<typename T> using add_pointer_t = typename add_pointer<T>::type; /* decay */ template<typename T> struct decay { using U = std::remove_reference_t<T>; using type = std::conditional_t< std::is_array<U>::value, std::remove_extent_t<U>*, std::conditional_t< std::is_function<U>::value, std::add_pointer_t<U>, std::remove_cv_t<U>>>; }; /* is_same */ /*! * \brief Traits to test if two types are the same */ template<typename T1, typename T2> struct is_same { static constexpr const bool value = false; }; /*! * \copydoc is_same */ template<typename T1> struct is_same <T1, T1> { static constexpr const bool value = true; }; /* is_integral */ template <typename> struct is_integral { static constexpr const bool value = false; }; template <typename T> struct is_integral <const T>{ static constexpr const bool value = is_integral<T>::value; }; template <> struct is_integral <bool> { static constexpr const bool value = true; }; template <> struct is_integral <char> { static constexpr const bool value = true; }; template <> struct is_integral <signed char> { static constexpr const bool value = true; }; template <> struct is_integral<unsigned char> { static constexpr const bool value = true; }; template <> struct is_integral<short> { static constexpr const bool value = true; }; template <> struct is_integral<unsigned short> { static constexpr const bool value = true; }; template <> struct is_integral<int> { static constexpr const bool value = true; }; template <> struct is_integral<unsigned int> { static constexpr const bool value = true; }; template <> struct is_integral<long> { static constexpr const bool value = true; }; template <> struct is_integral<unsigned long> { static constexpr const bool value = true; }; template <> struct is_integral<long long> { static constexpr const bool value = true; }; template <> struct is_integral<unsigned long long> { static constexpr const bool value = true; }; } //end of namespace std #endif <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkSliceBySliceImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkSimpleFilterWatcher.h" #include "itkPipelineMonitorImageFilter.h" #include "itkTestingMacros.h" #include "itkMedianImageFilter.h" void sliceCallBack(itk::Object* object, const itk::EventObject &, void*) { // the same typedefs than in the main function - should be done in a nicer way const int Dimension = 3; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::SliceBySliceImageFilter< ImageType, ImageType > FilterType; typedef itk::MedianImageFilter< FilterType::InternalInputImageType, FilterType::InternalOutputImageType > MedianType; // real stuff begins here // get the slice by slice filter and the median filter FilterType * filter = dynamic_cast< FilterType * >( object ); MedianType * median = dynamic_cast< MedianType * >( filter->GetModifiableInputFilter() ); // std::cout << "callback! slice: " << filter->GetSliceIndex() << std::endl; // set half of the slice number as radius MedianType::InputSizeType radius; radius.Fill( filter->GetSliceIndex() / 2 ); median->SetRadius( radius ); } int itkSliceBySliceImageFilterTest(int argc, char * argv[]) { if( argc != 4 ) { std::cerr << "usage: " << argv[0] << " input output slicingDimension" << std::endl; return EXIT_FAILURE; } const int Dimension = 3; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); typedef itk::SliceBySliceImageFilter< ImageType, ImageType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->DebugOn(); filter->SetInput( reader->GetOutput() ); typedef itk::MedianImageFilter< FilterType::InternalInputImageType, FilterType::InternalOutputImageType > MedianType; MedianType::Pointer median = MedianType::New(); filter->SetFilter( median ); typedef itk::PipelineMonitorImageFilter<FilterType::InternalOutputImageType> MonitorType; MonitorType::Pointer monitor = MonitorType::New(); itk::CStyleCommand::Pointer command = itk::CStyleCommand::New(); command->SetCallback( *sliceCallBack ); filter->AddObserver( itk::IterationEvent(), command ); itk::SimpleFilterWatcher watcher(filter, "filter"); typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( argv[2] ); unsigned int slicingDimension; std::istringstream istrm( argv[3] ); istrm >> slicingDimension; filter->SetDimension( slicingDimension ); std::cout << "Slicing dimension: " << slicingDimension << std::endl; std::cout << "Slicing dimension: " << filter->GetDimension() << std::endl; try { writer->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } // set up a requested region of just one pixel and verify that was // all that was produced. std::cout << "Testing with requested region..." << std::endl; ImageType::Pointer temp = filter->GetOutput(); temp->DisconnectPipeline(); temp = ITK_NULLPTR; ImageType::RegionType rr = reader->GetOutput()->GetLargestPossibleRegion(); for (unsigned int i = 0; i < ImageType::ImageDimension; ++i) { rr.SetIndex(i, rr.GetIndex(i)+rr.GetSize(i)/2); rr.SetSize(i,1); } monitor->SetInput(median->GetOutput()); filter->SetOutputFilter(monitor); filter->GetOutput()->SetRequestedRegion(rr); try { filter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } // check that one slice executed is just one pixel and the input // filter just update that region TEST_EXPECT_EQUAL( monitor->GetNumberOfUpdates(), 1 ); TEST_EXPECT_EQUAL( monitor->GetOutputRequestedRegions()[0].GetNumberOfPixels(), 1 ); TEST_EXPECT_TRUE( monitor->VerifyAllInputCanStream(1) ); // // Test that a sliced version of the input image information is passed // through to the internal filters // ImageType::Pointer image = ImageType::New(); image->SetRegions(reader->GetOutput()->GetLargestPossibleRegion()); image->Allocate(); ImageType::SpacingType spacing; ImageType::PointType origin; for ( unsigned int i = 0; i < ImageType::ImageDimension; ++i ) { spacing[i] = i + 0.1; origin[i] = i + 0.2; } image->SetSpacing(spacing); image->SetOrigin(origin); filter->SetInput(image); filter->Update(); FilterType::InternalInputImageType::SpacingType expectedInternalSpacing; FilterType::InternalInputImageType::PointType expectedInternalOrigin; for ( unsigned int i = 0, internal_i = 0; internal_i < FilterType::InternalImageDimension; ++i, ++internal_i ) { if ( i == slicingDimension ) { ++i; } expectedInternalSpacing[internal_i] = spacing[i]; expectedInternalOrigin[internal_i] = origin[i]; } TEST_EXPECT_EQUAL( monitor->GetUpdatedOutputSpacing(), expectedInternalSpacing ); TEST_EXPECT_EQUAL( monitor->GetUpdatedOutputOrigin(), expectedInternalOrigin ); // // Exercise PrintSelf() // filter->Print( std::cout ); // // Exercise exceptions // bool caughtException; FilterType::Pointer badFilter = FilterType::New(); std::cout << "Testing with no filter set..." << std::endl; badFilter->SetInput( reader->GetOutput() ); caughtException = false; try { badFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cout << "Caught expected exception" << std::endl; std::cout << excp << std::endl; caughtException = true; } if (!caughtException) { return EXIT_FAILURE; } std::cout << "Testing with no output filter set..." << std::endl; badFilter->SetInput( reader->GetOutput() ); badFilter->SetInputFilter( median ); caughtException = false; try { badFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cout << "Caught expected exception" << std::endl; std::cout << excp << std::endl; caughtException = true; } if (!caughtException) { return EXIT_FAILURE; } // check NULL input/output TRY_EXPECT_EXCEPTION(badFilter->SetInputFilter(ITK_NULLPTR)); TRY_EXPECT_EXCEPTION(badFilter->SetOutputFilter(ITK_NULLPTR)); return EXIT_SUCCESS; } <commit_msg>COMP: Valgrind detects uninitialized memory read<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkSliceBySliceImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkSimpleFilterWatcher.h" #include "itkPipelineMonitorImageFilter.h" #include "itkTestingMacros.h" #include "itkMedianImageFilter.h" void sliceCallBack(itk::Object* object, const itk::EventObject &, void*) { // the same typedefs than in the main function - should be done in a nicer way const int Dimension = 3; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::SliceBySliceImageFilter< ImageType, ImageType > FilterType; typedef itk::MedianImageFilter< FilterType::InternalInputImageType, FilterType::InternalOutputImageType > MedianType; // real stuff begins here // get the slice by slice filter and the median filter FilterType * filter = dynamic_cast< FilterType * >( object ); MedianType * median = dynamic_cast< MedianType * >( filter->GetModifiableInputFilter() ); // std::cout << "callback! slice: " << filter->GetSliceIndex() << std::endl; // set half of the slice number as radius MedianType::InputSizeType radius; radius.Fill( filter->GetSliceIndex() / 2 ); median->SetRadius( radius ); } int itkSliceBySliceImageFilterTest(int argc, char * argv[]) { if( argc != 4 ) { std::cerr << "usage: " << argv[0] << " input output slicingDimension" << std::endl; return EXIT_FAILURE; } const int Dimension = 3; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); typedef itk::SliceBySliceImageFilter< ImageType, ImageType > FilterType; FilterType::Pointer filter = FilterType::New(); filter->DebugOn(); filter->SetInput( reader->GetOutput() ); typedef itk::MedianImageFilter< FilterType::InternalInputImageType, FilterType::InternalOutputImageType > MedianType; MedianType::Pointer median = MedianType::New(); filter->SetFilter( median ); typedef itk::PipelineMonitorImageFilter<FilterType::InternalOutputImageType> MonitorType; MonitorType::Pointer monitor = MonitorType::New(); itk::CStyleCommand::Pointer command = itk::CStyleCommand::New(); command->SetCallback( *sliceCallBack ); filter->AddObserver( itk::IterationEvent(), command ); itk::SimpleFilterWatcher watcher(filter, "filter"); typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( filter->GetOutput() ); writer->SetFileName( argv[2] ); unsigned int slicingDimension; std::istringstream istrm( argv[3] ); istrm >> slicingDimension; filter->SetDimension( slicingDimension ); std::cout << "Slicing dimension: " << slicingDimension << std::endl; std::cout << "Slicing dimension: " << filter->GetDimension() << std::endl; try { writer->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } // set up a requested region of just one pixel and verify that was // all that was produced. std::cout << "Testing with requested region..." << std::endl; ImageType::Pointer temp = filter->GetOutput(); temp->DisconnectPipeline(); temp = ITK_NULLPTR; ImageType::RegionType rr = reader->GetOutput()->GetLargestPossibleRegion(); for (unsigned int i = 0; i < ImageType::ImageDimension; ++i) { rr.SetIndex(i, rr.GetIndex(i)+rr.GetSize(i)/2); rr.SetSize(i,1); } monitor->SetInput(median->GetOutput()); filter->SetOutputFilter(monitor); filter->GetOutput()->SetRequestedRegion(rr); try { filter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } // check that one slice executed is just one pixel and the input // filter just update that region TEST_EXPECT_EQUAL( monitor->GetNumberOfUpdates(), 1 ); TEST_EXPECT_EQUAL( monitor->GetOutputRequestedRegions()[0].GetNumberOfPixels(), 1 ); TEST_EXPECT_TRUE( monitor->VerifyAllInputCanStream(1) ); // // Test that a sliced version of the input image information is passed // through to the internal filters // ImageType::Pointer image = ImageType::New(); image->SetRegions(reader->GetOutput()->GetLargestPossibleRegion()); image->Allocate(true); ImageType::SpacingType spacing; ImageType::PointType origin; for ( unsigned int i = 0; i < ImageType::ImageDimension; ++i ) { spacing[i] = i + 0.1; origin[i] = i + 0.2; } image->SetSpacing(spacing); image->SetOrigin(origin); filter->SetInput(image); filter->Update(); FilterType::InternalInputImageType::SpacingType expectedInternalSpacing; FilterType::InternalInputImageType::PointType expectedInternalOrigin; for ( unsigned int i = 0, internal_i = 0; internal_i < FilterType::InternalImageDimension; ++i, ++internal_i ) { if ( i == slicingDimension ) { ++i; } expectedInternalSpacing[internal_i] = spacing[i]; expectedInternalOrigin[internal_i] = origin[i]; } TEST_EXPECT_EQUAL( monitor->GetUpdatedOutputSpacing(), expectedInternalSpacing ); TEST_EXPECT_EQUAL( monitor->GetUpdatedOutputOrigin(), expectedInternalOrigin ); // // Exercise PrintSelf() // filter->Print( std::cout ); // // Exercise exceptions // bool caughtException; FilterType::Pointer badFilter = FilterType::New(); std::cout << "Testing with no filter set..." << std::endl; badFilter->SetInput( reader->GetOutput() ); caughtException = false; try { badFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cout << "Caught expected exception" << std::endl; std::cout << excp << std::endl; caughtException = true; } if (!caughtException) { return EXIT_FAILURE; } std::cout << "Testing with no output filter set..." << std::endl; badFilter->SetInput( reader->GetOutput() ); badFilter->SetInputFilter( median ); caughtException = false; try { badFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cout << "Caught expected exception" << std::endl; std::cout << excp << std::endl; caughtException = true; } if (!caughtException) { return EXIT_FAILURE; } // check NULL input/output TRY_EXPECT_EXCEPTION(badFilter->SetInputFilter(ITK_NULLPTR)); TRY_EXPECT_EXCEPTION(badFilter->SetOutputFilter(ITK_NULLPTR)); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: testOptimizationExample.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Cassidy Kelly * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ // Author: Cassidy Kelly //============================================================================== //============================================================================== #include <OpenSim/OpenSim.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <istream> using namespace OpenSim; using namespace std; #define ARM26_DESIGN_SPACE_DIM 6 #define REF_MAX_VEL 5.43 // Reference solution used for testing. const static double refControls[ARM26_DESIGN_SPACE_DIM] = {0.01, 0.01, 0.0639327, 0.99, 0.99, 0.72858}; int main() { try { Storage result("Arm26_noActivation_states.sto"), standard("std_Arm26_noActivation_states.sto"); CHECK_STORAGE_AGAINST_STANDARD(result, standard, Array<double>(0.01, 16), __FILE__, __LINE__, "Arm26 no activation states failed"); cout << "Arm26 no activation states passed\n"; // Check the optimization result acheived at least a velocity of 5.43 m/s, and that the control values are within 20% of the reference values. ifstream resFile; resFile.open("Arm26_optimization_result"); ASSERT(resFile.is_open(), __FILE__, __LINE__, "Can't open optimization result file" ); vector<double> resVec; for ( ; ; ) { double tmp; resFile >> tmp; if (!resFile.good()) break; resVec.push_back(tmp); } ASSERT(resVec.size() == ARM26_DESIGN_SPACE_DIM+1, __FILE__, __LINE__, "Optimization result size mismatch" ); for (int i = 0; i < ARM26_DESIGN_SPACE_DIM-1; i++) { ASSERT(fabs(resVec[i] - refControls[i])/refControls[i] < 0.2, __FILE__, __LINE__, "Control value does not match reference" ); } ASSERT(resVec[ARM26_DESIGN_SPACE_DIM+1] < REF_MAX_VEL, __FILE__, __LINE__, "Optimized velocity smaller than reference" ); cout << "Arm26 optimization results passed\n"; } catch (const Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } <commit_msg>fixed off-by-1 error...oops<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: testOptimizationExample.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Cassidy Kelly * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ // Author: Cassidy Kelly //============================================================================== //============================================================================== #include <OpenSim/OpenSim.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> #include <istream> using namespace OpenSim; using namespace std; #define ARM26_DESIGN_SPACE_DIM 6 #define REF_MAX_VEL 5.43 // Reference solution used for testing. const static double refControls[ARM26_DESIGN_SPACE_DIM] = {0.01, 0.01, 0.0639327, 0.99, 0.99, 0.72858}; int main() { try { Storage result("Arm26_noActivation_states.sto"), standard("std_Arm26_noActivation_states.sto"); CHECK_STORAGE_AGAINST_STANDARD(result, standard, Array<double>(0.01, 16), __FILE__, __LINE__, "Arm26 no activation states failed"); cout << "Arm26 no activation states passed\n"; // Check the optimization result acheived at least a velocity of 5.43 m/s, and that the control values are within 20% of the reference values. ifstream resFile; resFile.open("Arm26_optimization_result"); ASSERT(resFile.is_open(), __FILE__, __LINE__, "Can't open optimization result file" ); vector<double> resVec; for ( ; ; ) { double tmp; resFile >> tmp; if (!resFile.good()) break; resVec.push_back(tmp); } ASSERT(resVec.size() == ARM26_DESIGN_SPACE_DIM+1, __FILE__, __LINE__, "Optimization result size mismatch" ); for (int i = 0; i < ARM26_DESIGN_SPACE_DIM-1; i++) { ASSERT(fabs(resVec[i] - refControls[i])/refControls[i] < 0.2, __FILE__, __LINE__, "Control value does not match reference" ); } ASSERT(resVec[ARM26_DESIGN_SPACE_DIM] > REF_MAX_VEL, __FILE__, __LINE__, "Optimized velocity smaller than reference" ); cout << "Arm26 optimization results passed\n"; } catch (const Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } <|endoftext|>
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // TubeTK includes #include "tubeCLIFilterWatcher.h" #include "tubeCLIProgressReporter.h" #include "tubeMessage.h" // TubeTKITK includes #include "tubeSegmentUsingOtsuThreshold.h" // ITK includes #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkTimeProbesCollectorBase.h> #include "SegmentUsingOtsuThresholdCLP.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ); // Must follow include of "...CLP.h" and forward declaration of int DoIt( ... ). #include "tubeCLIHelperFunctions.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; // setup progress reporting double progress = 0.0; tube::CLIProgressReporter progressReporter( "SegmentUsingOtsuThreshold", CLPProcessInformation ); progressReporter.Start(); progressReporter.Report( progress ); // The timeCollector to perform basic profiling of algorithmic components itk::TimeProbesCollectorBase timeCollector; // typedefs typedef tube::SegmentUsingOtsuThreshold< TPixel, VDimension > FilterType; // Load input image timeCollector.Start("Load data"); typedef typename FilterType::InputImageType InputImageType; typedef itk::ImageFileReader< InputImageType > ImageReaderType; typename ImageReaderType::Pointer inputReader = ImageReaderType::New(); try { inputReader->SetFileName( inputVolume.c_str() ); inputReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error loading input image: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } // Load mask image if provided typedef typename FilterType::MaskImageType MaskImageType; typedef itk::ImageFileReader< MaskImageType > MaskReaderType; typename MaskReaderType::Pointer maskReader = MaskReaderType::New(); if( maskVolume.size() > 0 ) { try { maskReader->SetFileName( maskVolume.c_str() ); maskReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error reading input mask: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } timeCollector.Stop("Load data"); progress = 0.1; progressReporter.Report( progress ); // run otsu thresholding timeCollector.Start("Otsu thresholding"); typename FilterType::Pointer filter = FilterType::New(); filter->SetInput( inputReader->GetOutput() ); if( maskVolume.size() > 0 ) { filter->SetMaskValue( maskValue ); filter->SetMaskImage( maskReader->GetOutput() ); } filter->Update(); std::cout << "Chosen threshold = " << filter->GetThreshold() << std::endl; timeCollector.Stop("Otsu thresholding"); progress = 0.8; // At about 80% done progressReporter.Report( progress ); // write output typedef typename FilterType::OutputImageType OutputImageType; typedef itk::ImageFileWriter< OutputImageType > OutputWriterType; timeCollector.Start("Write segmentation mask"); typename OutputWriterType::Pointer writer = OutputWriterType::New(); try { writer->SetFileName( outputVolume.c_str() ); writer->SetInput( filter->GetOutput() ); writer->SetUseCompression( true ); writer->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error writing segmentation mask: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } timeCollector.Stop("Write segmentation mask"); progress = 1.0; progressReporter.Report( progress ); progressReporter.End(); timeCollector.Report(); return EXIT_SUCCESS; } // Main int main( int argc, char * argv[] ) { PARSE_ARGS; // You may need to update this line if, in the project's .xml CLI file, // you change the variable name for the inputVolume. return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv ); } <commit_msg>Small style change in SegmentUsingOtsuThreshold<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // ITK includes #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkTimeProbesCollectorBase.h> // TubeTKITK includes #include "tubeSegmentUsingOtsuThreshold.h" // TubeTK includes #include "tubeCLIFilterWatcher.h" #include "tubeCLIProgressReporter.h" #include "tubeMessage.h" #include "SegmentUsingOtsuThresholdCLP.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ); // Must follow include of "...CLP.h" and forward declaration of int DoIt( ... ). #include "tubeCLIHelperFunctions.h" template< class TPixel, unsigned int VDimension > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; // setup progress reporting double progress = 0.0; tube::CLIProgressReporter progressReporter( "SegmentUsingOtsuThreshold", CLPProcessInformation ); progressReporter.Start(); progressReporter.Report( progress ); // The timeCollector to perform basic profiling of algorithmic components itk::TimeProbesCollectorBase timeCollector; // typedefs typedef tube::SegmentUsingOtsuThreshold< TPixel, VDimension > FilterType; // Load input image timeCollector.Start("Load data"); typedef typename FilterType::InputImageType InputImageType; typedef itk::ImageFileReader< InputImageType > ImageReaderType; typename ImageReaderType::Pointer inputReader = ImageReaderType::New(); try { inputReader->SetFileName( inputVolume.c_str() ); inputReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error loading input image: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } // Load mask image if provided typedef typename FilterType::MaskImageType MaskImageType; typedef itk::ImageFileReader< MaskImageType > MaskReaderType; typename MaskReaderType::Pointer maskReader = MaskReaderType::New(); if( maskVolume.size() > 0 ) { try { maskReader->SetFileName( maskVolume.c_str() ); maskReader->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error reading input mask: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } } timeCollector.Stop("Load data"); progress = 0.1; progressReporter.Report( progress ); // run otsu thresholding timeCollector.Start("Otsu thresholding"); typename FilterType::Pointer filter = FilterType::New(); filter->SetInput( inputReader->GetOutput() ); if( maskVolume.size() > 0 ) { filter->SetMaskValue( maskValue ); filter->SetMaskImage( maskReader->GetOutput() ); } filter->Update(); std::cout << "Chosen threshold = " << filter->GetThreshold() << std::endl; timeCollector.Stop("Otsu thresholding"); progress = 0.8; // At about 80% done progressReporter.Report( progress ); // write output typedef typename FilterType::OutputImageType OutputImageType; typedef itk::ImageFileWriter< OutputImageType > OutputWriterType; timeCollector.Start("Write segmentation mask"); typename OutputWriterType::Pointer writer = OutputWriterType::New(); try { writer->SetFileName( outputVolume.c_str() ); writer->SetInput( filter->GetOutput() ); writer->SetUseCompression( true ); writer->Update(); } catch( itk::ExceptionObject & err ) { tube::ErrorMessage( "Error writing segmentation mask: " + std::string(err.GetDescription()) ); timeCollector.Report(); return EXIT_FAILURE; } timeCollector.Stop("Write segmentation mask"); progress = 1.0; progressReporter.Report( progress ); progressReporter.End(); timeCollector.Report(); return EXIT_SUCCESS; } // Main int main( int argc, char * argv[] ) { PARSE_ARGS; // You may need to update this line if, in the project's .xml CLI file, // you change the variable name for the inputVolume. return tube::ParseArgsAndCallDoIt( inputVolume, argc, argv ); } <|endoftext|>
<commit_before>#include "master.hpp" namespace factor { bool factor_vm::fatal_erroring_p; static inline void fa_diddly_atal_error() { printf("fatal_error in fatal_error!\n"); breakpoint(); ::_exit(86); } void fatal_error(const char *msg, cell tagged) { if (factor_vm::fatal_erroring_p) fa_diddly_atal_error(); factor_vm::fatal_erroring_p = true; std::cout << "fatal_error: " << msg; std::cout << ": " << (void*)tagged; std::cout << std::endl; abort(); } void critical_error(const char *msg, cell tagged) { std::cout << "You have triggered a bug in Factor. Please report.\n"; std::cout << "critical_error: " << msg; std::cout << ": " << std::hex << tagged << std::dec; std::cout << std::endl; current_vm()->factorbug(); } void out_of_memory() { std::cout << "Out of memory\n\n"; current_vm()->dump_generations(); abort(); } void factor_vm::general_error(vm_error_type error, cell arg1, cell arg2) { faulting_p = true; /* Reset local roots before allocating anything */ data_roots.clear(); bignum_roots.clear(); code_roots.clear(); /* If we had an underflow or overflow, data or retain stack pointers might be out of bounds, so fix them before allocating anything */ ctx->fix_stacks(); /* If error was thrown during heap scan, we re-enable the GC */ gc_off = false; /* If the error handler is set, we rewind any C stack frames and pass the error to user-space. */ if(!current_gc && to_boolean(special_objects[ERROR_HANDLER_QUOT])) { #ifdef FACTOR_DEBUG /* Doing a GC here triggers all kinds of funny errors */ primitive_compact_gc(); #endif /* Now its safe to allocate and GC */ cell error_object = allot_array_4(special_objects[OBJ_ERROR], tag_fixnum(error),arg1,arg2); ctx->push(error_object); /* The unwind-native-frames subprimitive will clear faulting_p if it was successfully reached. */ unwind_native_frames(special_objects[ERROR_HANDLER_QUOT], ctx->callstack_top); } /* Error was thrown in early startup before error handler is set, so just crash. */ else { std::cout << "You have triggered a bug in Factor. Please report.\n"; std::cout << "error: " << error << std::endl; std::cout << "arg 1: "; print_obj(arg1); std::cout << std::endl; std::cout << "arg 2: "; print_obj(arg2); std::cout << std::endl; factorbug(); abort(); } } void factor_vm::type_error(cell type, cell tagged) { general_error(ERROR_TYPE,tag_fixnum(type),tagged); } void factor_vm::not_implemented_error() { general_error(ERROR_NOT_IMPLEMENTED,false_object,false_object); } void factor_vm::verify_memory_protection_error(cell addr) { /* Called from the OS-specific top halves of the signal handlers to make sure it's safe to dispatch to memory_protection_error */ if(fatal_erroring_p) fa_diddly_atal_error(); if(faulting_p && !code->safepoint_p(addr)) fatal_error("Double fault", addr); else if(fep_p) fatal_error("Memory protection fault during low-level debugger", addr); else if(atomic::load(&current_gc_p)) fatal_error("Memory protection fault during gc", addr); } void factor_vm::memory_protection_error(cell pc, cell addr) { if(code->safepoint_p(addr)) safepoint.handle_safepoint(this, pc); else if(ctx->datastack_seg->underflow_p(addr)) general_error(ERROR_DATASTACK_UNDERFLOW,false_object,false_object); else if(ctx->datastack_seg->overflow_p(addr)) general_error(ERROR_DATASTACK_OVERFLOW,false_object,false_object); else if(ctx->retainstack_seg->underflow_p(addr)) general_error(ERROR_RETAINSTACK_UNDERFLOW,false_object,false_object); else if(ctx->retainstack_seg->overflow_p(addr)) general_error(ERROR_RETAINSTACK_OVERFLOW,false_object,false_object); else if(ctx->callstack_seg->underflow_p(addr)) general_error(ERROR_CALLSTACK_OVERFLOW,false_object,false_object); else if(ctx->callstack_seg->overflow_p(addr)) general_error(ERROR_CALLSTACK_UNDERFLOW,false_object,false_object); else general_error(ERROR_MEMORY,from_unsigned_cell(addr),false_object); } void factor_vm::signal_error(cell signal) { general_error(ERROR_SIGNAL,from_unsigned_cell(signal),false_object); } void factor_vm::divide_by_zero_error() { general_error(ERROR_DIVIDE_BY_ZERO,false_object,false_object); } void factor_vm::fp_trap_error(unsigned int fpu_status) { general_error(ERROR_FP_TRAP,tag_fixnum(fpu_status),false_object); } /* For testing purposes */ void factor_vm::primitive_unimplemented() { not_implemented_error(); } void factor_vm::memory_signal_handler_impl() { memory_protection_error(signal_fault_pc, signal_fault_addr); if (!signal_resumable) { /* In theory we should only get here if the callstack overflowed during a safepoint */ general_error(ERROR_CALLSTACK_OVERFLOW,false_object,false_object); } } void memory_signal_handler_impl() { current_vm()->memory_signal_handler_impl(); } void factor_vm::synchronous_signal_handler_impl() { signal_error(signal_number); } void synchronous_signal_handler_impl() { current_vm()->synchronous_signal_handler_impl(); } void factor_vm::fp_signal_handler_impl() { /* Clear pending exceptions to avoid getting stuck in a loop */ set_fpu_state(get_fpu_state()); fp_trap_error(signal_fpu_status); } void fp_signal_handler_impl() { current_vm()->fp_signal_handler_impl(); } } <commit_msg>errors.cpp: general_error() throws away its args when it calls compact_gc() when compiled with DEBUG=1. Save the args as data_roots instead. Fixes #615. See #620.<commit_after>#include "master.hpp" namespace factor { bool factor_vm::fatal_erroring_p; static inline void fa_diddly_atal_error() { printf("fatal_error in fatal_error!\n"); breakpoint(); ::_exit(86); } void fatal_error(const char *msg, cell tagged) { if (factor_vm::fatal_erroring_p) fa_diddly_atal_error(); factor_vm::fatal_erroring_p = true; std::cout << "fatal_error: " << msg; std::cout << ": " << (void*)tagged; std::cout << std::endl; abort(); } void critical_error(const char *msg, cell tagged) { std::cout << "You have triggered a bug in Factor. Please report.\n"; std::cout << "critical_error: " << msg; std::cout << ": " << std::hex << tagged << std::dec; std::cout << std::endl; current_vm()->factorbug(); } void out_of_memory() { std::cout << "Out of memory\n\n"; current_vm()->dump_generations(); abort(); } void factor_vm::general_error(vm_error_type error, cell arg1_, cell arg2_) { faulting_p = true; /* Reset local roots before allocating anything */ data_roots.clear(); bignum_roots.clear(); code_roots.clear(); data_root<object> arg1(arg1_,this); data_root<object> arg2(arg2_,this); /* If we had an underflow or overflow, data or retain stack pointers might be out of bounds, so fix them before allocating anything */ ctx->fix_stacks(); /* If error was thrown during heap scan, we re-enable the GC */ gc_off = false; /* If the error handler is set, we rewind any C stack frames and pass the error to user-space. */ if(!current_gc && to_boolean(special_objects[ERROR_HANDLER_QUOT])) { #ifdef FACTOR_DEBUG /* Doing a GC here triggers all kinds of funny errors */ primitive_compact_gc(); #endif /* Now its safe to allocate and GC */ cell error_object = allot_array_4(special_objects[OBJ_ERROR], tag_fixnum(error),arg1.value(),arg2.value()); ctx->push(error_object); /* The unwind-native-frames subprimitive will clear faulting_p if it was successfully reached. */ unwind_native_frames(special_objects[ERROR_HANDLER_QUOT], ctx->callstack_top); } /* Error was thrown in early startup before error handler is set, so just crash. */ else { std::cout << "You have triggered a bug in Factor. Please report.\n"; std::cout << "error: " << error << std::endl; std::cout << "arg 1: "; print_obj(arg1.value()); std::cout << std::endl; std::cout << "arg 2: "; print_obj(arg2.value()); std::cout << std::endl; factorbug(); abort(); } } void factor_vm::type_error(cell type, cell tagged) { general_error(ERROR_TYPE,tag_fixnum(type),tagged); } void factor_vm::not_implemented_error() { general_error(ERROR_NOT_IMPLEMENTED,false_object,false_object); } void factor_vm::verify_memory_protection_error(cell addr) { /* Called from the OS-specific top halves of the signal handlers to make sure it's safe to dispatch to memory_protection_error */ if(fatal_erroring_p) fa_diddly_atal_error(); if(faulting_p && !code->safepoint_p(addr)) fatal_error("Double fault", addr); else if(fep_p) fatal_error("Memory protection fault during low-level debugger", addr); else if(atomic::load(&current_gc_p)) fatal_error("Memory protection fault during gc", addr); } void factor_vm::memory_protection_error(cell pc, cell addr) { if(code->safepoint_p(addr)) safepoint.handle_safepoint(this, pc); else if(ctx->datastack_seg->underflow_p(addr)) general_error(ERROR_DATASTACK_UNDERFLOW,false_object,false_object); else if(ctx->datastack_seg->overflow_p(addr)) general_error(ERROR_DATASTACK_OVERFLOW,false_object,false_object); else if(ctx->retainstack_seg->underflow_p(addr)) general_error(ERROR_RETAINSTACK_UNDERFLOW,false_object,false_object); else if(ctx->retainstack_seg->overflow_p(addr)) general_error(ERROR_RETAINSTACK_OVERFLOW,false_object,false_object); else if(ctx->callstack_seg->underflow_p(addr)) general_error(ERROR_CALLSTACK_OVERFLOW,false_object,false_object); else if(ctx->callstack_seg->overflow_p(addr)) general_error(ERROR_CALLSTACK_UNDERFLOW,false_object,false_object); else general_error(ERROR_MEMORY,from_unsigned_cell(addr),false_object); } void factor_vm::signal_error(cell signal) { general_error(ERROR_SIGNAL,from_unsigned_cell(signal),false_object); } void factor_vm::divide_by_zero_error() { general_error(ERROR_DIVIDE_BY_ZERO,false_object,false_object); } void factor_vm::fp_trap_error(unsigned int fpu_status) { general_error(ERROR_FP_TRAP,tag_fixnum(fpu_status),false_object); } /* For testing purposes */ void factor_vm::primitive_unimplemented() { not_implemented_error(); } void factor_vm::memory_signal_handler_impl() { memory_protection_error(signal_fault_pc, signal_fault_addr); if (!signal_resumable) { /* In theory we should only get here if the callstack overflowed during a safepoint */ general_error(ERROR_CALLSTACK_OVERFLOW,false_object,false_object); } } void memory_signal_handler_impl() { current_vm()->memory_signal_handler_impl(); } void factor_vm::synchronous_signal_handler_impl() { signal_error(signal_number); } void synchronous_signal_handler_impl() { current_vm()->synchronous_signal_handler_impl(); } void factor_vm::fp_signal_handler_impl() { /* Clear pending exceptions to avoid getting stuck in a loop */ set_fpu_state(get_fpu_state()); fp_trap_error(signal_fpu_status); } void fp_signal_handler_impl() { current_vm()->fp_signal_handler_impl(); } } <|endoftext|>
<commit_before>#include <QCoreApplication> #include <QDebug> #include "wakeproto.h" const unsigned char crc8Table[256] = { 0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97, 0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E, 0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4, 0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D, 0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11, 0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8, 0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52, 0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB, 0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA, 0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13, 0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9, 0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50, 0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C, 0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95, 0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F, 0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6, 0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED, 0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54, 0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE, 0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17, 0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B, 0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2, 0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28, 0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91, 0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0, 0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69, 0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93, 0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A, 0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56, 0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF, 0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15, 0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC }; Wakeproto::Wakeproto() { packet_started = 0; data_started = 0; bytes = 0; num_of_bytes = 0; qDebug() << "Wakeproto module loaded" << endl; } void Wakeproto::test() { qDebug() << "Wakeproto init completed" << endl; } QByteArray Wakeproto::createpacket(unsigned char address, unsigned char cmd, QByteArray data) { QByteArray packet; unsigned char tx_crc = 0xFF; tx_crc = crc8Table[tx_crc ^ FEND]; tx_crc = crc8Table[tx_crc ^ address]; tx_crc = crc8Table[tx_crc ^ cmd]; tx_crc = crc8Table[tx_crc ^ data.size()]; foreach (unsigned char k, data) { tx_crc = crc8Table[tx_crc ^ k]; } packet.append(address); // Addr packet.append(cmd); // CMD packet.append(data.size()); // N packet.append(data); // data packet.append(tx_crc); // CRC packet = stuffing(packet); packet.prepend(FEND); // FEND return packet; } int Wakeproto::getpacket(QByteArray data) { QByteArray rx_buffer = data; QByteArray rx_data; unsigned char rx_crc_calculated = 0xFF; unsigned char rx_crc_actual = 0xFF; foreach (unsigned char rx_byte, rx_buffer) { if (rx_byte == FEND && packet_started == 1) { // FEND, ݣ - bytes.clear(); bytes.append(rx_byte); num_of_bytes = 0; rx_data.clear(); rx_buffer.clear(); } else if (packet_started) { // Bytes destuffing if(rx_byte == TFEND && bytes.endsWith(FESC)){ bytes.chop(1); bytes.append(FEND); } else if (rx_byte == TFESC && bytes.endsWith(FESC)) { bytes.chop(1); bytes.append(FESC); } else { bytes.append(rx_byte); } // We received full header? if (bytes.size() == 4) { // TODO: implement ADDR & CMD check // fixme: what is 'n' ? //num_of_bytes = bytes.at(n); data_started = 1; } if(data_started && bytes.size() == 1 + 1 + 1 + 1 + num_of_bytes + 1) { // FEND + ADDR + CMD + N + DATA + CRC //rx_data = bytes.mid(datastream,bytes.size()-5); rx_data = bytes.mid(datastream,5); foreach (unsigned char k, rx_data) { rx_crc_calculated = crc8Table[rx_crc_calculated ^ k]; } rx_crc_actual = bytes.right(1).at(0); if (rx_crc_actual != rx_crc_calculated) { // TODO: inform on CRC error //qDebug() << "[RX] CRC error" << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl; //rx_crc_error_count++; // Send NACK //bytes.clear(); //bytes.append(0xAE); //send_packet(201,60,bytes); } else { // TODO: Handle received packet // qDebug() << "[RX] FEND" << endl // << "[RX] ADDR: " << QString::number(static_cast<unsigned char>(bytes.at(addr))) << endl // << "[RX] CMD: " << QString::number(static_cast<unsigned char>(bytes.at(cmd))) << endl // << "[RX] N: " << QString::number(static_cast<unsigned char>(bytes.at(n))) << endl // << "[RX] DATA: " << rx_data.toHex() << endl // << "[RX] CRC: " << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl // << "----------------------------" << endl; //process_packet(bytes.at(cmd), rx_data); } data_started = 0; packet_started = 0; num_of_bytes = 0; bytes.clear(); rx_data.clear(); rx_buffer.clear(); } } else if (rx_byte == FEND) { bytes.append(rx_byte); packet_started = 1; } } return 0; } QByteArray Wakeproto::stuffing(QByteArray packet) { QByteArray stuffed_packet; foreach (unsigned char byte, packet) { switch (byte) { case FEND: stuffed_packet.append(FESC); stuffed_packet.append(TFEND); break; case FESC: stuffed_packet.append(FESC); stuffed_packet.append(TFESC); break; default: stuffed_packet.append(byte); break; } } return stuffed_packet; } <commit_msg>Fixed bux in rx_buff<commit_after>#include <QCoreApplication> #include <QDebug> #include "wakeproto.h" const unsigned char crc8Table[256] = { 0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97, 0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E, 0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4, 0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D, 0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11, 0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8, 0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52, 0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB, 0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA, 0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13, 0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9, 0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50, 0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C, 0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95, 0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F, 0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6, 0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED, 0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54, 0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE, 0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17, 0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B, 0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2, 0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28, 0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91, 0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0, 0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69, 0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93, 0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A, 0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56, 0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF, 0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15, 0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC }; Wakeproto::Wakeproto() { packet_started = 0; data_started = 0; bytes = 0; num_of_bytes = 0; qDebug() << "Wakeproto module loaded" << endl; } void Wakeproto::test() { qDebug() << "Wakeproto init completed" << endl; } QByteArray Wakeproto::createpacket(unsigned char address, unsigned char cmd, QByteArray data) { QByteArray packet; unsigned char tx_crc = 0xFF; tx_crc = crc8Table[tx_crc ^ FEND]; tx_crc = crc8Table[tx_crc ^ address]; tx_crc = crc8Table[tx_crc ^ cmd]; tx_crc = crc8Table[tx_crc ^ data.size()]; foreach (unsigned char k, data) { tx_crc = crc8Table[tx_crc ^ k]; } packet.append(address); // Addr packet.append(cmd); // CMD packet.append(data.size()); // N packet.append(data); // data packet.append(tx_crc); // CRC packet = stuffing(packet); packet.prepend(FEND); // FEND return packet; } int Wakeproto::getpacket(QByteArray data) { QByteArray rx_buffer = data; QByteArray rx_data; unsigned char rx_crc_calculated = 0xFF; unsigned char rx_crc_actual = 0xFF; foreach (unsigned char rx_byte, rx_buffer) { if (rx_byte == FEND && packet_started == 1) { // FEND, ݣ - bytes.clear(); bytes.append(rx_byte); num_of_bytes = 0; rx_data.clear(); rx_buffer.clear(); } else if (packet_started) { // Bytes destuffing if(rx_byte == TFEND && bytes.endsWith(FESC)){ bytes.chop(1); bytes.append(FEND); } else if (rx_byte == TFESC && bytes.endsWith(FESC)) { bytes.chop(1); bytes.append(FESC); } else { bytes.append(rx_byte); } // We received full header? if (bytes.size() == 4) { // TODO: implement ADDR & CMD check // fixme: what is 'n' ? //num_of_bytes = bytes.at(n); data_started = 1; } if(data_started && bytes.size() == 1 + 1 + 1 + 1 + num_of_bytes + 1) { // FEND + ADDR + CMD + N + DATA + CRC rx_data = bytes.mid(datastream,bytes.size()-5); foreach (unsigned char k, rx_data) { rx_crc_calculated = crc8Table[rx_crc_calculated ^ k]; } rx_crc_actual = bytes.right(1).at(0); if (rx_crc_actual != rx_crc_calculated) { // TODO: inform on CRC error //qDebug() << "[RX] CRC error" << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl; //rx_crc_error_count++; // Send NACK //bytes.clear(); //bytes.append(0xAE); //send_packet(201,60,bytes); } else { // TODO: Handle received packet // qDebug() << "[RX] FEND" << endl // << "[RX] ADDR: " << QString::number(static_cast<unsigned char>(bytes.at(addr))) << endl // << "[RX] CMD: " << QString::number(static_cast<unsigned char>(bytes.at(cmd))) << endl // << "[RX] N: " << QString::number(static_cast<unsigned char>(bytes.at(n))) << endl // << "[RX] DATA: " << rx_data.toHex() << endl // << "[RX] CRC: " << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl // << "----------------------------" << endl; //process_packet(bytes.at(cmd), rx_data); } data_started = 0; packet_started = 0; num_of_bytes = 0; bytes.clear(); rx_data.clear(); rx_buffer.clear(); } } else if (rx_byte == FEND) { bytes.append(rx_byte); packet_started = 1; } } return 0; } QByteArray Wakeproto::stuffing(QByteArray packet) { QByteArray stuffed_packet; foreach (unsigned char byte, packet) { switch (byte) { case FEND: stuffed_packet.append(FESC); stuffed_packet.append(TFEND); break; case FESC: stuffed_packet.append(FESC); stuffed_packet.append(TFESC); break; default: stuffed_packet.append(byte); break; } } return stuffed_packet; } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #pragma once #include <typeinfo> #if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED #include <libmemcached-1.0/memcached.h> #include <libmemcachedutil-1.0/ostream.hpp> #include <libtest/memcached.hpp> #endif #if defined(HAVE_LIBGEARMAN) && HAVE_LIBGEARMAN #include <libgearman-1.0/ostream.hpp> #endif namespace libtest { LIBTEST_API bool jenkins_is_caller(void); LIBTEST_API bool gdb_is_caller(void); LIBTEST_API bool _in_valgrind(const char *file, int line, const char *func); LIBTEST_API bool helgrind_is_caller(void); template <class T_comparable> bool _compare_truth(const char *file, int line, const char *func, T_comparable __expected, const char *assertation_label) { if (__expected == false) { libtest::stream::make_cerr(file, line, func) << "Assertation \"" << assertation_label << "\""; return false; } return true; } template <class T1_comparable, class T2_comparable> bool _compare(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual, bool use_io) { if (__expected != __actual) { if (use_io) { libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\""; } return false; } return true; } template <class T1_comparable, class T2_comparable> bool _compare_strcmp(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual) { if (__expected == NULL) { FATAL("Expected value was NULL, programmer error"); } if (__actual == NULL) { libtest::stream::make_cerr(file, line, func) << "Expected " << __expected << " but got NULL"; return false; } if (strncmp(__expected, __actual, strlen(__expected))) { libtest::stream::make_cerr(file, line, func) << "Expected " << __expected << " passed \"" << __actual << "\""; return false; } return true; } template <class T_comparable> bool _compare_zero(const char *file, int line, const char *func, T_comparable __actual) { if (T_comparable(0) != __actual) { libtest::stream::make_cerr(file, line, func) << "Expected 0 got \"" << __actual << "\""; return false; } return true; } template <class T1_comparable, class T2_comparable> bool _ne_compare(const char *file, int line, const char *func, T1_comparable __expected, T2_comparable __actual, bool io_error= true) { if (__expected == __actual) { if (io_error) { libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\""; } return false; } return true; } template <class T_comparable, class T_expression_string> bool _assert_truth(const char *file, int line, const char *func, T_comparable __truth, T_expression_string __expression, const char* __explain= NULL) { if (__truth) { return true; } if (__explain) { libtest::stream::make_cerr(file, line, func) << "Assertion \"" << __expression << "\" warning:" << __explain; } return false; } } // namespace libtest <commit_msg>Fixes NULL comparisons issue.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #pragma once #include <typeinfo> #if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED #include <libmemcached-1.0/memcached.h> #include <libmemcachedutil-1.0/ostream.hpp> #include <libtest/memcached.hpp> #endif #if defined(HAVE_LIBGEARMAN) && HAVE_LIBGEARMAN #include <libgearman-1.0/ostream.hpp> #endif namespace libtest { LIBTEST_API bool jenkins_is_caller(void); LIBTEST_API bool gdb_is_caller(void); LIBTEST_API bool _in_valgrind(const char *file, int line, const char *func); LIBTEST_API bool helgrind_is_caller(void); template <class T_comparable> bool _compare_truth(const char *file, int line, const char *func, T_comparable __expected, const char *assertation_label) { if (__expected == false) { libtest::stream::make_cerr(file, line, func) << "Assertation \"" << assertation_label << "\""; return false; } return true; } template <class T1_comparable, class T2_comparable> bool _compare(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual, bool use_io) { if (__expected != __actual) { if (use_io) { libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\""; } return false; } return true; } template <class T1_comparable, class T2_comparable> bool _compare_strcmp(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual) { if (strncmp(__expected, __actual, strlen(__expected))) { libtest::stream::make_cerr(file, line, func) << "Expected " << __expected << " passed \"" << __actual << "\""; return false; } return true; } template <class T_comparable> bool _compare_zero(const char *file, int line, const char *func, T_comparable __actual) { if (T_comparable(0) != __actual) { libtest::stream::make_cerr(file, line, func) << "Expected 0 got \"" << __actual << "\""; return false; } return true; } template <class T1_comparable, class T2_comparable> bool _ne_compare(const char *file, int line, const char *func, T1_comparable __expected, T2_comparable __actual, bool io_error= true) { if (__expected == __actual) { if (io_error) { libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\""; } return false; } return true; } template <class T_comparable, class T_expression_string> bool _assert_truth(const char *file, int line, const char *func, T_comparable __truth, T_expression_string __expression, const char* __explain= NULL) { if (__truth) { return true; } if (__explain) { libtest::stream::make_cerr(file, line, func) << "Assertion \"" << __expression << "\" warning:" << __explain; } return false; } } // namespace libtest <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/mailbox_synchronizer.h" #include "base/bind.h" #include "gpu/command_buffer/service/mailbox_manager.h" #include "gpu/command_buffer/service/texture_manager.h" #include "ui/gl/gl_implementation.h" namespace gpu { namespace gles2 { namespace { MailboxSynchronizer* g_instance = NULL; } // anonymous namespace // static bool MailboxSynchronizer::Initialize() { DCHECK(!g_instance); DCHECK(gfx::GetGLImplementation() != gfx::kGLImplementationNone) << "GL bindings not initialized"; switch (gfx::GetGLImplementation()) { case gfx::kGLImplementationMockGL: break; case gfx::kGLImplementationEGLGLES2: #if !defined(OS_MACOSX) { if (!gfx::g_driver_egl.ext.b_EGL_KHR_image_base || !gfx::g_driver_egl.ext.b_EGL_KHR_gl_texture_2D_image || !gfx::g_driver_gl.ext.b_GL_OES_EGL_image || !gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync) { LOG(WARNING) << "MailboxSync not supported due to missing EGL " "image/fence support"; return false; } } break; #endif default: NOTREACHED(); return false; } g_instance = new MailboxSynchronizer; return true; } // static void MailboxSynchronizer::Terminate() { DCHECK(g_instance); delete g_instance; g_instance = NULL; } // static MailboxSynchronizer* MailboxSynchronizer::GetInstance() { return g_instance; } MailboxSynchronizer::TargetName::TargetName(unsigned target, const Mailbox& mailbox) : target(target), mailbox(mailbox) {} MailboxSynchronizer::TextureGroup::TextureGroup( const TextureDefinition& definition) : definition(definition) {} MailboxSynchronizer::TextureGroup::~TextureGroup() {} MailboxSynchronizer::TextureVersion::TextureVersion( linked_ptr<TextureGroup> group) : version(group->definition.version()), group(group) {} MailboxSynchronizer::TextureVersion::~TextureVersion() {} MailboxSynchronizer::MailboxSynchronizer() {} MailboxSynchronizer::~MailboxSynchronizer() { DCHECK_EQ(0U, textures_.size()); } void MailboxSynchronizer::ReassociateMailboxLocked( const TargetName& target_name, TextureGroup* group) { lock_.AssertAcquired(); for (TextureMap::iterator it = textures_.begin(); it != textures_.end(); it++) { std::set<TargetName>::iterator mb_it = it->second.group->mailboxes.find(target_name); if (it->second.group != group && mb_it != it->second.group->mailboxes.end()) { it->second.group->mailboxes.erase(mb_it); } } group->mailboxes.insert(target_name); } linked_ptr<MailboxSynchronizer::TextureGroup> MailboxSynchronizer::GetGroupForMailboxLocked(const TargetName& target_name) { lock_.AssertAcquired(); for (TextureMap::iterator it = textures_.begin(); it != textures_.end(); it++) { std::set<TargetName>::const_iterator mb_it = it->second.group->mailboxes.find(target_name); if (mb_it != it->second.group->mailboxes.end()) return it->second.group; } return make_linked_ptr<MailboxSynchronizer::TextureGroup>(NULL); } Texture* MailboxSynchronizer::CreateTextureFromMailbox(unsigned target, const Mailbox& mailbox) { base::AutoLock lock(lock_); TargetName target_name(target, mailbox); linked_ptr<TextureGroup> group = GetGroupForMailboxLocked(target_name); if (group.get()) { Texture* new_texture = group->definition.CreateTexture(); if (new_texture) textures_.insert(std::make_pair(new_texture, TextureVersion(group))); return new_texture; } return NULL; } void MailboxSynchronizer::TextureDeleted(Texture* texture) { base::AutoLock lock(lock_); TextureMap::iterator it = textures_.find(texture); if (it != textures_.end()) { // TODO: We could avoid the update if this was the last ref. UpdateTextureLocked(it->first, it->second); textures_.erase(it); } } void MailboxSynchronizer::PushTextureUpdates(MailboxManager* manager) { base::AutoLock lock(lock_); for (MailboxManager::MailboxToTextureMap::const_iterator texture_it = manager->mailbox_to_textures_.begin(); texture_it != manager->mailbox_to_textures_.end(); texture_it++) { TargetName target_name(texture_it->first.target, texture_it->first.mailbox); Texture* texture = texture_it->second->first; // TODO(sievers): crbug.com/352274 // Should probably only fail if it already *has* mipmaps, while allowing // incomplete textures here. Also reconsider how to fail otherwise. bool needs_mips = texture->min_filter() != GL_NEAREST && texture->min_filter() != GL_LINEAR; if (target_name.target != GL_TEXTURE_2D || needs_mips) continue; TextureMap::iterator it = textures_.find(texture); if (it != textures_.end()) { TextureVersion& texture_version = it->second; TextureGroup* group = texture_version.group.get(); std::set<TargetName>::const_iterator mb_it = group->mailboxes.find(target_name); if (mb_it == group->mailboxes.end()) { // We previously did not associate this texture with the given mailbox. // Unlink other texture groups from the mailbox. ReassociateMailboxLocked(target_name, group); } UpdateTextureLocked(texture, texture_version); } else { linked_ptr<TextureGroup> group = make_linked_ptr(new TextureGroup( TextureDefinition(target_name.target, texture, 1, NULL))); // Unlink other textures from this mailbox in case the name is not new. ReassociateMailboxLocked(target_name, group.get()); textures_.insert(std::make_pair(texture, TextureVersion(group))); } } } void MailboxSynchronizer::UpdateTextureLocked(Texture* texture, TextureVersion& texture_version) { lock_.AssertAcquired(); gfx::GLImage* gl_image = texture->GetLevelImage(texture->target(), 0); TextureGroup* group = texture_version.group.get(); scoped_refptr<NativeImageBuffer> image_buffer = group->definition.image(); // Make sure we don't clobber with an older version if (!group->definition.IsOlderThan(texture_version.version)) return; // Also don't push redundant updates. Note that it would break the // versioning. if (group->definition.Matches(texture)) return; if (gl_image && !image_buffer->IsClient(gl_image)) { LOG(ERROR) << "MailboxSync: Incompatible attachment"; return; } group->definition = TextureDefinition(texture->target(), texture, ++texture_version.version, gl_image ? image_buffer : NULL); } void MailboxSynchronizer::PullTextureUpdates(MailboxManager* manager) { base::AutoLock lock(lock_); for (MailboxManager::MailboxToTextureMap::const_iterator texture_it = manager->mailbox_to_textures_.begin(); texture_it != manager->mailbox_to_textures_.end(); texture_it++) { Texture* texture = texture_it->second->first; TextureMap::iterator it = textures_.find(texture); if (it != textures_.end()) { TextureDefinition& definition = it->second.group->definition; if (it->second.version == definition.version() || definition.IsOlderThan(it->second.version)) continue; it->second.version = definition.version(); definition.UpdateTexture(texture); } } } } // namespace gles2 } // namespace gpu <commit_msg>Cherry-pick: Android Webview: Skip managed resources in mailbox sync<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/mailbox_synchronizer.h" #include "base/bind.h" #include "gpu/command_buffer/service/mailbox_manager.h" #include "gpu/command_buffer/service/texture_manager.h" #include "ui/gl/gl_implementation.h" namespace gpu { namespace gles2 { namespace { MailboxSynchronizer* g_instance = NULL; } // anonymous namespace // static bool MailboxSynchronizer::Initialize() { DCHECK(!g_instance); DCHECK(gfx::GetGLImplementation() != gfx::kGLImplementationNone) << "GL bindings not initialized"; switch (gfx::GetGLImplementation()) { case gfx::kGLImplementationMockGL: break; case gfx::kGLImplementationEGLGLES2: #if !defined(OS_MACOSX) { if (!gfx::g_driver_egl.ext.b_EGL_KHR_image_base || !gfx::g_driver_egl.ext.b_EGL_KHR_gl_texture_2D_image || !gfx::g_driver_gl.ext.b_GL_OES_EGL_image || !gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync) { LOG(WARNING) << "MailboxSync not supported due to missing EGL " "image/fence support"; return false; } } break; #endif default: NOTREACHED(); return false; } g_instance = new MailboxSynchronizer; return true; } // static void MailboxSynchronizer::Terminate() { DCHECK(g_instance); delete g_instance; g_instance = NULL; } // static MailboxSynchronizer* MailboxSynchronizer::GetInstance() { return g_instance; } MailboxSynchronizer::TargetName::TargetName(unsigned target, const Mailbox& mailbox) : target(target), mailbox(mailbox) {} MailboxSynchronizer::TextureGroup::TextureGroup( const TextureDefinition& definition) : definition(definition) {} MailboxSynchronizer::TextureGroup::~TextureGroup() {} MailboxSynchronizer::TextureVersion::TextureVersion( linked_ptr<TextureGroup> group) : version(group->definition.version()), group(group) {} MailboxSynchronizer::TextureVersion::~TextureVersion() {} MailboxSynchronizer::MailboxSynchronizer() {} MailboxSynchronizer::~MailboxSynchronizer() { DCHECK_EQ(0U, textures_.size()); } void MailboxSynchronizer::ReassociateMailboxLocked( const TargetName& target_name, TextureGroup* group) { lock_.AssertAcquired(); for (TextureMap::iterator it = textures_.begin(); it != textures_.end(); it++) { std::set<TargetName>::iterator mb_it = it->second.group->mailboxes.find(target_name); if (it->second.group != group && mb_it != it->second.group->mailboxes.end()) { it->second.group->mailboxes.erase(mb_it); } } group->mailboxes.insert(target_name); } linked_ptr<MailboxSynchronizer::TextureGroup> MailboxSynchronizer::GetGroupForMailboxLocked(const TargetName& target_name) { lock_.AssertAcquired(); for (TextureMap::iterator it = textures_.begin(); it != textures_.end(); it++) { std::set<TargetName>::const_iterator mb_it = it->second.group->mailboxes.find(target_name); if (mb_it != it->second.group->mailboxes.end()) return it->second.group; } return make_linked_ptr<MailboxSynchronizer::TextureGroup>(NULL); } Texture* MailboxSynchronizer::CreateTextureFromMailbox(unsigned target, const Mailbox& mailbox) { base::AutoLock lock(lock_); TargetName target_name(target, mailbox); linked_ptr<TextureGroup> group = GetGroupForMailboxLocked(target_name); if (group.get()) { Texture* new_texture = group->definition.CreateTexture(); if (new_texture) textures_.insert(std::make_pair(new_texture, TextureVersion(group))); return new_texture; } return NULL; } void MailboxSynchronizer::TextureDeleted(Texture* texture) { base::AutoLock lock(lock_); TextureMap::iterator it = textures_.find(texture); if (it != textures_.end()) { // TODO: We could avoid the update if this was the last ref. UpdateTextureLocked(it->first, it->second); textures_.erase(it); } } void MailboxSynchronizer::PushTextureUpdates(MailboxManager* manager) { base::AutoLock lock(lock_); for (MailboxManager::MailboxToTextureMap::const_iterator texture_it = manager->mailbox_to_textures_.begin(); texture_it != manager->mailbox_to_textures_.end(); texture_it++) { TargetName target_name(texture_it->first.target, texture_it->first.mailbox); Texture* texture = texture_it->second->first; // TODO(sievers): crbug.com/352274 // Should probably only fail if it already *has* mipmaps, while allowing // incomplete textures here. Also reconsider how to fail otherwise. bool needs_mips = texture->min_filter() != GL_NEAREST && texture->min_filter() != GL_LINEAR; if (target_name.target != GL_TEXTURE_2D || needs_mips) continue; TextureMap::iterator it = textures_.find(texture); if (it != textures_.end()) { TextureVersion& texture_version = it->second; TextureGroup* group = texture_version.group.get(); std::set<TargetName>::const_iterator mb_it = group->mailboxes.find(target_name); if (mb_it == group->mailboxes.end()) { // We previously did not associate this texture with the given mailbox. // Unlink other texture groups from the mailbox. ReassociateMailboxLocked(target_name, group); } UpdateTextureLocked(texture, texture_version); } else { // Skip compositor resources/tile textures. // TODO: Remove this, see crbug.com/399226. if (texture->pool() == GL_TEXTURE_POOL_MANAGED_CHROMIUM) continue; linked_ptr<TextureGroup> group = make_linked_ptr(new TextureGroup( TextureDefinition(target_name.target, texture, 1, NULL))); // Unlink other textures from this mailbox in case the name is not new. ReassociateMailboxLocked(target_name, group.get()); textures_.insert(std::make_pair(texture, TextureVersion(group))); } } } void MailboxSynchronizer::UpdateTextureLocked(Texture* texture, TextureVersion& texture_version) { lock_.AssertAcquired(); gfx::GLImage* gl_image = texture->GetLevelImage(texture->target(), 0); TextureGroup* group = texture_version.group.get(); scoped_refptr<NativeImageBuffer> image_buffer = group->definition.image(); // Make sure we don't clobber with an older version if (!group->definition.IsOlderThan(texture_version.version)) return; // Also don't push redundant updates. Note that it would break the // versioning. if (group->definition.Matches(texture)) return; if (gl_image && !image_buffer->IsClient(gl_image)) { LOG(ERROR) << "MailboxSync: Incompatible attachment"; return; } group->definition = TextureDefinition(texture->target(), texture, ++texture_version.version, gl_image ? image_buffer : NULL); } void MailboxSynchronizer::PullTextureUpdates(MailboxManager* manager) { base::AutoLock lock(lock_); for (MailboxManager::MailboxToTextureMap::const_iterator texture_it = manager->mailbox_to_textures_.begin(); texture_it != manager->mailbox_to_textures_.end(); texture_it++) { Texture* texture = texture_it->second->first; TextureMap::iterator it = textures_.find(texture); if (it != textures_.end()) { TextureDefinition& definition = it->second.group->definition; if (it->second.version == definition.version() || definition.IsOlderThan(it->second.version)) continue; it->second.version = definition.version(); definition.UpdateTexture(texture); } } } } // namespace gles2 } // namespace gpu <|endoftext|>
<commit_before>/*========================================================================= Copyright (c) Kitware Inc. All rights reserved. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay and Charles Law, Kitware 2012 // This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF) #include "vtkHyperTreeGridGeometry.h" #include "vtkHyperTreeGridSource.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkNew.h" #include "vtkPolyDataMapper.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" int TestHyperTreeGridTernary3DGeometry( int argc, char* argv[] ) { vtkNew<vtkHyperTreeGridSource> fractal; fractal->SetMaximumLevel( 3 ); fractal->SetGridSize( 3, 4, 2 ); fractal->SetDimension( 3 ); fractal->SetAxisBranchFactor( 3 ); vtkNew<vtkHyperTreeGridGeometry> geometry; geometry->SetInputConnection( fractal->GetOutputPort() ); geometry->Update(); vtkPolyData* pd = geometry->GetOutput(); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection( geometry->GetOutputPort() ); mapper->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() ); vtkNew<vtkActor> actor; actor->SetMapper( mapper.GetPointer() ); // Create camera double bd[6]; pd->GetBounds( bd ); vtkNew<vtkCamera> camera; camera->SetClippingRange( 1., 100. ); camera->SetFocalPoint( pd->GetCenter() ); camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] ); // Create a renderer, add actors to it vtkNew<vtkRenderer> renderer; renderer->SetActiveCamera( camera.GetPointer() ); renderer->SetBackground( 1., 1., 1. ); renderer->AddActor( actor.GetPointer() ); // Create a renderWindow vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer( renderer.GetPointer() ); renWin->SetSize( 300, 300 ); renWin->SetMultiSamples( 0 ); // Create interactor vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); // Render and test renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; } <commit_msg>A very challenging test for the 3D hyper tree geometry filter<commit_after>/*========================================================================= Copyright (c) Kitware Inc. All rights reserved. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay and Charles Law, Kitware 2012 // This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF) #include "vtkHyperTreeGridGeometry.h" #include "vtkHyperTreeGridSource.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkNew.h" #include "vtkProperty.h" #include "vtkPolyDataMapper.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" int TestHyperTreeGridTernary3DGeometry( int argc, char* argv[] ) { // Hyper tree grid vtkNew<vtkHyperTreeGridSource> htGrid; int maxLevel = 5; htGrid->SetMaximumLevel( maxLevel ); htGrid->SetGridSize( 3, 3, 2 ); htGrid->SetDimension( 3 ); htGrid->SetAxisBranchFactor( 3 ); htGrid->DualOn(); htGrid->SetDescriptor( "RRR .R. .RR ..R ..R .R.|R.......................... ........................... ........................... .............R............. ....RR.RR........R......... .....RRRR.....R.RR......... ........................... ........................... ...........................|........................... ........................... ........................... ...RR.RR.......RR.......... ........................... RR......................... ........................... ........................... ........................... ........................... ........................... ........................... ........................... ............RRR............|........................... ........................... .......RR.................. ........................... ........................... ........................... ........................... ........................... ........................... ........................... ...........................|........................... ..........................." ); // Geometry vtkNew<vtkHyperTreeGridGeometry> geometry; geometry->SetInputConnection( htGrid->GetOutputPort() ); geometry->Update(); vtkPolyData* pd = geometry->GetOutput(); // Mappers vtkNew<vtkPolyDataMapper> mapper1; mapper1->SetInputConnection( geometry->GetOutputPort() ); mapper1->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() ); mapper1->SetResolveCoincidentTopologyToPolygonOffset(); mapper1->SetResolveCoincidentTopologyPolygonOffsetParameters( 0, 1 ); vtkNew<vtkPolyDataMapper> mapper2; mapper2->SetInputConnection( geometry->GetOutputPort() ); mapper2->ScalarVisibilityOff(); mapper2->SetResolveCoincidentTopologyToPolygonOffset(); mapper2->SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 ); // Actors vtkNew<vtkActor> actor1; actor1->SetMapper( mapper1.GetPointer() ); vtkNew<vtkActor> actor2; actor2->SetMapper( mapper2.GetPointer() ); actor2->GetProperty()->SetRepresentationToWireframe(); actor2->GetProperty()->SetColor( .7, .7, .7 ); // Camera double bd[6]; pd->GetBounds( bd ); vtkNew<vtkCamera> camera; camera->SetClippingRange( 1., 100. ); camera->SetFocalPoint( pd->GetCenter() ); camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] ); // Renderer vtkNew<vtkRenderer> renderer; renderer->SetActiveCamera( camera.GetPointer() ); renderer->SetBackground( 1., 1., 1. ); renderer->AddActor( actor1.GetPointer() ); renderer->AddActor( actor2.GetPointer() ); // Render window vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer( renderer.GetPointer() ); renWin->SetSize( 300, 300 ); renWin->SetMultiSamples( 0 ); // Interactor vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); // Render and test renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; } <|endoftext|>
<commit_before>#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> int main(int argc, char *argv[]) { // Global menubar is broken for qt5 apps in Ubuntu Unity, see: // https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853 // This workaround enables a local menubar. qputenv("UBUNTU_MENUPROXY","0"); // Don't write .pyc files. qputenv("PYTHONDONTWRITEBYTECODE", "1"); QApplication app(argc, argv); QString app_dir = app.applicationDirPath(); QString main_qml = "/qml/main.qml"; QString path_prefix; QString url_prefix; app.setApplicationName("YubiKey Manager"); app.setOrganizationName("Yubico"); app.setOrganizationDomain("com.yubico"); // A lock file is used, to ensure only one running instance at the time. QString tmpDir = QDir::tempPath(); QLockFile lockFile(tmpDir + "/ykman-gui.lock"); if(!lockFile.tryLock(100)) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("YubiKey Manager is already running."); msgBox.exec(); return 1; } if (QFileInfo::exists(":" + main_qml)) { // Embedded resources path_prefix = ":"; url_prefix = "qrc://"; } else if (QFileInfo::exists(app_dir + main_qml)) { // Try relative to executable path_prefix = app_dir; url_prefix = app_dir; } else { //Assume qml/main.qml in cwd. app_dir = "."; path_prefix = "."; url_prefix = "."; } app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png")); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("appDir", app_dir); engine.rootContext()->setContextProperty("urlPrefix", url_prefix); engine.rootContext()->setContextProperty("appVersion", APP_VERSION); engine.load(QUrl(url_prefix + main_qml)); if (argc > 2 && strcmp(argv[1], "--log-level") == 0) { if (argc > 4 && strcmp(argv[3], "--log-file") == 0) { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, argv[2]), Q_ARG(QVariant, argv[4])); } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, argv[2])); } } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging"); } return app.exec(); } <commit_msg>Use QCommandLineParser instead of raw argv inspection<commit_after>#include <QApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <stdlib.h> #include <QtGlobal> #include <QtWidgets> int main(int argc, char *argv[]) { // Global menubar is broken for qt5 apps in Ubuntu Unity, see: // https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853 // This workaround enables a local menubar. qputenv("UBUNTU_MENUPROXY","0"); // Don't write .pyc files. qputenv("PYTHONDONTWRITEBYTECODE", "1"); QApplication app(argc, argv); QString app_dir = app.applicationDirPath(); QString main_qml = "/qml/main.qml"; QString path_prefix; QString url_prefix; app.setApplicationName("YubiKey Manager"); app.setApplicationVersion(APP_VERSION); app.setOrganizationName("Yubico"); app.setOrganizationDomain("com.yubico"); // A lock file is used, to ensure only one running instance at the time. QString tmpDir = QDir::tempPath(); QLockFile lockFile(tmpDir + "/ykman-gui.lock"); if(!lockFile.tryLock(100)) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("YubiKey Manager is already running."); msgBox.exec(); return 1; } if (QFileInfo::exists(":" + main_qml)) { // Embedded resources path_prefix = ":"; url_prefix = "qrc://"; } else if (QFileInfo::exists(app_dir + main_qml)) { // Try relative to executable path_prefix = app_dir; url_prefix = app_dir; } else { //Assume qml/main.qml in cwd. app_dir = "."; path_prefix = "."; url_prefix = "."; } app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png")); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty("appDir", app_dir); engine.rootContext()->setContextProperty("urlPrefix", url_prefix); engine.rootContext()->setContextProperty("appVersion", APP_VERSION); engine.load(QUrl(url_prefix + main_qml)); QCommandLineParser parser; parser.setApplicationDescription("Cross-platform application for YubiKey configuration"); parser.addHelpOption(); parser.addVersionOption(); parser.addOptions({ {"log-level", QCoreApplication::translate("main", "Set log level to <LEVEL>"), QCoreApplication::translate("main", "LEVEL")}, {"log-file", QCoreApplication::translate("main", "Print logs to <FILE> instead of standard output; ignored without --log-level"), QCoreApplication::translate("main", "FILE")}, }); parser.process(app); if (parser.isSet("log-level")) { if (parser.isSet("log-file")) { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, parser.value("log-level")), Q_ARG(QVariant, parser.value("log-file"))); } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, parser.value("log-level"))); } } else { QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging"); } return app.exec(); } <|endoftext|>
<commit_before>/* * feature suite - Feature detection suite * * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch * Please read <http://foxel.ch/license> for more information. * * * Author(s): * * Nils Hamel <[email protected]> * * * This file is part of the FOXEL project <http://foxel.ch>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. * * You are required to attribute the work as explained in the "Usage and * Attribution" section of <http://foxel.ch/license>. */ /* Source - Includes */ # include "feature-image-expose.hpp" /* Source - Entry point */ int main ( int argc, char ** argv ) { /* Path variables */ char fsImgIPath[256] = { 0 }; char fsImgOPath[256] = { 0 }; /* Parameters variables */ float fsFixMean ( 0.0 ); float fsFixStdd ( 0.0 ); /* Statistical variables */ float fsMean ( 0.0 ); float fsStdd ( 0.0 ); /* Image variable */ cv::Mat fsImage; /* Search in parameters */ lc_stdp( lc_stda( argc, argv, "--input" , "-i" ), argv, fsImgIPath, LC_STRING ); lc_stdp( lc_stda( argc, argv, "--output", "-o" ), argv, fsImgOPath, LC_STRING ); lc_stdp( lc_stda( argc, argv, "--mean" , "-m" ), argv, & fsFixMean , LC_FLOAT ); lc_stdp( lc_stda( argc, argv, "--stdd" , "-s" ), argv, & fsFixStdd , LC_FLOAT ); /* Software swicth */ if ( ( lc_stda( argc, argv, "--help", "-h" ) ) || ( argc <= 1 ) ) { /* Display message */ std::cout << FS_HELP; } else { /* Read input image */ fsImage = cv::imread( fsImgIPath, CV_LOAD_IMAGE_COLOR ); /* Verify image reading */ if ( fsImage.data != NULL ) { /* Create array on image bytes */ std::vector < char > fsBytes( fsImage.data, fsImage.data + fsImage.rows * fsImage.cols * fsImage.channels() ); /* Compute histogram mean */ fsMean = LC_VMEAN( fsBytes ); /* Compute histogram standard deviation */ fsStdd = LC_VSTDD( fsBytes, fsMean ); /* Software switch */ if ( lc_stda( argc, argv, "--set", "-e" ) ) { /* Apply exposure correction */ fsImage = ( ( fsImage - fsMean ) / fsStdd ) * fsFixStdd + fsFixMean; /* Write result image */ if ( imwrite( fsImgOPath, fsImage ) ) { /* Display message */ std::cout << "Exported " << fsImgOPath << std::endl; /* Display message */ } else { std::cout << "Error : Unable to write output image" << std::endl; } } else if ( lc_stda( argc, argv, "--get", "-g" ) ) { /* Display image histogramm mean and standard deviation */ std::cout << fsMean << " " << fsStdd << std::endl; } /* Display message */ } else { std::cout << "Error : Unable to read input image" << std::endl; } } /* Return to system */ return( EXIT_SUCCESS ); } <commit_msg>Adding mean and standard deviation separate management in feature-image-expose<commit_after>/* * feature suite - Feature detection suite * * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch * Please read <http://foxel.ch/license> for more information. * * * Author(s): * * Nils Hamel <[email protected]> * * * This file is part of the FOXEL project <http://foxel.ch>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * Additional Terms: * * You are required to preserve legal notices and author attributions in * that material or in the Appropriate Legal Notices displayed by works * containing it. * * You are required to attribute the work as explained in the "Usage and * Attribution" section of <http://foxel.ch/license>. */ /* Source - Includes */ # include "feature-image-expose.hpp" /* Source - Entry point */ int main ( int argc, char ** argv ) { /* Path variables */ char fsImgIPath[256] = { 0 }; char fsImgOPath[256] = { 0 }; /* Execution mode variables */ char fsMode[256] = { 0 }; /* Parameters variables */ float fsFixMean ( 0.0 ); float fsFixStdd ( 0.0 ); /* Statistical variables */ float fsMean ( 0.0 ); float fsStdD ( 0.0 ); /* Image variable */ cv::Mat fsImage; /* Search in parameters */ lc_stdp( lc_stda( argc, argv, "--input" , "-i" ), argv, fsImgIPath, LC_STRING ); lc_stdp( lc_stda( argc, argv, "--output", "-o" ), argv, fsImgOPath, LC_STRING ); lc_stdp( lc_stda( argc, argv, "--mode" , "-d" ), argv, fsMode , LC_STRING ); lc_stdp( lc_stda( argc, argv, "--mean" , "-m" ), argv, & fsFixMean , LC_FLOAT ); lc_stdp( lc_stda( argc, argv, "--stdd" , "-s" ), argv, & fsFixStdd , LC_FLOAT ); /* Software swicth */ if ( ( lc_stda( argc, argv, "--help", "-h" ) ) || ( argc <= 1 ) ) { /* Display message */ std::cout << FS_HELP; } else { /* Read input image */ fsImage = cv::imread( fsImgIPath, CV_LOAD_IMAGE_COLOR ); /* Verify image reading */ if ( fsImage.data != NULL ) { /* Create array on image bytes */ std::vector < char > fsBytes( fsImage.data, fsImage.data + fsImage.rows * fsImage.cols * fsImage.channels() ); /* Software switch */ if ( lc_stda( argc, argv, "--get", "-g" ) ) { /* Check execution mode */ if ( ( strcmp( fsMode, "mean" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) { /* Compute histogram mean */ fsMean = LC_VMEAN( fsBytes ); /* Display mean value */ std::cout << fsMean << std::endl; } if ( ( strcmp( fsMode, "std" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) { /* Compute histogram standard deviation */ fsStdD = LC_VSTDD( fsBytes, fsMean ); /* Display standard deviation value */ std::cout << fsStdD << std::endl; } } else if ( lc_stda( argc, argv, "--set", "-e" ) ) { /* Check execution mode */ if ( ( strcmp( fsMode, "mean" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) { /* Compute histogram mean */ fsMean = LC_VMEAN( fsBytes ); /* Check execution mode */ if ( strcmp( fsMode, "both" ) != 0 ) { /* Exposure correction */ fsImage = ( fsImage - fsMean ) + fsFixMean; } } if ( ( strcmp( fsMode, "std" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) { /* Compute histogram standard deviation */ fsStdD = LC_VSTDD( fsBytes, fsMean ); /* Check execution mode */ if ( strcmp( fsMode, "both" ) != 0 ) { /* Exposure correction */ fsImage = ( fsImage / fsStdD ) * fsFixStdd; } } /* Check execution mode */ if ( strcmp( fsMode, "both" ) == 0 ) { /* Exposure correction */ fsImage = ( ( fsImage - fsMean ) / fsStdD ) * fsFixStdd + fsFixMean; } /* Write result image */ if ( imwrite( fsImgOPath, fsImage ) == false ) { /* Display message */ std::cout << "Error : Unable to write output image" << std::endl; } /* Display message */ } else { std::cout << "Error : Execution switch not provided" << std::endl; } /* Display message */ } else { std::cout << "Error : Unable to read input image" << std::endl; } } /* Return to system */ return( EXIT_SUCCESS ); } <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #pragma once #include <Tensile/Predicates.hpp> #include <Tensile/ContractionProblem.hpp> #include <array> #include <cstddef> #include <vector> namespace Tensile { namespace Predicates { /** * \addtogroup Predicates * @{ */ /** * @brief ContractionProblem predicates */ namespace Contraction { struct FreeSizeAMultiple: public Predicate_CRTP<FreeSizeAMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; FreeSizeAMultiple() = default; FreeSizeAMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "FreeSizeAMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.freeSizeA(index) % value == 0; } }; struct FreeSizeBMultiple: public Predicate_CRTP<FreeSizeBMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; FreeSizeBMultiple() = default; FreeSizeBMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "FreeSizeBMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.freeSizeA(index) % value == 0; } }; struct BatchSizeMultiple: public Predicate_CRTP<BatchSizeMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; BatchSizeMultiple() = default; BatchSizeMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "BatchSizeMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.batchSize(index) % value == 0; } }; struct BatchSizeEqual: public Predicate_CRTP<BatchSizeEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; BatchSizeEqual() = default; BatchSizeEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "BatchSizeEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.batchSize(index) == value; } }; struct BoundSizeMultiple: public Predicate_CRTP<BoundSizeMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; int64_t index; size_t value; BoundSizeMultiple() = default; BoundSizeMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "BoundSizeMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { if (index < 0) return problem.boundSize(problem.boundIndices().size()+index) % value == 0; else return problem.boundSize(index) % value == 0; } }; struct ProblemSizeEqual: public Predicate_CRTP<ProblemSizeEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; ProblemSizeEqual() = default; ProblemSizeEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "ProblemSizeEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.problemSizes()[index] == value; } }; struct MaxProblemSizeGreaterThan: public Predicate_CRTP<MaxProblemSizeGreaterThan, ContractionProblem> { enum { HasIndex = false, HasValue = true }; size_t value; MaxProblemSizeGreaterThan() = default; MaxProblemSizeGreaterThan(size_t value): value(value) {} static std::string Type() { return "MaxProblemSizeGreaterThan"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.maxProblemSize() > value; } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << *this << ": (" << problem.maxProblemSize() << " > " << value << ") == " << rv; return rv; } }; struct LeadingFreeSizesGreaterOrEqual: public Predicate_CRTP<LeadingFreeSizesGreaterOrEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; size_t value; LeadingFreeSizesGreaterOrEqual() = default; LeadingFreeSizesGreaterOrEqual(size_t value): value(value) {} static std::string Type() { return "LeadingFreeSizesGreaterOrEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { // do we need this? // this assert is not currenly used in rocblas // enabling it is causing test failures //return problem.freeSizeA(0) >= value // && problem.freeSizeB(0) >= value; return true; } }; struct StrideAEqual: public Predicate_CRTP<StrideAEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; StrideAEqual() = default; StrideAEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "StrideAEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.a().strides()[index] == value ; } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << *this << ": (" << problem.a().strides()[index] << " == " << value << ") == " << rv; return rv; } }; struct StrideBEqual: public Predicate_CRTP<StrideBEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; StrideBEqual() = default; StrideBEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "StrideBEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.b().strides()[index] == value ; } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << *this << ": (" << problem.b().strides()[index] << " == " << value << ") == " << rv; return rv; } }; struct CDStridesEqual: public Predicate_CRTP<CDStridesEqual, ContractionProblem> { enum { HasIndex = false, HasValue = false }; static std::string Type() { return "CDStridesEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.c().strides() == problem.d().strides(); } }; struct LDCEqualsLDD: public Predicate_CRTP<LDCEqualsLDD, ContractionProblem> { enum { HasIndex = false, HasValue = false }; static std::string Type() { return "LDCEqualsLDD"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.c().strides()[1] == problem.d().strides()[1]; } }; struct BetaZero: public Predicate_CRTP<BetaZero, ContractionProblem> { enum { HasIndex = false, HasValue = false }; BetaZero() = default; static std::string Type() { return "BetaZero"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.beta() == 0.0; } }; struct BetaOne: public Predicate_CRTP<BetaOne, ContractionProblem> { enum { HasIndex = false, HasValue = false }; BetaOne() = default; static std::string Type() { return "BetaOne"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.beta() == 1.0; } }; struct HighPrecisionAccumulateEqual: public Predicate_CRTP<HighPrecisionAccumulateEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; bool value; HighPrecisionAccumulateEqual() = default; HighPrecisionAccumulateEqual(bool value): value(value) {} static std::string Type() { return "HighPrecisionAccumulate"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.highPrecisionAccumulate() == value; } }; struct TypesEqual: public Predicate_CRTP<TypesEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; TypesEqual() = default; std::array<DataType, 4> value; static std::string Type() { return "TypesEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.a().dataType() == value[0] && problem.b().dataType() == value[1] && problem.c().dataType() == value[2] && problem.d().dataType() == value[3]; } virtual std::string toString() const override { return concatenate(this->type(), "(a:", value[0], ", b:", value[1], ", c:", value[2], ", d:", value[3], ")"); } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << this->type() << "(a:" << problem.a().dataType() << " == " << value[0] << "&& b:" << problem.b().dataType() << " == " << value[1] << "&& c:" << problem.c().dataType() << " == " << value[2] << "&& d:" << problem.d().dataType() << " == " << value[3] << "): " << rv; return rv; } }; struct OperationIdentifierEqual: public Predicate_CRTP<OperationIdentifierEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; OperationIdentifierEqual() = default; std::string value; static std::string Type() { return "OperationIdentifierEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.operationIdentifier() == value; } }; } /** * @} */ } } <commit_msg>fix for bug fixes<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #pragma once #include <Tensile/Predicates.hpp> #include <Tensile/ContractionProblem.hpp> #include <array> #include <cstddef> #include <vector> namespace Tensile { namespace Predicates { /** * \addtogroup Predicates * @{ */ /** * @brief ContractionProblem predicates */ namespace Contraction { struct FreeSizeAMultiple: public Predicate_CRTP<FreeSizeAMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; FreeSizeAMultiple() = default; FreeSizeAMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "FreeSizeAMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.freeSizeA(index) % value == 0; } }; struct FreeSizeBMultiple: public Predicate_CRTP<FreeSizeBMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; FreeSizeBMultiple() = default; FreeSizeBMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "FreeSizeBMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.freeSizeA(index) % value == 0; } }; struct BatchSizeMultiple: public Predicate_CRTP<BatchSizeMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; BatchSizeMultiple() = default; BatchSizeMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "BatchSizeMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.batchSize(index) % value == 0; } }; struct BatchSizeEqual: public Predicate_CRTP<BatchSizeEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; BatchSizeEqual() = default; BatchSizeEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "BatchSizeEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.batchSize(index) == value; } }; struct BoundSizeMultiple: public Predicate_CRTP<BoundSizeMultiple, ContractionProblem> { enum { HasIndex = true, HasValue = true }; int64_t index; size_t value; BoundSizeMultiple() = default; BoundSizeMultiple(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "BoundSizeMultiple"; } virtual bool operator()(ContractionProblem const& problem) const override { if (index < 0) return problem.boundSize(problem.boundIndices().size()+index) % value == 0; else return problem.boundSize(index) % value == 0; } }; struct ProblemSizeEqual: public Predicate_CRTP<ProblemSizeEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; ProblemSizeEqual() = default; ProblemSizeEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "ProblemSizeEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.problemSizes()[index] == value; } }; struct MaxProblemSizeGreaterThan: public Predicate_CRTP<MaxProblemSizeGreaterThan, ContractionProblem> { enum { HasIndex = false, HasValue = true }; size_t value; MaxProblemSizeGreaterThan() = default; MaxProblemSizeGreaterThan(size_t value): value(value) {} static std::string Type() { return "MaxProblemSizeGreaterThan"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.maxProblemSize() > value; } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << *this << ": (" << problem.maxProblemSize() << " > " << value << ") == " << rv; return rv; } }; struct LeadingFreeSizesGreaterOrEqual: public Predicate_CRTP<LeadingFreeSizesGreaterOrEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; size_t value; LeadingFreeSizesGreaterOrEqual() = default; LeadingFreeSizesGreaterOrEqual(size_t value): value(value) {} static std::string Type() { return "LeadingFreeSizesGreaterOrEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { // do we need this? // this assert is not currenly used in rocblas // enabling it is causing test failures return problem.freeSizeA(0) >= value && problem.freeSizeB(0) >= value; } }; struct StrideAEqual: public Predicate_CRTP<StrideAEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; StrideAEqual() = default; StrideAEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "StrideAEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.a().strides()[index] == value ; } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << *this << ": (" << problem.a().strides()[index] << " == " << value << ") == " << rv; return rv; } }; struct StrideBEqual: public Predicate_CRTP<StrideBEqual, ContractionProblem> { enum { HasIndex = true, HasValue = true }; size_t index; size_t value; StrideBEqual() = default; StrideBEqual(size_t index, size_t value): index(index), value(value) {} static std::string Type() { return "StrideBEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.b().strides()[index] == value ; } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << *this << ": (" << problem.b().strides()[index] << " == " << value << ") == " << rv; return rv; } }; struct CDStridesEqual: public Predicate_CRTP<CDStridesEqual, ContractionProblem> { enum { HasIndex = false, HasValue = false }; static std::string Type() { return "CDStridesEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.c().strides() == problem.d().strides(); } }; struct LDCEqualsLDD: public Predicate_CRTP<LDCEqualsLDD, ContractionProblem> { enum { HasIndex = false, HasValue = false }; static std::string Type() { return "LDCEqualsLDD"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.c().strides()[1] == problem.d().strides()[1]; } }; struct BetaZero: public Predicate_CRTP<BetaZero, ContractionProblem> { enum { HasIndex = false, HasValue = false }; BetaZero() = default; static std::string Type() { return "BetaZero"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.beta() == 0.0; } }; struct BetaOne: public Predicate_CRTP<BetaOne, ContractionProblem> { enum { HasIndex = false, HasValue = false }; BetaOne() = default; static std::string Type() { return "BetaOne"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.beta() == 1.0; } }; struct HighPrecisionAccumulateEqual: public Predicate_CRTP<HighPrecisionAccumulateEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; bool value; HighPrecisionAccumulateEqual() = default; HighPrecisionAccumulateEqual(bool value): value(value) {} static std::string Type() { return "HighPrecisionAccumulate"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.highPrecisionAccumulate() == value; } }; struct TypesEqual: public Predicate_CRTP<TypesEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; TypesEqual() = default; std::array<DataType, 4> value; static std::string Type() { return "TypesEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.a().dataType() == value[0] && problem.b().dataType() == value[1] && problem.c().dataType() == value[2] && problem.d().dataType() == value[3]; } virtual std::string toString() const override { return concatenate(this->type(), "(a:", value[0], ", b:", value[1], ", c:", value[2], ", d:", value[3], ")"); } virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override { bool rv = (*this)(problem); stream << this->type() << "(a:" << problem.a().dataType() << " == " << value[0] << "&& b:" << problem.b().dataType() << " == " << value[1] << "&& c:" << problem.c().dataType() << " == " << value[2] << "&& d:" << problem.d().dataType() << " == " << value[3] << "): " << rv; return rv; } }; struct OperationIdentifierEqual: public Predicate_CRTP<OperationIdentifierEqual, ContractionProblem> { enum { HasIndex = false, HasValue = true }; OperationIdentifierEqual() = default; std::string value; static std::string Type() { return "OperationIdentifierEqual"; } virtual bool operator()(ContractionProblem const& problem) const override { return problem.operationIdentifier() == value; } }; } /** * @} */ } } <|endoftext|>
<commit_before>/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "data.hpp" #include "internal/sys.hpp" #include "pciaccess.hpp" #include <linux/pci_regs.h> #include <stdplus/types.hpp> // Some versions of the linux/pci_regs.h header don't define this #ifndef PCI_STD_NUM_BARS #define PCI_STD_NUM_BARS 6 #endif // !PCI_STD_NUM_BARS namespace host_tool { class PciBridgeIntf { public: virtual ~PciBridgeIntf() = default; virtual void write(const stdplus::span<const std::uint8_t> data) = 0; virtual void configure(const ipmi_flash::PciConfigResponse& config) = 0; virtual std::size_t getDataLength() = 0; }; class PciAccessBridge : public PciBridgeIntf { public: virtual ~PciAccessBridge(); virtual void write(const stdplus::span<const std::uint8_t> data) override; virtual void configure(const ipmi_flash::PciConfigResponse& configResp) override{}; std::size_t getDataLength() override { return dataLength; } protected: /** * Finds the PCI device matching @a match and saves a reference to it in @a * dev. Also maps the memory region described in BAR number @a bar to * address @a addr, */ PciAccessBridge(const struct pci_id_match* match, int bar, std::size_t dataOffset, std::size_t dataLength, const PciAccess* pci); struct pci_device* dev = nullptr; std::uint8_t* addr = nullptr; std::size_t size = 0; private: std::size_t dataOffset; std::size_t dataLength; protected: const PciAccess* pci; }; class NuvotonPciBridge : public PciAccessBridge { public: explicit NuvotonPciBridge(const PciAccess* pci, bool skipBridgeDisable = false) : PciAccessBridge(&match, bar, dataOffset, dataLength, pci), skipBridgeDisable(skipBridgeDisable) { enableBridge(); } ~NuvotonPciBridge() { if (!skipBridgeDisable) disableBridge(); } private: static constexpr std::uint32_t vid = 0x1050; static constexpr std::uint32_t did = 0x0750; static constexpr int bar = 0; static constexpr struct pci_id_match match { vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY }; static constexpr pciaddr_t bridge = 0x04; static constexpr std::uint8_t bridgeEnabled = 0x02; static constexpr std::size_t dataOffset = 0x0; static constexpr std::size_t dataLength = 0x4000; void enableBridge(); void disableBridge(); bool skipBridgeDisable; }; class AspeedPciBridge : public PciAccessBridge { public: explicit AspeedPciBridge(const PciAccess* pci, bool skipBridgeDisable = false) : PciAccessBridge(&match, bar, dataOffset, dataLength, pci), skipBridgeDisable(skipBridgeDisable) { enableBridge(); } ~AspeedPciBridge() { if (!skipBridgeDisable) disableBridge(); } void configure(const ipmi_flash::PciConfigResponse& configResp) override; private: static constexpr std::uint32_t vid = 0x1a03; static constexpr std::uint32_t did = 0x2000; static constexpr int bar = 1; static constexpr struct pci_id_match match { vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY }; static constexpr std::size_t config = 0x0f000; static constexpr std::size_t bridge = 0x0f004; static constexpr std::uint32_t bridgeEnabled = 0x1; static constexpr std::size_t dataOffset = 0x10000; static constexpr std::size_t dataLength = 0x10000; void enableBridge(); void disableBridge(); bool skipBridgeDisable; }; } // namespace host_tool <commit_msg>tools: remove shadow field<commit_after>/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "data.hpp" #include "internal/sys.hpp" #include "pciaccess.hpp" #include <linux/pci_regs.h> #include <stdplus/types.hpp> // Some versions of the linux/pci_regs.h header don't define this #ifndef PCI_STD_NUM_BARS #define PCI_STD_NUM_BARS 6 #endif // !PCI_STD_NUM_BARS namespace host_tool { class PciBridgeIntf { public: virtual ~PciBridgeIntf() = default; virtual void write(const stdplus::span<const std::uint8_t> data) = 0; virtual void configure(const ipmi_flash::PciConfigResponse& config) = 0; virtual std::size_t getDataLength() = 0; }; class PciAccessBridge : public PciBridgeIntf { public: virtual ~PciAccessBridge(); virtual void write(const stdplus::span<const std::uint8_t> data) override; virtual void configure(const ipmi_flash::PciConfigResponse& configResp) override{}; std::size_t getDataLength() override { return dataLength; } protected: /** * Finds the PCI device matching @a match and saves a reference to it in @a * dev. Also maps the memory region described in BAR number @a bar to * address @a addr, */ PciAccessBridge(const struct pci_id_match* match, int bar, std::size_t dataOffset, std::size_t dataLength, const PciAccess* pci); struct pci_device* dev = nullptr; std::uint8_t* addr = nullptr; std::size_t size = 0; private: std::size_t dataOffset; std::size_t dataLength; protected: const PciAccess* pci; }; class NuvotonPciBridge : public PciAccessBridge { public: explicit NuvotonPciBridge(const PciAccess* pciAccess, bool skipBridgeDisable = false) : PciAccessBridge(&match, bar, dataOffset, dataLength, pciAccess), skipBridgeDisable(skipBridgeDisable) { enableBridge(); } ~NuvotonPciBridge() { if (!skipBridgeDisable) disableBridge(); } private: static constexpr std::uint32_t vid = 0x1050; static constexpr std::uint32_t did = 0x0750; static constexpr int bar = 0; static constexpr struct pci_id_match match { vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY }; static constexpr pciaddr_t bridge = 0x04; static constexpr std::uint8_t bridgeEnabled = 0x02; static constexpr std::size_t dataOffset = 0x0; static constexpr std::size_t dataLength = 0x4000; void enableBridge(); void disableBridge(); bool skipBridgeDisable; }; class AspeedPciBridge : public PciAccessBridge { public: explicit AspeedPciBridge(const PciAccess* pciAccess, bool skipBridgeDisable = false) : PciAccessBridge(&match, bar, dataOffset, dataLength, pciAccess), skipBridgeDisable(skipBridgeDisable) { enableBridge(); } ~AspeedPciBridge() { if (!skipBridgeDisable) disableBridge(); } void configure(const ipmi_flash::PciConfigResponse& configResp) override; private: static constexpr std::uint32_t vid = 0x1a03; static constexpr std::uint32_t did = 0x2000; static constexpr int bar = 1; static constexpr struct pci_id_match match { vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY }; static constexpr std::size_t config = 0x0f000; static constexpr std::size_t bridge = 0x0f004; static constexpr std::uint32_t bridgeEnabled = 0x1; static constexpr std::size_t dataOffset = 0x10000; static constexpr std::size_t dataLength = 0x10000; void enableBridge(); void disableBridge(); bool skipBridgeDisable; }; } // namespace host_tool <|endoftext|>
<commit_before>/* Copyright (c) 2012 Sweetdumplings <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QtGui> #include "pQDoubleListChooser.h" pQDoubleListChooser::pQDoubleListChooser(QWidget *parent) :QWidget(parent) { toLeft=new QPushButton("<-"); toRight=new QPushButton("->"); LeftList=new QListWidget; RightList=new QListWidget; //build the ui QHBoxLayout *mainlayout=new QHBoxLayout; QVBoxLayout *buttonlayout=new QVBoxLayout; buttonlayout->addWidget(toLeft); buttonlayout->addWidget(toRight); mainlayout->addWidget(LeftList); mainlayout->addLayout(buttonlayout); mainlayout->addWidget(RightList); //connect slots and signals connect(toLeft,SIGNAL(clicked()),this,SLOT(toLeftClicked())); connect(toRight,SIGNAL(clicked()),this,SLOT(toRightClicked())); connect(LeftList,SIGNAL(itemDoubleClicked(QListWidgetItem *)), this,SLOT(LeftListDoubleClicked())); connect(RightList,SIGNAL(itemDoubleClicked(QListWidgetItem *)), this,SLOT(RightListDoubleClicked())); setLayout(mainlayout); } /* * movetoSide functions * These functions will help users to move the items. * They show the way to use addItem and removeItemWidget */ void pQDoubleListChooser::movetoRight(){ QList<QListWidgetItem *> need_to_move=LeftList->selectedItems(); QList<QListWidgetItem *>::iterator i=need_to_move.begin(); for (;i!=need_to_move.end();++i){ QListWidgetItem *newitem=new QListWidgetItem(*(*i)); RightList->addItem(newitem); } for (i=need_to_move.begin();i!=need_to_move.end();++i){ LeftList->removeItemWidget((*i)); delete (*i); //Important: the delete sentence is necessary. //After "delete", the useless memory will be return to the system //and the item on UI will disappear. } } void pQDoubleListChooser::movetoLeft(){ QList<QListWidgetItem *> need_to_move=RightList->selectedItems(); QList<QListWidgetItem *>::const_iterator i=need_to_move.begin(); for (;i!=need_to_move.end();++i){ QListWidgetItem *newitem=new QListWidgetItem(*(*i)); LeftList->addItem(newitem); } for (i=need_to_move.begin();i!=need_to_move.end();++i){ RightList->removeItemWidget((*i)); delete (*i); } } //Slots void pQDoubleListChooser::toLeftClicked(){ this->movetoLeft(); } void pQDoubleListChooser::toRightClicked(){ this->movetoRight(); } void pQDoubleListChooser::LeftListDoubleClicked(){ this->movetoRight(); } void pQDoubleListChooser::RightListDoubleClicked(){ this->movetoLeft(); } <commit_msg>add size policy(Preferred) to DoubleListChooser<commit_after>/* Copyright (c) 2012 Sweetdumplings <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QtGui> #include "pQDoubleListChooser.h" pQDoubleListChooser::pQDoubleListChooser(QWidget *parent) :QWidget(parent) { toLeft=new QPushButton("<-"); toRight=new QPushButton("->"); LeftList=new QListWidget; RightList=new QListWidget; //build the ui QHBoxLayout *mainlayout=new QHBoxLayout; QVBoxLayout *buttonlayout=new QVBoxLayout; QSizePolicy listsizepolicy(QSizePolicy::Preferred ,QSizePolicy::Preferred); listsizepolicy.setHorizontalStretch(3); LeftList->setSizePolicy(listsizepolicy); RightList->setSizePolicy(listsizepolicy); buttonlayout->addWidget(toLeft); buttonlayout->addWidget(toRight); mainlayout->addWidget(LeftList); mainlayout->addLayout(buttonlayout); mainlayout->addWidget(RightList); //connect slots and signals connect(toLeft,SIGNAL(clicked()),this,SLOT(toLeftClicked())); connect(toRight,SIGNAL(clicked()),this,SLOT(toRightClicked())); connect(LeftList,SIGNAL(itemDoubleClicked(QListWidgetItem *)), this,SLOT(LeftListDoubleClicked())); connect(RightList,SIGNAL(itemDoubleClicked(QListWidgetItem *)), this,SLOT(RightListDoubleClicked())); setLayout(mainlayout); } /* * movetoSide functions * These functions will help users to move the items. * They show the way to use addItem and removeItemWidget */ void pQDoubleListChooser::movetoRight(){ QList<QListWidgetItem *> need_to_move=LeftList->selectedItems(); QList<QListWidgetItem *>::iterator i=need_to_move.begin(); for (;i!=need_to_move.end();++i){ QListWidgetItem *newitem=new QListWidgetItem(*(*i)); RightList->addItem(newitem); } for (i=need_to_move.begin();i!=need_to_move.end();++i){ LeftList->removeItemWidget((*i)); delete (*i); //Important: the delete sentence is necessary. //After "delete", the useless memory will be return to the system //and the item on UI will disappear. } } void pQDoubleListChooser::movetoLeft(){ QList<QListWidgetItem *> need_to_move=RightList->selectedItems(); QList<QListWidgetItem *>::const_iterator i=need_to_move.begin(); for (;i!=need_to_move.end();++i){ QListWidgetItem *newitem=new QListWidgetItem(*(*i)); LeftList->addItem(newitem); } for (i=need_to_move.begin();i!=need_to_move.end();++i){ RightList->removeItemWidget((*i)); delete (*i); } } //Slots void pQDoubleListChooser::toLeftClicked(){ this->movetoLeft(); } void pQDoubleListChooser::toRightClicked(){ this->movetoRight(); } void pQDoubleListChooser::LeftListDoubleClicked(){ this->movetoRight(); } void pQDoubleListChooser::RightListDoubleClicked(){ this->movetoLeft(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Exception.h" #include "FastSpinlock.h" #include "DummyClients.h" #include "PlayerSession.h" #include "GameSession.h" #include "IocpManager.h" #include "GameLiftManager.h" #include "PacketType.h" #include "DummyClients.h" #include "Log.h" #include <Rpc.h> #include <aws/core/utils/Outcome.h> #include <aws/gamelift/model/CreateGameSessionRequest.h> #include <aws/gamelift/model/CreatePlayerSessionsRequest.h> #include <aws/gamelift/model/StartGameSessionPlacementRequest.h> #include <aws/gamelift/model/DescribeGameSessionPlacementRequest.h> #include <aws/gamelift/model/DescribeGameSessionDetailsRequest.h> GameSession::~GameSession() { for (auto it : mReadySessionList) { delete it; } } bool GameSession::PreparePlayerSessions() { CRASH_ASSERT(LThreadType == THREAD_MAIN); for (int i = 0; i < mMaxPlayerCount - TEST_PLAYER_SESSION_EXCEPT; ++i) { PlayerSession* client = new PlayerSession(this); if (false == client->PrepareSession()) return false; mReadySessionList.push_back(client); } return true; } bool GameSession::CreateGameSession() { FastSpinlockGuard guard(mLock); Aws::GameLift::Model::CreateGameSessionRequest req; auto aliasId = GGameLiftManager->GetAliasId(); if (aliasId == "TEST_LOCAL") { req.SetFleetId(std::string("fleet-") + mGameSessionName); } else { req.SetAliasId(aliasId); } req.SetName(mGameSessionName); req.SetMaximumPlayerSessionCount(mMaxPlayerCount); auto outcome = GGameLiftManager->GetAwsClient()->CreateGameSession(req); if (outcome.IsSuccess()) { auto gs = outcome.GetResult().GetGameSession(); mPort = gs.GetPort(); mIpAddress = gs.GetIpAddress(); mGameSessionId = gs.GetGameSessionId(); return true; } GConsoleLog->PrintOut(true, "%s\n", outcome.GetError().GetMessageA().c_str()); return false; } bool GameSession::CreatePlayerSessions() { FastSpinlockGuard guard(mLock); Aws::GameLift::Model::CreatePlayerSessionsRequest req; req.SetGameSessionId(mGameSessionId); std::vector<std::string> playerIds; for (int i = 0; i < mMaxPlayerCount - TEST_PLAYER_SESSION_EXCEPT; ++i) ///< must be less than 25 { std::string pid = "DummyPlayer" + std::to_string(mStartPlayerId + i); playerIds.push_back(pid); } req.SetPlayerIds(playerIds); auto outcome = GGameLiftManager->GetAwsClient()->CreatePlayerSessions(req); if (outcome.IsSuccess()) { mPlayerSessionList = outcome.GetResult().GetPlayerSessions(); return true; } GConsoleLog->PrintOut(true, "%s\n", outcome.GetError().GetMessageA().c_str()); return false; } bool GameSession::ConnectPlayerSessions() { FastSpinlockGuard guard(mLock); auto it = mReadySessionList.begin(); int idx = mStartPlayerId; for (auto& playerSessionItem : mPlayerSessionList) { (*it)->AddRef(); if (false == (*it)->ConnectRequest(playerSessionItem.GetPlayerSessionId(), idx++)) return false; Sleep(10); ++it; } return true; } void GameSession::DisconnectPlayerSessions() { FastSpinlockGuard guard(mLock); for (auto session : mReadySessionList) { if (session->IsConnected()) session->DisconnectRequest(DR_ACTIVE); } } bool GameSession::StartGameSessionPlacement() { FastSpinlockGuard guard(mLock); /// region reset for a match queue... GGameLiftManager->SetUpAwsClient(GGameLiftManager->GetRegion()); GeneratePlacementId(); Aws::GameLift::Model::StartGameSessionPlacementRequest req; req.SetGameSessionQueueName(GGameLiftManager->GetMatchQueue()); req.SetMaximumPlayerSessionCount(MAX_PLAYER_PER_GAME); req.SetPlacementId(mPlacementId); auto outcome = GGameLiftManager->GetAwsClient()->StartGameSessionPlacement(req); if (outcome.IsSuccess()) { auto status = outcome.GetResult().GetGameSessionPlacement().GetStatus(); if (status == Aws::GameLift::Model::GameSessionPlacementState::PENDING) { return CheckGameSessionPlacement(); } if (status == Aws::GameLift::Model::GameSessionPlacementState::FULFILLED) { auto gs = outcome.GetResult().GetGameSessionPlacement(); mGameSessionId = gs.GetGameSessionArn(); mIpAddress = gs.GetIpAddress(); mPort = gs.GetPort(); /// change region... GGameLiftManager->SetUpAwsClient(gs.GetGameSessionRegion()); return true; } } GConsoleLog->PrintOut(true, "%s\n", outcome.GetError().GetMessageA().c_str()); return false; } bool GameSession::CheckGameSessionPlacement() { while (true) { Aws::GameLift::Model::DescribeGameSessionPlacementRequest req; req.SetPlacementId(mPlacementId); auto outcome = GGameLiftManager->GetAwsClient()->DescribeGameSessionPlacement(req); if (outcome.IsSuccess()) { auto gs = outcome.GetResult().GetGameSessionPlacement(); if (gs.GetStatus() == Aws::GameLift::Model::GameSessionPlacementState::FULFILLED) { mGameSessionId = gs.GetGameSessionArn(); mIpAddress = gs.GetIpAddress(); mPort = gs.GetPort(); /// change region... auto region = gs.GetGameSessionRegion(); GGameLiftManager->SetUpAwsClient(region); return true; } } else { break; } Sleep(500); } return false; } void GameSession::GeneratePlacementId() { UUID uuid; UuidCreate(&uuid); unsigned char* str = nullptr; UuidToStringA(&uuid, &str); mPlacementId.clear(); mPlacementId = std::string((char*)str); RpcStringFreeA(&str); }<commit_msg>*fixed: simplifying to get a game session info<commit_after>#include "stdafx.h" #include "Exception.h" #include "FastSpinlock.h" #include "DummyClients.h" #include "PlayerSession.h" #include "GameSession.h" #include "IocpManager.h" #include "GameLiftManager.h" #include "PacketType.h" #include "DummyClients.h" #include "Log.h" #include <Rpc.h> #include <aws/core/utils/Outcome.h> #include <aws/gamelift/model/CreateGameSessionRequest.h> #include <aws/gamelift/model/CreatePlayerSessionsRequest.h> #include <aws/gamelift/model/StartGameSessionPlacementRequest.h> #include <aws/gamelift/model/DescribeGameSessionPlacementRequest.h> #include <aws/gamelift/model/DescribeGameSessionDetailsRequest.h> GameSession::~GameSession() { for (auto it : mReadySessionList) { delete it; } } bool GameSession::PreparePlayerSessions() { CRASH_ASSERT(LThreadType == THREAD_MAIN); for (int i = 0; i < mMaxPlayerCount - TEST_PLAYER_SESSION_EXCEPT; ++i) { PlayerSession* client = new PlayerSession(this); if (false == client->PrepareSession()) return false; mReadySessionList.push_back(client); } return true; } bool GameSession::CreateGameSession() { FastSpinlockGuard guard(mLock); Aws::GameLift::Model::CreateGameSessionRequest req; auto aliasId = GGameLiftManager->GetAliasId(); if (aliasId == "TEST_LOCAL") { req.SetFleetId(std::string("fleet-") + mGameSessionName); } else { req.SetAliasId(aliasId); } req.SetName(mGameSessionName); req.SetMaximumPlayerSessionCount(mMaxPlayerCount); auto outcome = GGameLiftManager->GetAwsClient()->CreateGameSession(req); if (outcome.IsSuccess()) { auto gs = outcome.GetResult().GetGameSession(); mPort = gs.GetPort(); mIpAddress = gs.GetIpAddress(); mGameSessionId = gs.GetGameSessionId(); return true; } GConsoleLog->PrintOut(true, "%s\n", outcome.GetError().GetMessageA().c_str()); return false; } bool GameSession::CreatePlayerSessions() { FastSpinlockGuard guard(mLock); Aws::GameLift::Model::CreatePlayerSessionsRequest req; req.SetGameSessionId(mGameSessionId); std::vector<std::string> playerIds; for (int i = 0; i < mMaxPlayerCount - TEST_PLAYER_SESSION_EXCEPT; ++i) ///< must be less than 25 { std::string pid = "DummyPlayer" + std::to_string(mStartPlayerId + i); playerIds.push_back(pid); } req.SetPlayerIds(playerIds); auto outcome = GGameLiftManager->GetAwsClient()->CreatePlayerSessions(req); if (outcome.IsSuccess()) { mPlayerSessionList = outcome.GetResult().GetPlayerSessions(); return true; } GConsoleLog->PrintOut(true, "%s\n", outcome.GetError().GetMessageA().c_str()); return false; } bool GameSession::ConnectPlayerSessions() { FastSpinlockGuard guard(mLock); auto it = mReadySessionList.begin(); int idx = mStartPlayerId; for (auto& playerSessionItem : mPlayerSessionList) { (*it)->AddRef(); if (false == (*it)->ConnectRequest(playerSessionItem.GetPlayerSessionId(), idx++)) return false; Sleep(10); ++it; } return true; } void GameSession::DisconnectPlayerSessions() { FastSpinlockGuard guard(mLock); for (auto session : mReadySessionList) { if (session->IsConnected()) session->DisconnectRequest(DR_ACTIVE); } } bool GameSession::StartGameSessionPlacement() { FastSpinlockGuard guard(mLock); /// region reset for a match queue... GGameLiftManager->SetUpAwsClient(GGameLiftManager->GetRegion()); GeneratePlacementId(); Aws::GameLift::Model::StartGameSessionPlacementRequest req; req.SetGameSessionQueueName(GGameLiftManager->GetMatchQueue()); req.SetMaximumPlayerSessionCount(MAX_PLAYER_PER_GAME); req.SetPlacementId(mPlacementId); auto outcome = GGameLiftManager->GetAwsClient()->StartGameSessionPlacement(req); if (outcome.IsSuccess()) { auto status = outcome.GetResult().GetGameSessionPlacement().GetStatus(); if (status == Aws::GameLift::Model::GameSessionPlacementState::PENDING) { return CheckGameSessionPlacement(); } if (status == Aws::GameLift::Model::GameSessionPlacementState::FULFILLED) { auto gs = outcome.GetResult().GetGameSessionPlacement(); mGameSessionId = gs.GetGameSessionArn(); mIpAddress = gs.GetIpAddress(); mPort = gs.GetPort(); /// change region... GGameLiftManager->SetUpAwsClient(gs.GetGameSessionRegion()); return true; } } GConsoleLog->PrintOut(true, "%s\n", outcome.GetError().GetMessageA().c_str()); return false; } bool GameSession::CheckGameSessionPlacement() { while (true) { Aws::GameLift::Model::DescribeGameSessionPlacementRequest req; req.SetPlacementId(mPlacementId); auto outcome = GGameLiftManager->GetAwsClient()->DescribeGameSessionPlacement(req); if (outcome.IsSuccess()) { auto gs = outcome.GetResult().GetGameSessionPlacement(); if (gs.GetStatus() == Aws::GameLift::Model::GameSessionPlacementState::FULFILLED) { mGameSessionId = gs.GetGameSessionArn(); mIpAddress = gs.GetIpAddress(); mPort = gs.GetPort(); /// change region... GGameLiftManager->SetUpAwsClient(gs.GetGameSessionRegion()); return true; } } else { break; } Sleep(500); } return false; } void GameSession::GeneratePlacementId() { UUID uuid; UuidCreate(&uuid); unsigned char* str = nullptr; UuidToStringA(&uuid, &str); mPlacementId.clear(); mPlacementId = std::string((char*)str); RpcStringFreeA(&str); }<|endoftext|>
<commit_before>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif /* don't be a boring tuna */ #warning you are ugly #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "util/funcs.h" #include "configuration.h" #include "script/script.h" #include "music.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ const int Global::TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) Global::TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; /* game counter, controls FPS */ void inc_speed_counter(){ /* probably put input polling here, InputManager::poll() */ Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); /* if you need to count seconds for some reason.. */ void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ const char * message = "Bug! Caught a memory violation. Shutting down..\n"; int dont_care = write(1, message, 48); dont_care = dont_care; // Global::shutdown_message = "Bug! Caught a memory violation. Shutting down.."; Bitmap::setGfxModeText(); allegro_exit(); /* write to a log file or something because sigsegv shouldn't * normally happen. */ exit(1); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } /* should probably call the janitor here or something */ static void close_paintown(){ Music::pause(); Bitmap::setGfxModeText(); allegro_exit(); exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Data path is " << Util::getDataPath() << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; out<<"Install joystick: "<<install_joystick(JOY_TYPE_AUTODETECT)<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; out << "Initialize random number generator" << endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode(SWITCH_BACKGROUND); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); out << "Initialize network" << endl; Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <commit_msg>print build time<commit_after>#include <allegro.h> #ifdef ALLEGRO_WINDOWS #include <winalleg.h> #endif #ifndef ALLEGRO_WINDOWS #include <signal.h> #include <string.h> #endif /* don't be a boring tuna */ #warning you are ugly #include "globals.h" #include "init.h" #include <pthread.h> #include "network/network.h" #include <ostream> #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" #include "util/bitmap.h" #include "util/funcs.h" #include "configuration.h" #include "script/script.h" #include "music.h" using namespace std; volatile int Global::speed_counter = 0; volatile int Global::second_counter = 0; /* the original engine was running at 90 ticks per second, but we dont * need to render that fast, so TICS_PER_SECOND is really fps and * LOGIC_MULTIPLIER will be used to adjust the speed counter to its * original value. */ const int Global::TICS_PER_SECOND = 40; const double Global::LOGIC_MULTIPLIER = (double) 90 / (double) Global::TICS_PER_SECOND; pthread_mutex_t Global::loading_screen_mutex; bool Global::done_loading = false; const int Global::WINDOWED = GFX_AUTODETECT_WINDOWED; const int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN; /* game counter, controls FPS */ void inc_speed_counter(){ /* probably put input polling here, InputManager::poll() */ Global::speed_counter += 1; } END_OF_FUNCTION( inc_speed_counter ); /* if you need to count seconds for some reason.. */ void inc_second_counter() { Global::second_counter += 1; } END_OF_FUNCTION( inc_second_counter ); #ifndef ALLEGRO_WINDOWS static void handleSigSegV(int i, siginfo_t * sig, void * data){ const char * message = "Bug! Caught a memory violation. Shutting down..\n"; int dont_care = write(1, message, 48); dont_care = dont_care; // Global::shutdown_message = "Bug! Caught a memory violation. Shutting down.."; Bitmap::setGfxModeText(); allegro_exit(); /* write to a log file or something because sigsegv shouldn't * normally happen. */ exit(1); } #else #endif /* catch a socket being closed prematurely on unix */ #ifndef ALLEGRO_WINDOWS static void handleSigPipe( int i, siginfo_t * sig, void * data ){ } /* static void handleSigUsr1( int i, siginfo_t * sig, void * data ){ pthread_exit( NULL ); } */ #endif static void registerSignals(){ #ifndef ALLEGRO_WINDOWS struct sigaction action; memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigPipe; sigaction( SIGPIPE, &action, NULL ); memset( &action, 0, sizeof(struct sigaction) ); action.sa_sigaction = handleSigSegV; sigaction( SIGSEGV, &action, NULL ); /* action.sa_sigaction = handleSigUsr1; sigaction( SIGUSR1, &action, NULL ); */ #endif } /* should probably call the janitor here or something */ static void close_paintown(){ Music::pause(); Bitmap::setGfxModeText(); allegro_exit(); exit(0); } END_OF_FUNCTION(close_paintown) bool Global::init( int gfx ){ ostream & out = Global::debug( 0 ); out << "-- BEGIN init --" << endl; out << "Data path is " << Util::getDataPath() << endl; out << "Paintown version " << Global::getVersionString() << endl; out << "Build date " << __DATE__ << " " << __TIME__ << endl; out << "Allegro version: " << ALLEGRO_VERSION_STR << endl; out <<"Allegro init: "<<allegro_init()<<endl; out <<"Install timer: "<<install_timer()<<endl; set_volume_per_voice( 0 ); out<<"Install sound: "<<install_sound( DIGI_AUTODETECT, MIDI_NONE, "" )<<endl; /* png */ loadpng_init(); Bitmap::SCALE_X = GFX_X; Bitmap::SCALE_Y = GFX_Y; Configuration::loadConfigurations(); const int sx = Configuration::getScreenWidth(); const int sy = Configuration::getScreenHeight(); out<<"Install keyboard: "<<install_keyboard()<<endl; out<<"Install mouse: "<<install_mouse()<<endl; out<<"Install joystick: "<<install_joystick(JOY_TYPE_AUTODETECT)<<endl; /* 16 bit color depth */ set_color_depth( 16 ); /* set up the screen */ out<<"Set gfx mode: " << Bitmap::setGraphicsMode( gfx, sx, sy ) <<endl; LOCK_VARIABLE( speed_counter ); LOCK_VARIABLE( second_counter ); LOCK_FUNCTION( (void *)inc_speed_counter ); LOCK_FUNCTION( (void *)inc_second_counter ); /* set up the timers */ out<<"Install game timer: "<<install_int_ex( inc_speed_counter, BPS_TO_TIMER( TICS_PER_SECOND ) )<<endl; out<<"Install second timer: "<<install_int_ex( inc_second_counter, BPS_TO_TIMER( 1 ) )<<endl; out << "Initialize random number generator" << endl; /* initialize random number generator */ srand( time( NULL ) ); /* keep running in the background */ set_display_switch_mode(SWITCH_BACKGROUND); /* close window when the X is pressed */ LOCK_FUNCTION(close_paintown); set_close_button_callback(close_paintown); /* music */ atexit( &dumb_exit ); atexit( Network::closeAll ); dumb_register_packfiles(); registerSignals(); out << "Initialize network" << endl; Network::init(); /* this mutex is used to show the loading screen while the game loads */ pthread_mutex_init( &Global::loading_screen_mutex, NULL ); out<<"-- END init --"<<endl; return true; } <|endoftext|>
<commit_before>#include <functional> #include <initializer_list> #include <string> #include <vector> #include <unordered_map> #include <algorithm> #include <iostream> #include <memory> namespace parser{ using namespace std; struct Sign{ std::string name; bool isTerm; Sign(std::string n, bool t): name(move(n)), isTerm(move(t)) {} Sign(std::string n): name(move(n)), isTerm(true) {} Sign(): name(""), isTerm(true) {} operator std::string() const{ return name; } bool operator==(const Sign& rhs) const{ return name == rhs.name; }; inline bool operator!=(const Sign& rhs) const{ return !(*this == rhs); } }; class HashSign { public: size_t operator()(const Sign& s) const { const int C = 9873967; size_t t = 0; for(int i = 0; i != s.name.size(); ++i) { t = t * C + (char)s.name[i]; } return t; } }; struct Item{ Sign left; std::vector<Sign> rights; int pos; Item(Sign l, vector<Sign> r): pos(0), left(move(l)), rights(move(r)) {} Sign nextSign(){ if(isLast()) return Sign(); return rights.at(pos); } void next(){ pos++; } bool isLast(){ return pos == rights.size(); } int posOf(Sign s){ int i = 0; for(auto v : rights){ if(v == s) return i; i++; } return -1; } friend std::ostream& operator<<(std::ostream &out, const Item &i){ out << std::string(i.left) <<" => "; if(i.pos == 0){ out<< " . "; } for(int j=0;j<i.rights.size();j++){ out << std::string(i.rights.at(j)); if(i.pos == j+1){ out<< " . "; }else{ out<<" "; } } out << "\n"; return out; } }; struct State{ int id; vector<Item> items; vector<Item> expands; State(): id(-1) {} State(int id): id(id) {} void append(vector<Item> newItems){ this->items.insert(items.end(), move(newItems).begin(), move(newItems).end()); } void expand(vector<Item> newItems){ this->expands.insert(expands.end(), move(newItems).begin(), move(newItems).end()); } void merge(){ this->items.insert(items.end(), expands.begin(), expands.end()); } friend std::ostream& operator<<(std::ostream &out, const State &s){ out <<"- Q"<< std::to_string(s.id) <<" -\n"; for(auto item : s.items){ cout <<" "<< item; } for(auto item : s.expands){ cout <<" "<< item; } out << "\n"; return out; } }; Sign mS(std::string name){ return Sign(name,false); } Sign mtS(std::string name){ return Sign(name); } auto E = mS("E"); auto Eq = mS("Eq"); auto T = mS("T"); auto Tq = mS("Tq"); auto F = mS("F"); auto S = mS("S"); auto Eps = mtS("Epsilon"); auto Fin = mtS("Fin"); std::vector<Item> grammar; std::vector<Item> getItems(Sign s){ std::vector<Item> res; for(auto& i : grammar){ if(i.left.name == s.name){ res.push_back(i); } } return res; } std::vector<Sign> first(Sign sign){ if(sign.isTerm){ return {sign}; } std::vector<Sign> res; auto items = getItems( sign ); if(items.size() == 0) return res; for(auto& i : items){ auto ext = first(i.rights[0]); if(find(ext.begin(), ext.end(), Eps) != ext.end()){ ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end()); res.insert(res.end(), ext.begin(), ext.end()); if(i.rights.size() >= 2){ auto nxt = first(i.rights[1]); res.insert(res.end(), nxt.begin(), nxt.end()); }else{ res.push_back( Eps); } }else{ res.insert(res.end(), ext.begin(), ext.end()); } } return res; } std::vector<Sign> first(vector<Sign>& l){ if(l.size() == 0) return {Eps}; std::vector<Sign> res; auto it = l.begin(); if(*it == Eps) return {Eps}; if((*it).isTerm) return {*it}; auto ext = first(*it); if(find(ext.begin(), ext.end(), Eps) != ext.end()){ ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end()); res.insert(res.end(), ext.begin(), ext.end()); if(l.size() >= 2 ){ it++; auto next = first(*it); res.insert(res.end(), next.begin(), next.end()); }else{ res.push_back(Eps); } } return ext; } std::vector<Sign> follow(Sign s){ std::vector<Sign> res; if(s == E){ res.push_back(Fin); } for(auto rit = grammar.cbegin(); rit != grammar.cend(); ++rit){ auto ls = (*rit).left; if(ls == s) continue; auto rs = (*rit).rights; for(size_t i = 1; i < rs.size(); i++){ if(rs[i] == s){ if(i + 1 < rs.size()){ auto ext = first(rs[i+1]); if(find(ext.begin(), ext.end(), Eps) != ext.end()){ auto left = follow(ls); res.insert(res.end(), left.begin(), left.end()); } ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end()); res.insert(res.end(), ext.begin(), ext.end()); }else{ auto left = follow(ls); res.insert(res.end(), left.begin(), left.end()); } } } } return res; } /* std::vector<Sign> follow(Sign s){ if(s == E) return { Eps }; cout << string(s) << endl; std::vector<Sign> res; for(auto item : grammar){ if(item.posOf(s) == -1) continue; if(item.posOf(s) == item.rights.size()-1){ if(s != item.left){ auto newFollow = follow(item.left); res.insert(res.end(), newFollow.begin(), newFollow.end()); } }else{ res.push_back(item.rights.at(item.posOf(s)+1)); } } return res; } */ unordered_map<Sign, vector<Sign>, HashSign> follows; vector<shared_ptr<State>> DFAutomaton; unordered_map<string, int> transitions; int cnt = 0; void generateDFAutomaton(int st){ /* cout<< "generateDFAutomaton("<<st<<") \n"; for(auto i : (*DFAutomaton[st]).items) cout << i; cout << "============\n"; cnt++; if(cnt > 100) return; */ vector<int> newStateNumbers; auto state = DFAutomaton.at(st); for(auto item : state->items){ //cout <<" size is "<< state->items.size() << endl; Sign first = item.nextSign(); if(first.name=="") continue; //cout << string(first) << endl; if(!first.isTerm){ state->expand(getItems(first)); } if(!item.isLast()){ if(transitions.find(first.name) == transitions.end()){ DFAutomaton.push_back(make_shared<State>(DFAutomaton.size() - 1)); transitions[first] = DFAutomaton.size() - 1; newStateNumbers.push_back(DFAutomaton.size() - 1); //cout<<"** \n"<< item <<" added "<< DFAutomaton.size() - 1 << endl; item.next(); DFAutomaton.at(DFAutomaton.size() - 1)->append({item}); } } } //cout << "extends\n"; for(auto item : state->expands){ Sign first = item.nextSign(); if(first.name=="") continue; //cout << string(first) << endl; if(!item.isLast()){ if(transitions.find(first.name) == transitions.end()){ DFAutomaton.push_back(make_shared<State>(DFAutomaton.size() - 1)); transitions[first] = DFAutomaton.size() - 1; newStateNumbers.push_back(DFAutomaton.size() - 1); } //cout<<"** \n"<< item <<" added "<< DFAutomaton.size() - 1 << endl; item.next(); DFAutomaton.at(DFAutomaton.size() - 1)->append({item}); } } for(auto itr = transitions.begin(); itr != transitions.end(); ++itr) { std::cout << "key = " << itr->first << ", val = " << itr->second << "\n"; } for(auto s : newStateNumbers){ //cout<< st <<"'s sub generateDFAutomaton("<<s<<") "<<(*DFAutomaton[s]).items.size()<<"\n"; generateDFAutomaton(s); } } void setup(){ grammar.push_back(Item( E, { T, Eq } )); grammar.push_back(Item( Eq, {mtS("+"), T, Eq } )); grammar.push_back(Item( Eq, { Eps } )); grammar.push_back(Item( T, { F, Tq} )); grammar.push_back(Item( Tq, { mtS("*"), F, Tq } )); grammar.push_back(Item( Tq, { Eps } )); grammar.push_back(Item( F, { mtS("("), E, mtS(")")} )); grammar.push_back(Item( F, { mtS("i")} )); grammar.push_back(Item( S, { E, Fin} )); for(auto I : grammar){ follows.emplace( I.left, follow(I.left)); } auto Q0 = make_shared<State>(0); Q0->append(getItems(S)); DFAutomaton.push_back(Q0); generateDFAutomaton(0); cout << "=======\n"; for(int i=0;i<DFAutomaton.size();i++){ cout << *DFAutomaton[i] << endl; } } using namespace std; void test(Sign S){ std::cout << "==== First is ==="<<std::string(S)<< " ===\n"; for(auto& s: first(S)){ std::cout << std::string(s) << std::endl; } std::cout<<"===== Follow is ===\n"; for(auto& r: follow(S)){ std::cout << std::string(r) << std::endl; } } void parser(){ setup(); /* test(E); test(Eq); test(T); test(Tq); test(F); std::cout<<"===\n"; std::vector<Item> items = { Item( mS("S"), { E, Fin}) }; closure(items); std::cout<<"~~~~~~~~~~~~~~~\n"; for(auto i : items) std::cout << i; //delete items; //create_dfa(); //for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){ // if(rit.second) // rit.second.reset(); //} */ } } int main(){ parser::parser(); return 0; } /* * ==== T === * ( * i * === * FIN * ) * + * ==== Tq === * * * Epsilon * === * FIN * ) * + * ==== F === * ( * i * === * FIN * ) * + * * * === */ <commit_msg>[Add] LR parse table<commit_after>#include <functional> #include <initializer_list> #include <string> #include <vector> #include <unordered_map> #include <algorithm> #include <iomanip> #include <iostream> #include <memory> namespace parser{ using namespace std; struct Sign{ std::string name; bool isTerm; Sign(std::string n, bool t): name(move(n)), isTerm(move(t)) {} Sign(std::string n): name(move(n)), isTerm(true) {} Sign(): name(""), isTerm(true) {} operator std::string() const{ return name; } bool operator==(const Sign& rhs) const{ return name == rhs.name; }; inline bool operator!=(const Sign& rhs) const{ return !(*this == rhs); } }; class HashSign { public: size_t operator()(const Sign& s) const { const int C = 9873967; size_t t = 0; for(int i = 0; i != s.name.size(); ++i) { t = t * C + (char)s.name[i]; } return t; } }; struct Item{ Sign left; std::vector<Sign> rights; int pos; Item(Sign l, vector<Sign> r): pos(0), left(move(l)), rights(move(r)) {} Sign nextSign(){ if(isLast()) return Sign(); return rights.at(pos); } void next(){ pos++; } bool isLast(){ return pos == rights.size(); } int posOf(Sign s){ int i = 0; for(auto v : rights){ if(v == s) return i; i++; } return -1; } friend std::ostream& operator<<(std::ostream &out, const Item &i){ out << std::string(i.left) <<" => "; if(i.pos == 0){ out<< " . "; } for(int j=0;j<i.rights.size();j++){ out << std::string(i.rights.at(j)); if(i.pos == j+1){ out<< " . "; }else{ out<<" "; } } out << "\n"; return out; } }; struct State{ int id; vector<Item> items; vector<Item> expands; State(): id(-1) {} State(int id): id(id) {} void append(vector<Item> newItems){ this->items.insert(items.end(), move(newItems).begin(), move(newItems).end()); } void expand(vector<Item> newItems){ this->expands.insert(expands.end(), move(newItems).begin(), move(newItems).end()); } void merge(){ this->items.insert(items.end(), expands.begin(), expands.end()); } friend std::ostream& operator<<(std::ostream &out, const State &s){ out <<"- Q"<< std::to_string(s.id) <<" -\n"; for(auto item : s.items){ cout <<" "<< item; } for(auto item : s.expands){ cout <<" "<< item; } out << "\n"; return out; } }; struct Action{ int id; enum A{ SHIFT, GOTO, REDUCE, ACCEPT } action; Action(int id,A action): id(move(id)), action(move(action)) {} }; Sign mS(std::string name){ return Sign(name,false); } Sign mtS(std::string name){ return Sign(name); } auto E = mS("E"); auto Eq = mS("Eq"); auto T = mS("T"); auto Tq = mS("Tq"); auto F = mS("F"); auto S = mS("S"); auto Eps = mtS("Epsilon"); auto Fin = mtS("Fin"); std::vector<Item> grammar; std::vector<Item> getItems(Sign s){ std::vector<Item> res; for(auto& i : grammar){ if(i.left.name == s.name){ res.push_back(i); } } return res; } std::vector<Sign> first(Sign sign){ if(sign.isTerm){ return {sign}; } std::vector<Sign> res; auto items = getItems( sign ); if(items.size() == 0) return res; for(auto& i : items){ auto ext = first(i.rights[0]); if(find(ext.begin(), ext.end(), Eps) != ext.end()){ ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end()); res.insert(res.end(), ext.begin(), ext.end()); if(i.rights.size() >= 2){ auto nxt = first(i.rights[1]); res.insert(res.end(), nxt.begin(), nxt.end()); }else{ res.push_back( Eps); } }else{ res.insert(res.end(), ext.begin(), ext.end()); } } return res; } std::vector<Sign> first(vector<Sign>& l){ if(l.size() == 0) return {Eps}; std::vector<Sign> res; auto it = l.begin(); if(*it == Eps) return {Eps}; if((*it).isTerm) return {*it}; auto ext = first(*it); if(find(ext.begin(), ext.end(), Eps) != ext.end()){ ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end()); res.insert(res.end(), ext.begin(), ext.end()); if(l.size() >= 2 ){ it++; auto next = first(*it); res.insert(res.end(), next.begin(), next.end()); }else{ res.push_back(Eps); } } return ext; } std::vector<Sign> follow(Sign s){ std::vector<Sign> res; if(s == E){ res.push_back(Fin); } for(auto rit = grammar.cbegin(); rit != grammar.cend(); ++rit){ auto ls = (*rit).left; if(ls == s) continue; auto rs = (*rit).rights; for(size_t i = 1; i < rs.size(); i++){ if(rs[i] == s){ if(i + 1 < rs.size()){ auto ext = first(rs[i+1]); if(find(ext.begin(), ext.end(), Eps) != ext.end()){ auto left = follow(ls); res.insert(res.end(), left.begin(), left.end()); } ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end()); res.insert(res.end(), ext.begin(), ext.end()); }else{ auto left = follow(ls); res.insert(res.end(), left.begin(), left.end()); } } } } return res; } /* std::vector<Sign> follow(Sign s){ if(s == E) return { Eps }; cout << string(s) << endl; std::vector<Sign> res; for(auto item : grammar){ if(item.posOf(s) == -1) continue; if(item.posOf(s) == item.rights.size()-1){ if(s != item.left){ auto newFollow = follow(item.left); res.insert(res.end(), newFollow.begin(), newFollow.end()); } }else{ res.push_back(item.rights.at(item.posOf(s)+1)); } } return res; } */ unordered_map<Sign, vector<Sign>, HashSign> follows; vector<shared_ptr<State>> DFAutomaton; unordered_multimap<Sign, pair<int,int>, HashSign> transitions; int cnt = 0; void generateDFAutomaton(int st){ /* cout<< "generateDFAutomaton("<<st<<") \n"; for(auto i : (*DFAutomaton[st]).items) cout << i; cout << "============\n"; cnt++; if(cnt > 100) return; */ vector<int> newStateNumbers; auto state = DFAutomaton.at(st); for(auto item : state->items){ //cout <<" size is "<< state->items.size() << endl; Sign first = item.nextSign(); if(first.name=="") continue; //cout << string(first) << endl; if(!first.isTerm){ state->expand(getItems(first)); } if(!item.isLast()){ if(transitions.find(first.name) == transitions.end()){ DFAutomaton.push_back(make_shared<State>(DFAutomaton.size())); transitions.emplace(first, make_pair( DFAutomaton.size()-1, st)); newStateNumbers.push_back(DFAutomaton.size() - 1); //cout<<"** \n"<< item <<" added "<< DFAutomaton.size() - 1 << endl; item.next(); DFAutomaton.at(DFAutomaton.size() - 1)->append({item}); } } } //cout << "extends\n"; for(auto item : state->expands){ Sign first = item.nextSign(); if(first.name=="") continue; //cout << string(first) << endl; if(!item.isLast()){ if(transitions.find(first.name) == transitions.end()){ DFAutomaton.push_back(make_shared<State>(DFAutomaton.size())); transitions.emplace(first, make_pair( DFAutomaton.size()-1, st)); newStateNumbers.push_back(DFAutomaton.size() - 1); } //cout<<"** \n"<< item <<" added "<< DFAutomaton.size() - 1 << endl; item.next(); DFAutomaton.at(DFAutomaton.size() - 1)->append({item}); } } for(auto s : newStateNumbers){ //cout<< st <<"'s sub generateDFAutomaton("<<s<<") "<<(*DFAutomaton[s]).items.size()<<"\n"; generateDFAutomaton(s); } } void setup(){ grammar.push_back(Item( E, { T, Eq } )); grammar.push_back(Item( Eq, {mtS("+"), T, Eq } )); grammar.push_back(Item( Eq, { Eps } )); grammar.push_back(Item( T, { F, Tq} )); grammar.push_back(Item( Tq, { mtS("*"), F, Tq } )); grammar.push_back(Item( Tq, { Eps } )); grammar.push_back(Item( F, { mtS("("), E, mtS(")")} )); grammar.push_back(Item( F, { mtS("i")} )); grammar.push_back(Item( S, { E, Fin} )); for(auto I : grammar){ follows.emplace( I.left, follow(I.left)); } auto Q0 = make_shared<State>(0); Q0->append(getItems(S)); DFAutomaton.push_back(Q0); generateDFAutomaton(0); cout << "=======\n"; for(int i=0;i<DFAutomaton.size();i++){ cout << *DFAutomaton[i] << endl; } for(auto itr = transitions.begin(); itr != transitions.end(); ++itr) { std::cout << "key = " << itr->first.name << ": from:"<< itr->second.second<< " to:" << itr->second.first << "\n"; } vector<unordered_map<Sign, shared_ptr<Action>, HashSign>> parserTable(DFAutomaton.size()); for(auto it = transitions.begin(); it != transitions.end(); ++it){ if(it->first.isTerm){ parserTable.at(it->second.second).emplace( it->first, make_shared<Action>(it->second.first, Action::SHIFT)); cout <<"shift("<< it->second.second <<","<< it->second.first <<")\n"; }else{ parserTable.at(it->second.second).emplace( it->first, make_shared<Action>(it->second.first, Action::GOTO)); cout <<"goto("<< it->second.second <<","<< it->second.first <<")\n"; } } vector<Sign> signs{mtS("i"), mtS("*"), mtS("+"), mtS("("), mtS(")"), E, Eq, T, Tq, F}; cout<<" |"; for(auto s : signs){ cout <<setw(2)<< string(s) <<"| "; } cout << endl; for(int i=0;i< parserTable.size();i++){ cout <<setw(2)<< i << "|"; for(auto s : signs){ if(parserTable.at(i).find(s) != parserTable.at(i).end()){ auto ac = parserTable.at(i).find(s)->second; if(ac->action == Action::SHIFT){ cout << "s"<<setw(2)<< ac->id <<"|"; }else{ cout << "g"<<setw(2)<< ac->id <<"|"; } }else{ cout << " |"; } } cout << endl; } // parserTableparserTable. } using namespace std; void test(Sign S){ std::cout << "==== First is ==="<<std::string(S)<< " ===\n"; for(auto& s: first(S)){ std::cout << std::string(s) << std::endl; } std::cout<<"===== Follow is ===\n"; for(auto& r: follow(S)){ std::cout << std::string(r) << std::endl; } } void parser(){ setup(); /* test(E); test(Eq); test(T); test(Tq); test(F); std::cout<<"===\n"; std::vector<Item> items = { Item( mS("S"), { E, Fin}) }; closure(items); std::cout<<"~~~~~~~~~~~~~~~\n"; for(auto i : items) std::cout << i; //delete items; //create_dfa(); //for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){ // if(rit.second) // rit.second.reset(); //} */ } } int main(){ parser::parser(); return 0; } /* * ==== T === * ( * i * === * FIN * ) * + * ==== Tq === * * * Epsilon * === * FIN * ) * + * ==== F === * ( * i * === * FIN * ) * + * * * === */ <|endoftext|>
<commit_before>#include "parser.hpp" #include <iostream> #include <sstream> #include <tuple> #include <map> #include "error.hpp" std::tuple<int64_t, bool> get_int(std::stringstream &ss, const std::string &sn, const int &ln) { int64_t integer_token; ss >> integer_token; if (ss.fail()) { std::cerr << Error() << "Invalid integer literal in " << sn << '.' << ln << std::endl; return std::make_tuple(0, true); } return std::make_tuple(integer_token, false); } std::tuple<int64_t, bool> get_reg(std::stringstream &ss, const std::string &sn, const int &ln) { // @TODO Check if integer value is actually valid int64_t integer_token; ss >> integer_token; if (ss.fail()) { std::cerr << Error() << "Invalid register literal in " << sn << '.' << ln << std::endl; return std::make_tuple(0, true); } return std::make_tuple(integer_token, false); } bool check_empty(std::stringstream &ss, const std::string &sn, const int &ln) { std::string token; if (ss >> token) { std::cerr << Error() << "Expected newline but found '" << token << "' in " << sn << '.' << ln << std::endl; return true; } return false; } Code parse(std::ifstream& src, std::string& src_name) { // Rely that src is opened and at the proper point Code code; int line_num = 0; std::string line; std::map<std::string, int64_t> label_dict; std::map<int64_t, std::string> label_refs; while (std::getline(src, line)) { line_num++; if (line.empty()) continue; std::stringstream line_stream(line); std::string token; line_stream >> token; // Check if line is a comment if (token[0] == ';') continue; // Check if line is a label if (token[0] == '@') { // @TODO Check if label is already defined and don't allow // substitutions. label_dict[token] = code.curr_index; continue; } if (token == "halt") { code.push_op(op::halt); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "noop") { code.push_op(op::noop); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "add") { code.push_op(op::add); auto tmp1 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp1)) return Code(); code.push_int(std::get<0>(tmp1)); auto tmp2 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp2)) return Code(); code.push_int(std::get<0>(tmp2)); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "cil") { code.push_op(op::cil); auto tmp1 = get_int(line_stream, src_name, line_num); if (std::get<1>(tmp1)) return Code(); code.push_int(std::get<0>(tmp1)); auto tmp2 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp2)) return Code(); code.push_int(std::get<0>(tmp2)); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "ofv") { code.push_op(op::ofv); auto tmp1 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp1)) return Code(); code.push_int(std::get<0>(tmp1)); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "onl") { code.push_op(op::onl); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jmp") { code.push_op(op::jmp); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jgt") { code.push_op(op::jgt); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jeq") { code.push_op(op::jeq); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jlt") { code.push_op(op::jlt); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else { std::cerr << Error() << "Unkown instruction '" << token << "' in " << src_name << '.' << line_num << std::endl; return Code(); } } // Push a halt at the end code.push_op(op::halt); for (auto &ref : label_refs) { const auto index_to_change = ref.first; const auto referenced_label = ref.second; const auto find_result = label_dict.find(referenced_label); if (find_result == label_dict.end()) { // @TODO Add information about where this label was used std::cerr << Error() << "Unknown label " << referenced_label << std::endl; return Code(); } const auto referenced_index = find_result->second; code.change(index_to_change, var(referenced_index)); } return code; } <commit_msg>Allow comment after instructions<commit_after>#include "parser.hpp" #include <iostream> #include <sstream> #include <tuple> #include <map> #include "error.hpp" std::tuple<int64_t, bool> get_int(std::stringstream &ss, const std::string &sn, const int &ln) { int64_t integer_token; ss >> integer_token; if (ss.fail()) { std::cerr << Error() << "Invalid integer literal in " << sn << '.' << ln << std::endl; return std::make_tuple(0, true); } return std::make_tuple(integer_token, false); } std::tuple<int64_t, bool> get_reg(std::stringstream &ss, const std::string &sn, const int &ln) { // @TODO Check if integer value is actually valid int64_t integer_token; ss >> integer_token; if (ss.fail()) { std::cerr << Error() << "Invalid register literal in " << sn << '.' << ln << std::endl; return std::make_tuple(0, true); } return std::make_tuple(integer_token, false); } bool check_empty(std::stringstream &ss, const std::string &sn, const int &ln) { std::string token; if (ss >> token) { // Allow comments if (token[0] == ';') return false; std::cerr << Error() << "Expected newline but found '" << token << "' in " << sn << '.' << ln << std::endl; return true; } return false; } Code parse(std::ifstream& src, std::string& src_name) { // Rely that src is opened and at the proper point Code code; int line_num = 0; std::string line; std::map<std::string, int64_t> label_dict; std::map<int64_t, std::string> label_refs; while (std::getline(src, line)) { line_num++; if (line.empty()) continue; std::stringstream line_stream(line); std::string token; line_stream >> token; // Check if line is a comment if (token[0] == ';') continue; // Check if line is a label if (token[0] == '@') { // @TODO Check if label is already defined and don't allow // substitutions. label_dict[token] = code.curr_index; continue; } if (token == "halt") { code.push_op(op::halt); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "noop") { code.push_op(op::noop); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "add") { code.push_op(op::add); auto tmp1 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp1)) return Code(); code.push_int(std::get<0>(tmp1)); auto tmp2 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp2)) return Code(); code.push_int(std::get<0>(tmp2)); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "cil") { code.push_op(op::cil); auto tmp1 = get_int(line_stream, src_name, line_num); if (std::get<1>(tmp1)) return Code(); code.push_int(std::get<0>(tmp1)); auto tmp2 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp2)) return Code(); code.push_int(std::get<0>(tmp2)); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "ofv") { code.push_op(op::ofv); auto tmp1 = get_reg(line_stream, src_name, line_num); if (std::get<1>(tmp1)) return Code(); code.push_int(std::get<0>(tmp1)); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "onl") { code.push_op(op::onl); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jmp") { code.push_op(op::jmp); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jgt") { code.push_op(op::jgt); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jeq") { code.push_op(op::jeq); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else if (token == "jlt") { code.push_op(op::jlt); line_stream >> token; label_refs[code.curr_index] = token; code.push_int(-1); if (check_empty(line_stream, src_name, line_num)) return Code(); } else { std::cerr << Error() << "Unkown instruction '" << token << "' in " << src_name << '.' << line_num << std::endl; return Code(); } } // Push a halt at the end code.push_op(op::halt); for (auto &ref : label_refs) { const auto index_to_change = ref.first; const auto referenced_label = ref.second; const auto find_result = label_dict.find(referenced_label); if (find_result == label_dict.end()) { // @TODO Add information about where this label was used std::cerr << Error() << "Unknown label " << referenced_label << std::endl; return Code(); } const auto referenced_index = find_result->second; code.change(index_to_change, var(referenced_index)); } return code; } <|endoftext|>
<commit_before>#ifndef ATL_PARSER_HPP #define ATL_PARSER_HPP /** * @file /home/ryan/programming/atl/parser.hpp * @author Ryan Domigan <ryan_domigan@[email protected]> * Created on Jun 29, 2013 */ #include <iterator> #include <sstream> #include <string> #include <vector> #include <iostream> #include <functional> #include <iterator> #include "./exception.hpp" #include "./type.hpp" #include "./conversion.hpp" #include "./type_testing.hpp" #include "./helpers.hpp" #include "./print.hpp" namespace atl { // A simple minded parser, this just transforms a string into an // Ast. There are a couple of reserved symbols: // // '(' ')' : Open and close an Ast branch // // DELIM '\'' : 'n expands to (quote n) (should probably be a // macro). Can still be used as part of a // variable name (ie x and x' are both valid // symbols). // // '\"' : starts and ends a string literal // // DELIM 0..9 DELIM: a number (a number must be all digits ie // 124567, possibly with a decimal point. If // there is a non-digit ie 12345a, it is a // symbol. hex/octal/binary representations // are not a thing ATM). // ';' : comments out to the end of line class ParseString { private: template<class Itr> void skip_ws_and_comments(Itr &itr, Itr const& end) { for(; itr != end; ++itr) { if(*itr == ';') for(; (itr != end) && (*itr != '\n'); ++itr); else if(!std::isspace(*itr)) return; if(*itr == '\n') ++_line; } } GC &_gc; unsigned long _line; static const string delim; /* symbol deliminator */ static const string _ws; /* white space */ string scratch; inline bool digit(char c) { return ((c >= '0') && (c <= '9')); } bool string_is_number(const string& str) { return (digit(str[0]) || ((str[0] == '-') && (str.length() > 1) && digit(str[1]))); } template<class Itr> void parse(AstSubstrate &vec, Itr &&itr, Itr &&end) { for(; itr != end; ++itr) { switch(*itr) { case '\n': ++_line; case ' ': /* whitespace */ case '\t': continue; case ';': /* comment */ for(; itr != end && *itr != '\n'; ++itr); if(*itr == '\n') ++_line; continue; case '\'': { /* quote */ auto quote = push_nested_ast(vec); vec.push_back(wrap<Quote>()); ++itr; parse(vec, itr, end); quote.end_ast(); return; } case '(': { /* sub expression */ ++itr; if(*itr == ')') { push_nested_ast(vec); return; } auto ast = push_nested_ast(vec); while(*itr != ')') { if(itr == end) throw UnbalancedParens (to_string(_line) .append(": error: unbalanced parens")); parse(vec, itr, end); } ++itr; ast.end_ast(); return; } case ')': return; case '"': { /* string */ std::string *str = reinterpret_cast<std::string*>(_gc.make<String>()); for(++itr; *itr != '"'; ++itr) { if(itr == end) throw to_string(_line) .append("string not terminated."); if(*itr == '\n') ++_line; str->push_back(*itr); } ++itr; vec.emplace_back(tag<String>::value, str); return; } default: { scratch.clear(); for(; (itr != end) && (delim.find(*itr) == string::npos); ++itr) scratch.push_back(*itr); if((itr != end) && (*itr == '\n')) ++_line; if(string_is_number(scratch)) { vec.push_back(wrap(atoi(scratch.c_str()))); } else { vec.push_back(_gc.amake<Symbol>(scratch)); } return; } } } return; } public: ParseString(GC &gc) : _gc(gc) { _line = 1; //_gc.mark_callback( [this](GC &gc) { _gc.mark(_mark); }); } /* parse one S-expression from a string into an ast */ PassByValue string_(const std::string& input) { auto& vec = _gc.sequence(); auto itr = input.begin(), end = input.end(); parse(vec, itr, end); // Check that there was just one expression in our string while(itr != input.end() && std::isspace(*itr)) ++itr; if(itr != input.end()) throw MultiExpressionString(std::string("More than one expression in `") .append(input) .append("`")); return PassByValue(*vec.begin()); } /* parse one S-expression from a stream into an ast */ PassByValue stream(istream &stream) s{ auto initial_flags = stream.flags(); noskipws(stream); auto& vec = _gc.sequence(); auto itr = istreambuf_iterator<char>(stream), end = istreambuf_iterator<char>(); parse(vec, itr, end); // Swallow any following whitepace or comments so the caller // of the parser doesn't have to check. skip_ws_and_comments(itr, end); stream.flags(initial_flags); return PassByValue(*vec.begin()); } void reset_line_number() { _line = 1; } }; const std::string ParseString::_ws = " \n\t"; const std::string ParseString::delim = "()\" \n\t"; } #endif <commit_msg>Fix typo in parser<commit_after>#ifndef ATL_PARSER_HPP #define ATL_PARSER_HPP /** * @file /home/ryan/programming/atl/parser.hpp * @author Ryan Domigan <ryan_domigan@[email protected]> * Created on Jun 29, 2013 */ #include <iterator> #include <sstream> #include <string> #include <vector> #include <iostream> #include <functional> #include <iterator> #include "./exception.hpp" #include "./type.hpp" #include "./conversion.hpp" #include "./type_testing.hpp" #include "./helpers.hpp" #include "./print.hpp" namespace atl { // A simple minded parser, this just transforms a string into an // Ast. There are a couple of reserved symbols: // // '(' ')' : Open and close an Ast branch // // DELIM '\'' : 'n expands to (quote n) (should probably be a // macro). Can still be used as part of a // variable name (ie x and x' are both valid // symbols). // // '\"' : starts and ends a string literal // // DELIM 0..9 DELIM: a number (a number must be all digits ie // 124567, possibly with a decimal point. If // there is a non-digit ie 12345a, it is a // symbol. hex/octal/binary representations // are not a thing ATM). // ';' : comments out to the end of line class ParseString { private: template<class Itr> void skip_ws_and_comments(Itr &itr, Itr const& end) { for(; itr != end; ++itr) { if(*itr == ';') for(; (itr != end) && (*itr != '\n'); ++itr); else if(!std::isspace(*itr)) return; if(*itr == '\n') ++_line; } } GC &_gc; unsigned long _line; static const string delim; /* symbol deliminator */ static const string _ws; /* white space */ string scratch; inline bool digit(char c) { return ((c >= '0') && (c <= '9')); } bool string_is_number(const string& str) { return (digit(str[0]) || ((str[0] == '-') && (str.length() > 1) && digit(str[1]))); } template<class Itr> void parse(AstSubstrate &vec, Itr &&itr, Itr &&end) { for(; itr != end; ++itr) { switch(*itr) { case '\n': ++_line; case ' ': /* whitespace */ case '\t': continue; case ';': /* comment */ for(; itr != end && *itr != '\n'; ++itr); if(*itr == '\n') ++_line; continue; case '\'': { /* quote */ auto quote = push_nested_ast(vec); vec.push_back(wrap<Quote>()); ++itr; parse(vec, itr, end); quote.end_ast(); return; } case '(': { /* sub expression */ ++itr; if(*itr == ')') { push_nested_ast(vec); return; } auto ast = push_nested_ast(vec); while(*itr != ')') { if(itr == end) throw UnbalancedParens (to_string(_line) .append(": error: unbalanced parens")); parse(vec, itr, end); } ++itr; ast.end_ast(); return; } case ')': return; case '"': { /* string */ std::string *str = reinterpret_cast<std::string*>(_gc.make<String>()); for(++itr; *itr != '"'; ++itr) { if(itr == end) throw to_string(_line) .append("string not terminated."); if(*itr == '\n') ++_line; str->push_back(*itr); } ++itr; vec.emplace_back(tag<String>::value, str); return; } default: { scratch.clear(); for(; (itr != end) && (delim.find(*itr) == string::npos); ++itr) scratch.push_back(*itr); if((itr != end) && (*itr == '\n')) ++_line; if(string_is_number(scratch)) { vec.push_back(wrap(atoi(scratch.c_str()))); } else { vec.push_back(_gc.amake<Symbol>(scratch)); } return; } } } return; } public: ParseString(GC &gc) : _gc(gc) { _line = 1; //_gc.mark_callback( [this](GC &gc) { _gc.mark(_mark); }); } /* parse one S-expression from a string into an ast */ PassByValue string_(const std::string& input) { auto& vec = _gc.sequence(); auto itr = input.begin(), end = input.end(); parse(vec, itr, end); // Check that there was just one expression in our string while(itr != input.end() && std::isspace(*itr)) ++itr; if(itr != input.end()) throw MultiExpressionString(std::string("More than one expression in `") .append(input) .append("`")); return PassByValue(*vec.begin()); } /* parse one S-expression from a stream into an ast */ PassByValue stream(istream &stream) { auto initial_flags = stream.flags(); noskipws(stream); auto& vec = _gc.sequence(); auto itr = istreambuf_iterator<char>(stream), end = istreambuf_iterator<char>(); parse(vec, itr, end); // Swallow any following whitepace or comments so the caller // of the parser doesn't have to check. skip_ws_and_comments(itr, end); stream.flags(initial_flags); return PassByValue(*vec.begin()); } void reset_line_number() { _line = 1; } }; const std::string ParseString::_ws = " \n\t"; const std::string ParseString::delim = "()\" \n\t"; } #endif <|endoftext|>
<commit_before>#include <iostream> #include <boost/timer.hpp> #include <stdio.h> int main( int argc, char **argv ) { boost::timer t; std::cout << "max timespan: " << t.elapsed_max() / 3600 << "h" << std::endl; std::cout << "min timespan: " << t.elapsed_min() << "s" << std::endl; std::cout << "now times elapsed: " << t.elapsed() << "s" << std::endl; getchar(); return 0; } <commit_msg>a more meaningful example for boost.<commit_after>#include <cstdio> #include <boost/date_time/posix_time/posix_time.hpp> int main( void ) { namespace pt = boost::posix_time; pt::ptime now = pt::second_clock::local_time(); printf( "%s\t->\t%04d-%02d-%02d %02d:%02d:%02d\n" , "date '+%Y-%m-%d %H:%M:%S'" , now.date().year() , now.date().month() , now.date().day() , now.time_of_day().hours() , now.time_of_day().minutes() , now.time_of_day().seconds() ); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * TeapotNet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/mutex.h" #include "tpn/exception.h" namespace tpn { Mutex::Mutex(void) : mLockCount(0), mRelockCount(0) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); //pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); if(pthread_mutex_init(&mMutex, &attr) != 0) throw Exception("Unable to create mutex"); } Mutex::~Mutex(void) { pthread_mutex_destroy(&mMutex); } void Mutex::lock(int count) { if(count <= 0) return; int ret = pthread_mutex_lock(&mMutex); if(ret != 0 && ret != EDEADLK) throw Exception("Unable to lock mutex"); if(ret == 0) Assert(mLockCount == 0); mLockedBy = pthread_self(); mLockCount+= count; } bool Mutex::tryLock(void) { int ret = pthread_mutex_trylock(&mMutex); if(ret == EBUSY) return false; if(ret != 0 && ret != EDEADLK) throw Exception("Unable to lock mutex"); if(ret == 0) Assert(mLockCount == 0); mLockedBy = pthread_self(); mLockCount++; return true; } void Mutex::unlock(void) { if(!mLockCount) throw Exception("Mutex is not locked"); if(!pthread_equal(mLockedBy, pthread_self())) throw Exception("Mutex is locked by another thread"); mLockCount--; if(mLockCount == 0) { int ret = pthread_mutex_unlock(&mMutex); if(ret != 0) throw Exception("Unable to unlock mutex"); } } int Mutex::unlockAll(void) { if(!mLockCount) throw Exception("Mutex is not locked"); if(!pthread_equal(mLockedBy, pthread_self())) throw Exception("Mutex is locked by another thread"); mRelockCount = mLockCount; mLockCount = 0; int ret = pthread_mutex_unlock(&mMutex); if(ret != 0) throw Exception("Unable to unlock mutex"); return mRelockCount; } void Mutex::relockAll(void) { lock(mRelockCount); mRelockCount = 0; } int Mutex::lockCount(void) const { return mLockCount; } } <commit_msg>Fixed random issues with mutexes<commit_after>/************************************************************************* * Copyright (C) 2011-2012 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of TeapotNet. * * * * TeapotNet is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * TeapotNet is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with TeapotNet. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #include "tpn/mutex.h" #include "tpn/exception.h" namespace tpn { Mutex::Mutex(void) : mLockCount(0), mRelockCount(0) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); //pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); if(pthread_mutex_init(&mMutex, &attr) != 0) throw Exception("Unable to create mutex"); } Mutex::~Mutex(void) { pthread_mutex_destroy(&mMutex); } void Mutex::lock(int count) { if(count <= 0) return; int ret = pthread_mutex_lock(&mMutex); if(ret != 0 && ret != EDEADLK) throw Exception("Unable to lock mutex"); if(ret == 0) Assert(mLockCount == 0); mLockedBy = pthread_self(); mLockCount+= count; } bool Mutex::tryLock(void) { int ret = pthread_mutex_trylock(&mMutex); if(ret == EBUSY) return false; if(ret != 0 && ret != EDEADLK) throw Exception("Unable to lock mutex"); if(ret == 0) Assert(mLockCount == 0); mLockedBy = pthread_self(); mLockCount++; return true; } void Mutex::unlock(void) { if(!mLockCount) throw Exception("Mutex is not locked"); //if(!pthread_equal(mLockedBy, pthread_self())) // throw Exception("Mutex is locked by another thread"); mLockCount--; if(mLockCount == 0) { int ret = pthread_mutex_unlock(&mMutex); if(ret != 0) throw Exception("Unable to unlock mutex"); } } int Mutex::unlockAll(void) { if(!mLockCount) throw Exception("Mutex is not locked"); //if(!pthread_equal(mLockedBy, pthread_self())) // throw Exception("Mutex is locked by another thread"); mRelockCount = mLockCount; mLockCount = 0; int ret = pthread_mutex_unlock(&mMutex); if(ret != 0) throw Exception("Unable to unlock mutex"); return mRelockCount; } void Mutex::relockAll(void) { lock(mRelockCount); mRelockCount = 0; } int Mutex::lockCount(void) const { return mLockCount; } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // varchar_type.cpp // // Identification: src/codegen/type/varchar_type.cpp // // Copyright (c) 2015-2017, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "codegen/type/varchar_type.h" #include "codegen/lang/if.h" #include "codegen/proxy/string_functions_proxy.h" #include "codegen/proxy/values_runtime_proxy.h" #include "codegen/type/boolean_type.h" #include "codegen/type/integer_type.h" #include "codegen/type/timestamp_type.h" #include "codegen/proxy/timestamp_functions_proxy.h" #include "codegen/value.h" namespace peloton { namespace codegen { namespace type { namespace { // Comparison struct CompareVarchar : public TypeSystem::SimpleNullableComparison { bool SupportsTypes(const type::Type &left_type, const type::Type &right_type) const override { return left_type.GetSqlType() == Varchar::Instance() && left_type == right_type; } // Call ValuesRuntime::CompareStrings(). This function behaves like strcmp(), // returning a values less than, equal to, or greater than zero if left is // found to be less than, matches, or is greater than the right value. llvm::Value *CallCompareStrings(CodeGen &codegen, const Value &left, const Value &right) const { // Setup the function arguments and invoke the call std::vector<llvm::Value *> args = {left.GetValue(), left.GetLength(), right.GetValue(), right.GetLength()}; return codegen.Call(ValuesRuntimeProxy::CompareStrings, args); } Value CompareLtImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is < 0 result = codegen->CreateICmpSLT(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareLteImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is <= 0 result = codegen->CreateICmpSLE(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareEqImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is == 0 result = codegen->CreateICmpEQ(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareNeImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is == 0 result = codegen->CreateICmpNE(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareGtImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is > 0 result = codegen->CreateICmpSGT(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareGteImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is >= 0 result = codegen->CreateICmpSGE(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareForSortImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Return the comparison return Value{Integer::Instance(), result}; } }; struct Ascii : public TypeSystem::SimpleNullableUnaryOperator { bool SupportsType(const Type &type) const override { return type.GetSqlType() == Varchar::Instance(); } Type ResultType(UNUSED_ATTRIBUTE const Type &val_type) const override { return Integer::Instance(); } Value Impl(CodeGen &codegen, const Value &val) const override { llvm::Value *raw_ret = codegen.Call(StringFunctionsProxy::Ascii, {val.GetValue(), val.GetLength()}); return Value{Integer::Instance(), raw_ret}; } }; struct Like : public TypeSystem::BinaryOperator { bool SupportsTypes(const Type &left_type, const Type &right_type) const override { return left_type.GetSqlType() == Varchar::Instance() && left_type == right_type; } Type ResultType(UNUSED_ATTRIBUTE const Type &left_type, UNUSED_ATTRIBUTE const Type &right_type) const override { return Boolean::Instance(); } Value Impl(CodeGen &codegen, const Value &left, const Value &right) const { // Call StringFunctions::Like(...) llvm::Value *raw_ret = codegen.Call(StringFunctionsProxy::Like, {left.GetValue(), left.GetLength(), right.GetValue(), right.GetLength()}); // Return the result return Value{Boolean::Instance(), raw_ret}; } Value Eval(CodeGen &codegen, const Value &left, const Value &right, UNUSED_ATTRIBUTE OnError on_error) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); if (!left.IsNullable()) { return Impl(codegen, left, right); } // The input string is NULLable, perform NULL check codegen::Value null_ret, not_null_ret; lang::If input_null{codegen, left.IsNull(codegen)}; { // Input is null, return false null_ret = codegen::Value{Boolean::Instance(), codegen.ConstBool(false)}; } input_null.ElseBlock(); { not_null_ret = Impl(codegen, left, right); } return input_null.BuildPHI(null_ret, not_null_ret); } }; struct Length : public TypeSystem::UnaryOperator { bool SupportsType(const Type &type) const override { return type.GetSqlType() == Varchar::Instance(); } Type ResultType(UNUSED_ATTRIBUTE const Type &val_type) const override { return Integer::Instance(); } Value DoWork(CodeGen &codegen, const Value &val) const override { llvm::Value *raw_ret = codegen.Call(StringFunctionsProxy::Length, {val.GetValue(), val.GetLength()}); return Value{Integer::Instance(), raw_ret}; } }; // DateTrunc // TODO(lma): Move this to the Timestamp type once the function lookup logic is // corrected. struct DateTrunc : public TypeSystem::BinaryOperator { bool SupportsTypes(const Type &left_type, const Type &right_type) const override { return left_type.GetSqlType() == Varchar::Instance() && right_type.GetSqlType() == Timestamp::Instance(); } Type ResultType(UNUSED_ATTRIBUTE const Type &left_type, UNUSED_ATTRIBUTE const Type &right_type) const override { return Type{Timestamp::Instance()}; } Value DoWork(CodeGen &codegen, const Value &left, const Value &right, UNUSED_ATTRIBUTE OnError on_error) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); llvm::Value *raw_ret = codegen.Call(TimestampFunctionsProxy::DateTrunc, {left.GetValue(), right.GetValue()}); return Value{Timestamp::Instance(), raw_ret}; } }; //===----------------------------------------------------------------------===// // TYPE SYSTEM CONSTRUCTION //===----------------------------------------------------------------------===// // The list of types a SQL varchar type can be implicitly casted to const std::vector<peloton::type::TypeId> kImplicitCastingTable = { peloton::type::TypeId::VARCHAR}; // Explicit casting rules static std::vector<TypeSystem::CastInfo> kExplicitCastingTable = {}; // Comparison operations static CompareVarchar kCompareVarchar; static std::vector<TypeSystem::ComparisonInfo> kComparisonTable = { {kCompareVarchar}}; // Unary operators static Ascii kAscii; static Length kLength; static std::vector<TypeSystem::UnaryOpInfo> kUnaryOperatorTable = { {OperatorId::Ascii, kAscii}, {OperatorId::Length, kLength}}; // Binary operations static Like kLike; static DateTrunc kDateTrunc; static std::vector<TypeSystem::BinaryOpInfo> kBinaryOperatorTable = { {OperatorId::Like, kLike}, {OperatorId::DateTrunc, kDateTrunc}}; // Nary operations static std::vector<TypeSystem::NaryOpInfo> kNaryOperatorTable = {}; } // anonymous namespace //===----------------------------------------------------------------------===// // TINYINT TYPE CONFIGURATION //===----------------------------------------------------------------------===// // Initialize the VARCHAR SQL type with the configured type system Varchar::Varchar() : SqlType(peloton::type::TypeId::VARCHAR), type_system_(kImplicitCastingTable, kExplicitCastingTable, kComparisonTable, kUnaryOperatorTable, kBinaryOperatorTable, kNaryOperatorTable) {} Value Varchar::GetMinValue(UNUSED_ATTRIBUTE CodeGen &codegen) const { throw Exception{"The VARCHAR type does not have a minimum value ..."}; } Value Varchar::GetMaxValue(UNUSED_ATTRIBUTE CodeGen &codegen) const { throw Exception{"The VARCHAR type does not have a maximum value ..."}; } Value Varchar::GetNullValue(CodeGen &codegen) const { return Value{Type{TypeId(), true}, codegen.NullPtr(codegen.CharPtrType()), codegen.Const32(0), codegen.ConstBool(true)}; } void Varchar::GetTypeForMaterialization(CodeGen &codegen, llvm::Type *&val_type, llvm::Type *&len_type) const { val_type = codegen.CharPtrType(); len_type = codegen.Int32Type(); } llvm::Function *Varchar::GetOutputFunction( CodeGen &codegen, UNUSED_ATTRIBUTE const Type &type) const { // TODO: We should use the length information in the type? return ValuesRuntimeProxy::OutputVarchar.GetFunction(codegen); } } // namespace type } // namespace codegen } // namespace peloton <commit_msg>Formatting + comments<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // varchar_type.cpp // // Identification: src/codegen/type/varchar_type.cpp // // Copyright (c) 2015-2017, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "codegen/type/varchar_type.h" #include "codegen/lang/if.h" #include "codegen/proxy/string_functions_proxy.h" #include "codegen/proxy/values_runtime_proxy.h" #include "codegen/type/boolean_type.h" #include "codegen/type/integer_type.h" #include "codegen/type/timestamp_type.h" #include "codegen/proxy/timestamp_functions_proxy.h" #include "codegen/value.h" namespace peloton { namespace codegen { namespace type { namespace { // Comparison struct CompareVarchar : public TypeSystem::SimpleNullableComparison { bool SupportsTypes(const type::Type &left_type, const type::Type &right_type) const override { return left_type.GetSqlType() == Varchar::Instance() && left_type == right_type; } // Call ValuesRuntime::CompareStrings(). This function behaves like strcmp(), // returning a values less than, equal to, or greater than zero if left is // found to be less than, matches, or is greater than the right value. llvm::Value *CallCompareStrings(CodeGen &codegen, const Value &left, const Value &right) const { // Setup the function arguments and invoke the call std::vector<llvm::Value *> args = {left.GetValue(), left.GetLength(), right.GetValue(), right.GetLength()}; return codegen.Call(ValuesRuntimeProxy::CompareStrings, args); } Value CompareLtImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is < 0 result = codegen->CreateICmpSLT(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareLteImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is <= 0 result = codegen->CreateICmpSLE(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareEqImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is == 0 result = codegen->CreateICmpEQ(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareNeImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is == 0 result = codegen->CreateICmpNE(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareGtImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is > 0 result = codegen->CreateICmpSGT(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareGteImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Check if the result is >= 0 result = codegen->CreateICmpSGE(result, codegen.Const32(0)); // Return the comparison return Value{Boolean::Instance(), result}; } Value CompareForSortImpl(CodeGen &codegen, const Value &left, const Value &right) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Call CompareStrings(...) llvm::Value *result = CallCompareStrings(codegen, left, right); // Return the comparison return Value{Integer::Instance(), result}; } }; struct Ascii : public TypeSystem::SimpleNullableUnaryOperator { bool SupportsType(const Type &type) const override { return type.GetSqlType() == Varchar::Instance(); } Type ResultType(UNUSED_ATTRIBUTE const Type &val_type) const override { return Integer::Instance(); } Value Impl(CodeGen &codegen, const Value &val) const override { llvm::Value *raw_ret = codegen.Call(StringFunctionsProxy::Ascii, {val.GetValue(), val.GetLength()}); return Value{Integer::Instance(), raw_ret}; } }; struct Like : public TypeSystem::BinaryOperator { bool SupportsTypes(const Type &left_type, const Type &right_type) const override { return left_type.GetSqlType() == Varchar::Instance() && left_type == right_type; } Type ResultType(UNUSED_ATTRIBUTE const Type &left_type, UNUSED_ATTRIBUTE const Type &right_type) const override { return Boolean::Instance(); } Value Impl(CodeGen &codegen, const Value &left, const Value &right) const { // Call StringFunctions::Like(...) llvm::Value *raw_ret = codegen.Call(StringFunctionsProxy::Like, {left.GetValue(), left.GetLength(), right.GetValue(), right.GetLength()}); // Return the result return Value{Boolean::Instance(), raw_ret}; } Value Eval(CodeGen &codegen, const Value &left, const Value &right, UNUSED_ATTRIBUTE OnError on_error) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); // Pre-condition: Left value is the input string; right value is the pattern if (!left.IsNullable()) { return Impl(codegen, left, right); } codegen::Value null_ret, not_null_ret; lang::If input_null{codegen, left.IsNull(codegen)}; { // Input is null, return false null_ret = codegen::Value{Boolean::Instance(), codegen.ConstBool(false)}; } input_null.ElseBlock(); { // Input is not null, invoke LIKE not_null_ret = Impl(codegen, left, right); } return input_null.BuildPHI(null_ret, not_null_ret); } }; struct Length : public TypeSystem::UnaryOperator { bool SupportsType(const Type &type) const override { return type.GetSqlType() == Varchar::Instance(); } Type ResultType(UNUSED_ATTRIBUTE const Type &val_type) const override { return Integer::Instance(); } Value DoWork(CodeGen &codegen, const Value &val) const override { llvm::Value *raw_ret = codegen.Call(StringFunctionsProxy::Length, {val.GetValue(), val.GetLength()}); return Value{Integer::Instance(), raw_ret}; } }; // DateTrunc // TODO(lma): Move this to the Timestamp type once the function lookup logic is // corrected. struct DateTrunc : public TypeSystem::BinaryOperator { bool SupportsTypes(const Type &left_type, const Type &right_type) const override { return left_type.GetSqlType() == Varchar::Instance() && right_type.GetSqlType() == Timestamp::Instance(); } Type ResultType(UNUSED_ATTRIBUTE const Type &left_type, UNUSED_ATTRIBUTE const Type &right_type) const override { return Type{Timestamp::Instance()}; } Value DoWork(CodeGen &codegen, const Value &left, const Value &right, UNUSED_ATTRIBUTE OnError on_error) const override { PL_ASSERT(SupportsTypes(left.GetType(), right.GetType())); llvm::Value *raw_ret = codegen.Call(TimestampFunctionsProxy::DateTrunc, {left.GetValue(), right.GetValue()}); return Value{Timestamp::Instance(), raw_ret}; } }; //===----------------------------------------------------------------------===// // TYPE SYSTEM CONSTRUCTION //===----------------------------------------------------------------------===// // The list of types a SQL varchar type can be implicitly casted to const std::vector<peloton::type::TypeId> kImplicitCastingTable = { peloton::type::TypeId::VARCHAR}; // Explicit casting rules static std::vector<TypeSystem::CastInfo> kExplicitCastingTable = {}; // Comparison operations static CompareVarchar kCompareVarchar; static std::vector<TypeSystem::ComparisonInfo> kComparisonTable = { {kCompareVarchar}}; // Unary operators static Ascii kAscii; static Length kLength; static std::vector<TypeSystem::UnaryOpInfo> kUnaryOperatorTable = { {OperatorId::Ascii, kAscii}, {OperatorId::Length, kLength}}; // Binary operations static Like kLike; static DateTrunc kDateTrunc; static std::vector<TypeSystem::BinaryOpInfo> kBinaryOperatorTable = { {OperatorId::Like, kLike}, {OperatorId::DateTrunc, kDateTrunc}}; // Nary operations static std::vector<TypeSystem::NaryOpInfo> kNaryOperatorTable = {}; } // anonymous namespace //===----------------------------------------------------------------------===// // TINYINT TYPE CONFIGURATION //===----------------------------------------------------------------------===// // Initialize the VARCHAR SQL type with the configured type system Varchar::Varchar() : SqlType(peloton::type::TypeId::VARCHAR), type_system_(kImplicitCastingTable, kExplicitCastingTable, kComparisonTable, kUnaryOperatorTable, kBinaryOperatorTable, kNaryOperatorTable) {} Value Varchar::GetMinValue(UNUSED_ATTRIBUTE CodeGen &codegen) const { throw Exception{"The VARCHAR type does not have a minimum value ..."}; } Value Varchar::GetMaxValue(UNUSED_ATTRIBUTE CodeGen &codegen) const { throw Exception{"The VARCHAR type does not have a maximum value ..."}; } Value Varchar::GetNullValue(CodeGen &codegen) const { return Value{Type{TypeId(), true}, codegen.NullPtr(codegen.CharPtrType()), codegen.Const32(0), codegen.ConstBool(true)}; } void Varchar::GetTypeForMaterialization(CodeGen &codegen, llvm::Type *&val_type, llvm::Type *&len_type) const { val_type = codegen.CharPtrType(); len_type = codegen.Int32Type(); } llvm::Function *Varchar::GetOutputFunction( CodeGen &codegen, UNUSED_ATTRIBUTE const Type &type) const { // TODO: We should use the length information in the type? return ValuesRuntimeProxy::OutputVarchar.GetFunction(codegen); } } // namespace type } // namespace codegen } // namespace peloton <|endoftext|>
<commit_before>#include <stack.cpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.pop()==1); } /*SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); }*/ SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.push(2); s.pop(); REQUIRE(s.count()==1); REQUIRE(s.pop()==1); } SCENARIO("prisv", "[prisv]"){ stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.pop()==1); } SCENARIO("copy", "[copy]"){ stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.pop()==1); } SCENARIO("test", "[test]"){ stack<int> s; REQUIRE(s.count()==0); }/* SCENARIO("empty", "[empty]"){ stack<int> s; REQUIRE(s.empty()==true); } */ <commit_msg>Update init.cpp<commit_after>#include <stack.cpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.push(2); s.pop(); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("prisv", "[prisv]"){ stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("copy", "[copy]"){ stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.top()==1); } SCENARIO("test", "[test]"){ stack<int> s; REQUIRE(s.count()==0); }/* SCENARIO("empty", "[empty]"){ stack<int> s; REQUIRE(s.empty()==true); } */ <|endoftext|>
<commit_before>#ifndef EXCHANGE_ENDPOINT_BY_SWAPPING #define EXCHANGE_ENDPOINT_BY_SWAPPING #include<algorithm> #include<functional> #include<iterator> //cbegin, cend #include<type_traits> //result_of_t #include<utility> #include<vector> namespace nAlgorithm { //vector<vector<return type of BinaryOp>> template<class BidIter,class BinaryOp> std::vector<std::vector<std::result_of_t<BinaryOp(typename std::iterator_traits<BidIter>::value_type,typename std::iterator_traits<BidIter>::value_type)>>> exchange_endpoint_by_swapping(const BidIter begin,const BidIter end,const BinaryOp op) { using namespace std; using Vec=vector<vector<pair<const BidIter,const BidIter>>>; function<void(BidIter,BidIter,Vec &,size_t)> exchange_endpoint_by_swapping_; function<void(BidIter,BidIter,Vec &,size_t)> to_right_{[&](BidIter to_right,const BidIter to_left,Vec &vec,const size_t level){ vec.back().emplace_back(to_right,next(to_right)); advance(to_right,1); if(to_right==to_left) exchange_endpoint_by_swapping_(to_right,prev(to_left),vec,level+1); else exchange_endpoint_by_swapping_(to_right,to_left,vec,level+1); }}; function<void(BidIter,BidIter,Vec &,size_t)> to_left_{[&](const BidIter to_right,BidIter to_left,Vec &vec,const size_t level){ vec.back().emplace_back(prev(to_left),to_left); advance(to_left,-1); if(to_right==to_left) exchange_endpoint_by_swapping_(next(to_right),to_left,vec,level+1); else exchange_endpoint_by_swapping_(to_right,to_left,vec,level+1); }}; exchange_endpoint_by_swapping_=[&,begin,end](const BidIter to_right,const BidIter to_left,Vec &vec,const size_t level){ if(next(to_right)==to_left) to_right_(to_right,to_left,vec,level); else { bool copy{false}; if(to_right!=prev(end)) { to_right_(to_right,to_left,vec,level); copy=true; } if(to_left!=begin) { if(copy) vec.emplace_back(std::cbegin(vec.back()),next(std::cbegin(vec.back()),level)); to_left_(to_right,to_left,vec,level); } } }; if(static_cast<size_t>(distance(begin,end))<2) return {}; Vec vec(1); //not {} exchange_endpoint_by_swapping_(begin,prev(end),vec,0); result_of_t<decltype(exchange_endpoint_by_swapping<BidIter,BinaryOp>)&(BidIter,BidIter,BinaryOp)> result; result.reserve(vec.size()); for(auto &val:vec) { result.emplace_back(); result.reserve(val.size()); transform(std::cbegin(val),std::cend(val),back_inserter(result.back()),[op](const pair<const BidIter,const BidIter> &val){return op(*val.first,*val.second);}); } return result; } } #endif<commit_msg>add const to auto &val<commit_after>#ifndef EXCHANGE_ENDPOINT_BY_SWAPPING #define EXCHANGE_ENDPOINT_BY_SWAPPING #include<algorithm> #include<functional> #include<iterator> //cbegin, cend #include<type_traits> //result_of_t #include<utility> #include<vector> namespace nAlgorithm { //vector<vector<return type of BinaryOp>> template<class BidIter,class BinaryOp> std::vector<std::vector<std::result_of_t<BinaryOp(typename std::iterator_traits<BidIter>::value_type,typename std::iterator_traits<BidIter>::value_type)>>> exchange_endpoint_by_swapping(const BidIter begin,const BidIter end,const BinaryOp op) { using namespace std; using Vec=vector<vector<pair<const BidIter,const BidIter>>>; function<void(BidIter,BidIter,Vec &,size_t)> exchange_endpoint_by_swapping_; function<void(BidIter,BidIter,Vec &,size_t)> to_right_{[&](BidIter to_right,const BidIter to_left,Vec &vec,const size_t level){ vec.back().emplace_back(to_right,next(to_right)); advance(to_right,1); if(to_right==to_left) exchange_endpoint_by_swapping_(to_right,prev(to_left),vec,level+1); else exchange_endpoint_by_swapping_(to_right,to_left,vec,level+1); }}; function<void(BidIter,BidIter,Vec &,size_t)> to_left_{[&](const BidIter to_right,BidIter to_left,Vec &vec,const size_t level){ vec.back().emplace_back(prev(to_left),to_left); advance(to_left,-1); if(to_right==to_left) exchange_endpoint_by_swapping_(next(to_right),to_left,vec,level+1); else exchange_endpoint_by_swapping_(to_right,to_left,vec,level+1); }}; exchange_endpoint_by_swapping_=[&,begin,end](const BidIter to_right,const BidIter to_left,Vec &vec,const size_t level){ if(next(to_right)==to_left) to_right_(to_right,to_left,vec,level); else { bool copy{false}; if(to_right!=prev(end)) { to_right_(to_right,to_left,vec,level); copy=true; } if(to_left!=begin) { if(copy) vec.emplace_back(std::cbegin(vec.back()),next(std::cbegin(vec.back()),level)); to_left_(to_right,to_left,vec,level); } } }; if(static_cast<size_t>(distance(begin,end))<2) return {}; Vec vec(1); //not {} exchange_endpoint_by_swapping_(begin,prev(end),vec,0); result_of_t<decltype(exchange_endpoint_by_swapping<BidIter,BinaryOp>)&(BidIter,BidIter,BinaryOp)> result; result.reserve(vec.size()); for(const auto &val:vec) { result.emplace_back(); result.reserve(val.size()); transform(std::cbegin(val),std::cend(val),back_inserter(result.back()),[op](const pair<const BidIter,const BidIter> &val){return op(*val.first,*val.second);}); } return result; } } #endif<|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { cout << "hello world/n"; return 0; } <commit_msg>empty swap created<commit_after>#include <iostream> using namespace std; void swap(int &a, int &b){ } int main() { cout << "hello world/n"; return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cassert> #include <iostream> // std::cout #include <algorithm> // std::swap_ranges #include <boost/thread/thread.hpp> #include <boost/lockfree/queue.hpp> #include <boost/atomic.hpp> #include "Chromosome.hpp" #include "Manager.hpp" /* bool testChromosomeCreation() { Chromosome<int > population(100); population.set(0, 100); assert(population[0] == 100); std::cout << "Passed" << std::endl; return true; }*/ double calculate(Chromosome<unsigned int> chromosome); /** * Test create chromosome of type int */ void testChromosomeCreation_uint() { unsigned int chromo_size = 8; unsigned int min_value = 0; unsigned int max_value = 7; std::vector<Chromosome<unsigned int> > children; std::vector<unsigned int> rand_chrom = {2,5,6,1,3,5,4,2}; // Uses the default constructor to make all the ints. Chromosome<unsigned int> chromosome(chromo_size); // Creates {0,0,0,0,0,0,0,0,0,0} Chromosome<unsigned int> chromosome2(rand_chrom); Chromosome<unsigned int>::initialize(chromo_size, min_value, max_value); chromosome.cloning(children); // Check that the child is actually in the children assert(children.size() == 1); std::cout << "Passed child size increased" << std::endl; // Check that the clone is equal to the parent assert(chromosome == children[0]); std::cout << "Passed parent equal to clone" << std::endl; chromosome.cloning(children); children.back().mutate(); // Check that the child is actually in the children assert(children.size() == 2); std::cout << "Passed child size increased" << std::endl; // Check that the mutant is equal to the parent if(chromosome != children[1]) { std::cout << "Passed parent not equal to mutant" << std::endl; } else { // Note this does not necessary mean the mutate function isnt working. // (since it will pick a random number within the range, it my pick the same number and still be accurate). std::cout << "Failed parent equal to mutant" << std::endl; } for (unsigned int i = 0; i < 8; i++) { std::cout << children[1][i]; if(i +1 < 8) { std::cout << ","; } } std::cout << '\n'; chromosome.crossover(chromosome2, children); // Check that the child is actually in the children assert(children.size() == 4); std::cout << "Passed child size increased" << std::endl; // Check that the crossover1 is equal to the parent assert(chromosome != children[2]); std::cout << "Passed parent not equal to crossover1" << std::endl; for (unsigned int i = 0; i < 8; i++) { std::cout << children[2][i]; if(i +1 < 8) { std::cout << ","; } } std::cout << '\n'; for (unsigned int i = 0; i < 8; i++) { std::cout << children[3][i]; if(i +1 < 8) { std::cout << ","; } } std::cout << '\n'; // Check that the crossover2 is equal to the parent assert(chromosome != children[3]); std::cout << "Passed parent not equal to crossover2" << std::endl; unsigned int pop_size = 10; std::vector<Chromosome<int> > population; Chromosome<int>::initialize(chromo_size, min_value, max_value); Chromosome<int>::initPopulation(population, pop_size, chromo_size); // Check that the population is initialized to the correct size. assert(population.size() == pop_size); for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << population[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } std::cout << "All Chromosome<int> Tests Passed" << std::endl; } void testSelection_uint() { unsigned int pop_size = 10; unsigned int chromo_size = 8; unsigned int min_value = 0; unsigned int max_value = 7; unsigned int max_gen = 1000; bool use_self_adaptive = false; double mutation_rate = 0.1; double mutation_change_rate = 0.1; double similarity_index = 0.1; double crossover_rate = 0.4; //double cloning_rate = 0.5; unsigned int num_threads = 1; // Create a test population of 10 std::vector<Chromosome<unsigned int> > pop(pop_size); // Init the chromosome operations Chromosome<unsigned int>::initialize(chromo_size, min_value, max_value); // Create a random chromosome population Chromosome<unsigned int>::initPopulation(pop, pop_size, chromo_size); std::cout << "Init pop = " << std::endl; for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << pop[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } std::vector<Result > fitness(pop_size); // Create a set of fitness values std::vector<double > fitness_values = { 0.1, 0.4, 0.2, 0.6, 0.7, 0.8, 0.5, 0.75, 0.92, 0.8 }; for(unsigned int i = 0; i < fitness.size(); i++) { fitness[i] = Result(i, fitness_values[i]); } RouletteWheel rw; std::vector<std::pair<unsigned int, double > > list; for(unsigned int i = 0; i < fitness.size(); i ++) { list.push_back(std::pair<unsigned int, double >(fitness[i].index, fitness[i].result)); } rw.init(list); unsigned int count = 0; while (count < pop_size) { Chromosome<unsigned int> cur = pop[rw.next()]; std::cout << "Next Chromosome = "; for (unsigned int i = 0; i < chromo_size; i++) { std::cout << cur[i]; if (i+1 < chromo_size) { std::cout << ","; } } std::cout << std::endl; count++; } // TODO test Manager::breed Manager<unsigned int> manager(pop_size, chromo_size, max_gen, max_value, min_value, use_self_adaptive, mutation_rate, mutation_change_rate, similarity_index, crossover_rate, num_threads); manager.initPopulation(); std::cout << "Init the chromosomes" << std::endl; std::vector<Chromosome<unsigned int > > init_pop = manager.getPopulation(); for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << init_pop[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } manager.breed(fitness); std::cout << "Breed the chromosomes" << std::endl; std::vector<Chromosome<unsigned int> > breed_pop = manager.getPopulation(); for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << breed_pop[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } std::vector<unsigned int> regTwo = {0,2,4,6,1,3,5,7}; // Not solution (1 collisions) // solution {7,3,0,2,5,1,6,4}; std::vector<unsigned int> regOne = {10,11,12,13,14,15,16,17}; Chromosome<unsigned int> first(regOne); Chromosome<unsigned int> second(regTwo); std::vector<Chromosome<unsigned int> >child; first.crossover(second, child); std::cout << "CHROMOSOME CROSSOVER" << std::endl; for (unsigned int j = 0; j < chromo_size; j++) { std::cout << first[j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; for (unsigned int j = 0; j < chromo_size; j++) { std::cout << second[j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; std::cout << "RESULT" << std::endl; for (unsigned int i = 0; i < 2; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << child[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } //std::cout << "Fitness for regTwo = " << calculate(regTwo) << std::endl; } void testManager_uint() { unsigned int pop_size = 50; unsigned int chromo_size = 8; unsigned int min_value = 0; unsigned int max_value = 7; unsigned int max_gen = 1000; bool use_self_adaptive = false; double mutation_rate = 0.1; double mutation_change_rate = 0.1; double similarity_index = 0.1; double crossover_rate = 0.4; unsigned int num_threads = 5; Manager<unsigned int > manager(pop_size, chromo_size, max_gen, max_value, min_value, use_self_adaptive, mutation_rate, mutation_change_rate, similarity_index, crossover_rate, num_threads); manager.initPopulation(); std::cout << "Initial Population " << std::endl; std::vector<Chromosome<unsigned int> > initial_pop = manager.getPopulation(); for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << initial_pop[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } //test Manager::run after calling for a single generation manager.run(&calculate); std::cout << "Result Population: " << std::endl; std::vector<Chromosome<unsigned int> > final_pop = manager.getPopulation(); for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << final_pop[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } } double calculate(Chromosome<unsigned int> chromosome) { unsigned int numCollisions = 0; //int numCollisions = 0; for (int i = 0; i < chromosome.size(); ++i) { /* Wrap around the genes in the chromosome to check each one */ for (int j = (i + 1) % chromosome.size(); j != i; ++j, j %= chromosome.size()) { /* Check for vertical collision */ if (chromosome[i] == chromosome[j]) { ++numCollisions; } /* Check for diagnoal collision, they have a collision if their slope is 1 */ int Yi = chromosome[i]; int Yj = chromosome[j]; if (fabs((double) (i - j) / (Yi - Yj)) == 1.0) { ++numCollisions; } } } /* Return the base case of 1, to prevent divide by zero if NO collisions occur */ if (numCollisions == 0) { numCollisions= 1; } // TODO search for results // This might be best done in a double result = 1.0 / numCollisions; return result;//, result == 1); } int main(int argc, char **argv) { // EXAMPLES // boost::atomic_int producer_count(0); //boost::thread t(&testChromosomeCreation_uint); // boost::lockfree::queue<int> queue(128); //Skip program name if any argc -= (argc > 0); argv += (argc > 0); //testChromosomeCreation_uint(); //std::cout << std::endl; //testSelection_uint(); //std::cout << std::endl; testManager_uint(); return 0; } <commit_msg>REMOVED: testing methods from the main that are old and broken<commit_after>#include <cstdio> #include <cassert> #include <iostream> // std::cout #include <algorithm> // std::swap_ranges #include <boost/thread/thread.hpp> #include <boost/lockfree/queue.hpp> #include <boost/atomic.hpp> #include "Chromosome.hpp" #include "Manager.hpp" /* bool testChromosomeCreation() { Chromosome<int > population(100); population.set(0, 100); assert(population[0] == 100); std::cout << "Passed" << std::endl; return true; }*/ double calculate(Chromosome<unsigned int> chromosome); void testManager_uint() { unsigned int pop_size = 50; unsigned int chromo_size = 8; unsigned int min_value = 0; unsigned int max_value = 7; unsigned int max_gen = 1000; bool use_self_adaptive = false; double mutation_rate = 0.1; double mutation_change_rate = 0.1; double similarity_index = 0.1; double crossover_rate = 0.4; unsigned int num_threads = 5; Manager<unsigned int > manager(pop_size, chromo_size, max_gen, max_value, min_value, use_self_adaptive, mutation_rate, mutation_change_rate, similarity_index, crossover_rate, num_threads); manager.initPopulation(); std::cout << "Initial Population " << std::endl; std::vector<Chromosome<unsigned int> > initial_pop = manager.getPopulation(); for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << initial_pop[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } //test Manager::run after calling for a single generation manager.run(&calculate); std::cout << "Result Population: " << std::endl; std::vector<Chromosome<unsigned int> > final_pop = manager.getPopulation(); for (unsigned int i = 0; i < pop_size; i++) { for (unsigned int j = 0; j < chromo_size; j++) { std::cout << final_pop[i][j]; if(j +1 < chromo_size) { std::cout << ","; } } std::cout << '\n'; } } double calculate(Chromosome<unsigned int> chromosome) { unsigned int numCollisions = 0; //int numCollisions = 0; for (int i = 0; i < chromosome.size(); ++i) { /* Wrap around the genes in the chromosome to check each one */ for (int j = (i + 1) % chromosome.size(); j != i; ++j, j %= chromosome.size()) { /* Check for vertical collision */ if (chromosome[i] == chromosome[j]) { ++numCollisions; } /* Check for diagnoal collision, they have a collision if their slope is 1 */ int Yi = chromosome[i]; int Yj = chromosome[j]; if (fabs((double) (i - j) / (Yi - Yj)) == 1.0) { ++numCollisions; } } } /* Return the base case of 1, to prevent divide by zero if NO collisions occur */ if (numCollisions == 0) { numCollisions= 1; } // TODO search for results // This might be best done in a double result = 1.0 / numCollisions; return result;//, result == 1); } int main(int argc, char **argv) { // EXAMPLES // boost::atomic_int producer_count(0); //boost::thread t(&testChromosomeCreation_uint); // boost::lockfree::queue<int> queue(128); //Skip program name if any argc -= (argc > 0); argv += (argc > 0); testManager_uint(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: prov.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: abi $ $Date: 2002-10-29 13:41:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _PROV_HXX_ #define _PROV_HXX_ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIERFACTORY_HPP_ #include <com/sun/star/ucb/XContentIdentifierFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XFILEIDENTIFIERCONVERTER_HPP_ #include <com/sun/star/ucb/XFileIdentifierConverter.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif // FileProvider namespace fileaccess { // Forward declaration class BaseContent; class shell; class FileProvider: public cppu::OWeakObject, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XTypeProvider, public com::sun::star::ucb::XContentProvider, public com::sun::star::ucb::XContentIdentifierFactory, public com::sun::star::beans::XPropertySet, public com::sun::star::ucb::XFileIdentifierConverter { friend class BaseContent; public: FileProvider( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMSF ); ~FileProvider(); // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& aType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName( void ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw(com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( void ) throw( com::sun::star::uno::RuntimeException ); static com::sun::star::uno::Reference< com::sun::star::lang::XSingleServiceFactory > SAL_CALL createServiceFactory( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxServiceMgr ); #if SUPD > 583 static com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL CreateInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMultiServiceFactory ); #else static com::sun::star::uno::Reference< com::sun::star::uno::XInterface > CreateInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMultiServiceFactory ); #endif // XTypeProvider XTYPEPROVIDER_DECL() // XContentProvider virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL queryContent( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( com::sun::star::ucb::IllegalIdentifierException, com::sun::star::uno::RuntimeException ); // XContentIdentifierFactory virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier > SAL_CALL createContentIdentifier( const rtl::OUString& ContentId ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL compareContentIds( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id1, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id2 ) throw( com::sun::star::uno::RuntimeException ); // XProperySet virtual com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setPropertyValue( const rtl::OUString& aPropertyName, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::beans::PropertyVetoException, com::sun::star::lang::IllegalArgumentException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL getPropertyValue( const rtl::OUString& PropertyName ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addPropertyChangeListener( const rtl::OUString& aPropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XPropertyChangeListener >& xListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const rtl::OUString& aPropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XPropertyChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addVetoableChangeListener( const rtl::OUString& PropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XVetoableChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeVetoableChangeListener( const rtl::OUString& PropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XVetoableChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); // XFileIdentifierConverter virtual sal_Int32 SAL_CALL getFileProviderLocality( const rtl::OUString& BaseURL ) throw( com::sun::star::uno::RuntimeException ); virtual rtl::OUString SAL_CALL getFileURLFromSystemPath( const rtl::OUString& BaseURL, const rtl::OUString& SystemPath ) throw( com::sun::star::uno::RuntimeException ); virtual rtl::OUString SAL_CALL getSystemPathFromFileURL( const rtl::OUString& URL ) throw( com::sun::star::uno::RuntimeException ); private: // methods com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > getConfiguration() const; com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > getHierAccess( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& sProvider, const char* file ) const; rtl::OUString getKey( const com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess >& xHierAccess, const char* key ) const; void SAL_CALL initSubstVars( void ); void SAL_CALL subst( rtl::OUString& sValue ); rtl::OUString m_sInstPath; rtl::OUString m_sUserPath; // Members com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xMultiServiceFactory; void SAL_CALL initProperties( void ); vos::OMutex m_aMutex; rtl::OUString m_HostName; rtl::OUString m_HomeDirectory; sal_Int32 m_FileSystemNotation; com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > m_xPropertySetInfo; shell* m_pMyShell; }; } // end namespace fileaccess #endif <commit_msg>INTEGRATION: CWS relocinst (1.11.134); FILE MERGED 2004/04/22 11:31:18 kso 1.11.134.1: #116448# - Does no longer use ooSetupInstallPath and OfficeInstall config items. - removed mountpoints support (not needed any longer). CVS: ----------------------------------------------------------------------<commit_after>/************************************************************************* * * $RCSfile: prov.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2004-05-10 14:22:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _PROV_HXX_ #define _PROV_HXX_ #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIERFACTORY_HPP_ #include <com/sun/star/ucb/XContentIdentifierFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XFILEIDENTIFIERCONVERTER_HPP_ #include <com/sun/star/ucb/XFileIdentifierConverter.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif // FileProvider namespace fileaccess { // Forward declaration class BaseContent; class shell; class FileProvider: public cppu::OWeakObject, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XTypeProvider, public com::sun::star::ucb::XContentProvider, public com::sun::star::ucb::XContentIdentifierFactory, public com::sun::star::beans::XPropertySet, public com::sun::star::ucb::XFileIdentifierConverter { friend class BaseContent; public: FileProvider( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMSF ); ~FileProvider(); // XInterface virtual com::sun::star::uno::Any SAL_CALL queryInterface( const com::sun::star::uno::Type& aType ) throw( com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( void ) throw(); virtual void SAL_CALL release( void ) throw(); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName( void ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw(com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( void ) throw( com::sun::star::uno::RuntimeException ); static com::sun::star::uno::Reference< com::sun::star::lang::XSingleServiceFactory > SAL_CALL createServiceFactory( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxServiceMgr ); static com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL CreateInstance( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xMultiServiceFactory ); // XTypeProvider XTYPEPROVIDER_DECL() // XContentProvider virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL queryContent( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( com::sun::star::ucb::IllegalIdentifierException, com::sun::star::uno::RuntimeException ); // XContentIdentifierFactory virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier > SAL_CALL createContentIdentifier( const rtl::OUString& ContentId ) throw( com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL compareContentIds( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id1, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id2 ) throw( com::sun::star::uno::RuntimeException ); // XProperySet virtual com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setPropertyValue( const rtl::OUString& aPropertyName, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::beans::PropertyVetoException, com::sun::star::lang::IllegalArgumentException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL getPropertyValue( const rtl::OUString& PropertyName ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addPropertyChangeListener( const rtl::OUString& aPropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XPropertyChangeListener >& xListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); virtual void SAL_CALL removePropertyChangeListener( const rtl::OUString& aPropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XPropertyChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addVetoableChangeListener( const rtl::OUString& PropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XVetoableChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeVetoableChangeListener( const rtl::OUString& PropertyName, const com::sun::star::uno::Reference< com::sun::star::beans::XVetoableChangeListener >& aListener ) throw( com::sun::star::beans::UnknownPropertyException, com::sun::star::lang::WrappedTargetException, com::sun::star::uno::RuntimeException); // XFileIdentifierConverter virtual sal_Int32 SAL_CALL getFileProviderLocality( const rtl::OUString& BaseURL ) throw( com::sun::star::uno::RuntimeException ); virtual rtl::OUString SAL_CALL getFileURLFromSystemPath( const rtl::OUString& BaseURL, const rtl::OUString& SystemPath ) throw( com::sun::star::uno::RuntimeException ); virtual rtl::OUString SAL_CALL getSystemPathFromFileURL( const rtl::OUString& URL ) throw( com::sun::star::uno::RuntimeException ); private: // methods // Members com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xMultiServiceFactory; void SAL_CALL initProperties( void ); vos::OMutex m_aMutex; rtl::OUString m_HostName; rtl::OUString m_HomeDirectory; sal_Int32 m_FileSystemNotation; com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > m_xPropertySetInfo; shell* m_pMyShell; }; } // end namespace fileaccess #endif <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <sstream> //#define VEXCL_SHOW_KERNELS #include <vexcl/vexcl.hpp> #include <vexcl/generator.hpp> #include <boost/numeric/odeint.hpp> #include <boost/numeric/odeint/algebra/vector_space_algebra.hpp> #include <boost/numeric/odeint/external/vexcl/vexcl_resize.hpp> namespace odeint = boost::numeric::odeint; typedef double value_type; typedef vex::generator::symbolic<value_type> symbolic_state; typedef vex::vector<value_type> real_state; template <class state_type> void sys_func(const state_type &x, state_type &dxdt, value_type t) { dxdt = 0.042 * x; } int main() { const size_t n = 1024 * 1024; const double dt = 0.01; const double t_max = 100.0; vex::Context ctx( vex::Filter::Env, CL_QUEUE_PROFILING_ENABLE ); std::cout << ctx; // Custom kernel body will be recorded here: std::ostringstream body; vex::generator::set_recorder(body); // This state type is used for kernel recording. symbolic_state sym_x(symbolic_state::Parameter); // Construct arbitrary stepper with symbolic state type... odeint::runge_kutta4< symbolic_state , value_type , symbolic_state , value_type , odeint::vector_space_algebra, odeint::default_operations > sym_stepper; // ... record one step to a kernel body, ... sym_stepper.do_step(sys_func<symbolic_state>, sym_x, 0, dt); // ... and construct custom kernel: auto kernel = vex::generator::build_kernel(ctx.queue(), "test", body.str(), sym_x); // Construct and init real state vector: real_state x(ctx.queue(), n); x = 1.0; vex::profiler prof(ctx.queue()); // Do integration loop: prof.tic_cl("Custom"); for(value_type t = 0; t < t_max; t += dt) kernel(x); prof.toc("Custom"); // Show result: std::cout << "Custom kernel: " << x[0] << std::endl; //------------------------------------------------------------ // Compare result with normal odeint solution. odeint::runge_kutta4< real_state , value_type , real_state , value_type , odeint::vector_space_algebra, odeint::default_operations > stepper; x = 1.0; prof.tic_cl("odeint"); for(value_type t = 0; t < t_max; t += dt) stepper.do_step(sys_func<real_state>, x, t, dt); prof.toc("odeint"); std::cout << "odeint: " << x[0] << std::endl; std::cout << prof; } <commit_msg>Replaced symbolic example with Lorenz attractor ensemble<commit_after>#include <iostream> #include <vector> #include <array> #include <functional> //#define VEXCL_SHOW_KERNELS #include <vexcl/vexcl.hpp> #include <vexcl/exclusive.hpp> #include <vexcl/generator.hpp> // http://headmyshoulder.github.com/odeint-v2 #include <boost/numeric/odeint.hpp> namespace odeint = boost::numeric::odeint; namespace fusion = boost::fusion; typedef double value_type; typedef vex::generator::symbolic< value_type > sym_value; typedef std::array<sym_value, 3> sym_state; // System function for Lorenz attractor ensemble ODE. // [1] http://headmyshoulder.github.com/odeint-v2/doc/boost_numeric_odeint/tutorial/chaotic_systems_and_lyapunov_exponents.html // This is only used to record operations chain for autogenerated kernel. struct sys_func { const value_type sigma; const value_type b; const sym_value &R; sys_func(value_type sigma, value_type b, const sym_value &R) : sigma(sigma), b(b), R(R) {} void operator()( const sym_state &x , sym_state &dxdt , value_type t ) const { dxdt[0] = sigma * (x[1] - x[0]); dxdt[1] = R * x[0] - x[1] - x[0] * x[2]; dxdt[2] = x[0] * x[1] - b * x[2]; } }; int main( int argc , char **argv ) { size_t n; const value_type dt = 0.01; const value_type t_max = 100.0; using namespace std; n = argc > 1 ? atoi( argv[1] ) : 1024; vex::Context ctx( vex::Filter::Exclusive( vex::Filter::DoublePrecision && vex::Filter::Env ) ); cout << ctx << endl; // Custom kernel body will be recorded here: std::ostringstream body; vex::generator::set_recorder(body); // State types that would become kernel parameters: sym_state sym_S = {{ sym_value::Parameter, sym_value::Parameter, sym_value::Parameter }}; // Const kernel parameter. sym_value sym_R(sym_value::Parameter, sym_value::Vector, sym_value::Const); // Symbolic stepper: odeint::runge_kutta4< sym_state , value_type , sym_state , value_type , odeint::range_algebra , odeint::default_operations > sym_stepper; sys_func sys(10.0, 8.0 / 3.0, sym_R); sym_stepper.do_step(std::ref(sys), sym_S, 0, dt); auto kernel = vex::generator::build_kernel(ctx.queue(), "lorenz", body.str(), sym_S[0], sym_S[1], sym_S[2], sym_R ); // Real state initialization: value_type Rmin = 0.1 , Rmax = 50.0 , dR = ( Rmax - Rmin ) / value_type( n - 1 ); std::vector<value_type> r( n ); for( size_t i=0 ; i<n ; ++i ) r[i] = Rmin + dR * value_type( i ); vex::vector<value_type> X(ctx.queue(), n); vex::vector<value_type> Y(ctx.queue(), n); vex::vector<value_type> Z(ctx.queue(), n); vex::vector<value_type> R(ctx.queue(), r); X = 10.0; Y = 10.0; Z = 10.0; // Integration loop: for(value_type t = 0; t < t_max; t += dt) kernel(X, Y, Z, R); std::vector< value_type > result( n ); vex::copy( X , result ); cout << result[0] << endl; } <|endoftext|>
<commit_before>/** * Copyright (C) 2006 Brad Hards <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QtCrypto> #include <QtTest/QtTest> #ifdef QT_STATICPLUGIN #include "import_plugins.h" #endif class TLSUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testCipherList(); private: QCA::Initializer* m_init; }; void TLSUnitTest::initTestCase() { m_init = new QCA::Initializer; } void TLSUnitTest::cleanupTestCase() { delete m_init; } void TLSUnitTest::testCipherList() { if(!QCA::isSupported("tls", "qca-ossl")) QWARN("TLS not supported for qca-ossl"); else { QCA::TLS *tls = new QCA::TLS(QCA::TLS::Stream, 0, "qca-ossl"); QStringList cipherList = tls->supportedCipherSuites(QCA::TLS::TLS_v1); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") ); // Fedora 20 openssl has no this cipher suites. // I just believe that F20 has the most strict patent rules // and Fedora list is the minimal default list. // It should fit for every openssl distribuition. // QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") ); cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v3); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") ); // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") ); // Debian testing (jessie) has no these ciphers. So disable them. // cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v2); // QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); } } QTEST_MAIN(TLSUnitTest) #include "tlsunittest.moc" <commit_msg>Disable missed openssl cipher suites<commit_after>/** * Copyright (C) 2006 Brad Hards <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QtCrypto> #include <QtTest/QtTest> #ifdef QT_STATICPLUGIN #include "import_plugins.h" #endif class TLSUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testCipherList(); private: QCA::Initializer* m_init; }; void TLSUnitTest::initTestCase() { m_init = new QCA::Initializer; } void TLSUnitTest::cleanupTestCase() { delete m_init; } void TLSUnitTest::testCipherList() { if(!QCA::isSupported("tls", "qca-ossl")) QWARN("TLS not supported for qca-ossl"); else { QCA::TLS *tls = new QCA::TLS(QCA::TLS::Stream, 0, "qca-ossl"); QStringList cipherList = tls->supportedCipherSuites(QCA::TLS::TLS_v1); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") ); // Fedora 26 openssl has no this cipher suites. // QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") ); // QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") ); // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") ); // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") ); // Fedora 20 openssl has no this cipher suites. // I just believe that F20 has the most strict patent rules // and Fedora list is the minimal default list. // It should fit for every openssl distribuition. // QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") ); cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v3); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") ); // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") ); // Debian testing (jessie) has no these ciphers. So disable them. // cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v2); // QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") ); // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); } } QTEST_MAIN(TLSUnitTest) #include "tlsunittest.moc" <|endoftext|>
<commit_before>#include "engine/base64.hpp" #include "engine/hint.hpp" #include "mocks/mock_datafacade.hpp" #include <boost/test/unit_test.hpp> #include <boost/test/test_case_template.hpp> #include <iostream> #include <algorithm> // RFC 4648 "The Base16, Base32, and Base64 Data Encodings" BOOST_AUTO_TEST_SUITE(base64) // For test vectors see section 10: https://tools.ietf.org/html/rfc4648#section-10 BOOST_AUTO_TEST_CASE(rfc4648_test_vectors) { using namespace osrm::engine; BOOST_CHECK_EQUAL(encodeBase64(""), ""); BOOST_CHECK_EQUAL(encodeBase64("f"), "Zg=="); BOOST_CHECK_EQUAL(encodeBase64("fo"), "Zm8="); BOOST_CHECK_EQUAL(encodeBase64("foo"), "Zm9v"); BOOST_CHECK_EQUAL(encodeBase64("foob"), "Zm9vYg=="); BOOST_CHECK_EQUAL(encodeBase64("fooba"), "Zm9vYmE="); BOOST_CHECK_EQUAL(encodeBase64("foobar"), "Zm9vYmFy"); } BOOST_AUTO_TEST_CASE(rfc4648_test_vectors_roundtrip) { using namespace osrm::engine; BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("")), ""); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("f")), "f"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("fo")), "fo"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("foo")), "foo"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("foob")), "foob"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("fooba")), "fooba"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("foobar")), "foobar"); } BOOST_AUTO_TEST_CASE(hint_encoding_decoding_roundtrip) { using namespace osrm::engine; using namespace osrm::util; const Coordinate coordinate; const PhantomNode phantom; const osrm::test::MockDataFacade facade{}; const Hint hint{coordinate, phantom, facade.GetCheckSum()}; const auto base64 = hint.ToBase64(); BOOST_CHECK(0 == std::count(begin(base64), end(base64), '+')); BOOST_CHECK(0 == std::count(begin(base64), end(base64), '/')); const auto decoded = Hint::FromBase64(base64); BOOST_CHECK_EQUAL(hint, decoded); } BOOST_AUTO_TEST_CASE(hint_encoding_decoding_roundtrip_bytewise) { using namespace osrm::engine; using namespace osrm::util; const Coordinate coordinate; const PhantomNode phantom; const osrm::test::MockDataFacade facade{}; const Hint hint{coordinate, phantom, facade.GetCheckSum()}; const auto decoded = Hint::FromBase64(hint.ToBase64()); BOOST_CHECK(std::equal(reinterpret_cast<const unsigned char *>(&hint), reinterpret_cast<const unsigned char *>(&hint) + sizeof(Hint), reinterpret_cast<const unsigned char *>(&decoded))); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Fix base64 test wrt. Hint no longer taking coordinate in ctor<commit_after>#include "engine/base64.hpp" #include "engine/hint.hpp" #include "mocks/mock_datafacade.hpp" #include <boost/test/unit_test.hpp> #include <boost/test/test_case_template.hpp> #include <iostream> #include <algorithm> // RFC 4648 "The Base16, Base32, and Base64 Data Encodings" BOOST_AUTO_TEST_SUITE(base64) // For test vectors see section 10: https://tools.ietf.org/html/rfc4648#section-10 BOOST_AUTO_TEST_CASE(rfc4648_test_vectors) { using namespace osrm::engine; BOOST_CHECK_EQUAL(encodeBase64(""), ""); BOOST_CHECK_EQUAL(encodeBase64("f"), "Zg=="); BOOST_CHECK_EQUAL(encodeBase64("fo"), "Zm8="); BOOST_CHECK_EQUAL(encodeBase64("foo"), "Zm9v"); BOOST_CHECK_EQUAL(encodeBase64("foob"), "Zm9vYg=="); BOOST_CHECK_EQUAL(encodeBase64("fooba"), "Zm9vYmE="); BOOST_CHECK_EQUAL(encodeBase64("foobar"), "Zm9vYmFy"); } BOOST_AUTO_TEST_CASE(rfc4648_test_vectors_roundtrip) { using namespace osrm::engine; BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("")), ""); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("f")), "f"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("fo")), "fo"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("foo")), "foo"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("foob")), "foob"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("fooba")), "fooba"); BOOST_CHECK_EQUAL(decodeBase64(encodeBase64("foobar")), "foobar"); } BOOST_AUTO_TEST_CASE(hint_encoding_decoding_roundtrip) { using namespace osrm::engine; using namespace osrm::util; const Coordinate coordinate; const PhantomNode phantom; const osrm::test::MockDataFacade facade{}; const Hint hint{phantom, facade.GetCheckSum()}; const auto base64 = hint.ToBase64(); BOOST_CHECK(0 == std::count(begin(base64), end(base64), '+')); BOOST_CHECK(0 == std::count(begin(base64), end(base64), '/')); const auto decoded = Hint::FromBase64(base64); BOOST_CHECK_EQUAL(hint, decoded); } BOOST_AUTO_TEST_CASE(hint_encoding_decoding_roundtrip_bytewise) { using namespace osrm::engine; using namespace osrm::util; const Coordinate coordinate; const PhantomNode phantom; const osrm::test::MockDataFacade facade{}; const Hint hint{phantom, facade.GetCheckSum()}; const auto decoded = Hint::FromBase64(hint.ToBase64()); BOOST_CHECK(std::equal(reinterpret_cast<const unsigned char *>(&hint), reinterpret_cast<const unsigned char *>(&hint) + sizeof(Hint), reinterpret_cast<const unsigned char *>(&decoded))); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <Windows.h> #include <WinInet.h> // Disable exception handler warnings. #pragma warning( disable : 4530 ) #include <fstream> #include "common/windows/string_utils-inl.h" #include "common/windows/http_upload.h" namespace google_airbag { using std::ifstream; using std::ios; static const wchar_t kUserAgent[] = L"Airbag/1.0 (Windows)"; // Helper class which closes an internet handle when it goes away class HTTPUpload::AutoInternetHandle { public: explicit AutoInternetHandle(HINTERNET handle) : handle_(handle) {} ~AutoInternetHandle() { if (handle_) { InternetCloseHandle(handle_); } } HINTERNET get() { return handle_; } private: HINTERNET handle_; }; // static bool HTTPUpload::SendRequest(const wstring &url, const map<wstring, wstring> &parameters, const wstring &upload_file, const wstring &file_part_name) { // TODO(bryner): support non-ASCII parameter names if (!CheckParameters(parameters)) { return false; } // Break up the URL and make sure we can handle it wchar_t scheme[16], host[256], path[256]; URL_COMPONENTS components; memset(&components, 0, sizeof(components)); components.dwStructSize = sizeof(components); components.lpszScheme = scheme; components.dwSchemeLength = sizeof(scheme); components.lpszHostName = host; components.dwHostNameLength = sizeof(host); components.lpszUrlPath = path; components.dwUrlPathLength = sizeof(path); if (!InternetCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &components)) { return false; } bool secure = false; if (wcscmp(scheme, L"https") == 0) { secure = true; } else if (wcscmp(scheme, L"http") != 0) { return false; } AutoInternetHandle internet(InternetOpen(kUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, // proxy name NULL, // proxy bypass 0)); // flags if (!internet.get()) { return false; } AutoInternetHandle connection(InternetConnect(internet.get(), host, components.nPort, NULL, // user name NULL, // password INTERNET_SERVICE_HTTP, 0, // flags NULL)); // context if (!connection.get()) { return false; } DWORD http_open_flags = secure ? INTERNET_FLAG_SECURE : 0; AutoInternetHandle request(HttpOpenRequest(connection.get(), L"POST", path, NULL, // version NULL, // referer NULL, // agent type http_open_flags, NULL)); // context if (!request.get()) { return false; } wstring boundary = GenerateMultipartBoundary(); wstring content_type_header = GenerateRequestHeader(boundary); HttpAddRequestHeaders(request.get(), content_type_header.c_str(), -1, HTTP_ADDREQ_FLAG_ADD); string request_body; GenerateRequestBody(parameters, upload_file, file_part_name, boundary, &request_body); if (!HttpSendRequest(request.get(), NULL, 0, const_cast<char *>(request_body.data()), static_cast<DWORD>(request_body.size()))) { return false; } // The server indicates a successful upload with HTTP status 200. wchar_t http_status[4]; DWORD http_status_size = sizeof(http_status); if (!HttpQueryInfo(request.get(), HTTP_QUERY_STATUS_CODE, static_cast<LPVOID>(&http_status), &http_status_size, 0)) { return false; } return (wcscmp(http_status, L"200") == 0); } // static wstring HTTPUpload::GenerateMultipartBoundary() { // The boundary has 27 '-' characters followed by 16 hex digits static const wchar_t kBoundaryPrefix[] = L"---------------------------"; static const int kBoundaryLength = 27 + 16 + 1; // Generate some random numbers to fill out the boundary int r0 = rand(); int r1 = rand(); wchar_t temp[kBoundaryLength]; WindowsStringUtils::safe_swprintf(temp, kBoundaryLength, L"%s%08X%08X", kBoundaryPrefix, r0, r1); return wstring(temp); } // static wstring HTTPUpload::GenerateRequestHeader(const wstring &boundary) { wstring header = L"Content-Type: multipart/form-data; boundary="; header += boundary; return header; } // static bool HTTPUpload::GenerateRequestBody(const map<wstring, wstring> &parameters, const wstring &upload_file, const wstring &file_part_name, const wstring &boundary, string *request_body) { vector<char> contents; GetFileContents(upload_file, &contents); if (contents.empty()) { return false; } string boundary_str = WideToUTF8(boundary); if (boundary_str.empty()) { return false; } request_body->clear(); // Append each of the parameter pairs as a form-data part for (map<wstring, wstring>::const_iterator pos = parameters.begin(); pos != parameters.end(); ++pos) { request_body->append("--" + boundary_str + "\r\n"); request_body->append("Content-Disposition: form-data; name=\"" + WideToUTF8(pos->first) + "\"\r\n\r\n" + WideToUTF8(pos->second) + "\r\n"); } // Now append the upload file as a binary (octet-stream) part string filename_utf8 = WideToUTF8(upload_file); if (filename_utf8.empty()) { return false; } string file_part_name_utf8 = WideToUTF8(file_part_name); if (file_part_name_utf8.empty()) { return false; } request_body->append("--" + boundary_str + "\r\n"); request_body->append("Content-Disposition: form-data; " "name=\"" + file_part_name_utf8 + "\"; " "filename=\"" + filename_utf8 + "\"\r\n"); request_body->append("Content-Type: application/octet-stream\r\n"); request_body->append("\r\n"); request_body->append(&(contents[0]), contents.size()); request_body->append("\r\n"); request_body->append("--" + boundary_str + "--\r\n"); return true; } // static void HTTPUpload::GetFileContents(const wstring &filename, vector<char> *contents) { // The "open" method on pre-MSVC8 ifstream implementations doesn't accept a // wchar_t* filename, so use _wfopen directly in that case. For VC8 and // later, _wfopen has been deprecated in favor of _wfopen_s, which does // not exist in earlier versions, so let the ifstream open the file itself. #if _MSC_VER >= 1400 // MSVC 2005/8 ifstream file; file.open(filename.c_str(), ios::binary); #else // _MSC_VER >= 1400 ifstream file(_wfopen(filename.c_str(), L"rb")); #endif // _MSC_VER >= 1400 if (file.is_open()) { file.seekg(0, ios::end); int length = file.tellg(); contents->resize(length); file.seekg(0, ios::beg); file.read(&((*contents)[0]), length); file.close(); } else { contents->clear(); } } // static string HTTPUpload::WideToUTF8(const wstring &wide) { if (wide.length() == 0) { return string(); } // compute the length of the buffer we'll need int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, NULL, 0, NULL, NULL); if (charcount == 0) { return string(); } // convert char *buf = new char[charcount]; WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, buf, charcount, NULL, NULL); string result(buf); delete[] buf; return result; } // static bool HTTPUpload::CheckParameters(const map<wstring, wstring> &parameters) { for (map<wstring, wstring>::const_iterator pos = parameters.begin(); pos != parameters.end(); ++pos) { const wstring &str = pos->first; if (str.size() == 0) { return false; // disallow empty parameter names } for (unsigned int i = 0; i < str.size(); ++i) { wchar_t c = str[i]; if (c < 32 || c == '"' || c > 127) { return false; } } } return true; } } // namespace google_airbag <commit_msg>Fix a crash when attempting to upload a zero-length dump file (#83) r=mmentovai<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <assert.h> #include <Windows.h> #include <WinInet.h> // Disable exception handler warnings. #pragma warning( disable : 4530 ) #include <fstream> #include "common/windows/string_utils-inl.h" #include "common/windows/http_upload.h" namespace google_airbag { using std::ifstream; using std::ios; static const wchar_t kUserAgent[] = L"Airbag/1.0 (Windows)"; // Helper class which closes an internet handle when it goes away class HTTPUpload::AutoInternetHandle { public: explicit AutoInternetHandle(HINTERNET handle) : handle_(handle) {} ~AutoInternetHandle() { if (handle_) { InternetCloseHandle(handle_); } } HINTERNET get() { return handle_; } private: HINTERNET handle_; }; // static bool HTTPUpload::SendRequest(const wstring &url, const map<wstring, wstring> &parameters, const wstring &upload_file, const wstring &file_part_name) { // TODO(bryner): support non-ASCII parameter names if (!CheckParameters(parameters)) { return false; } // Break up the URL and make sure we can handle it wchar_t scheme[16], host[256], path[256]; URL_COMPONENTS components; memset(&components, 0, sizeof(components)); components.dwStructSize = sizeof(components); components.lpszScheme = scheme; components.dwSchemeLength = sizeof(scheme); components.lpszHostName = host; components.dwHostNameLength = sizeof(host); components.lpszUrlPath = path; components.dwUrlPathLength = sizeof(path); if (!InternetCrackUrl(url.c_str(), static_cast<DWORD>(url.size()), 0, &components)) { return false; } bool secure = false; if (wcscmp(scheme, L"https") == 0) { secure = true; } else if (wcscmp(scheme, L"http") != 0) { return false; } AutoInternetHandle internet(InternetOpen(kUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, // proxy name NULL, // proxy bypass 0)); // flags if (!internet.get()) { return false; } AutoInternetHandle connection(InternetConnect(internet.get(), host, components.nPort, NULL, // user name NULL, // password INTERNET_SERVICE_HTTP, 0, // flags NULL)); // context if (!connection.get()) { return false; } DWORD http_open_flags = secure ? INTERNET_FLAG_SECURE : 0; AutoInternetHandle request(HttpOpenRequest(connection.get(), L"POST", path, NULL, // version NULL, // referer NULL, // agent type http_open_flags, NULL)); // context if (!request.get()) { return false; } wstring boundary = GenerateMultipartBoundary(); wstring content_type_header = GenerateRequestHeader(boundary); HttpAddRequestHeaders(request.get(), content_type_header.c_str(), -1, HTTP_ADDREQ_FLAG_ADD); string request_body; GenerateRequestBody(parameters, upload_file, file_part_name, boundary, &request_body); if (!HttpSendRequest(request.get(), NULL, 0, const_cast<char *>(request_body.data()), static_cast<DWORD>(request_body.size()))) { return false; } // The server indicates a successful upload with HTTP status 200. wchar_t http_status[4]; DWORD http_status_size = sizeof(http_status); if (!HttpQueryInfo(request.get(), HTTP_QUERY_STATUS_CODE, static_cast<LPVOID>(&http_status), &http_status_size, 0)) { return false; } return (wcscmp(http_status, L"200") == 0); } // static wstring HTTPUpload::GenerateMultipartBoundary() { // The boundary has 27 '-' characters followed by 16 hex digits static const wchar_t kBoundaryPrefix[] = L"---------------------------"; static const int kBoundaryLength = 27 + 16 + 1; // Generate some random numbers to fill out the boundary int r0 = rand(); int r1 = rand(); wchar_t temp[kBoundaryLength]; WindowsStringUtils::safe_swprintf(temp, kBoundaryLength, L"%s%08X%08X", kBoundaryPrefix, r0, r1); return wstring(temp); } // static wstring HTTPUpload::GenerateRequestHeader(const wstring &boundary) { wstring header = L"Content-Type: multipart/form-data; boundary="; header += boundary; return header; } // static bool HTTPUpload::GenerateRequestBody(const map<wstring, wstring> &parameters, const wstring &upload_file, const wstring &file_part_name, const wstring &boundary, string *request_body) { vector<char> contents; GetFileContents(upload_file, &contents); if (contents.empty()) { return false; } string boundary_str = WideToUTF8(boundary); if (boundary_str.empty()) { return false; } request_body->clear(); // Append each of the parameter pairs as a form-data part for (map<wstring, wstring>::const_iterator pos = parameters.begin(); pos != parameters.end(); ++pos) { request_body->append("--" + boundary_str + "\r\n"); request_body->append("Content-Disposition: form-data; name=\"" + WideToUTF8(pos->first) + "\"\r\n\r\n" + WideToUTF8(pos->second) + "\r\n"); } // Now append the upload file as a binary (octet-stream) part string filename_utf8 = WideToUTF8(upload_file); if (filename_utf8.empty()) { return false; } string file_part_name_utf8 = WideToUTF8(file_part_name); if (file_part_name_utf8.empty()) { return false; } request_body->append("--" + boundary_str + "\r\n"); request_body->append("Content-Disposition: form-data; " "name=\"" + file_part_name_utf8 + "\"; " "filename=\"" + filename_utf8 + "\"\r\n"); request_body->append("Content-Type: application/octet-stream\r\n"); request_body->append("\r\n"); if (!contents.empty()) { request_body->append(&(contents[0]), contents.size()); } request_body->append("\r\n"); request_body->append("--" + boundary_str + "--\r\n"); return true; } // static void HTTPUpload::GetFileContents(const wstring &filename, vector<char> *contents) { // The "open" method on pre-MSVC8 ifstream implementations doesn't accept a // wchar_t* filename, so use _wfopen directly in that case. For VC8 and // later, _wfopen has been deprecated in favor of _wfopen_s, which does // not exist in earlier versions, so let the ifstream open the file itself. #if _MSC_VER >= 1400 // MSVC 2005/8 ifstream file; file.open(filename.c_str(), ios::binary); #else // _MSC_VER >= 1400 ifstream file(_wfopen(filename.c_str(), L"rb")); #endif // _MSC_VER >= 1400 if (file.is_open()) { file.seekg(0, ios::end); int length = file.tellg(); contents->resize(length); if (length != 0) { file.seekg(0, ios::beg); file.read(&((*contents)[0]), length); } file.close(); } else { contents->clear(); } } // static string HTTPUpload::WideToUTF8(const wstring &wide) { if (wide.length() == 0) { return string(); } // compute the length of the buffer we'll need int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, NULL, 0, NULL, NULL); if (charcount == 0) { return string(); } // convert char *buf = new char[charcount]; WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1, buf, charcount, NULL, NULL); string result(buf); delete[] buf; return result; } // static bool HTTPUpload::CheckParameters(const map<wstring, wstring> &parameters) { for (map<wstring, wstring>::const_iterator pos = parameters.begin(); pos != parameters.end(); ++pos) { const wstring &str = pos->first; if (str.size() == 0) { return false; // disallow empty parameter names } for (unsigned int i = 0; i < str.size(); ++i) { wchar_t c = str[i]; if (c < 32 || c == '"' || c > 127) { return false; } } } return true; } } // namespace google_airbag <|endoftext|>
<commit_before>/** * Copyright (C) 2006 Brad Hards <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QtCrypto> #include <QtTest/QtTest> class TLSUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testCipherList(); private: QCA::Initializer* m_init; }; void TLSUnitTest::initTestCase() { m_init = new QCA::Initializer; #include "../fixpaths.include" } void TLSUnitTest::cleanupTestCase() { delete m_init; } void TLSUnitTest::testCipherList() { if(!QCA::isSupported("tls", "qca-openssl")) QWARN("TLS not supported for qca-openssl"); else { QStringList cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::TLS_v1, "qca-openssl"); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") ); QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") ); cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::SSL_v3, "qca-openssl"); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") ); QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") ); cipherList = QCA::TLS::supportedCipherSuites(QCA::TLS::SSL_v2, "qca-openssl"); QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_64_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); } } QTEST_MAIN(TLSUnitTest) #include "tlsunittest.moc" <commit_msg>update based on api changes<commit_after>/** * Copyright (C) 2006 Brad Hards <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QtCrypto> #include <QtTest/QtTest> class TLSUnitTest : public QObject { Q_OBJECT private slots: void initTestCase(); void cleanupTestCase(); void testCipherList(); private: QCA::Initializer* m_init; }; void TLSUnitTest::initTestCase() { m_init = new QCA::Initializer; #include "../fixpaths.include" } void TLSUnitTest::cleanupTestCase() { delete m_init; } void TLSUnitTest::testCipherList() { if(!QCA::isSupported("tls", "qca-openssl")) QWARN("TLS not supported for qca-openssl"); else { QCA::TLS *tls = new QCA::TLS(QCA::TLS::Stream, 0, "qca-openssl"); QStringList cipherList = tls->supportedCipherSuites(QCA::TLS::TLS_v1); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") ); QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") ); QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") ); cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v3); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") ); QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_SHA") ); QVERIFY( cipherList.contains("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_MD5") ); QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") ); QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") ); QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") ); cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v2); QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_64_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") ); QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") ); } } QTEST_MAIN(TLSUnitTest) #include "tlsunittest.moc" <|endoftext|>
<commit_before>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include "BaseDemo.hpp" #include "vl/EdgeExtractor.hpp" #include "vl/EdgeRenderer.hpp" #include "vl/LoadWriterManager.hpp" class App_EdgeRendering: public BaseDemo { public: void setupScene() { // setup common states vl::ref<vl::Light> camera_light = new vl::Light(0); vl::ref<vl::EnableSet> enables = new vl::EnableSet; enables->enable(vl::EN_DEPTH_TEST); enables->enable(vl::EN_LIGHTING); // red material fx vl::ref<vl::Effect> red_fx = new vl::Effect; red_fx->shader()->setEnableSet(enables.get()); red_fx->shader()->gocMaterial()->setDiffuse(vlut::red); red_fx->shader()->setRenderState(camera_light.get()); // green material fx vl::ref<vl::Effect> green_fx = new vl::Effect; green_fx->shader()->setEnableSet(enables.get()); green_fx->shader()->gocMaterial()->setDiffuse(vlut::green); green_fx->shader()->setRenderState(camera_light.get()); // blue material fx vl::ref<vl::Effect> yellow_fx = new vl::Effect; yellow_fx->shader()->setEnableSet(enables.get()); yellow_fx->shader()->gocMaterial()->setDiffuse(vlut::yellow); yellow_fx->shader()->setRenderState(camera_light.get()); // add box, cylinder, cone actors to the scene vl::ref<vl::Geometry> geom1 = vlut::makeBox (vl::vec3(-7,0,0),5,5,5); vl::ref<vl::Geometry> geom2 = vlut::makeCylinder(vl::vec3(0,0,0), 5,5, 10,2, true, true); vl::ref<vl::Geometry> geom3 = vlut::makeCone (vl::vec3(+7,0,0),5,5, 20, true); // needed since we enabled the lighting geom1->computeNormals(); geom2->computeNormals(); geom3->computeNormals(); // add the actors to the scene sceneManager()->tree()->addActor( geom1.get(), red_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom2.get(), green_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom3.get(), yellow_fx.get(), mRendering->transform() ); } void initEvent() { BaseDemo::initEvent(); // retrieve the default rendering mRendering = (vl::VisualizationLibrary::rendering()->as<vl::Rendering>()); // retrieve the default renderer, which we'll use as the solid-renderer mSolidRenderer = mRendering->renderer(); // create our EdgeRenderer mEdgeRenderer = new vl::EdgeRenderer; // we set the clear flags to be vl::CF_CLEAR_DEPTH (by default is set to CF_CLEAR_COLOR_DEPTH) because // when the wireframe rendering starts we want to preserve the color-buffer as generated by the solid // rendering but we want to clear the Z-buffer as it is needed by the hidden-line-removal algorithm // implemented by vl::EdgeRenderer. mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); // target the same opengl window mEdgeRenderer->setRenderTarget(mSolidRenderer->renderTarget()); // enqueue the EdgeRenderer in the rendering, will be executed after mSolidRenderer mRendering->renderers().push_back( mEdgeRenderer.get() ); // hidden line and crease options mEdgeRenderer->setShowHiddenLines(true); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setCreaseAngle(35.0f); // style options mEdgeRenderer->setLineWidth(2.0f); mEdgeRenderer->setSmoothLines(true); mEdgeRenderer->setDefaultLineColor(vlut::black); // fills mSceneManager with a few actors. // the beauty of this system is that you setup your actors ony once in a single scene managers and // they will be rendered twice, first using a normal renderer and then using the wireframe renderer. setupScene(); } // user controls: // '1' = edge rendering off. // '2' = edge rendering on: silhouette only. // '3' = edge rendering on: silhouette + creases. // '4' = edge rendering on: silhouette + creases + hidden lines. // '5' = hidden line removal wireframe: silhouette + creases. // '6' = hidden line removal wireframe: silhouette + creases + hidden lines. void keyPressEvent(unsigned short ch, vl::EKey key) { BaseDemo::keyPressEvent(ch, key); if (ch == '1') { mSolidRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setEnableMask(0); vl::Log::print("Edge rendering disabled.\n"); } else if (ch == '2') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(false); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = off, hidden lines = off.\n"); } else if (ch == '3') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = off.\n"); } else if (ch == '4') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = on.\n"); } else if (ch == '5') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = off.\n"); } if (ch == '6') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = on.\n"); } } void resizeEvent(int w, int h) { vl::Camera* camera = mRendering->camera(); camera->viewport()->setWidth ( w ); camera->viewport()->setHeight( h ); camera->setProjectionAsPerspective(); } void loadModel(const std::vector<vl::String>& files) { // resets the scene mSceneManager->tree()->actors()->clear(); // resets the EdgeRenderer cache mEdgeRenderer->clearCache(); for(unsigned int i=0; i<files.size(); ++i) { vl::ref<vl::ResourceDatabase> resource_db = vl::loadResource(files[i],true); if (!resource_db || resource_db->count<vl::Actor>() == 0) { vl::Log::error("No data found.\n"); continue; } std::vector< vl::ref<vl::Actor> > actors; resource_db->get<vl::Actor>(actors); for(unsigned i=0; i<actors.size(); ++i) { vl::ref<vl::Actor> actor = actors[i].get(); // define a reasonable Shader actor->effect()->shader()->setRenderState( new vl::Light(0) ); actor->effect()->shader()->enable(vl::EN_DEPTH_TEST); actor->effect()->shader()->enable(vl::EN_LIGHTING); actor->effect()->shader()->gocLightModel()->setTwoSide(true); // add the actor to the scene mSceneManager->tree()->addActor( actor.get() ); } } // position the camera to nicely see the objects in the scene trackball()->adjustView( mSceneManager.get(), vl::vec3(0,0,1)/*direction*/, vl::vec3(0,1,0)/*up*/, 1.0f/*bias*/ ); } // laod the files dropped in the window void fileDroppedEvent(const std::vector<vl::String>& files) { loadModel(files); } protected: vl::ref< vl::Renderer > mSolidRenderer; vl::ref< vl::EdgeRenderer > mEdgeRenderer; vl::ref<vl::Rendering> mRendering; vl::ref<vl::SceneManagerActorTree> mSceneManager; }; // Have fun! <commit_msg>code cosmetics.<commit_after>/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.com */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #include "BaseDemo.hpp" #include "vl/EdgeExtractor.hpp" #include "vl/EdgeRenderer.hpp" #include "vl/LoadWriterManager.hpp" class App_EdgeRendering: public BaseDemo { public: void initEvent() { BaseDemo::initEvent(); // retrieve the default rendering mRendering = (vl::VisualizationLibrary::rendering()->as<vl::Rendering>()); // retrieve the default renderer, which we'll use as the solid-renderer mSolidRenderer = mRendering->renderer(); // create our EdgeRenderer mEdgeRenderer = new vl::EdgeRenderer; // we set the clear flags to be vl::CF_CLEAR_DEPTH (by default is set to CF_CLEAR_COLOR_DEPTH) because // when the wireframe rendering starts we want to preserve the color-buffer as generated by the solid // rendering but we want to clear the Z-buffer as it is needed by the hidden-line-removal algorithm // implemented by vl::EdgeRenderer. mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); // target the same opengl window mEdgeRenderer->setRenderTarget(mSolidRenderer->renderTarget()); // enqueue the EdgeRenderer in the rendering, will be executed after mSolidRenderer mRendering->renderers().push_back( mEdgeRenderer.get() ); // hidden line and crease options mEdgeRenderer->setShowHiddenLines(true); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setCreaseAngle(35.0f); // style options mEdgeRenderer->setLineWidth(2.0f); mEdgeRenderer->setSmoothLines(true); mEdgeRenderer->setDefaultLineColor(vlut::black); // fills mSceneManager with a few actors. // the beauty of this system is that you setup your actors ony once in a single scene managers and // they will be rendered twice, first using a normal renderer and then using the wireframe renderer. setupScene(); } // populates the scene void setupScene() { // setup common states vl::ref<vl::Light> camera_light = new vl::Light(0); vl::ref<vl::EnableSet> enables = new vl::EnableSet; enables->enable(vl::EN_DEPTH_TEST); enables->enable(vl::EN_LIGHTING); // red material fx vl::ref<vl::Effect> red_fx = new vl::Effect; red_fx->shader()->setEnableSet(enables.get()); red_fx->shader()->gocMaterial()->setDiffuse(vlut::red); red_fx->shader()->setRenderState(camera_light.get()); // green material fx vl::ref<vl::Effect> green_fx = new vl::Effect; green_fx->shader()->setEnableSet(enables.get()); green_fx->shader()->gocMaterial()->setDiffuse(vlut::green); green_fx->shader()->setRenderState(camera_light.get()); // blue material fx vl::ref<vl::Effect> yellow_fx = new vl::Effect; yellow_fx->shader()->setEnableSet(enables.get()); yellow_fx->shader()->gocMaterial()->setDiffuse(vlut::yellow); yellow_fx->shader()->setRenderState(camera_light.get()); // add box, cylinder, cone actors to the scene vl::ref<vl::Geometry> geom1 = vlut::makeBox (vl::vec3(-7,0,0),5,5,5); vl::ref<vl::Geometry> geom2 = vlut::makeCylinder(vl::vec3(0,0,0), 5,5, 10,2, true, true); vl::ref<vl::Geometry> geom3 = vlut::makeCone (vl::vec3(+7,0,0),5,5, 20, true); // needed since we enabled the lighting geom1->computeNormals(); geom2->computeNormals(); geom3->computeNormals(); // add the actors to the scene sceneManager()->tree()->addActor( geom1.get(), red_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom2.get(), green_fx.get(), mRendering->transform() ); sceneManager()->tree()->addActor( geom3.get(), yellow_fx.get(), mRendering->transform() ); } // user controls: // '1' = edge rendering off. // '2' = edge rendering on: silhouette only. // '3' = edge rendering on: silhouette + creases. // '4' = edge rendering on: silhouette + creases + hidden lines. // '5' = hidden line removal wireframe: silhouette + creases. // '6' = hidden line removal wireframe: silhouette + creases + hidden lines. void keyPressEvent(unsigned short ch, vl::EKey key) { BaseDemo::keyPressEvent(ch, key); if (ch == '1') { mSolidRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setEnableMask(0); vl::Log::print("Edge rendering disabled.\n"); } else if (ch == '2') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(false); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = off, hidden lines = off.\n"); } else if (ch == '3') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = off.\n"); } else if (ch == '4') { mSolidRenderer->setEnableMask(0xFFFFFFFF); // preserve color buffer, clear depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Edge rendering enabled. Creases = on, hidden lines = on.\n"); } else if (ch == '5') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(false); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = off.\n"); } if (ch == '6') { mSolidRenderer->setEnableMask(0); // clear color and depth buffer mEdgeRenderer->setClearFlags(vl::CF_CLEAR_COLOR_DEPTH); mEdgeRenderer->setEnableMask(0xFFFFFFFF); mEdgeRenderer->setShowCreases(true); mEdgeRenderer->setShowHiddenLines(true); vl::Log::print("Hidden line removal wireframe enabled. Creases = on, hidden lines = on.\n"); } } void resizeEvent(int w, int h) { vl::Camera* camera = mRendering->camera(); camera->viewport()->setWidth ( w ); camera->viewport()->setHeight( h ); camera->setProjectionAsPerspective(); } void loadModel(const std::vector<vl::String>& files) { // resets the scene mSceneManager->tree()->actors()->clear(); // resets the EdgeRenderer cache mEdgeRenderer->clearCache(); for(unsigned int i=0; i<files.size(); ++i) { vl::ref<vl::ResourceDatabase> resource_db = vl::loadResource(files[i],true); if (!resource_db || resource_db->count<vl::Actor>() == 0) { vl::Log::error("No data found.\n"); continue; } std::vector< vl::ref<vl::Actor> > actors; resource_db->get<vl::Actor>(actors); for(unsigned i=0; i<actors.size(); ++i) { vl::ref<vl::Actor> actor = actors[i].get(); // define a reasonable Shader actor->effect()->shader()->setRenderState( new vl::Light(0) ); actor->effect()->shader()->enable(vl::EN_DEPTH_TEST); actor->effect()->shader()->enable(vl::EN_LIGHTING); actor->effect()->shader()->gocLightModel()->setTwoSide(true); // add the actor to the scene mSceneManager->tree()->addActor( actor.get() ); } } // position the camera to nicely see the objects in the scene trackball()->adjustView( mSceneManager.get(), vl::vec3(0,0,1)/*direction*/, vl::vec3(0,1,0)/*up*/, 1.0f/*bias*/ ); } // laod the files dropped in the window void fileDroppedEvent(const std::vector<vl::String>& files) { loadModel(files); } protected: vl::ref< vl::Renderer > mSolidRenderer; vl::ref< vl::EdgeRenderer > mEdgeRenderer; vl::ref<vl::Rendering> mRendering; vl::ref<vl::SceneManagerActorTree> mSceneManager; }; // Have fun! <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "libjoynrclustercontroller/mqtt/MosquittoConnection.h" #include "joynr/ClusterControllerSettings.h" #include "joynr/MessagingSettings.h" #include "joynr/exceptions/JoynrException.h" namespace joynr { INIT_LOGGER(MosquittoConnection); MosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings, const ClusterControllerSettings& ccSettings, const std::string& clientId) : mosquittopp(clientId.c_str(), false), messagingSettings(messagingSettings), host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()), port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()), channelId(), subscribeChannelMid(), topic(), additionalTopics(), additionalTopicsMutex(), isConnected(false), isRunning(false), isChannelIdRegistered(false), subscribedToChannelTopic(false), readyToSend(false), onMessageReceived(), onReadyToSendChangedMutex(), onReadyToSendChanged() { mosqpp::lib_init(); if (ccSettings.isMqttTlsEnabled()) { int rc = tls_set(ccSettings.getMqttCertificateAuthorityPemFilename().c_str(), NULL, ccSettings.getMqttCertificatePemFilename().c_str(), ccSettings.getMqttPrivateKeyPemFilename().c_str()); if (rc != MOSQ_ERR_SUCCESS) { JOYNR_LOG_ERROR( logger, "Could not initialize TLS connection - {}", mosqpp::strerror(rc)); } } else { JOYNR_LOG_DEBUG(logger, "MQTT connection not encrypted"); } } MosquittoConnection::~MosquittoConnection() { stop(); stopLoop(true); mosqpp::lib_cleanup(); } void MosquittoConnection::on_disconnect(int rc) { setReadyToSend(false); isConnected = false; if (rc == 0) { JOYNR_LOG_DEBUG(logger, "Disconnected from tcp://{}:{}", host, port); } else { JOYNR_LOG_ERROR(logger, "Unexpectedly disconnected from tcp://{}:{}, error: {}", host, port, mosqpp::strerror(rc)); reconnect(); return; } stopLoop(); } void MosquittoConnection::on_log(int level, const char* str) { if (level == MOSQ_LOG_ERR) { JOYNR_LOG_ERROR(logger, "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_WARNING) { JOYNR_LOG_WARN(logger, "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_INFO) { JOYNR_LOG_INFO(logger, "Mosquitto Log: {}", str); } else { // MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level JOYNR_LOG_DEBUG(logger, "Mosquitto Log: {}", str); } } std::uint16_t MosquittoConnection::getMqttQos() const { return mqttQos; } std::string MosquittoConnection::getMqttPrio() const { static const std::string value("low"); return value; } bool MosquittoConnection::isMqttRetain() const { return mqttRetain; } void MosquittoConnection::start() { JOYNR_LOG_TRACE( logger, "Start called with isRunning: {}, isConnected: {}", isRunning, isConnected); JOYNR_LOG_DEBUG(logger, "Try to connect to tcp://{}:{}", host, port); connect_async(host.c_str(), port, messagingSettings.getMqttKeepAliveTimeSeconds().count()); reconnect_delay_set(messagingSettings.getMqttReconnectDelayTimeSeconds().count(), messagingSettings.getMqttReconnectDelayTimeSeconds().count(), false); startLoop(); } void MosquittoConnection::startLoop() { int rc = loop_start(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_TRACE(logger, "Mosquitto loop started"); isRunning = true; } else { JOYNR_LOG_ERROR(logger, "Mosquitto loop start failed: error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); } } void MosquittoConnection::stop() { if (isConnected) { int rc = disconnect(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_TRACE(logger, "Mosquitto Connection disconnected"); } else { JOYNR_LOG_ERROR(logger, "Mosquitto disconnect failed: error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); stopLoop(true); mosqpp::lib_cleanup(); } } else if (isRunning) { stopLoop(true); mosqpp::lib_cleanup(); } setReadyToSend(false); } void MosquittoConnection::stopLoop(bool force) { int rc = loop_stop(force); if (rc == MOSQ_ERR_SUCCESS) { isRunning = false; JOYNR_LOG_TRACE(logger, "Mosquitto loop stopped"); } else { JOYNR_LOG_ERROR(logger, "Mosquitto loop stop failed: error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); } } void MosquittoConnection::on_connect(int rc) { if (rc > 0) { JOYNR_LOG_ERROR(logger, "Mosquitto Connection Error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); } else { JOYNR_LOG_DEBUG(logger, "Mosquitto Connection established"); isConnected = true; createSubscriptions(); } } void MosquittoConnection::createSubscriptions() { while (!isChannelIdRegistered && isRunning) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } try { subscribeToTopicInternal(topic, true); std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); for (const std::string& additionalTopic : additionalTopics) { subscribeToTopicInternal(additionalTopic); } } catch (const exceptions::JoynrRuntimeException& error) { JOYNR_LOG_ERROR(logger, "Error subscribing to Mqtt topic, error: ", error.getMessage()); } } void MosquittoConnection::subscribeToTopicInternal(const std::string& topic, const bool isChannelTopic) { int* mid = nullptr; if (isChannelTopic) { mid = &subscribeChannelMid; } int rc = subscribe(mid, topic.c_str(), getMqttQos()); switch (rc) { case (MOSQ_ERR_SUCCESS): JOYNR_LOG_DEBUG(logger, "Subscribed to {}", topic); break; case (MOSQ_ERR_NO_CONN): JOYNR_LOG_DEBUG(logger, "Subscription to {} failed: error: {} (not connected to a broker). " "Subscription will be restored on connect.", topic, std::to_string(rc)); break; default: // MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM std::string errorMsg = "Subscription to " + topic + " failed: error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")"; throw exceptions::JoynrRuntimeException(errorMsg); } } void MosquittoConnection::subscribeToTopic(const std::string& topic) { while (!isChannelIdRegistered && isRunning) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) != additionalTopics.end()) { JOYNR_LOG_DEBUG(logger, "already subscribed to topic {}", topic); return; } subscribeToTopicInternal(topic); additionalTopics.insert(topic); } } void MosquittoConnection::unsubscribeFromTopic(const std::string& topic) { if (isChannelIdRegistered) { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) == additionalTopics.end()) { JOYNR_LOG_DEBUG(logger, "Unsubscribe called for non existing topic {}", topic); return; } additionalTopics.erase(topic); if (isConnected && isRunning) { int rc = unsubscribe(nullptr, topic.c_str()); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_DEBUG(logger, "Unsubscribed from {}", topic); } else { // MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN JOYNR_LOG_ERROR(logger, "Unsubscribe from {} failed: error: {} ({})", topic, std::to_string(rc), mosqpp::strerror(rc)); } } } } void MosquittoConnection::publishMessage( const std::string& topic, const int qosLevel, const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure, uint32_t payloadlen = 0, const void* payload = nullptr) { JOYNR_LOG_DEBUG(logger, "Publish to {}", topic); int mid; int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain()); if (!(rc == MOSQ_ERR_SUCCESS)) { if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) { onFailure(exceptions::JoynrMessageNotSentException( "message could not be sent: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")")); } // MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors onFailure(exceptions::JoynrDelayMessageException( "error sending message: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")")); } JOYNR_LOG_TRACE(logger, "published message with mqtt message id {}", std::to_string(mid)); } void MosquittoConnection::registerChannelId(const std::string& channelId) { this->channelId = channelId; topic = channelId + "/" + getMqttPrio() + "/" + "#"; isChannelIdRegistered = true; } void MosquittoConnection::registerReceiveCallback( std::function<void(smrf::ByteVector&&)> onMessageReceived) { this->onMessageReceived = onMessageReceived; } void MosquittoConnection::registerReadyToSendChangedCallback( std::function<void(bool)> onReadyToSendChanged) { std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); this->onReadyToSendChanged = std::move(onReadyToSendChanged); } bool MosquittoConnection::isSubscribedToChannelTopic() const { return subscribedToChannelTopic; } bool MosquittoConnection::isReadyToSend() const { return readyToSend; } void MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos) { JOYNR_LOG_DEBUG(logger, "Subscribed (mid: {} with granted QOS {}", mid, granted_qos[0]); for (int i = 1; i < qos_count; i++) { JOYNR_LOG_DEBUG(logger, "QOS: {} granted {}", i, granted_qos[i]); } if (mid == subscribeChannelMid) { subscribedToChannelTopic = true; setReadyToSend(isConnected); } } void MosquittoConnection::on_message(const mosquitto_message* message) { if (!onMessageReceived) { JOYNR_LOG_ERROR( logger, "Discarding received message, since onMessageReceived callback is empty."); return; } std::uint8_t* data = static_cast<std::uint8_t*>(message->payload); smrf::ByteVector rawMessage(data, data + message->payloadlen); onMessageReceived(std::move(rawMessage)); } void MosquittoConnection::on_publish(int mid) { JOYNR_LOG_TRACE(logger, "published message with mid {}", std::to_string(mid)); } void MosquittoConnection::setReadyToSend(bool readyToSend) { if (this->readyToSend != readyToSend) { this->readyToSend = readyToSend; std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); if (onReadyToSendChanged) { onReadyToSendChanged(readyToSend); } } } } // namespace joynr <commit_msg>[C++] Always log MQTT client ID when creating an MQTT connection.<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ #include "libjoynrclustercontroller/mqtt/MosquittoConnection.h" #include "joynr/ClusterControllerSettings.h" #include "joynr/MessagingSettings.h" #include "joynr/exceptions/JoynrException.h" namespace joynr { INIT_LOGGER(MosquittoConnection); MosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings, const ClusterControllerSettings& ccSettings, const std::string& clientId) : mosquittopp(clientId.c_str(), false), messagingSettings(messagingSettings), host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()), port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()), channelId(), subscribeChannelMid(), topic(), additionalTopics(), additionalTopicsMutex(), isConnected(false), isRunning(false), isChannelIdRegistered(false), subscribedToChannelTopic(false), readyToSend(false), onMessageReceived(), onReadyToSendChangedMutex(), onReadyToSendChanged() { JOYNR_LOG_INFO(logger, "Init mosquitto connection using MQTT client ID: {}", clientId); mosqpp::lib_init(); if (ccSettings.isMqttTlsEnabled()) { int rc = tls_set(ccSettings.getMqttCertificateAuthorityPemFilename().c_str(), NULL, ccSettings.getMqttCertificatePemFilename().c_str(), ccSettings.getMqttPrivateKeyPemFilename().c_str()); if (rc != MOSQ_ERR_SUCCESS) { JOYNR_LOG_ERROR( logger, "Could not initialize TLS connection - {}", mosqpp::strerror(rc)); } } else { JOYNR_LOG_DEBUG(logger, "MQTT connection not encrypted"); } } MosquittoConnection::~MosquittoConnection() { stop(); stopLoop(true); mosqpp::lib_cleanup(); } void MosquittoConnection::on_disconnect(int rc) { setReadyToSend(false); isConnected = false; if (rc == 0) { JOYNR_LOG_DEBUG(logger, "Disconnected from tcp://{}:{}", host, port); } else { JOYNR_LOG_ERROR(logger, "Unexpectedly disconnected from tcp://{}:{}, error: {}", host, port, mosqpp::strerror(rc)); reconnect(); return; } stopLoop(); } void MosquittoConnection::on_log(int level, const char* str) { if (level == MOSQ_LOG_ERR) { JOYNR_LOG_ERROR(logger, "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_WARNING) { JOYNR_LOG_WARN(logger, "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_INFO) { JOYNR_LOG_INFO(logger, "Mosquitto Log: {}", str); } else { // MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level JOYNR_LOG_DEBUG(logger, "Mosquitto Log: {}", str); } } std::uint16_t MosquittoConnection::getMqttQos() const { return mqttQos; } std::string MosquittoConnection::getMqttPrio() const { static const std::string value("low"); return value; } bool MosquittoConnection::isMqttRetain() const { return mqttRetain; } void MosquittoConnection::start() { JOYNR_LOG_TRACE( logger, "Start called with isRunning: {}, isConnected: {}", isRunning, isConnected); JOYNR_LOG_DEBUG(logger, "Try to connect to tcp://{}:{}", host, port); connect_async(host.c_str(), port, messagingSettings.getMqttKeepAliveTimeSeconds().count()); reconnect_delay_set(messagingSettings.getMqttReconnectDelayTimeSeconds().count(), messagingSettings.getMqttReconnectDelayTimeSeconds().count(), false); startLoop(); } void MosquittoConnection::startLoop() { int rc = loop_start(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_TRACE(logger, "Mosquitto loop started"); isRunning = true; } else { JOYNR_LOG_ERROR(logger, "Mosquitto loop start failed: error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); } } void MosquittoConnection::stop() { if (isConnected) { int rc = disconnect(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_TRACE(logger, "Mosquitto Connection disconnected"); } else { JOYNR_LOG_ERROR(logger, "Mosquitto disconnect failed: error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); stopLoop(true); mosqpp::lib_cleanup(); } } else if (isRunning) { stopLoop(true); mosqpp::lib_cleanup(); } setReadyToSend(false); } void MosquittoConnection::stopLoop(bool force) { int rc = loop_stop(force); if (rc == MOSQ_ERR_SUCCESS) { isRunning = false; JOYNR_LOG_TRACE(logger, "Mosquitto loop stopped"); } else { JOYNR_LOG_ERROR(logger, "Mosquitto loop stop failed: error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); } } void MosquittoConnection::on_connect(int rc) { if (rc > 0) { JOYNR_LOG_ERROR(logger, "Mosquitto Connection Error: {} ({})", std::to_string(rc), mosqpp::strerror(rc)); } else { JOYNR_LOG_DEBUG(logger, "Mosquitto Connection established"); isConnected = true; createSubscriptions(); } } void MosquittoConnection::createSubscriptions() { while (!isChannelIdRegistered && isRunning) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } try { subscribeToTopicInternal(topic, true); std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); for (const std::string& additionalTopic : additionalTopics) { subscribeToTopicInternal(additionalTopic); } } catch (const exceptions::JoynrRuntimeException& error) { JOYNR_LOG_ERROR(logger, "Error subscribing to Mqtt topic, error: ", error.getMessage()); } } void MosquittoConnection::subscribeToTopicInternal(const std::string& topic, const bool isChannelTopic) { int* mid = nullptr; if (isChannelTopic) { mid = &subscribeChannelMid; } int rc = subscribe(mid, topic.c_str(), getMqttQos()); switch (rc) { case (MOSQ_ERR_SUCCESS): JOYNR_LOG_DEBUG(logger, "Subscribed to {}", topic); break; case (MOSQ_ERR_NO_CONN): JOYNR_LOG_DEBUG(logger, "Subscription to {} failed: error: {} (not connected to a broker). " "Subscription will be restored on connect.", topic, std::to_string(rc)); break; default: // MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM std::string errorMsg = "Subscription to " + topic + " failed: error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")"; throw exceptions::JoynrRuntimeException(errorMsg); } } void MosquittoConnection::subscribeToTopic(const std::string& topic) { while (!isChannelIdRegistered && isRunning) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) != additionalTopics.end()) { JOYNR_LOG_DEBUG(logger, "already subscribed to topic {}", topic); return; } subscribeToTopicInternal(topic); additionalTopics.insert(topic); } } void MosquittoConnection::unsubscribeFromTopic(const std::string& topic) { if (isChannelIdRegistered) { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) == additionalTopics.end()) { JOYNR_LOG_DEBUG(logger, "Unsubscribe called for non existing topic {}", topic); return; } additionalTopics.erase(topic); if (isConnected && isRunning) { int rc = unsubscribe(nullptr, topic.c_str()); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_DEBUG(logger, "Unsubscribed from {}", topic); } else { // MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN JOYNR_LOG_ERROR(logger, "Unsubscribe from {} failed: error: {} ({})", topic, std::to_string(rc), mosqpp::strerror(rc)); } } } } void MosquittoConnection::publishMessage( const std::string& topic, const int qosLevel, const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure, uint32_t payloadlen = 0, const void* payload = nullptr) { JOYNR_LOG_DEBUG(logger, "Publish to {}", topic); int mid; int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain()); if (!(rc == MOSQ_ERR_SUCCESS)) { if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) { onFailure(exceptions::JoynrMessageNotSentException( "message could not be sent: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")")); } // MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors onFailure(exceptions::JoynrDelayMessageException( "error sending message: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")")); } JOYNR_LOG_TRACE(logger, "published message with mqtt message id {}", std::to_string(mid)); } void MosquittoConnection::registerChannelId(const std::string& channelId) { this->channelId = channelId; topic = channelId + "/" + getMqttPrio() + "/" + "#"; isChannelIdRegistered = true; } void MosquittoConnection::registerReceiveCallback( std::function<void(smrf::ByteVector&&)> onMessageReceived) { this->onMessageReceived = onMessageReceived; } void MosquittoConnection::registerReadyToSendChangedCallback( std::function<void(bool)> onReadyToSendChanged) { std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); this->onReadyToSendChanged = std::move(onReadyToSendChanged); } bool MosquittoConnection::isSubscribedToChannelTopic() const { return subscribedToChannelTopic; } bool MosquittoConnection::isReadyToSend() const { return readyToSend; } void MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos) { JOYNR_LOG_DEBUG(logger, "Subscribed (mid: {} with granted QOS {}", mid, granted_qos[0]); for (int i = 1; i < qos_count; i++) { JOYNR_LOG_DEBUG(logger, "QOS: {} granted {}", i, granted_qos[i]); } if (mid == subscribeChannelMid) { subscribedToChannelTopic = true; setReadyToSend(isConnected); } } void MosquittoConnection::on_message(const mosquitto_message* message) { if (!onMessageReceived) { JOYNR_LOG_ERROR( logger, "Discarding received message, since onMessageReceived callback is empty."); return; } std::uint8_t* data = static_cast<std::uint8_t*>(message->payload); smrf::ByteVector rawMessage(data, data + message->payloadlen); onMessageReceived(std::move(rawMessage)); } void MosquittoConnection::on_publish(int mid) { JOYNR_LOG_TRACE(logger, "published message with mid {}", std::to_string(mid)); } void MosquittoConnection::setReadyToSend(bool readyToSend) { if (this->readyToSend != readyToSend) { this->readyToSend = readyToSend; std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); if (onReadyToSendChanged) { onReadyToSendChanged(readyToSend); } } } } // namespace joynr <|endoftext|>
<commit_before>/** * @file CommonAPIClient.hpp * @author Denis Kotov * @date 3 Apr 2017 * @brief Contains CommonAPIClient wrapper class for creating client * @copyright MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git */ #ifndef ICC_COMMONAPI_CLIENT_COMPONENT_HPP #define ICC_COMMONAPI_CLIENT_COMPONENT_HPP #include <CommonAPI/CommonAPI.hpp> #include <type_traits> #include <logger/DummyLogger.hpp> namespace icc { namespace commonapi { template< template< typename ... _AttributeExtensions > class Proxy, typename Logger = icc::logger::DummyLogger > class CommonAPIClient : public Proxy<> , public virtual Logger { static_assert(std::is_base_of<CommonAPI::Proxy, Proxy<>>::value, "Proxy does not derived from CommonAPI::Proxy"); public: CommonAPIClient(const std::string &_domain, const std::string &_instance) : Proxy<>([=]() { Logger::debug("Building CommonAPIClient ..."); std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get(); auto proxy = runtime->buildProxy<Proxy>(_domain, _instance); if (!proxy) { Logger::error("proxy is nullptr"); } else { Logger::debug("CommonAPIClient is built successfully !!"); proxy->getProxyStatusEvent().subscribe( [=](const CommonAPI::AvailabilityStatus & _status) mutable { if (CommonAPI::AvailabilityStatus::AVAILABLE == _status) { Logger::debug("CommonAPIClient is connected"); connected(*this); } else { Logger::debug("CommonAPIClient is disconnected"); disconnected(*this); } }); } return proxy; }()) { Logger::debug("Constructor CommonAPIClient"); } CommonAPIClient(CommonAPIClient const &) = default; CommonAPIClient & operator=(CommonAPIClient const &) = default; CommonAPIClient(CommonAPIClient &&) = default; CommonAPIClient & operator=(CommonAPIClient &&) = default; virtual ~CommonAPIClient() = default; virtual void connected(Proxy<> &) = 0; virtual void disconnected(Proxy<> &) = 0; }; } } #endif // ICC_COMMONAPI_CLIENT_COMPONENT_HPP <commit_msg>Fixed warnings in CommonAPIClients<commit_after>/** * @file CommonAPIClient.hpp * @author Denis Kotov * @date 3 Apr 2017 * @brief Contains CommonAPIClient wrapper class for creating client * @copyright MIT License. Open source: https://github.com/redradist/Inter-Component-Communication.git */ #ifndef ICC_COMMONAPI_CLIENT_COMPONENT_HPP #define ICC_COMMONAPI_CLIENT_COMPONENT_HPP #include <CommonAPI/CommonAPI.hpp> #include <type_traits> #include <logger/DummyLogger.hpp> namespace icc { namespace commonapi { template< template< typename ... _AttributeExtensions > class Proxy, typename Logger = icc::logger::DummyLogger > class CommonAPIClient : public Proxy<> , public virtual Logger { static_assert(std::is_base_of<CommonAPI::Proxy, Proxy<>>::value, "Proxy does not derived from CommonAPI::Proxy"); public: CommonAPIClient(const std::string &_domain, const std::string &_instance) : Proxy<>([=]() { Logger::debug("Building CommonAPIClient ..."); std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get(); auto proxy = runtime->buildProxy<Proxy>(_domain, _instance); if (!proxy) { Logger::error("proxy is nullptr"); } else { Logger::debug("CommonAPIClient is built successfully !!"); proxy->getProxyStatusEvent().subscribe( [=](const CommonAPI::AvailabilityStatus & _status) mutable { if (CommonAPI::AvailabilityStatus::AVAILABLE == _status) { Logger::debug("CommonAPIClient is connected"); connected(*this); } else { Logger::debug("CommonAPIClient is disconnected"); disconnected(*this); } }); } return proxy; }()) { Logger::debug("Constructor CommonAPIClient"); } CommonAPIClient(CommonAPIClient const &) = default; CommonAPIClient & operator=(CommonAPIClient const &) = default; CommonAPIClient(CommonAPIClient &&) = delete; CommonAPIClient & operator=(CommonAPIClient &&) = delete; virtual ~CommonAPIClient() = default; virtual void connected(Proxy<> &) = 0; virtual void disconnected(Proxy<> &) = 0; }; } } #endif // ICC_COMMONAPI_CLIENT_COMPONENT_HPP <|endoftext|>
<commit_before>#ifndef DICE_GETNUMBEROPERATION_H #define DICE_GETNUMBEROPERATION_H #include "IOperation.hpp" class GetNumberOperation : public IOperation { const int _number; // stores number given by a constructor // It's called directly by evaluate, so check its doc. std::unique_ptr<RollResult> execute(); public: explicit GetNumberOperation(int); std::unique_ptr<RollResult> evaluate(); }; #endif //DICE_GETNUMBEROPERATION_H <commit_msg>Added documentation for GetNumberOperation class.<commit_after>#ifndef DICE_GETNUMBEROPERATION_H #define DICE_GETNUMBEROPERATION_H #include "IOperation.hpp" /** * \brief Creates RollResult from singular value. */ class GetNumberOperation : public IOperation { const int _number; // stores number given by a constructor // It's called directly by evaluate, so check its doc. std::unique_ptr<RollResult> execute(); public: /** * \brief Operation that creates singular value RollResult. * * It's a primitive operation that should be a base for decorators. * * \param number Integer value that we want to pass to other * operations. */ explicit GetNumberOperation(int number); /** * \brief Evaluates an operation. * * \return Returns unique pointer to RollResult containing singular * value specified while calling constructor. */ std::unique_ptr<RollResult> evaluate(); }; #endif //DICE_GETNUMBEROPERATION_H <|endoftext|>
<commit_before>#include "ledpoi.h" #include "ledpoi_utils.h" #include "memory/memoryTask.h" #include "dispatch/dispatchTask.h" #include "display/displayTask.h" #include "player/playerTask.h" #include "program/programTask.h" #include "wifi/wifiTask.h" #include "uart/uartTask.h" #include "ui/button.h" #include "selftest/selftestTask.h" // unless defined differently below this is the default log level #define DEFAULT_LOG_LEVEL ESP_LOG_INFO void logging_setup(){ esp_log_level_set(DSPCH_T, ESP_LOG_DEBUG); // dispatch task esp_log_level_set(DISP_T, DEFAULT_LOG_LEVEL); // display task esp_log_level_set(WIFI_T, ESP_LOG_DEBUG); // wifi task esp_log_level_set(UART_T, ESP_LOG_DEBUG); // uart task esp_log_level_set(PROG_T, ESP_LOG_DEBUG); // program task esp_log_level_set(PLAY_T, ESP_LOG_DEBUG); // play task esp_log_level_set(MEM_T, DEFAULT_LOG_LEVEL); // memory task esp_log_level_set(SELF_T, DEFAULT_LOG_LEVEL); // selftest task esp_log_level_set(BUT_T, DEFAULT_LOG_LEVEL); // button task esp_log_level_set(EXPL_T, DEFAULT_LOG_LEVEL); // example task esp_log_level_set(PLAYF_A, DEFAULT_LOG_LEVEL); // play frames action esp_log_level_set(NOACT_A, DEFAULT_LOG_LEVEL); // void ("no") action esp_log_level_set(ANIM_A, DEFAULT_LOG_LEVEL); // animation action esp_log_level_set(TIMER, DEFAULT_LOG_LEVEL); // timer util esp_log_level_set(POICMD, DEFAULT_LOG_LEVEL); // poi command util esp_log_level_set(ICACHE, DEFAULT_LOG_LEVEL); // image cache util esp_log_level_set(PCACHE, DEFAULT_LOG_LEVEL); // program cache util esp_log_level_set(RWIFIS, ESP_LOG_DEBUG); // Robust wifi server esp_log_level_set(WIFI_U, ESP_LOG_DEBUG); // Robust wifi server utils esp_log_level_set(FLASH, DEFAULT_LOG_LEVEL); // flash memory esp_log_level_set(PROGH, DEFAULT_LOG_LEVEL); // program handler esp_log_level_set(INTS, DEFAULT_LOG_LEVEL); // interaction state esp_log_level_set(SELF_H, DEFAULT_LOG_LEVEL); // selftest helper } void setup() { uart_setup(); // first one because this sets serial baudrate logging_setup(); // setup tasks and queues with sizes button_setup(); memory_setup(10); dispatch_setup(10); display_setup(5); player_setup(5); program_setup(3); wifi_setup(3); // start tasks with prios button_start(8); memory_start(8); dispatch_start(7); program_start(6, 5); player_start(4); display_start(3); wifi_start(8); uart_start(5); // send wifi start command to central dispatch queue after everything is set up PoiCommand cmdStartWifi ({CONNECT, 0, 0, 0, 0, 0}); sendToDispatch(cmdStartWifi, WIFI_T); // start selftest // selftest_start(5); // fill queues with example values PoiCommand cmdWorm ( {ANIMATE, RAINBOW, 1, 5, 0, 100} ); sendToDispatch(cmdWorm, WIFI_T); PoiCommand cmdBlack ( {SHOW_RGB, 0, 0, 0, 0, 0} ); // black sendToDispatch(cmdBlack, WIFI_T); } // everything works with tasks, we dont need the loop... void loop(){ delay(100000); // snow white sleep }<commit_msg>back to default log level<commit_after>#include "ledpoi.h" #include "ledpoi_utils.h" #include "memory/memoryTask.h" #include "dispatch/dispatchTask.h" #include "display/displayTask.h" #include "player/playerTask.h" #include "program/programTask.h" #include "wifi/wifiTask.h" #include "uart/uartTask.h" #include "ui/button.h" #include "selftest/selftestTask.h" // unless defined differently below this is the default log level #define DEFAULT_LOG_LEVEL ESP_LOG_INFO void logging_setup(){ esp_log_level_set(DSPCH_T, ESP_LOG_DEBUG); // dispatch task esp_log_level_set(DISP_T, DEFAULT_LOG_LEVEL); // display task esp_log_level_set(WIFI_T, ESP_LOG_DEBUG); // wifi task esp_log_level_set(UART_T, ESP_LOG_DEBUG); // uart task esp_log_level_set(PROG_T, ESP_LOG_DEBUG); // program task esp_log_level_set(PLAY_T, ESP_LOG_DEBUG); // play task esp_log_level_set(MEM_T, DEFAULT_LOG_LEVEL); // memory task esp_log_level_set(SELF_T, DEFAULT_LOG_LEVEL); // selftest task esp_log_level_set(BUT_T, DEFAULT_LOG_LEVEL); // button task esp_log_level_set(EXPL_T, DEFAULT_LOG_LEVEL); // example task esp_log_level_set(PLAYF_A, DEFAULT_LOG_LEVEL); // play frames action esp_log_level_set(NOACT_A, DEFAULT_LOG_LEVEL); // void ("no") action esp_log_level_set(ANIM_A, DEFAULT_LOG_LEVEL); // animation action esp_log_level_set(TIMER, DEFAULT_LOG_LEVEL); // timer util esp_log_level_set(POICMD, DEFAULT_LOG_LEVEL); // poi command util esp_log_level_set(ICACHE, DEFAULT_LOG_LEVEL); // image cache util esp_log_level_set(PCACHE, DEFAULT_LOG_LEVEL); // program cache util esp_log_level_set(RWIFIS, DEFAULT_LOG_LEVEL); // Robust wifi server esp_log_level_set(WIFI_U, DEFAULT_LOG_LEVEL); // Robust wifi server utils esp_log_level_set(FLASH, DEFAULT_LOG_LEVEL); // flash memory esp_log_level_set(PROGH, DEFAULT_LOG_LEVEL); // program handler esp_log_level_set(INTS, DEFAULT_LOG_LEVEL); // interaction state esp_log_level_set(SELF_H, DEFAULT_LOG_LEVEL); // selftest helper } void setup() { uart_setup(); // first one because this sets serial baudrate logging_setup(); // setup tasks and queues with sizes button_setup(); memory_setup(10); dispatch_setup(10); display_setup(5); player_setup(5); program_setup(3); wifi_setup(3); // start tasks with prios button_start(8); memory_start(8); dispatch_start(7); program_start(6, 5); player_start(4); display_start(3); wifi_start(8); uart_start(5); // send wifi start command to central dispatch queue after everything is set up PoiCommand cmdStartWifi ({CONNECT, 0, 0, 0, 0, 0}); sendToDispatch(cmdStartWifi, WIFI_T); // start selftest // selftest_start(5); // fill queues with example values PoiCommand cmdWorm ( {ANIMATE, RAINBOW, 1, 5, 0, 100} ); sendToDispatch(cmdWorm, WIFI_T); PoiCommand cmdBlack ( {SHOW_RGB, 0, 0, 0, 0, 0} ); // black sendToDispatch(cmdBlack, WIFI_T); } // everything works with tasks, we dont need the loop... void loop(){ delay(100000); // snow white sleep }<|endoftext|>
<commit_before>/* * File description: axon_client.cpp * Author information: Mike Raninger [email protected] * Copyright information: Copyright Mike Ranzinger */ #include "communication/messaging/axon_client.h" #include "communication/timeout_exception.h" #include <functional> using namespace std; namespace axon { namespace communication { struct CMessageSocket { CMessageSocket(CMessage::Ptr a_outboundMessage) : OutboundMessage(move(a_outboundMessage)) { } CMessage::Ptr OutboundMessage; CMessage::Ptr IncomingMessage; }; class CAxonClient::WaitHandle : public IMessageWaitHandle { public: typedef unique_ptr<WaitHandle> Ptr; WaitHandle(CAxonClient &a_client, CMessage::Ptr a_message, uint32_t a_timeout) : m_client(a_client), m_socket(move(a_message)), m_waited(false), m_timeout(a_timeout) { m_start = chrono::steady_clock::now(); } ~WaitHandle() { p_RemoveFromSocketList(true); } virtual void Wait() override; virtual CMessage::Ptr GetMessage() override; CAxonClient &m_client; CMessageSocket m_socket; bool m_waited; CMessage::Ptr m_message; chrono::steady_clock::time_point m_start; uint32_t m_timeout; private: void p_RemoveFromSocketList(bool a_getLock); }; CAxonClient::CAxonClient() { SetDefaultProtocol(); } CAxonClient::CAxonClient(const std::string& a_connectionString) { SetDefaultProtocol(); Connect(a_connectionString); } CAxonClient::CAxonClient(IDataConnection::Ptr a_connection) { SetDefaultProtocol(); Connect(move(a_connection)); } CAxonClient::CAxonClient(const std::string& a_connectionString, IProtocol::Ptr a_protocol) { SetProtocol(move(a_protocol)); Connect(a_connectionString); } CAxonClient::CAxonClient(IDataConnection::Ptr a_connection, IProtocol::Ptr a_protocol) { SetProtocol(move(a_protocol)); Connect(move(a_connection)); } CAxonClient::Ptr CAxonClient::Create() { return make_shared<CAxonClient>(); } CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString) { return make_shared<CAxonClient>(a_connectionString); } CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection) { return make_shared<CAxonClient>(move(a_connection)); } CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString, IProtocol::Ptr a_protocol) { return make_shared<CAxonClient>(a_connectionString, move(a_protocol)); } CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection, IProtocol::Ptr a_protocol) { return make_shared<CAxonClient>(move(a_connection), move(a_protocol)); } void CAxonClient::Connect(const std::string& a_connectionString) { Connect(IDataConnection::Create(a_connectionString)); } void CAxonClient::Connect(IDataConnection::Ptr a_connection) { m_connection = move(a_connection); if (m_connection) { #ifdef IS_WINDOWS int l_hack; m_connection->SetReceiveHandler( [this, l_hack](CDataBuffer a_buf) { p_OnDataReceived(move(a_buf)); }); #else m_connection->SetReceiveHandler(bind(&CAxonClient::p_OnDataReceived, this, placeholders::_1)); #endif } } void CAxonClient::SetDefaultProtocol() { SetProtocol(GetDefaultProtocol()); } void CAxonClient::SetProtocol(IProtocol::Ptr a_protocol) { if (!a_protocol) throw runtime_error("Invalid protocol. Cannot be null."); m_protocol = move(a_protocol); m_protocol->SetHandler(bind(&CAxonClient::p_OnMessageReceived, this, placeholders::_1)); } string CAxonClient::ConnectionString() const { if (!m_connection) return ""; return m_connection->ConnectionString(); } CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message) { return Send(a_message, 0); } CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message, uint32_t a_timeout) { IMessageWaitHandle::Ptr l_waitHandle = SendAsync(a_message, a_timeout); return l_waitHandle->GetMessage(); } IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message) { return SendAsync(a_message, 0); } IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message, uint32_t a_timeout) { if (!m_connection || !m_connection->IsOpen()) throw runtime_error("Cannot send data over a dead connection."); // Default timeout is 1 minute if (a_timeout == 0) a_timeout = 60000; WaitHandle::Ptr l_waitHandle(new WaitHandle(*this, a_message, a_timeout)); // Add the socket to the map of messages waiting to be handled { lock_guard<mutex> l_lock(m_pendingLock); m_pendingList.push_back(&l_waitHandle->m_socket); } p_Send(*a_message); return move(l_waitHandle); } //-------------------------------------------------------------- // Wait Handle Implementation //-------------------------------------------------------------- void CAxonClient::WaitHandle::Wait() { if (m_waited) return; auto l_durLeft = chrono::milliseconds(m_timeout) - chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start); unique_lock<mutex> l_waitLock(m_client.m_pendingLock); if (m_socket.IncomingMessage) { p_RemoveFromSocketList(false); m_waited = true; return; } if (l_durLeft < chrono::milliseconds(0)) throw CTimeoutException(m_timeout); while (!m_socket.IncomingMessage) { cv_status l_status = m_client.m_newMessageEvent.wait_for(l_waitLock, l_durLeft); l_durLeft = chrono::milliseconds(m_timeout) - chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start); if (m_socket.IncomingMessage || l_status == cv_status::timeout || l_durLeft < chrono::milliseconds(0)) { // Don't need to acquire the lock because we already have it p_RemoveFromSocketList(false); if (!m_socket.IncomingMessage) { throw CTimeoutException(m_timeout); } } } m_waited = true; } CMessage::Ptr CAxonClient::WaitHandle::GetMessage() { Wait(); return m_message; } void CAxonClient::WaitHandle::p_RemoveFromSocketList(bool a_getLock) { try { if (a_getLock) m_client.m_pendingLock.lock(); auto iter = find(m_client.m_pendingList.begin(), m_client.m_pendingList.end(), &m_socket); if (iter != m_client.m_pendingList.end()) m_client.m_pendingList.erase(iter); if (a_getLock) m_client.m_pendingLock.unlock(); } catch (...) { if (a_getLock) m_client.m_pendingLock.unlock(); throw; } } //-------------------------------------------------------------- void CAxonClient::SendNonBlocking(const CMessage::Ptr &a_message) { a_message->SetOneWay(true); p_Send(*a_message); } void CAxonClient::p_Send(const CMessage& a_message) { CDataBuffer l_buffer = m_protocol->SerializeMessage(a_message); m_connection->Send(l_buffer.ToShared()); } void CAxonClient::p_OnMessageReceived(const CMessage::Ptr& a_message) { // This function is invoked whenever the protocol has reconstructed // a message. There are 3 things that this object needs to try before // erroring out: // 1) Check to see if this message is a response from an outbound call // Resolution: Add the message to the new messages map and signal // that there is a new message // 2) Check to see if this instance has a handler for this message // Resolution: Handle the message and send the return value back out // 3) If this client is a child of a server, then see if the server // can handle the message. // // If none of the steps succeed, then throw a fault SetExecutingInstance(this); bool l_handled = false; { lock_guard<mutex> l_lock(m_pendingLock); const std::string &l_reqId = a_message->RequestId(); // See if the RequestId of this message is the Id of a message // in the outbound list auto iter = find_if(m_pendingList.begin(), m_pendingList.end(), [&l_reqId] (CMessageSocket *l_sock) { return l_reqId == l_sock->OutboundMessage->Id(); }); // This message is a result of an outbound request, so let // the blocking outbound requests know if (iter != m_pendingList.end()) { (*iter)->IncomingMessage = a_message; l_handled = true; } } if (l_handled) { // Wake up everyone that is currently waiting m_newMessageEvent.notify_all(); return; } // Ok, so this message isn't a result of an outbound call, so see if this // client has a handler for it CMessage::Ptr l_response; if (TryHandle(*a_message, l_response)) { // There was a handler for this message, so now // send it back out to the caller if (!a_message->IsOneWay()) SendNonBlocking(l_response); l_handled = true; } if (l_handled) return; if (TryHandleWithServer(*a_message, l_response)) { if (!a_message->IsOneWay()) SendNonBlocking(l_response); l_handled = true; } if (l_handled) return; // If this message is not a request, then send a fault back to the caller if (a_message->RequestId().empty() && !a_message->IsOneWay()) { l_response = make_shared<CMessage>(*a_message, CFaultException("The action '" + a_message->GetAction() + "' has no supported handlers.")); SendNonBlocking(l_response); } else { // This is probably due to a timeout // TODO: Log this } } void CAxonClient::p_OnDataReceived(CDataBuffer a_buffer) { // This function is invoked whenever the data connection // signals that data has been received from the remote peer. // In the case of the AxonClient, this should be immediately forwarded to // the protocol so that a message can be reconstructed from it. // The data connection owns the buffer, so a copy must be made m_protocol->Process(move(a_buffer)); } bool CAxonClient::TryHandleWithServer(const CMessage& a_msg, CMessage::Ptr& a_out) const { // Derived instances need to override this return false; } } } <commit_msg>Fixed a bug with the async call stuff<commit_after>/* * File description: axon_client.cpp * Author information: Mike Raninger [email protected] * Copyright information: Copyright Mike Ranzinger */ #include "communication/messaging/axon_client.h" #include "communication/timeout_exception.h" #include <functional> #include <assert.h> using namespace std; namespace axon { namespace communication { struct CMessageSocket { CMessageSocket(CMessage::Ptr a_outboundMessage) : OutboundMessage(move(a_outboundMessage)) { } CMessage::Ptr OutboundMessage; CMessage::Ptr IncomingMessage; }; class CAxonClient::WaitHandle : public IMessageWaitHandle { public: typedef unique_ptr<WaitHandle> Ptr; WaitHandle(CAxonClient &a_client, CMessage::Ptr a_message, uint32_t a_timeout) : m_client(a_client), m_socket(move(a_message)), m_waited(false), m_timeout(a_timeout) { m_start = chrono::steady_clock::now(); } ~WaitHandle() { p_RemoveFromSocketList(true); } virtual void Wait() override; virtual CMessage::Ptr GetMessage() override; CAxonClient &m_client; CMessageSocket m_socket; bool m_waited; chrono::steady_clock::time_point m_start; uint32_t m_timeout; private: void p_RemoveFromSocketList(bool a_getLock); }; CAxonClient::CAxonClient() { SetDefaultProtocol(); } CAxonClient::CAxonClient(const std::string& a_connectionString) { SetDefaultProtocol(); Connect(a_connectionString); } CAxonClient::CAxonClient(IDataConnection::Ptr a_connection) { SetDefaultProtocol(); Connect(move(a_connection)); } CAxonClient::CAxonClient(const std::string& a_connectionString, IProtocol::Ptr a_protocol) { SetProtocol(move(a_protocol)); Connect(a_connectionString); } CAxonClient::CAxonClient(IDataConnection::Ptr a_connection, IProtocol::Ptr a_protocol) { SetProtocol(move(a_protocol)); Connect(move(a_connection)); } CAxonClient::Ptr CAxonClient::Create() { return make_shared<CAxonClient>(); } CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString) { return make_shared<CAxonClient>(a_connectionString); } CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection) { return make_shared<CAxonClient>(move(a_connection)); } CAxonClient::Ptr CAxonClient::Create(const std::string& a_connectionString, IProtocol::Ptr a_protocol) { return make_shared<CAxonClient>(a_connectionString, move(a_protocol)); } CAxonClient::Ptr CAxonClient::Create(IDataConnection::Ptr a_connection, IProtocol::Ptr a_protocol) { return make_shared<CAxonClient>(move(a_connection), move(a_protocol)); } void CAxonClient::Connect(const std::string& a_connectionString) { Connect(IDataConnection::Create(a_connectionString)); } void CAxonClient::Connect(IDataConnection::Ptr a_connection) { m_connection = move(a_connection); if (m_connection) { #ifdef IS_WINDOWS int l_hack; m_connection->SetReceiveHandler( [this, l_hack](CDataBuffer a_buf) { p_OnDataReceived(move(a_buf)); }); #else m_connection->SetReceiveHandler(bind(&CAxonClient::p_OnDataReceived, this, placeholders::_1)); #endif } } void CAxonClient::SetDefaultProtocol() { SetProtocol(GetDefaultProtocol()); } void CAxonClient::SetProtocol(IProtocol::Ptr a_protocol) { if (!a_protocol) throw runtime_error("Invalid protocol. Cannot be null."); m_protocol = move(a_protocol); m_protocol->SetHandler(bind(&CAxonClient::p_OnMessageReceived, this, placeholders::_1)); } string CAxonClient::ConnectionString() const { if (!m_connection) return ""; return m_connection->ConnectionString(); } CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message) { return Send(a_message, 0); } CMessage::Ptr CAxonClient::Send(const CMessage::Ptr &a_message, uint32_t a_timeout) { IMessageWaitHandle::Ptr l_waitHandle = SendAsync(a_message, a_timeout); return l_waitHandle->GetMessage(); } IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message) { return SendAsync(a_message, 0); } IMessageWaitHandle::Ptr CAxonClient::SendAsync(const CMessage::Ptr& a_message, uint32_t a_timeout) { if (!m_connection || !m_connection->IsOpen()) throw runtime_error("Cannot send data over a dead connection."); // Default timeout is 1 minute if (a_timeout == 0) a_timeout = 60000; WaitHandle::Ptr l_waitHandle(new WaitHandle(*this, a_message, a_timeout)); // Add the socket to the map of messages waiting to be handled { lock_guard<mutex> l_lock(m_pendingLock); m_pendingList.push_back(&l_waitHandle->m_socket); } p_Send(*a_message); return move(l_waitHandle); } //-------------------------------------------------------------- // Wait Handle Implementation //-------------------------------------------------------------- void CAxonClient::WaitHandle::Wait() { if (m_waited) return; auto l_durLeft = chrono::milliseconds(m_timeout) - chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start); unique_lock<mutex> l_waitLock(m_client.m_pendingLock); if (m_socket.IncomingMessage) { p_RemoveFromSocketList(false); m_waited = true; return; } if (l_durLeft < chrono::milliseconds(0)) throw CTimeoutException(m_timeout); while (!m_socket.IncomingMessage) { cv_status l_status = m_client.m_newMessageEvent.wait_for(l_waitLock, l_durLeft); l_durLeft = chrono::milliseconds(m_timeout) - chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - m_start); if (m_socket.IncomingMessage || l_status == cv_status::timeout || l_durLeft < chrono::milliseconds(0)) { // Don't need to acquire the lock because we already have it p_RemoveFromSocketList(false); if (!m_socket.IncomingMessage) { throw CTimeoutException(m_timeout); } } } assert(m_socket.IncomingMessage); m_socket.IncomingMessage->FaultCheck(); m_waited = true; } CMessage::Ptr CAxonClient::WaitHandle::GetMessage() { Wait(); return m_socket.IncomingMessage; } void CAxonClient::WaitHandle::p_RemoveFromSocketList(bool a_getLock) { try { if (a_getLock) m_client.m_pendingLock.lock(); auto iter = find(m_client.m_pendingList.begin(), m_client.m_pendingList.end(), &m_socket); if (iter != m_client.m_pendingList.end()) m_client.m_pendingList.erase(iter); if (a_getLock) m_client.m_pendingLock.unlock(); } catch (...) { if (a_getLock) m_client.m_pendingLock.unlock(); throw; } } //-------------------------------------------------------------- void CAxonClient::SendNonBlocking(const CMessage::Ptr &a_message) { a_message->SetOneWay(true); p_Send(*a_message); } void CAxonClient::p_Send(const CMessage& a_message) { CDataBuffer l_buffer = m_protocol->SerializeMessage(a_message); m_connection->Send(l_buffer.ToShared()); } void CAxonClient::p_OnMessageReceived(const CMessage::Ptr& a_message) { // This function is invoked whenever the protocol has reconstructed // a message. There are 3 things that this object needs to try before // erroring out: // 1) Check to see if this message is a response from an outbound call // Resolution: Add the message to the new messages map and signal // that there is a new message // 2) Check to see if this instance has a handler for this message // Resolution: Handle the message and send the return value back out // 3) If this client is a child of a server, then see if the server // can handle the message. // // If none of the steps succeed, then throw a fault SetExecutingInstance(this); bool l_handled = false; { lock_guard<mutex> l_lock(m_pendingLock); const std::string &l_reqId = a_message->RequestId(); // See if the RequestId of this message is the Id of a message // in the outbound list auto iter = find_if(m_pendingList.begin(), m_pendingList.end(), [&l_reqId] (CMessageSocket *l_sock) { return l_reqId == l_sock->OutboundMessage->Id(); }); // This message is a result of an outbound request, so let // the blocking outbound requests know if (iter != m_pendingList.end()) { (*iter)->IncomingMessage = a_message; l_handled = true; } } if (l_handled) { // Wake up everyone that is currently waiting m_newMessageEvent.notify_all(); return; } // Ok, so this message isn't a result of an outbound call, so see if this // client has a handler for it CMessage::Ptr l_response; if (TryHandle(*a_message, l_response)) { // There was a handler for this message, so now // send it back out to the caller if (!a_message->IsOneWay()) SendNonBlocking(l_response); l_handled = true; } if (l_handled) return; if (TryHandleWithServer(*a_message, l_response)) { if (!a_message->IsOneWay()) SendNonBlocking(l_response); l_handled = true; } if (l_handled) return; // If this message is not a request, then send a fault back to the caller if (a_message->RequestId().empty() && !a_message->IsOneWay()) { l_response = make_shared<CMessage>(*a_message, CFaultException("The action '" + a_message->GetAction() + "' has no supported handlers.")); SendNonBlocking(l_response); } else { // This is probably due to a timeout // TODO: Log this } } void CAxonClient::p_OnDataReceived(CDataBuffer a_buffer) { // This function is invoked whenever the data connection // signals that data has been received from the remote peer. // In the case of the AxonClient, this should be immediately forwarded to // the protocol so that a message can be reconstructed from it. // The data connection owns the buffer, so a copy must be made m_protocol->Process(move(a_buffer)); } bool CAxonClient::TryHandleWithServer(const CMessage& a_msg, CMessage::Ptr& a_out) const { // Derived instances need to override this return false; } } } <|endoftext|>
<commit_before>#include <cstdlib> #include "mseq.hpp" #include "state.hpp" #include "automata.hpp" typedef Automata<mseq::empty> ::push_state<State<0>>::type ::push_state<State<1>>::type ::push_state<State<2, true>>::type ::start_state<2>::type automata; template <typename T> void print_type() { std::cout << __PRETTY_FUNCTION__ << std::endl; } int main() { print_type<automata>(); return 0; } <commit_msg>Update some tests<commit_after>#include <cstdlib> #include "mseq.hpp" #include "state.hpp" #include "automata.hpp" typedef Automata<> ::create_state<0>::type ::create_state<1, true>::type ::start_state<0>::type ::create_edge<0, 1, 'a'>::type ::create_edge<1, 1, 'a'>::type ::create_edge<1, 0, ','>::type automata; typedef automata::get_state<1>::type state1; template <typename T> void print_type() { std::cout << __PRETTY_FUNCTION__ << std::endl; } int main() { //if (automata::match("aa,a")::value) { // std::cout << "matched" << std::endl; //} print_type<automata>(); print_type<automata::get_edges_for<1>::type>(); //print_type<state1>(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <stdio.h> #include <errno.h> using namespace std; int main() { string userinput = ""; string login; if(!getlogin()) perror("getlogin"); else login = getlogin(); char hostname[64]; if(gethostname(hostname, sizeof hostname)) perror("gethostname"); while(userinput != "exit") { cout << getlogin() << "@" << hostname << " $ "; getline(cin, userinput); } return 0; } <commit_msg>got rid of main while to start parse<commit_after>#include <iostream> #include <unistd.h> #include <pwd.h> #include <sys/types.h> #include <stdio.h> #include <errno.h> using namespace std; int main() { string userinput = ""; string login; if(!getlogin()) perror("getlogin"); else login = getlogin(); char hostname[64]; if(gethostname(hostname, sizeof hostname)) perror("gethostname"); return 0; } <|endoftext|>
<commit_before>#include <iomanip> #include <cstdio> #include <cstdlib> #include <iostream> #include <vector> #include <omp.h> #include <sstream> #include <binUtils.h> #include <ompUtils.h> #include <parUtils.h> #include <octUtils.h> #include <TreeNode.h> #include <gensort.h> #include <sortRecord.h> #define MAX_DEPTH 30 #define SORT_FUNCTION par::HyperQuickSort // #define SORT_FUNCTION par::sampleSort // #define __VERIFY__ long getNumElements(char* code) { unsigned int slen = strlen(code); char dtype = code[0]; char tmp[128]; strncpy(tmp, code+1, slen-3); tmp[slen-3] = '\0'; // std::cout << "tmp is " << tmp << std::endl; long numBytes = atoi(tmp); switch(code[slen-2]) { case 'g': case 'G': numBytes *= 1024*1024*1024; break; case 'k': case 'K': numBytes *= 1024; break; case 'm': case 'M': numBytes *= 1024*1024; break; default: // std::cout << "unknown code " << code[slen-2] << std::endl; return 0; }; switch (dtype) { case 'd': // double array return numBytes/sizeof(double); break; case 'f': // float array return numBytes/sizeof(float); break; case 'i': // int array return numBytes/sizeof(int); break; case 'l': // long array return numBytes/sizeof(long); break; case 't': // treenode return numBytes/sizeof(ot::TreeNode); break; case 'x': // gensort record return numBytes/sizeof(sortRecord); break; default: return 0; }; } template <class T> bool verify(std::vector<T>& in_, std::vector<T> &out_, MPI_Comm comm){ // Find out my identity in the default communicator int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); std::vector<T> in; { int N_local=in_.size()*sizeof(T); std::vector<int> r_size(p, 0); std::vector<int> r_disp(p, 0); MPI_Gather(&N_local , 1, MPI_INT, &r_size[0], 1, MPI_INT, 0, comm); omp_par::scan(&r_size[0], &r_disp[0], p); if(!myrank) in.resize((r_size[p-1]+r_disp[p-1])/sizeof(T)); MPI_Gatherv((char*)&in_[0], N_local, MPI_BYTE, (char*)&in [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm); } std::vector<T> out; { int N_local=out_.size()*sizeof(T); std::vector<int> r_size(p, 0); std::vector<int> r_disp(p, 0); MPI_Gather(&N_local , 1, MPI_INT, &r_size[0], 1, MPI_INT, 0, comm); omp_par::scan(&r_size[0], &r_disp[0], p); if(!myrank) out.resize((r_size[p-1]+r_disp[p-1])/sizeof(T)); MPI_Gatherv((char*)&out_[0], N_local, MPI_BYTE, (char*)&out [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm); } if(in.size()!=out.size()){ std::cout<<"Wrong size: in="<<in.size()<<" out="<<out.size()<<'\n'; return false; } std::sort(&in[0], &in[in.size()]); for(long j=0;j<in.size();j++) if(in[j]!=out[j]){ std::cout<<"Failed at:"<<j<<'\n'; // std::cout<<"Failed at:"<<j<<"; in="<<in[j]<<" out="<<out[j]<<'\n'; return false; } return true; } double time_sort_bench(size_t N, MPI_Comm comm) { int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); typedef sortRecord Data_t; std::vector<Data_t> in(N); genRecords((char* )&(*(in.begin())), myrank, N); std::vector<Data_t> in_cpy=in; std::vector<Data_t> out; // Warmup run and verification. SORT_FUNCTION<Data_t>(in, out, comm); // SORT_FUNCTION<Data_t>(in_cpy, comm); in=in_cpy; #ifdef __VERIFY__ verify(in,out,comm); #endif //Sort MPI_Barrier(comm); double wtime=-omp_get_wtime(); SORT_FUNCTION<Data_t>(in, out, comm); // SORT_FUNCTION<Data_t>(in, comm); MPI_Barrier(comm); wtime+=omp_get_wtime(); return wtime; } double time_sort_tn(size_t N, MPI_Comm comm) { int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); int omp_p=omp_get_max_threads(); typedef ot::TreeNode Data_t; std::vector<Data_t> in(N); unsigned int s = (1u << MAX_DEPTH); #pragma omp parallel for for(int j=0;j<omp_p;j++){ unsigned int seed=j*p+myrank; size_t start=(j*N)/omp_p; size_t end=((j+1)*N)/omp_p; for(unsigned int i=start;i<end;i++){ ot::TreeNode node(rand_r(&seed)%s, rand_r(&seed)%s, rand_r(&seed)%s, MAX_DEPTH-1, 3, MAX_DEPTH); // ot::TreeNode node(binOp::reversibleHash(3*i*myrank)%s, binOp::reversibleHash(3*i*myrank+1)%s, binOp::reversibleHash(3*i*myrank+2)%s, MAX_DEPTH-1, 3, MAX_DEPTH); in[i]=node; } } // std::cout << "finished generating data " << std::endl; std::vector<Data_t> in_cpy=in; std::vector<Data_t> out; // Warmup run and verification. SORT_FUNCTION<Data_t>(in, out, comm); in=in_cpy; // SORT_FUNCTION<Data_t>(in_cpy, comm); #ifdef __VERIFY__ verify(in,out,comm); #endif //Sort MPI_Barrier(comm); double wtime=-omp_get_wtime(); SORT_FUNCTION<Data_t>(in, out, comm); // SORT_FUNCTION<Data_t>(in, comm); MPI_Barrier(comm); wtime+=omp_get_wtime(); return wtime; } template <class T> double time_sort(size_t N, MPI_Comm comm){ int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); int omp_p=omp_get_max_threads(); // Geerate random data std::vector<T> in(N); #pragma omp parallel for for(int j=0;j<omp_p;j++){ unsigned int seed=j*p+myrank; size_t start=(j*N)/omp_p; size_t end=((j+1)*N)/omp_p; for(unsigned int i=start;i<end;i++){ in[i]=rand_r(&seed); } } // for(unsigned int i=0;i<N;i++) in[i]=binOp::reversibleHash(myrank*i); // std::cout << "finished generating data " << std::endl; std::vector<T> in_cpy=in; std::vector<T> out; // Warmup run and verification. SORT_FUNCTION<T>(in, out, comm); in=in_cpy; // SORT_FUNCTION<T>(in_cpy, comm); #ifdef __VERIFY__ verify(in,out,comm); #endif //Sort MPI_Barrier(comm); double wtime=-omp_get_wtime(); SORT_FUNCTION<T>(in, out, comm); // SORT_FUNCTION<T>(in, comm); MPI_Barrier(comm); wtime+=omp_get_wtime(); return wtime; } int main(int argc, char **argv){ if (argc < 3) { std::cerr << "Usage: " << argv[0] << " numThreads typeSize" << std::endl; std::cerr << "\t\t typeSize is a character for type of data follwed by data size per node." << std::endl; std::cerr << "\t\t typeSize can be d-double, f-float, i-int, l-long, t-TreeNode or x-100byte record." << std::endl; std::cerr << "\t\t Examples:" << std::endl; std::cerr << "\t\t i1GB : integer array of size 1GB" << std::endl; std::cerr << "\t\t l1GB : long array of size 1GB" << std::endl; std::cerr << "\t\t t1GB : TreeNode array of size 1GB" << std::endl; std::cerr << "\t\t x4GB : 100byte array of size 4GB" << std::endl; return 1; } std::cout<<setiosflags(std::ios::fixed)<<std::setprecision(4)<<std::setiosflags(std::ios::right); //Set number of OpenMP threads to use. omp_set_num_threads(atoi(argv[1])); // Initialize MPI MPI_Init(&argc, &argv); // Find out my identity in the default communicator int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); // Find out number of processes int p; MPI_Comm_size(MPI_COMM_WORLD, &p); int proc_group=0; int min_np=1; MPI_Comm comm; for(int i=p;myrank<i && i>=min_np ;i=i>>1) proc_group++; MPI_Comm_split(MPI_COMM_WORLD, proc_group, myrank, &comm); std::vector<double> tt(10000,0); int k = 0; // in case size based runs are needed char dtype = argv[2][0]; long N = getNumElements(argv[2]); if (!N) { std::cerr << "illegal typeSize code provided: " << argv[2] << std::endl; return 2; } if (!myrank) std::cout << "sorting array of size " << N*p << " of type " << dtype << std::endl; // check if arguments are ok ... { // -- full size run double ttt; switch(dtype) { case 'd': ttt = time_sort<double>(N, MPI_COMM_WORLD); break; case 'f': ttt = time_sort<float>(N, MPI_COMM_WORLD); break; case 'i': ttt = time_sort<int>(N, MPI_COMM_WORLD); break; case 'l': ttt = time_sort<long>(N, MPI_COMM_WORLD); break; case 't': ttt = time_sort_tn(N, MPI_COMM_WORLD); break; case 'x': ttt = time_sort_bench(N, MPI_COMM_WORLD); break; }; if(!myrank){ tt[100*k+0]=ttt; } } { // smaller /2^k runs int myrank_; MPI_Comm_rank(comm, &myrank_); double ttt; switch(dtype) { case 'd': ttt = time_sort<double>(N, comm); break; case 'f': ttt = time_sort<float>(N, comm); break; case 'i': ttt = time_sort<int>(N, comm); break; case 'l': ttt = time_sort<long>(N, comm); break; case 't': ttt = time_sort_tn(N, comm); break; case 'x': ttt = time_sort_bench(N, comm); break; }; if(!myrank_){ tt[100*k+proc_group]=ttt; } } std::vector<double> tt_glb(10000); MPI_Reduce(&tt[0], &tt_glb[0], 10000, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if(!myrank){ std::cout<<"\nNew Sort:\n"; for(int i=0;i<proc_group;i++){ int np=p; if(i>0) np=(p>>(i-1))-(p>>i); std::cout<<"\tP="<<np<<' '; // for(int k=0;k<=log_N;k++) std::cout<<tt_glb[100*k+i]<<' '; std::cout<<'\n'; } } // Shut down MPI MPI_Finalize(); return 0; } <commit_msg>changes to test selection and kway. Do not use this version for runs<commit_after>#include <iomanip> #include <cstdio> #include <cstdlib> #include <iostream> #include <vector> #include <omp.h> #include <sstream> #include <binUtils.h> #include <ompUtils.h> #include <parUtils.h> #include <octUtils.h> #include <TreeNode.h> #include <gensort.h> #include <sortRecord.h> #define MAX_DEPTH 30 #define SORT_FUNCTION par::HyperQuickSort // #define SORT_FUNCTION par::sampleSort // #define __VERIFY__ long getNumElements(char* code) { unsigned int slen = strlen(code); char dtype = code[0]; char tmp[128]; strncpy(tmp, code+1, slen-3); tmp[slen-3] = '\0'; // std::cout << "tmp is " << tmp << std::endl; long numBytes = atoi(tmp); switch(code[slen-2]) { case 'g': case 'G': numBytes *= 1024*1024*1024; break; case 'k': case 'K': numBytes *= 1024; break; case 'm': case 'M': numBytes *= 1024*1024; break; default: // std::cout << "unknown code " << code[slen-2] << std::endl; return 0; }; switch (dtype) { case 'd': // double array return numBytes/sizeof(double); break; case 'f': // float array return numBytes/sizeof(float); break; case 'i': // int array return numBytes/sizeof(int); break; case 'l': // long array return numBytes/sizeof(long); break; case 't': // treenode return numBytes/sizeof(ot::TreeNode); break; case 'x': // gensort record return numBytes/sizeof(sortRecord); break; default: return 0; }; } template <class T> bool verify(std::vector<T>& in_, std::vector<T> &out_, MPI_Comm comm){ // Find out my identity in the default communicator int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); std::vector<T> in; { int N_local=in_.size()*sizeof(T); std::vector<int> r_size(p, 0); std::vector<int> r_disp(p, 0); MPI_Gather(&N_local , 1, MPI_INT, &r_size[0], 1, MPI_INT, 0, comm); omp_par::scan(&r_size[0], &r_disp[0], p); if(!myrank) in.resize((r_size[p-1]+r_disp[p-1])/sizeof(T)); MPI_Gatherv((char*)&in_[0], N_local, MPI_BYTE, (char*)&in [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm); } std::vector<T> out; { int N_local=out_.size()*sizeof(T); std::vector<int> r_size(p, 0); std::vector<int> r_disp(p, 0); MPI_Gather(&N_local , 1, MPI_INT, &r_size[0], 1, MPI_INT, 0, comm); omp_par::scan(&r_size[0], &r_disp[0], p); if(!myrank) out.resize((r_size[p-1]+r_disp[p-1])/sizeof(T)); MPI_Gatherv((char*)&out_[0], N_local, MPI_BYTE, (char*)&out [0], &r_size[0], &r_disp[0], MPI_BYTE, 0, comm); } if(in.size()!=out.size()){ std::cout<<"Wrong size: in="<<in.size()<<" out="<<out.size()<<'\n'; return false; } std::sort(&in[0], &in[in.size()]); for(long j=0;j<in.size();j++) if(in[j]!=out[j]){ std::cout<<"Failed at:"<<j<<'\n'; // std::cout<<"Failed at:"<<j<<"; in="<<in[j]<<" out="<<out[j]<<'\n'; return false; } return true; } double time_sort_bench(size_t N, MPI_Comm comm) { int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); typedef sortRecord Data_t; std::vector<Data_t> in(N); genRecords((char* )&(*(in.begin())), myrank, N); std::vector<Data_t> in_cpy=in; std::vector<Data_t> out; // Warmup run and verification. SORT_FUNCTION<Data_t>(in, out, comm); // SORT_FUNCTION<Data_t>(in_cpy, comm); in=in_cpy; #ifdef __VERIFY__ verify(in,out,comm); #endif //Sort MPI_Barrier(comm); double wtime=-omp_get_wtime(); SORT_FUNCTION<Data_t>(in, out, comm); // SORT_FUNCTION<Data_t>(in, comm); MPI_Barrier(comm); wtime+=omp_get_wtime(); return wtime; } double time_sort_tn(size_t N, MPI_Comm comm) { int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); int omp_p=omp_get_max_threads(); typedef ot::TreeNode Data_t; std::vector<Data_t> in(N); unsigned int s = (1u << MAX_DEPTH); #pragma omp parallel for for(int j=0;j<omp_p;j++){ unsigned int seed=j*p+myrank; size_t start=(j*N)/omp_p; size_t end=((j+1)*N)/omp_p; for(unsigned int i=start;i<end;i++){ ot::TreeNode node(rand_r(&seed)%s, rand_r(&seed)%s, rand_r(&seed)%s, MAX_DEPTH-1, 3, MAX_DEPTH); // ot::TreeNode node(binOp::reversibleHash(3*i*myrank)%s, binOp::reversibleHash(3*i*myrank+1)%s, binOp::reversibleHash(3*i*myrank+2)%s, MAX_DEPTH-1, 3, MAX_DEPTH); in[i]=node; } } // std::cout << "finished generating data " << std::endl; std::vector<Data_t> in_cpy=in; std::vector<Data_t> out; // Warmup run and verification. SORT_FUNCTION<Data_t>(in, out, comm); in=in_cpy; // SORT_FUNCTION<Data_t>(in_cpy, comm); #ifdef __VERIFY__ verify(in,out,comm); #endif //Sort MPI_Barrier(comm); double wtime=-omp_get_wtime(); SORT_FUNCTION<Data_t>(in, out, comm); // SORT_FUNCTION<Data_t>(in, comm); MPI_Barrier(comm); wtime+=omp_get_wtime(); return wtime; } template <class T> double time_sort(size_t N, MPI_Comm comm){ int myrank, p; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm,&p); int omp_p=omp_get_max_threads(); // Geerate random data std::vector<T> in(N); #pragma omp parallel for for(int j=0;j<omp_p;j++){ unsigned int seed=j*p+myrank; size_t start=(j*N)/omp_p; size_t end=((j+1)*N)/omp_p; for(unsigned int i=start;i<end;i++){ in[i]=rand_r(&seed); } } // for(unsigned int i=0;i<N;i++) in[i]=binOp::reversibleHash(myrank*i); // std::cout << "finished generating data " << std::endl; std::vector<T> in_cpy=in; std::vector<T> out; unsigned int kway = 7; DendroIntL Nglobal=p*N; std::vector<unsigned int> min_idx(kway), max_idx(kway); std::vector<DendroIntL> K(kway); for(size_t i = 0; i < kway; ++i) { min_idx[i] = 0; max_idx[i] = N; K[i] = (Nglobal*(i+1))/(kway+1); } std::sort(in.begin(), in.end()); double tselect =- omp_get_wtime(); std::vector<T> guess = par::GuessRangeMedian<T>(in, min_idx, max_idx, comm); std::vector<T> slct = par::Sorted_k_Select<T>(in, min_idx, max_idx, K, guess, comm); tselect += omp_get_wtime(); double pselect =- omp_get_wtime(); std::vector<T> pslct = par::Sorted_approx_Select(in, kway, comm); pselect += omp_get_wtime(); if (!myrank) { for(size_t i = 0; i < kway; ++i) { std::cout << slct[i] << " " << pslct[i] << std::endl; } std::cout << "times: " << tselect << " " << pselect << std::endl; } return 0.0; // Warmup run and verification. SORT_FUNCTION<T>(in, out, comm); in=in_cpy; // SORT_FUNCTION<T>(in_cpy, comm); #ifdef __VERIFY__ verify(in,out,comm); #endif //Sort MPI_Barrier(comm); double wtime=-omp_get_wtime(); SORT_FUNCTION<T>(in, out, comm); // SORT_FUNCTION<T>(in, comm); MPI_Barrier(comm); wtime+=omp_get_wtime(); return wtime; } int main(int argc, char **argv){ if (argc < 3) { std::cerr << "Usage: " << argv[0] << " numThreads typeSize" << std::endl; std::cerr << "\t\t typeSize is a character for type of data follwed by data size per node." << std::endl; std::cerr << "\t\t typeSize can be d-double, f-float, i-int, l-long, t-TreeNode or x-100byte record." << std::endl; std::cerr << "\t\t Examples:" << std::endl; std::cerr << "\t\t i1GB : integer array of size 1GB" << std::endl; std::cerr << "\t\t l1GB : long array of size 1GB" << std::endl; std::cerr << "\t\t t1GB : TreeNode array of size 1GB" << std::endl; std::cerr << "\t\t x4GB : 100byte array of size 4GB" << std::endl; return 1; } std::cout<<setiosflags(std::ios::fixed)<<std::setprecision(4)<<std::setiosflags(std::ios::right); //Set number of OpenMP threads to use. omp_set_num_threads(atoi(argv[1])); // Initialize MPI MPI_Init(&argc, &argv); // Find out my identity in the default communicator int myrank; MPI_Comm_rank(MPI_COMM_WORLD, &myrank); // Find out number of processes int p; MPI_Comm_size(MPI_COMM_WORLD, &p); int proc_group=0; int min_np=1; MPI_Comm comm; for(int i=p;myrank<i && i>=min_np ;i=i>>1) proc_group++; MPI_Comm_split(MPI_COMM_WORLD, proc_group, myrank, &comm); std::vector<double> tt(10000,0); int k = 0; // in case size based runs are needed char dtype = argv[2][0]; long N = getNumElements(argv[2]); if (!N) { std::cerr << "illegal typeSize code provided: " << argv[2] << std::endl; return 2; } if (!myrank) std::cout << "sorting array of size " << N*p << " of type " << dtype << std::endl; // check if arguments are ok ... { // -- full size run double ttt; switch(dtype) { case 'd': ttt = time_sort<double>(N, MPI_COMM_WORLD); break; case 'f': ttt = time_sort<float>(N, MPI_COMM_WORLD); break; case 'i': ttt = time_sort<int>(N, MPI_COMM_WORLD); break; case 'l': ttt = time_sort<long>(N, MPI_COMM_WORLD); break; case 't': ttt = time_sort_tn(N, MPI_COMM_WORLD); break; case 'x': ttt = time_sort_bench(N, MPI_COMM_WORLD); break; }; if(!myrank){ tt[100*k+0]=ttt; } } MPI_Finalize(); return 0; { // smaller /2^k runs int myrank_; MPI_Comm_rank(comm, &myrank_); double ttt; switch(dtype) { case 'd': ttt = time_sort<double>(N, comm); break; case 'f': ttt = time_sort<float>(N, comm); break; case 'i': ttt = time_sort<int>(N, comm); break; case 'l': ttt = time_sort<long>(N, comm); break; case 't': ttt = time_sort_tn(N, comm); break; case 'x': ttt = time_sort_bench(N, comm); break; }; if(!myrank_){ tt[100*k+proc_group]=ttt; } } std::vector<double> tt_glb(10000); MPI_Reduce(&tt[0], &tt_glb[0], 10000, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if(!myrank){ std::cout<<"\nNew Sort:\n"; for(int i=0;i<proc_group;i++){ int np=p; if(i>0) np=(p>>(i-1))-(p>>i); std::cout<<"\tP="<<np<<' '; // for(int k=0;k<=log_N;k++) std::cout<<tt_glb[100*k+i]<<' '; std::cout<<'\n'; } } // Shut down MPI MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>/* * StepParameters.hpp * * Created on: Feb 18, 2016 * Author: Péter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #pragma once #include "free_gait_core/TypeDefs.hpp" #include "free_gait_core/step/StepCompleter.hpp" namespace free_gait { class StepParameters { public: StepParameters() {} virtual ~StepParameters() {}; friend class StepCompleter; protected: struct FootstepParameters { std::string profileType = "triangle"; double profileHeight = 0.05; double averageVelocity = 0.3; double liftOffSpeed = 0.05; double touchdownSpeed = 0.07; double minimumDuration_ = 0.3; } footTargetParameters; struct EndEffectorTargetParameters { double averageVelocity = 0.15; double minimumDuration_ = 0.1; } endEffectorTargetParameters; struct LegModeParameters { double duration = 0.5; std::string frameId = "base"; } legModeParameters; struct BaseAutoParameters { double averageLinearVelocity = 0.14; double averageAngularVelocity = 0.25; double supportMargin = 0.05; double minimumDuration = 0.4; PlanarStance nominalPlanarStanceInBaseFrame; BaseAutoParameters() { Position2 position; position << 0.385, 0.25; nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LF_LEG, position); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RF_LEG, Position2(Eigen::Vector2d(position(0), -position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LH_LEG, Position2(Eigen::Vector2d(-position(0), position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RH_LEG, Position2(Eigen::Vector2d(-position(0), -position(1)))); } } baseAutoParameters; struct BaseTargetParameters { double averageLinearVelocity = 0.05; double averageAngularVelocity = 0.1; double minimumDuration = 0.7; } baseTargetParameters; struct BaseTrajectoryParameters { BaseTrajectoryParameters() { } } baseTrajectoryParameters; }; } /* namespace */ <commit_msg>Increased speed of footstep and base auto.<commit_after>/* * StepParameters.hpp * * Created on: Feb 18, 2016 * Author: Péter Fankhauser * Institute: ETH Zurich, Autonomous Systems Lab */ #pragma once #include "free_gait_core/TypeDefs.hpp" #include "free_gait_core/step/StepCompleter.hpp" namespace free_gait { class StepParameters { public: StepParameters() {} virtual ~StepParameters() {}; friend class StepCompleter; protected: struct FootstepParameters { std::string profileType = "triangle"; double profileHeight = 0.065; double averageVelocity = 0.5; double liftOffSpeed = 0.06; double touchdownSpeed = 0.08; double minimumDuration_ = 0.2; } footTargetParameters; struct EndEffectorTargetParameters { double averageVelocity = 0.15; double minimumDuration_ = 0.1; } endEffectorTargetParameters; struct LegModeParameters { double duration = 0.5; std::string frameId = "base"; } legModeParameters; struct BaseAutoParameters { double averageLinearVelocity = 0.18; double averageAngularVelocity = 0.32; double supportMargin = 0.05; double minimumDuration = 0.3; PlanarStance nominalPlanarStanceInBaseFrame; BaseAutoParameters() { Position2 position; position << 0.385, 0.25; nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LF_LEG, position); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RF_LEG, Position2(Eigen::Vector2d(position(0), -position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::LH_LEG, Position2(Eigen::Vector2d(-position(0), position(1)))); nominalPlanarStanceInBaseFrame.emplace(LimbEnum::RH_LEG, Position2(Eigen::Vector2d(-position(0), -position(1)))); } } baseAutoParameters; struct BaseTargetParameters { double averageLinearVelocity = 0.05; double averageAngularVelocity = 0.1; double minimumDuration = 0.7; } baseTargetParameters; struct BaseTrajectoryParameters { BaseTrajectoryParameters() { } } baseTrajectoryParameters; }; } /* namespace */ <|endoftext|>
<commit_before>#include "UDLR.h" UDLR::UDLR(std::shared_ptr<Ps3Controller>& _controller) : controller(_controller) { constexpr int width = 40; constexpr int height = 60; constexpr int padding = 15; UButton.addVertex(ofVec3f(0, padding)); UButton.addVertex(ofVec3f(width/2, padding + height - width)); UButton.addVertex(ofVec3f(width/2, padding + height)); UButton.addVertex(ofVec3f(-1*width/2, padding + height)); UButton.addVertex(ofVec3f(-1*width/2, padding + height - width)); } UDLR::~UDLR() { } const ofColor& UDLR::getColor(const float& val) { static ofColor c; c.set(val, val, val); return c; } void UDLR::draw() { using v = Ps3Controller::CVal; ofPushStyle(); ofPushMatrix(); ofFill(); ofSetColor(getColor(controller->getCVal(v::D))); UButton.draw(); ofRotateDeg(90); ofSetColor(getColor(controller->getCVal(v::L))); UButton.draw(); ofRotateDeg(90); ofSetColor(getColor(controller->getCVal(v::U))); UButton.draw(); ofRotateDeg(90); ofSetColor(getColor(controller->getCVal(v::R))); UButton.draw(); ofPopMatrix(); ofPopStyle(); } <commit_msg>less wrong<commit_after>#include "UDLR.h" UDLR::UDLR(std::shared_ptr<Ps3Controller>& _controller) : controller(_controller) { constexpr int width = 40; constexpr int height = 60; constexpr int padding = 15; UButton.addVertex(ofVec3f(0, padding)); UButton.addVertex(ofVec3f(width/2, padding + height - width)); UButton.addVertex(ofVec3f(width/2, padding + height)); UButton.addVertex(ofVec3f(-1*width/2, padding + height)); UButton.addVertex(ofVec3f(-1*width/2, padding + height - width)); UButton.addIndex(0); UButton.addIndex(1); UButton.addIndex(4); UButton.addIndex(1); UButton.addIndex(2); UButton.addIndex(3); UButton.addIndex(3); UButton.addIndex(4); UButton.addIndex(1); } UDLR::~UDLR() { } const ofColor& UDLR::getColor(const float& val) { static ofColor c; c.set(val, val, val); return c; } void UDLR::draw() { using v = Ps3Controller::CVal; ofPushStyle(); ofPushMatrix(); ofFill(); ofSetColor(getColor(controller->getCVal(v::D))); UButton.draw(); ofRotateDeg(90); ofSetColor(getColor(controller->getCVal(v::L))); UButton.draw(); ofRotateDeg(90); ofSetColor(getColor(controller->getCVal(v::U))); UButton.draw(); ofRotateDeg(90); ofSetColor(getColor(controller->getCVal(v::R))); UButton.draw(); ofPopMatrix(); ofPopStyle(); } <|endoftext|>
<commit_before>#include "User.hpp" #include "Network.hpp" #include "PawnDispatcher.hpp" #include "PawnCallback.hpp" #include "CLog.hpp" #include "utils.hpp" User::User(UserId_t pawn_id, json &data) : m_PawnId(pawn_id) { if (!utils::TryGetJsonValue(data, m_Id, "id")) { CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"id\" in \"{}\"", data.dump()); return; } Update(data); } void User::Update(json &data) { _valid = utils::TryGetJsonValue(data, m_Username, "username") && utils::TryGetJsonValue(data, m_Discriminator, "discriminator"); if (!_valid) { CLog::Get()->Log(LogLevel::ERROR, "can't update user: invalid JSON: \"{}\"", data.dump()); return; } utils::TryGetJsonValue(data, m_IsBot, "bot"); utils::TryGetJsonValue(data, m_IsVerified, "verified"); utils::TryGetJsonValue(data, m_Email, "email"); } void UserManager::Initialize() { assert(m_Initialized != m_InitValue); Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data) { if (!utils::IsValidJson(data, "user", json::value_t::object)) { // TODO: should be loglevel fatal CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"user\" in \"{}\"", data.dump()); return; } AddUser(data["user"]); // that's our bot m_Initialized++; }); Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::USER_UPDATE, [](json &data) { Snowflake_t user_id; if (!utils::TryGetJsonValue(data, user_id, "id")) { CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"id\" in \"{}\"", data.dump()); } PawnDispatcher::Get()->Dispatch([data, user_id]() mutable { auto const &user = UserManager::Get()->FindUserById(user_id); if (!user) { CLog::Get()->Log(LogLevel::ERROR, "can't update user: user id \"{}\" not cached", user_id); return; } user->Update(data); // forward DCC_OnUserUpdate(DCC_User:user); PawnCallbackManager::Get()->Call("DCC_OnUserUpdate", user->GetPawnId()); }); }); } bool UserManager::WaitForInitialization() { unsigned int const SLEEP_TIME_MS = 20, TIMEOUT_TIME_MS = 20 * 1000; unsigned int waited_time = 0; while (m_Initialized != m_InitValue) { std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS)); waited_time += SLEEP_TIME_MS; if (waited_time > TIMEOUT_TIME_MS) return false; } return true; } UserId_t UserManager::AddUser(json &data) { Snowflake_t sfid; if (!utils::TryGetJsonValue(data, sfid, "id")) { CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"id\" in \"{}\"", data.dump()); return INVALID_USER_ID; } User_t const &user = FindUserById(sfid); if (user) { CLog::Get()->Log(LogLevel::ERROR, "can't add user: user id \"{}\" already exists (PAWN id '{}')", sfid, user->GetPawnId()); return INVALID_USER_ID; } UserId_t id = 1; while (m_Users.find(id) != m_Users.end()) ++id; if (!m_Users.emplace(id, User_t(new User(id, data))).first->second) { CLog::Get()->Log(LogLevel::ERROR, "can't create user: duplicate key '{}'", id); return INVALID_USER_ID; } return id; } User_t const &UserManager::FindUser(UserId_t id) { static User_t invalid_user; auto it = m_Users.find(id); if (it == m_Users.end()) return invalid_user; return it->second; } User_t const &UserManager::FindUserByName( std::string const &name, std::string const &discriminator) { static User_t invalid_user; for (auto const &u : m_Users) { User_t const &user = u.second; if (user->GetUsername().compare(name) == 0 && user->GetDiscriminator().compare(discriminator) == 0) { return user; } } return invalid_user; } User_t const &UserManager::FindUserById(Snowflake_t const &sfid) { static User_t invalid_user; for (auto const &u : m_Users) { User_t const &user = u.second; if (user->GetId().compare(sfid) == 0) return user; } return invalid_user; } <commit_msg>return user id if it already exists<commit_after>#include "User.hpp" #include "Network.hpp" #include "PawnDispatcher.hpp" #include "PawnCallback.hpp" #include "CLog.hpp" #include "utils.hpp" User::User(UserId_t pawn_id, json &data) : m_PawnId(pawn_id) { if (!utils::TryGetJsonValue(data, m_Id, "id")) { CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"id\" in \"{}\"", data.dump()); return; } Update(data); } void User::Update(json &data) { _valid = utils::TryGetJsonValue(data, m_Username, "username") && utils::TryGetJsonValue(data, m_Discriminator, "discriminator"); if (!_valid) { CLog::Get()->Log(LogLevel::ERROR, "can't update user: invalid JSON: \"{}\"", data.dump()); return; } utils::TryGetJsonValue(data, m_IsBot, "bot"); utils::TryGetJsonValue(data, m_IsVerified, "verified"); utils::TryGetJsonValue(data, m_Email, "email"); } void UserManager::Initialize() { assert(m_Initialized != m_InitValue); Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::READY, [this](json &data) { if (!utils::IsValidJson(data, "user", json::value_t::object)) { // TODO: should be loglevel fatal CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"user\" in \"{}\"", data.dump()); return; } AddUser(data["user"]); // that's our bot m_Initialized++; }); Network::Get()->WebSocket().RegisterEvent(WebSocket::Event::USER_UPDATE, [](json &data) { Snowflake_t user_id; if (!utils::TryGetJsonValue(data, user_id, "id")) { CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"id\" in \"{}\"", data.dump()); } PawnDispatcher::Get()->Dispatch([data, user_id]() mutable { auto const &user = UserManager::Get()->FindUserById(user_id); if (!user) { CLog::Get()->Log(LogLevel::ERROR, "can't update user: user id \"{}\" not cached", user_id); return; } user->Update(data); // forward DCC_OnUserUpdate(DCC_User:user); PawnCallbackManager::Get()->Call("DCC_OnUserUpdate", user->GetPawnId()); }); }); } bool UserManager::WaitForInitialization() { unsigned int const SLEEP_TIME_MS = 20, TIMEOUT_TIME_MS = 20 * 1000; unsigned int waited_time = 0; while (m_Initialized != m_InitValue) { std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME_MS)); waited_time += SLEEP_TIME_MS; if (waited_time > TIMEOUT_TIME_MS) return false; } return true; } UserId_t UserManager::AddUser(json &data) { Snowflake_t sfid; if (!utils::TryGetJsonValue(data, sfid, "id")) { CLog::Get()->Log(LogLevel::ERROR, "invalid JSON: expected \"id\" in \"{}\"", data.dump()); return INVALID_USER_ID; } User_t const &user = FindUserById(sfid); if (user) return user->GetPawnId(); UserId_t id = 1; while (m_Users.find(id) != m_Users.end()) ++id; if (!m_Users.emplace(id, User_t(new User(id, data))).first->second) { CLog::Get()->Log(LogLevel::ERROR, "can't create user: duplicate key '{}'", id); return INVALID_USER_ID; } return id; } User_t const &UserManager::FindUser(UserId_t id) { static User_t invalid_user; auto it = m_Users.find(id); if (it == m_Users.end()) return invalid_user; return it->second; } User_t const &UserManager::FindUserByName( std::string const &name, std::string const &discriminator) { static User_t invalid_user; for (auto const &u : m_Users) { User_t const &user = u.second; if (user->GetUsername().compare(name) == 0 && user->GetDiscriminator().compare(discriminator) == 0) { return user; } } return invalid_user; } User_t const &UserManager::FindUserById(Snowflake_t const &sfid) { static User_t invalid_user; for (auto const &u : m_Users) { User_t const &user = u.second; if (user->GetId().compare(sfid) == 0) return user; } return invalid_user; } <|endoftext|>
<commit_before>// Copyright 2014 RethinkDB, all rights reserved. #ifndef CONCURRENCY_NEW_SEMAPHORE_HPP_ #define CONCURRENCY_NEW_SEMAPHORE_HPP_ #include "concurrency/cond_var.hpp" #include "containers/intrusive_list.hpp" // KSI: This is a horrible name, fix it. // This semaphore obeys first-in-line/first-acquisition semantics. The // new_semaphore_acq_t's will receive access to the semaphore in the same order that // such access was requested. Also, there aren't problems with starvation. Also, it // doesn't have naked lock and unlock functions, you have to use new_semaphore_acq_t. class new_semaphore_acq_t; class new_semaphore_t { public: explicit new_semaphore_t(int64_t capacity); ~new_semaphore_t(); int64_t capacity() const { return capacity_; } int64_t current() const { return current_; } void set_capacity(int64_t new_capacity); private: friend class new_semaphore_acq_t; void add_acquirer(new_semaphore_acq_t *acq); void remove_acquirer(new_semaphore_acq_t *acq); void pulse_waiters(); // Normally, current_ <= capacity_, and capacity_ doesn't change. current_ can // exceed capacity_ for three reasons. // 1. A call to change_acquired_count could force it to overflow. // 2. An acquirer will never be blocked while current_ is 0. // 3. An act of God could change capacity_ (currently unimplemented; hail Satan). int64_t capacity_; int64_t current_; intrusive_list_t<new_semaphore_acq_t> waiters_; DISABLE_COPYING(new_semaphore_t); }; class new_semaphore_acq_t : public intrusive_list_node_t<new_semaphore_acq_t> { public: // Construction is non-blocking, it gets you in line for the semaphore. You need // to call acquisition_signal()->wait() in order to wait for your acquisition of the // semaphore. Acquirers receive the semaphore in the same order that they've // acquired it. ~new_semaphore_acq_t(); new_semaphore_acq_t(); new_semaphore_acq_t(new_semaphore_t *semaphore, int64_t count); new_semaphore_acq_t(new_semaphore_acq_t &&movee); // Returns "how much" of the semaphore this acq has acquired or would acquire. int64_t count() const; // Changes "how much" of the semaphore this acq has acquired or would acquire. // If it's already acquired the semaphore, and new_count is bigger than the // current value of acquired_count(), it's possible that you'll make the // semaphore "overfull", meaning that current_ > capacity_. That's not ideal, // but it's O.K. void change_count(int64_t new_count); // Initializes the object. void init(new_semaphore_t *semaphore, int64_t count); void reset(); // Returns a signal that gets pulsed when this has successfully acquired the // semaphore. const signal_t *acquisition_signal() const { return &cond_; } private: friend class new_semaphore_t; // The semaphore this acquires (or NULL if this hasn't acquired a semaphore yet). new_semaphore_t *semaphore_; // The count of "how much" of the semaphore we've acquired (if semaphore_ is // non-NULL). int64_t count_; // Gets pulsed when we have successfully acquired the semaphore. cond_t cond_; DISABLE_COPYING(new_semaphore_acq_t); }; #endif // CONCURRENCY_NEW_SEMAPHORE_HPP_ <commit_msg>Removed KSI about renaming new_semaphore_t.<commit_after>// Copyright 2014 RethinkDB, all rights reserved. #ifndef CONCURRENCY_NEW_SEMAPHORE_HPP_ #define CONCURRENCY_NEW_SEMAPHORE_HPP_ #include "concurrency/cond_var.hpp" #include "containers/intrusive_list.hpp" // This semaphore obeys first-in-line/first-acquisition semantics. The // new_semaphore_acq_t's will receive access to the semaphore in the same order that // such access was requested. Also, there aren't problems with starvation. Also, it // doesn't have naked lock and unlock functions, you have to use new_semaphore_acq_t. class new_semaphore_acq_t; class new_semaphore_t { public: explicit new_semaphore_t(int64_t capacity); ~new_semaphore_t(); int64_t capacity() const { return capacity_; } int64_t current() const { return current_; } void set_capacity(int64_t new_capacity); private: friend class new_semaphore_acq_t; void add_acquirer(new_semaphore_acq_t *acq); void remove_acquirer(new_semaphore_acq_t *acq); void pulse_waiters(); // Normally, current_ <= capacity_, and capacity_ doesn't change. current_ can // exceed capacity_ for three reasons. // 1. A call to change_acquired_count could force it to overflow. // 2. An acquirer will never be blocked while current_ is 0. // 3. An act of God could change capacity_ (currently unimplemented; hail Satan). int64_t capacity_; int64_t current_; intrusive_list_t<new_semaphore_acq_t> waiters_; DISABLE_COPYING(new_semaphore_t); }; class new_semaphore_acq_t : public intrusive_list_node_t<new_semaphore_acq_t> { public: // Construction is non-blocking, it gets you in line for the semaphore. You need // to call acquisition_signal()->wait() in order to wait for your acquisition of the // semaphore. Acquirers receive the semaphore in the same order that they've // acquired it. ~new_semaphore_acq_t(); new_semaphore_acq_t(); new_semaphore_acq_t(new_semaphore_t *semaphore, int64_t count); new_semaphore_acq_t(new_semaphore_acq_t &&movee); // Returns "how much" of the semaphore this acq has acquired or would acquire. int64_t count() const; // Changes "how much" of the semaphore this acq has acquired or would acquire. // If it's already acquired the semaphore, and new_count is bigger than the // current value of acquired_count(), it's possible that you'll make the // semaphore "overfull", meaning that current_ > capacity_. That's not ideal, // but it's O.K. void change_count(int64_t new_count); // Initializes the object. void init(new_semaphore_t *semaphore, int64_t count); void reset(); // Returns a signal that gets pulsed when this has successfully acquired the // semaphore. const signal_t *acquisition_signal() const { return &cond_; } private: friend class new_semaphore_t; // The semaphore this acquires (or NULL if this hasn't acquired a semaphore yet). new_semaphore_t *semaphore_; // The count of "how much" of the semaphore we've acquired (if semaphore_ is // non-NULL). int64_t count_; // Gets pulsed when we have successfully acquired the semaphore. cond_t cond_; DISABLE_COPYING(new_semaphore_acq_t); }; #endif // CONCURRENCY_NEW_SEMAPHORE_HPP_ <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or [email protected]. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or [email protected]. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "image.h" #include <sys/procfs.h> // for /proc calls #include <sys/mman.h> // for mmap() test #include "condor_debug.h" #include "condor_syscalls.h" /* a few notes: * this is a pretty rough port * * data_start_addr() is basically an educated guess based on dump(1) * it is probably not entirely correct, but does seem to work! * * stack_end_addr() is generally well known for sparc machines * however it doesn't seem to appear in solaris header files * * JmpBufSP_Index() was derived by dumping the jmp_buf, allocating a * large chunk of memory on the stack, and dumping the jmp_buf again * whichever value changed by about sizeof(chuck) is the stack pointer * */ /* Return starting address of the data segment */ #if defined(X86) #include <sys/elf_386.h> #else #include <sys/elf_SPARC.h> #endif extern int _etext; long data_start_addr() { #if defined(X86) return ( (((long)&_etext) + ELF_386_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1); #else return ( (((long)&_etext) + ELF_SPARC_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1); #endif } /* Return ending address of the data segment */ long data_end_addr() { return (long)sbrk(0); } /* Return TRUE if the stack grows toward lower addresses, and FALSE otherwise. */ BOOL StackGrowsDown() { return TRUE; } /* Return the index into the jmp_buf where the stack pointer is stored. Expect that the jmp_buf will be viewed as an array of integers for this. */ int JmpBufSP_Index() { #if defined(X86) return 4; #else return 1; #endif } /* Return starting address of stack segment. */ long stack_start_addr() { long answer; jmp_buf env; (void)SETJMP( env ); return JMP_BUF_SP(env) & ~1023; // Curr sp, rounded down } /* Return ending address of stack segment. */ long stack_end_addr() { /* return 0xF8000000; -- for sun4[c] */ #if defined(X86) return 0x8048000; /* -- for x86 */ #else #if defined(Solaris27) return 0xFFBF0000; #else return 0xF0000000; #endif #endif } /* Patch any registers whose values should be different at restart time than they were at checkpoint time. */ void patch_registers( void *generic_ptr ) { // Nothing needed } // static prmap_t *my_map = NULL; static prmap_t my_map[ MAX_SEGS ]; static int prmap_count = 0; static int text_loc = -1, stack_loc = -1, heap_loc = -1; // static int mmap_loc = -1; /* Find the segment in my_map which contains the address in addr. Used to find the text segment. */ int find_map_for_addr(caddr_t addr) { int i; for (i = 0; i < prmap_count; i++) { if (addr >= my_map[i].pr_vaddr && addr <= my_map[i].pr_vaddr + my_map[i].pr_size){ return i; } } return -1; } /* Return the number of segments to be checkpointed. Note that this number includes the text segment, which should be ignored. On error, returns -1. */ extern "C" int SYSCALL(int ...); int num_segments( ) { int fd; char buf[100]; int scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED ); sprintf(buf, "/proc/%d", SYSCALL(SYS_getpid)); fd = SYSCALL(SYS_open, buf, O_RDWR, 0); if (fd < 0) { return -1; } SYSCALL(SYS_ioctl, fd, PIOCNMAP, &prmap_count); if (prmap_count > MAX_SEGS) { dprintf( D_ALWAYS, "Don't know how to grow segment map yet!\n" ); Suicide(); } /* if (my_map != NULL) { free(my_map); } my_map = (prmap_t *) malloc(sizeof(prmap_t) * (prmap_count + 1)); */ SYSCALL(SYS_ioctl, fd, PIOCMAP, my_map); /* find the text segment by finding where this function is located */ text_loc = find_map_for_addr((caddr_t) num_segments); /* identify the stack segment by looking for the bottom of the stack, because the top of the stack may be in the data area, often the case for programs which utilize threads or co-routine packages. */ if ( StackGrowsDown() ) stack_loc = find_map_for_addr((caddr_t) stack_end_addr()); else stack_loc = find_map_for_addr((caddr_t) stack_start_addr()); heap_loc = find_map_for_addr((caddr_t) data_start_addr()); // mmap_loc = find_map_for_addr((caddr_t) mmap); if (SYSCALL(SYS_close, fd) < 0) { dprintf(D_ALWAYS, "close: %s", strerror(errno)); } SetSyscalls( scm ); return prmap_count; } /* Assigns the bounds of the segment specified by seg_num to start and long, and the protections to prot. Returns -1 on error, 1 if this segment is the text segment, 2 if this segment is the stack segment, 3 if this segment is in the data segment, and 0 otherwise. */ int segment_bounds( int seg_num, RAW_ADDR &start, RAW_ADDR &end, int &prot ) { if (my_map == NULL) return -1; start = (long) my_map[seg_num].pr_vaddr; end = start + my_map[seg_num].pr_size; prot = my_map[seg_num].pr_mflags; // if (seg_num == mmap_loc) // fprintf(stderr, "Checkpointing segment containing mmap.\n" // "Segment %d (0x%x - 0x%x) contains mmap.\n", // seg_num, my_map[seg_num].pr_vaddr, // my_map[seg_num].pr_vaddr+my_map[seg_num].pr_size); if (seg_num == text_loc) return 1; else if (seg_num == stack_loc) return 2; else if (seg_num == heap_loc || ((unsigned)my_map[seg_num].pr_vaddr >= (unsigned)data_start_addr() && (unsigned)my_map[seg_num].pr_vaddr <= (unsigned)data_end_addr())) return 3; return 0; } struct ma_flags { int flag_val; char *flag_name; } MA_FLAGS[] = {{MA_READ, "MA_READ"}, {MA_WRITE, "MA_WRITE"}, {MA_EXEC, "MA_EXEC"}, {MA_SHARED, "MA_SHARED"}, {MA_BREAK, "MA_BREAK"}, {MA_STACK, "MA_STACK"}}; /* For use in debugging only. Displays the segment map of the current process. */ void display_prmap() { int i, j; num_segments(); for (i = 0; i < prmap_count; i++) { dprintf( D_ALWAYS, "addr = 0x%p, size = 0x%x, offset = 0x%x", my_map[i].pr_vaddr, my_map[i].pr_size, my_map[i].pr_off); for (j = 0; j < sizeof(MA_FLAGS) / sizeof(MA_FLAGS[0]); j++) { if (my_map[i].pr_mflags & MA_FLAGS[j].flag_val) { dprintf( D_ALWAYS, " %s", MA_FLAGS[j].flag_name); } } dprintf( D_ALWAYS, "\n"); } } <commit_msg>Updated the top stack pointer for solaris 2.8.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or [email protected]. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or [email protected]. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "image.h" #include <sys/procfs.h> // for /proc calls #include <sys/mman.h> // for mmap() test #include "condor_debug.h" #include "condor_syscalls.h" /* a few notes: * this is a pretty rough port * * data_start_addr() is basically an educated guess based on dump(1) * it is probably not entirely correct, but does seem to work! * * stack_end_addr() is generally well known for sparc machines * however it doesn't seem to appear in solaris header files * * JmpBufSP_Index() was derived by dumping the jmp_buf, allocating a * large chunk of memory on the stack, and dumping the jmp_buf again * whichever value changed by about sizeof(chuck) is the stack pointer * */ /* Return starting address of the data segment */ #if defined(X86) #include <sys/elf_386.h> #else #include <sys/elf_SPARC.h> #endif extern int _etext; long data_start_addr() { #if defined(X86) return ( (((long)&_etext) + ELF_386_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1); #else return ( (((long)&_etext) + ELF_SPARC_MAXPGSZ) + 0x8 - 1 ) & ~(0x8-1); #endif } /* Return ending address of the data segment */ long data_end_addr() { return (long)sbrk(0); } /* Return TRUE if the stack grows toward lower addresses, and FALSE otherwise. */ BOOL StackGrowsDown() { return TRUE; } /* Return the index into the jmp_buf where the stack pointer is stored. Expect that the jmp_buf will be viewed as an array of integers for this. */ int JmpBufSP_Index() { #if defined(X86) return 4; #else return 1; #endif } /* Return starting address of stack segment. */ long stack_start_addr() { long answer; jmp_buf env; (void)SETJMP( env ); return JMP_BUF_SP(env) & ~1023; // Curr sp, rounded down } /* Return ending address of stack segment. */ long stack_end_addr() { /* return 0xF8000000; -- for sun4[c] */ #if defined(X86) return 0x8048000; /* -- for x86 */ #else #if defined(Solaris27) || defined(Solaris28) return 0xFFBF0000; #else return 0xF0000000; #endif #endif } /* Patch any registers whose values should be different at restart time than they were at checkpoint time. */ void patch_registers( void *generic_ptr ) { // Nothing needed } // static prmap_t *my_map = NULL; static prmap_t my_map[ MAX_SEGS ]; static int prmap_count = 0; static int text_loc = -1, stack_loc = -1, heap_loc = -1; // static int mmap_loc = -1; /* Find the segment in my_map which contains the address in addr. Used to find the text segment. */ int find_map_for_addr(caddr_t addr) { int i; for (i = 0; i < prmap_count; i++) { if (addr >= my_map[i].pr_vaddr && addr <= my_map[i].pr_vaddr + my_map[i].pr_size){ return i; } } return -1; } /* Return the number of segments to be checkpointed. Note that this number includes the text segment, which should be ignored. On error, returns -1. */ extern "C" int SYSCALL(int ...); int num_segments( ) { int fd; char buf[100]; int scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED ); sprintf(buf, "/proc/%d", SYSCALL(SYS_getpid)); fd = SYSCALL(SYS_open, buf, O_RDWR, 0); if (fd < 0) { return -1; } SYSCALL(SYS_ioctl, fd, PIOCNMAP, &prmap_count); if (prmap_count > MAX_SEGS) { dprintf( D_ALWAYS, "Don't know how to grow segment map yet!\n" ); Suicide(); } /* if (my_map != NULL) { free(my_map); } my_map = (prmap_t *) malloc(sizeof(prmap_t) * (prmap_count + 1)); */ SYSCALL(SYS_ioctl, fd, PIOCMAP, my_map); /* find the text segment by finding where this function is located */ text_loc = find_map_for_addr((caddr_t) num_segments); /* identify the stack segment by looking for the bottom of the stack, because the top of the stack may be in the data area, often the case for programs which utilize threads or co-routine packages. */ if ( StackGrowsDown() ) stack_loc = find_map_for_addr((caddr_t) stack_end_addr()); else stack_loc = find_map_for_addr((caddr_t) stack_start_addr()); heap_loc = find_map_for_addr((caddr_t) data_start_addr()); // mmap_loc = find_map_for_addr((caddr_t) mmap); if (SYSCALL(SYS_close, fd) < 0) { dprintf(D_ALWAYS, "close: %s", strerror(errno)); } SetSyscalls( scm ); return prmap_count; } /* Assigns the bounds of the segment specified by seg_num to start and long, and the protections to prot. Returns -1 on error, 1 if this segment is the text segment, 2 if this segment is the stack segment, 3 if this segment is in the data segment, and 0 otherwise. */ int segment_bounds( int seg_num, RAW_ADDR &start, RAW_ADDR &end, int &prot ) { if (my_map == NULL) return -1; start = (long) my_map[seg_num].pr_vaddr; end = start + my_map[seg_num].pr_size; prot = my_map[seg_num].pr_mflags; // if (seg_num == mmap_loc) // fprintf(stderr, "Checkpointing segment containing mmap.\n" // "Segment %d (0x%x - 0x%x) contains mmap.\n", // seg_num, my_map[seg_num].pr_vaddr, // my_map[seg_num].pr_vaddr+my_map[seg_num].pr_size); if (seg_num == text_loc) return 1; else if (seg_num == stack_loc) return 2; else if (seg_num == heap_loc || ((unsigned)my_map[seg_num].pr_vaddr >= (unsigned)data_start_addr() && (unsigned)my_map[seg_num].pr_vaddr <= (unsigned)data_end_addr())) return 3; return 0; } struct ma_flags { int flag_val; char *flag_name; } MA_FLAGS[] = {{MA_READ, "MA_READ"}, {MA_WRITE, "MA_WRITE"}, {MA_EXEC, "MA_EXEC"}, {MA_SHARED, "MA_SHARED"}, {MA_BREAK, "MA_BREAK"}, {MA_STACK, "MA_STACK"}}; /* For use in debugging only. Displays the segment map of the current process. */ void display_prmap() { int i, j; num_segments(); for (i = 0; i < prmap_count; i++) { dprintf( D_ALWAYS, "addr = 0x%p, size = 0x%x, offset = 0x%x", my_map[i].pr_vaddr, my_map[i].pr_size, my_map[i].pr_off); for (j = 0; j < sizeof(MA_FLAGS) / sizeof(MA_FLAGS[0]); j++) { if (my_map[i].pr_mflags & MA_FLAGS[j].flag_val) { dprintf( D_ALWAYS, " %s", MA_FLAGS[j].flag_name); } } dprintf( D_ALWAYS, "\n"); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vclxaccessiblestatusbar.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:27:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX #define ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX #ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #include <toolkit/awt/vclxaccessiblecomponent.hxx> #endif #include <vector> class StatusBar; // ---------------------------------------------------- // class VCLXAccessibleStatusBar // ---------------------------------------------------- class VCLXAccessibleStatusBar : public VCLXAccessibleComponent { private: typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren; AccessibleChildren m_aAccessibleChildren; StatusBar* m_pStatusBar; protected: void UpdateShowing( sal_Int32 i, sal_Bool bShowing ); void UpdateItemName( sal_Int32 i ); void UpdateItemText( sal_Int32 i ); void InsertChild( sal_Int32 i ); void RemoveChild( sal_Int32 i ); virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); // XComponent virtual void SAL_CALL disposing(); public: VCLXAccessibleStatusBar( VCLXWindow* pVCLXWindow ); ~VCLXAccessibleStatusBar(); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); // XAccessibleContext virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XAccessibleComponent virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); }; #endif // ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.2.44); FILE MERGED 2008/04/01 14:58:50 thb 1.2.44.2: #i85898# Stripping all external header guards 2008/03/28 15:57:46 rt 1.2.44.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vclxaccessiblestatusbar.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX #define ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX #include <toolkit/awt/vclxaccessiblecomponent.hxx> #include <vector> class StatusBar; // ---------------------------------------------------- // class VCLXAccessibleStatusBar // ---------------------------------------------------- class VCLXAccessibleStatusBar : public VCLXAccessibleComponent { private: typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren; AccessibleChildren m_aAccessibleChildren; StatusBar* m_pStatusBar; protected: void UpdateShowing( sal_Int32 i, sal_Bool bShowing ); void UpdateItemName( sal_Int32 i ); void UpdateItemText( sal_Int32 i ); void InsertChild( sal_Int32 i ); void RemoveChild( sal_Int32 i ); virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); // XComponent virtual void SAL_CALL disposing(); public: VCLXAccessibleStatusBar( VCLXWindow* pVCLXWindow ); ~VCLXAccessibleStatusBar(); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); // XAccessibleContext virtual sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); // XAccessibleComponent virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAtPoint( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); }; #endif // ACCESSIBILITY_STANDARD_VCLXACCESSIBLESTATUSBAR_HXX <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../../StroikaPreComp.h" #if qHasFeature_libcurl #include <curl/curl.h> #endif #include "../../../Characters/Format.h" #include "../../../Characters/String_Constant.h" #include "../../../Debug/Trace.h" #include "../../../Execution/Exceptions.h" #include "../HTTP/Methods.h" #include "Client_libcurl.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Foundation::IO::Network::Transfer; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 // Uncomment this line to enable libcurl to print diagnostics to stderr //#define USE_LIBCURL_VERBOSE_ 1 #if qHasFeature_libcurl namespace { struct ModuleInit_ { ModuleInit_ () { ::curl_global_init (CURL_GLOBAL_ALL); } }; ModuleInit_ sIniter_; } #endif #if qHasFeature_libcurl class Connection_LibCurl::Rep_ : public _IRep { public: Connection::Options fOptions; public: Rep_ (const Connection::Options& options) : fOptions (options) { } Rep_ (const Rep_&) = delete; virtual ~Rep_ (); public: nonvirtual Rep_& operator= (const Rep_&) = delete; public: virtual DurationSecondsType GetTimeout () const override; virtual void SetTimeout (DurationSecondsType timeout) override; virtual URL GetURL () const override; virtual void SetURL (const URL& url) override; virtual void Close () override; virtual Response Send (const Request& request) override; private: nonvirtual void MakeHandleIfNeeded_ (); private: static size_t s_RequestPayloadReadHandler_ (char* buffer, size_t size, size_t nitems, void* userP); nonvirtual size_t RequestPayloadReadHandler_ (Byte* buffer, size_t bufSize); private: static size_t s_ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP); nonvirtual size_t ResponseWriteHandler_ (const Byte* ptr, size_t nBytes); private: static size_t s_ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP); nonvirtual size_t ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes); private: void* fCurlHandle_ { nullptr }; string fCURLCacheUTF8_URL_; // cuz of quirky memory management policies of libcurl string fCURLCacheUTF8_Method_; // cuz of quirky memory management policies of libcurl vector<Byte> fUploadData_; size_t fUploadDataCursor_ {}; vector<Byte> fResponseData_; Mapping<String, String> fResponseHeaders_; curl_slist* fSavedHeaders_ { nullptr }; }; #endif #if qHasFeature_libcurl namespace { wstring mkExceptMsg_ (LibCurlException::CURLcode ccode) { return String::FromUTF8 (curl_easy_strerror (static_cast<CURLcode> (ccode))).As<wstring> (); } } /* ******************************************************************************** ************************ Transfer::LibCurlException **************************** ******************************************************************************** */ LibCurlException::LibCurlException (CURLcode ccode) : StringException (mkExceptMsg_ (ccode)) , fCurlCode_ (ccode) { } void LibCurlException::DoThrowIfError (CURLcode status) { if (status != CURLE_OK) { DbgTrace (L"In LibCurlException::DoThrowIfError: throwing status %d (%s)", status, LibCurlException (status).As<String> ().c_str ()); Execution::DoThrow (LibCurlException (status)); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ****************** Transfer::Connection_LibCurl::Rep_ ************************** ******************************************************************************** */ Connection_LibCurl::Rep_::~Rep_ () { if (fCurlHandle_ != nullptr) { curl_easy_cleanup (fCurlHandle_); } if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } } DurationSecondsType Connection_LibCurl::Rep_::GetTimeout () const { AssertNotImplemented (); return 0; } void Connection_LibCurl::Rep_::SetTimeout (DurationSecondsType timeout) { MakeHandleIfNeeded_ (); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_TIMEOUT_MS, static_cast<int> (timeout * 1000))); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CONNECTTIMEOUT_MS, static_cast<int> (timeout * 1000))); } URL Connection_LibCurl::Rep_::GetURL () const { // needs work... - not sure this is safe - may need to cache orig... instead of reparsing... return URL::Parse (String::FromUTF8 (fCURLCacheUTF8_URL_).As<wstring> ()); } void Connection_LibCurl::Rep_::SetURL (const URL& url) { MakeHandleIfNeeded_ (); fCURLCacheUTF8_URL_ = String (url.GetFullURL ()).AsUTF8 (); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace ("Connection_LibCurl::Rep_::SetURL ('%s')", fCURLCacheUTF8_URL_.c_str ()); #endif LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCacheUTF8_URL_.c_str ())); } void Connection_LibCurl::Rep_::Close () { if (fCurlHandle_ != nullptr) { ::curl_easy_cleanup (fCurlHandle_); fCurlHandle_ = nullptr; } } size_t Connection_LibCurl::Rep_::s_RequestPayloadReadHandler_ (char* buffer, size_t size, size_t nitems, void* userP) { return reinterpret_cast<Rep_*> (userP)->RequestPayloadReadHandler_ (reinterpret_cast<Byte*> (buffer), size * nitems); } size_t Connection_LibCurl::Rep_::RequestPayloadReadHandler_ (Byte* buffer, size_t bufSize) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (SDKSTR ("Connection_LibCurl::Rep_::RequestPayloadReadHandler_")); #endif size_t bytes2Copy = fUploadData_.size () - fUploadDataCursor_; bytes2Copy = min (bytes2Copy, bufSize); memcpy (buffer, Traversal::Iterator2Pointer (begin (fUploadData_)) + fUploadDataCursor_, bytes2Copy); fUploadDataCursor_ += bytes2Copy; #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"bufSize = %d, bytes2Copy=%d", bufSize, bytes2Copy); #endif return bytes2Copy; } size_t Connection_LibCurl::Rep_::s_ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<Rep_*> (userP)->ResponseWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t Connection_LibCurl::Rep_::ResponseWriteHandler_ (const Byte* ptr, size_t nBytes) { fResponseData_.insert (fResponseData_.end (), ptr, ptr + nBytes); return nBytes; } size_t Connection_LibCurl::Rep_::s_ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<Rep_*> (userP)->ResponseHeaderWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t Connection_LibCurl::Rep_::ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes) { String from = String::FromUTF8 (reinterpret_cast<const char*> (ptr), reinterpret_cast<const char*> (ptr) + nBytes); String to; size_t i = from.find (':'); if (i != string::npos) { to = from.SubString (i + 1); from = from.SubString (0, i); } from = from.Trim (); to = to.Trim (); fResponseHeaders_.Add (from, to); return nBytes; } Response Connection_LibCurl::Rep_::Send (const Request& request) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (SDKSTR ("Connection_LibCurl::Rep_::Send")); DbgTrace (L"(method='%s')", request.fMethod.c_str ()); #endif MakeHandleIfNeeded_ (); fUploadData_ = request.fData.As<vector<Byte>> (); fUploadDataCursor_ = 0; fResponseData_.clear (); fResponseHeaders_.clear (); //grab useragent from request headers... //curl_easy_setopt (fCurlHandle_, CURLOPT_USERAGENT, "libcurl-agent/1.0"); Mapping<String, String> overrideHeaders = request.fOverrideHeaders; if (fOptions.fAssumeLowestCommonDenominatorHTTPServer) { static const LEGACY_Synchronized<Mapping<String, String>> kSilenceTheseHeaders_ = initializer_list<pair<String, String>> { { String_Constant (L"Expect"), String ()}, { String_Constant (L"Transfer-Encoding"), String ()} }; overrideHeaders = kSilenceTheseHeaders_ + overrideHeaders; } if (request.fMethod == HTTP::Methods::kGet) { if (not fCURLCacheUTF8_Method_.empty ()) { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , nullptr)); fCURLCacheUTF8_Method_.clear (); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPGET, 1)); } else if (request.fMethod == HTTP::Methods::kPost) { if (not fCURLCacheUTF8_Method_.empty ()) { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , nullptr)); fCURLCacheUTF8_Method_.clear (); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_POST, 1)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_POSTFIELDSIZE, fUploadData_.size ())); } else if (request.fMethod == HTTP::Methods::kPut) { if (not fCURLCacheUTF8_Method_.empty ()) { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , nullptr)); fCURLCacheUTF8_Method_.clear (); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_UPLOAD, fUploadData_.empty () ? 0 : 1)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_INFILESIZE , fUploadData_.size ())); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_PUT, 1)); } else { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPGET, 0)); if (not fCURLCacheUTF8_Method_.empty ()) { fCURLCacheUTF8_Method_ = request.fMethod.AsUTF8 (); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , fCURLCacheUTF8_Method_.c_str ())); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , 1)); } // grab initial headers and do POST/etc based on args in request... curl_slist* tmpH = nullptr; for (auto i : overrideHeaders) { tmpH = curl_slist_append (tmpH, (i.fKey + String_Constant (L": ") + i.fValue).AsUTF8 ().c_str ()); } AssertNotNull (fCurlHandle_); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPHEADER, tmpH)); if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } fSavedHeaders_ = tmpH; LibCurlException::DoThrowIfError (:: curl_easy_perform (fCurlHandle_)); long resultCode = 0; LibCurlException::DoThrowIfError (::curl_easy_getinfo (fCurlHandle_, CURLINFO_RESPONSE_CODE, &resultCode)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"returning status = %d, dataLen = %d", resultCode, fResponseData_.size ()); #endif return Response (move (fResponseData_), resultCode, move (fResponseHeaders_)); } void Connection_LibCurl::Rep_::MakeHandleIfNeeded_ () { if (fCurlHandle_ == nullptr) { ThrowIfNull (fCurlHandle_ = ::curl_easy_init ()); /* * Now setup COMMON options we ALWAYS set. */ LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCacheUTF8_URL_.c_str ())); #if USE_LIBCURL_VERBOSE_ LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_VERBOSE, 1)); #endif LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_READFUNCTION, s_RequestPayloadReadHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_READDATA, this)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEFUNCTION, s_ResponseWriteHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEDATA, this)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HEADERFUNCTION, s_ResponseHeaderWriteHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEHEADER, this)); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ********************** Transfer::Connection_LibCurl **************************** ******************************************************************************** */ Connection_LibCurl::Connection_LibCurl (const Options& options) : Connection (shared_ptr<_IRep> (new Rep_ (options))) { } #endif <commit_msg>remove obsolete LEGACY_Synchonized usage<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../../StroikaPreComp.h" #if qHasFeature_libcurl #include <curl/curl.h> #endif #include "../../../Characters/Format.h" #include "../../../Characters/String_Constant.h" #include "../../../Debug/Trace.h" #include "../../../Execution/Exceptions.h" #include "../HTTP/Methods.h" #include "Client_libcurl.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; using namespace Stroika::Foundation::IO::Network::Transfer; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 // Uncomment this line to enable libcurl to print diagnostics to stderr //#define USE_LIBCURL_VERBOSE_ 1 #if qHasFeature_libcurl namespace { struct ModuleInit_ { ModuleInit_ () { ::curl_global_init (CURL_GLOBAL_ALL); } }; ModuleInit_ sIniter_; } #endif #if qHasFeature_libcurl class Connection_LibCurl::Rep_ : public _IRep { public: Connection::Options fOptions; public: Rep_ (const Connection::Options& options) : fOptions (options) { } Rep_ (const Rep_&) = delete; virtual ~Rep_ (); public: nonvirtual Rep_& operator= (const Rep_&) = delete; public: virtual DurationSecondsType GetTimeout () const override; virtual void SetTimeout (DurationSecondsType timeout) override; virtual URL GetURL () const override; virtual void SetURL (const URL& url) override; virtual void Close () override; virtual Response Send (const Request& request) override; private: nonvirtual void MakeHandleIfNeeded_ (); private: static size_t s_RequestPayloadReadHandler_ (char* buffer, size_t size, size_t nitems, void* userP); nonvirtual size_t RequestPayloadReadHandler_ (Byte* buffer, size_t bufSize); private: static size_t s_ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP); nonvirtual size_t ResponseWriteHandler_ (const Byte* ptr, size_t nBytes); private: static size_t s_ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP); nonvirtual size_t ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes); private: void* fCurlHandle_ { nullptr }; string fCURLCacheUTF8_URL_; // cuz of quirky memory management policies of libcurl string fCURLCacheUTF8_Method_; // cuz of quirky memory management policies of libcurl vector<Byte> fUploadData_; size_t fUploadDataCursor_ {}; vector<Byte> fResponseData_; Mapping<String, String> fResponseHeaders_; curl_slist* fSavedHeaders_ { nullptr }; }; #endif #if qHasFeature_libcurl namespace { wstring mkExceptMsg_ (LibCurlException::CURLcode ccode) { return String::FromUTF8 (curl_easy_strerror (static_cast<CURLcode> (ccode))).As<wstring> (); } } /* ******************************************************************************** ************************ Transfer::LibCurlException **************************** ******************************************************************************** */ LibCurlException::LibCurlException (CURLcode ccode) : StringException (mkExceptMsg_ (ccode)) , fCurlCode_ (ccode) { } void LibCurlException::DoThrowIfError (CURLcode status) { if (status != CURLE_OK) { DbgTrace (L"In LibCurlException::DoThrowIfError: throwing status %d (%s)", status, LibCurlException (status).As<String> ().c_str ()); Execution::DoThrow (LibCurlException (status)); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ****************** Transfer::Connection_LibCurl::Rep_ ************************** ******************************************************************************** */ Connection_LibCurl::Rep_::~Rep_ () { if (fCurlHandle_ != nullptr) { curl_easy_cleanup (fCurlHandle_); } if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } } DurationSecondsType Connection_LibCurl::Rep_::GetTimeout () const { AssertNotImplemented (); return 0; } void Connection_LibCurl::Rep_::SetTimeout (DurationSecondsType timeout) { MakeHandleIfNeeded_ (); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_TIMEOUT_MS, static_cast<int> (timeout * 1000))); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CONNECTTIMEOUT_MS, static_cast<int> (timeout * 1000))); } URL Connection_LibCurl::Rep_::GetURL () const { // needs work... - not sure this is safe - may need to cache orig... instead of reparsing... return URL::Parse (String::FromUTF8 (fCURLCacheUTF8_URL_).As<wstring> ()); } void Connection_LibCurl::Rep_::SetURL (const URL& url) { MakeHandleIfNeeded_ (); fCURLCacheUTF8_URL_ = String (url.GetFullURL ()).AsUTF8 (); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace ("Connection_LibCurl::Rep_::SetURL ('%s')", fCURLCacheUTF8_URL_.c_str ()); #endif LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCacheUTF8_URL_.c_str ())); } void Connection_LibCurl::Rep_::Close () { if (fCurlHandle_ != nullptr) { ::curl_easy_cleanup (fCurlHandle_); fCurlHandle_ = nullptr; } } size_t Connection_LibCurl::Rep_::s_RequestPayloadReadHandler_ (char* buffer, size_t size, size_t nitems, void* userP) { return reinterpret_cast<Rep_*> (userP)->RequestPayloadReadHandler_ (reinterpret_cast<Byte*> (buffer), size * nitems); } size_t Connection_LibCurl::Rep_::RequestPayloadReadHandler_ (Byte* buffer, size_t bufSize) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (SDKSTR ("Connection_LibCurl::Rep_::RequestPayloadReadHandler_")); #endif size_t bytes2Copy = fUploadData_.size () - fUploadDataCursor_; bytes2Copy = min (bytes2Copy, bufSize); memcpy (buffer, Traversal::Iterator2Pointer (begin (fUploadData_)) + fUploadDataCursor_, bytes2Copy); fUploadDataCursor_ += bytes2Copy; #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"bufSize = %d, bytes2Copy=%d", bufSize, bytes2Copy); #endif return bytes2Copy; } size_t Connection_LibCurl::Rep_::s_ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<Rep_*> (userP)->ResponseWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t Connection_LibCurl::Rep_::ResponseWriteHandler_ (const Byte* ptr, size_t nBytes) { fResponseData_.insert (fResponseData_.end (), ptr, ptr + nBytes); return nBytes; } size_t Connection_LibCurl::Rep_::s_ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP) { return reinterpret_cast<Rep_*> (userP)->ResponseHeaderWriteHandler_ (reinterpret_cast<const Byte*> (ptr), size * nmemb); } size_t Connection_LibCurl::Rep_::ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes) { String from = String::FromUTF8 (reinterpret_cast<const char*> (ptr), reinterpret_cast<const char*> (ptr) + nBytes); String to; size_t i = from.find (':'); if (i != string::npos) { to = from.SubString (i + 1); from = from.SubString (0, i); } from = from.Trim (); to = to.Trim (); fResponseHeaders_.Add (from, to); return nBytes; } Response Connection_LibCurl::Rep_::Send (const Request& request) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx (SDKSTR ("Connection_LibCurl::Rep_::Send")); DbgTrace (L"(method='%s')", request.fMethod.c_str ()); #endif MakeHandleIfNeeded_ (); fUploadData_ = request.fData.As<vector<Byte>> (); fUploadDataCursor_ = 0; fResponseData_.clear (); fResponseHeaders_.clear (); //grab useragent from request headers... //curl_easy_setopt (fCurlHandle_, CURLOPT_USERAGENT, "libcurl-agent/1.0"); Mapping<String, String> overrideHeaders = request.fOverrideHeaders; if (fOptions.fAssumeLowestCommonDenominatorHTTPServer) { // @todo CONSIDER if we need to use Synchonized<> here. At one point we did, but perhaps no longer? // --LGP 2015-01-10 static const Mapping<String, String> kSilenceTheseHeaders_ {{ { String_Constant (L"Expect"), String ()}, { String_Constant (L"Transfer-Encoding"), String ()} } }; overrideHeaders = kSilenceTheseHeaders_ + overrideHeaders; } if (request.fMethod == HTTP::Methods::kGet) { if (not fCURLCacheUTF8_Method_.empty ()) { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , nullptr)); fCURLCacheUTF8_Method_.clear (); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPGET, 1)); } else if (request.fMethod == HTTP::Methods::kPost) { if (not fCURLCacheUTF8_Method_.empty ()) { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , nullptr)); fCURLCacheUTF8_Method_.clear (); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_POST, 1)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_POSTFIELDSIZE, fUploadData_.size ())); } else if (request.fMethod == HTTP::Methods::kPut) { if (not fCURLCacheUTF8_Method_.empty ()) { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , nullptr)); fCURLCacheUTF8_Method_.clear (); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_UPLOAD, fUploadData_.empty () ? 0 : 1)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_INFILESIZE , fUploadData_.size ())); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_PUT, 1)); } else { LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPGET, 0)); if (not fCURLCacheUTF8_Method_.empty ()) { fCURLCacheUTF8_Method_ = request.fMethod.AsUTF8 (); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , fCURLCacheUTF8_Method_.c_str ())); } LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_CUSTOMREQUEST , 1)); } // grab initial headers and do POST/etc based on args in request... curl_slist* tmpH = nullptr; for (auto i : overrideHeaders) { tmpH = curl_slist_append (tmpH, (i.fKey + String_Constant (L": ") + i.fValue).AsUTF8 ().c_str ()); } AssertNotNull (fCurlHandle_); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPHEADER, tmpH)); if (fSavedHeaders_ != nullptr) { curl_slist_free_all (fSavedHeaders_); fSavedHeaders_ = nullptr; } fSavedHeaders_ = tmpH; LibCurlException::DoThrowIfError (:: curl_easy_perform (fCurlHandle_)); long resultCode = 0; LibCurlException::DoThrowIfError (::curl_easy_getinfo (fCurlHandle_, CURLINFO_RESPONSE_CODE, &resultCode)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"returning status = %d, dataLen = %d", resultCode, fResponseData_.size ()); #endif return Response (move (fResponseData_), resultCode, move (fResponseHeaders_)); } void Connection_LibCurl::Rep_::MakeHandleIfNeeded_ () { if (fCurlHandle_ == nullptr) { ThrowIfNull (fCurlHandle_ = ::curl_easy_init ()); /* * Now setup COMMON options we ALWAYS set. */ LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCacheUTF8_URL_.c_str ())); #if USE_LIBCURL_VERBOSE_ LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_VERBOSE, 1)); #endif LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_READFUNCTION, s_RequestPayloadReadHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_READDATA, this)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEFUNCTION, s_ResponseWriteHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEDATA, this)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HEADERFUNCTION, s_ResponseHeaderWriteHandler_)); LibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_WRITEHEADER, this)); } } #endif #if qHasFeature_libcurl /* ******************************************************************************** ********************** Transfer::Connection_LibCurl **************************** ******************************************************************************** */ Connection_LibCurl::Connection_LibCurl (const Options& options) : Connection (shared_ptr<_IRep> (new Rep_ (options))) { } #endif <|endoftext|>
<commit_before>/********************************* ** Tsunagari Tile Engine ** ** area.cpp ** ** Copyright 2011-2012 OmegaSDG ** *********************************/ #include <algorithm> #include <math.h> #include <vector> #include <boost/foreach.hpp> #include <boost/shared_ptr.hpp> #include <Gosu/Graphics.hpp> #include <Gosu/Image.hpp> #include <Gosu/Math.hpp> #include <Gosu/Timing.hpp> #include "area.h" #include "common.h" #include "entity.h" #include "log.h" #include "python.h" #include "resourcer.h" #include "tile.h" #include "window.h" #include "world.h" #define ASSERT(x) if (!(x)) return false /* NOTE: In the TMX map format used by Tiled, tileset tiles start counting their Y-positions from 0, while layer tiles start counting from 1. I can't imagine why the author did this, but we have to take it into account. */ Area::Area(Viewport* view, Player* player, Music* music, const std::string& descriptor) : view(view), player(player), music(music), colorOverlay(0, 0, 0, 0), dim(0, 0, 0), tileDim(0, 0), loopX(false), loopY(false), beenFocused(false), redraw(true), descriptor(descriptor) { } Area::~Area() { } bool Area::init() { // Abstract method. return false; } void Area::focus() { if (!beenFocused) { beenFocused = true; runOnLoads(); } music->setIntro(musicIntro); music->setLoop(musicLoop); if (onFocusScripts.size()) { BOOST_FOREACH(const std::string& script, onFocusScripts) { pythonSetGlobal("Area", this); Resourcer* rc = Resourcer::instance(); rc->runPythonScript(script); } } } void Area::buttonDown(const Gosu::Button btn) { if (btn == Gosu::kbRight) player->startMovement(ivec2(1, 0)); else if (btn == Gosu::kbLeft) player->startMovement(ivec2(-1, 0)); else if (btn == Gosu::kbUp) player->startMovement(ivec2(0, -1)); else if (btn == Gosu::kbDown) player->startMovement(ivec2(0, 1)); else if (btn == Gosu::kbSpace) player->useTile(); } void Area::buttonUp(const Gosu::Button btn) { if (btn == Gosu::kbRight) player->stopMovement(ivec2(1, 0)); else if (btn == Gosu::kbLeft) player->stopMovement(ivec2(-1, 0)); else if (btn == Gosu::kbUp) player->stopMovement(ivec2(0, -1)); else if (btn == Gosu::kbDown) player->stopMovement(ivec2(0, 1)); } void Area::draw() { updateTileAnimations(); drawTiles(); drawEntities(); drawColorOverlay(); redraw = false; } bool Area::needsRedraw() const { if (redraw) return true; if (player->needsRedraw()) return true; // Do any on-screen tile types need to update their animations? const icube_t tiles = visibleTiles(); for (int z = tiles.z1; z < tiles.z2; z++) { for (int y = tiles.y1; y < tiles.y2; y++) { for (int x = tiles.x1; x < tiles.x2; x++) { const Tile& tile = getTile(x, y, z); const TileType* type = tile.getType(); if (type && type->needsRedraw()) return true; } } } return false; } void Area::requestRedraw() { redraw = true; } void Area::update(unsigned long dt) { pythonSetGlobal("Area", this); player->update(dt); if (onUpdateScripts.size()) { BOOST_FOREACH(const std::string& script, onUpdateScripts) { pythonSetGlobal("Area", this); Resourcer* rc = Resourcer::instance(); rc->runPythonScript(script); } } view->update(dt); music->update(); } AreaPtr Area::reset() { World* world = World::instance(); AreaPtr newSelf = world->getArea(descriptor, GETAREA_ALWAYS_CREATE); if (world->getFocusedArea().get() == this) { vicoord c = player->getTileCoords_vi(); world->focusArea(newSelf, c); } return newSelf; } void Area::setColorOverlay(int r, int g, int b, int a) { using namespace Gosu; if (0 <= r && r < 256 && 0 <= g && g < 256 && 0 <= b && b < 256 && 0 <= a && a < 256) { Color::Channel ac = (Color::Channel)a; Color::Channel rc = (Color::Channel)r; Color::Channel gc = (Color::Channel)g; Color::Channel bc = (Color::Channel)b; colorOverlay = Color(ac, rc, gc, bc); redraw = true; } else { PyErr_Format(PyExc_ValueError, "Area::color_overlay() arguments must be " "between 0 and 255"); } } const Tile& Area::getTile(int x, int y, int z) const { if (loopX) x = wrap(0, x, dim.x); if (loopY) y = wrap(0, y, dim.y); return map[z][y][x]; } const Tile& Area::getTile(int x, int y, double z) const { return getTile(x, y, depthIndex(z)); } const Tile& Area::getTile(icoord phys) const { return getTile(phys.x, phys.y, phys.z); } const Tile& Area::getTile(vicoord virt) const { return getTile(virt2phys(virt)); } Tile& Area::getTile(int x, int y, int z) { if (loopX) x = wrap(0, x, dim.x); if (loopY) y = wrap(0, y, dim.y); return map[z][y][x]; } Tile& Area::getTile(int x, int y, double z) { return getTile(x, y, depthIndex(z)); } Tile& Area::getTile(icoord phys) { return getTile(phys.x, phys.y, phys.z); } Tile& Area::getTile(vicoord virt) { return getTile(virt2phys(virt)); } TileType& Area::getTileType(int idx) { return tileTypes[idx]; } ivec3 Area::getDimensions() const { return dim; } ivec2 Area::getTileDimensions() const { return tileDim; } icube_t Area::visibleTileBounds() const { rvec2 screen = view->getVirtRes(); rvec2 off = view->getMapOffset(); int x1 = (int)floor(off.x / tileDim.x); int y1 = (int)floor(off.y / tileDim.y); int x2 = (int)ceil((screen.x + off.x) / tileDim.x); int y2 = (int)ceil((screen.y + off.y) / tileDim.y); return icube(x1, y1, 0, x2, y2, dim.z); } icube_t Area::visibleTiles() const { icube_t cube = visibleTileBounds(); if (!loopX) { cube.x1 = std::max(cube.x1, 0); cube.x2 = std::min(cube.x2, dim.x); } if (!loopY) { cube.y1 = std::max(cube.y1, 0); cube.y2 = std::min(cube.y2, dim.y); } return cube; } bool Area::inBounds(int x, int y, int z) const { return ((loopX || (0 <= x && x < dim.x)) && (loopY || (0 <= y && y < dim.y)) && 0 <= z && z < dim.z); } bool Area::inBounds(int x, int y, double z) const { return inBounds(x, y, depthIndex(z)); } bool Area::inBounds(icoord phys) const { return inBounds(phys.x, phys.y, phys.z); } bool Area::inBounds(vicoord virt) const { return inBounds(virt2phys(virt)); } bool Area::loopsInX() const { return loopX; } bool Area::loopsInY() const { return loopY; } const std::string Area::getDescriptor() const { return descriptor; } vicoord Area::phys2virt_vi(icoord phys) const { return vicoord(phys.x, phys.y, indexDepth(phys.z)); } rcoord Area::phys2virt_r(icoord phys) const { return rcoord( (double)phys.x * tileDim.x, (double)phys.y * tileDim.y, indexDepth(phys.z) ); } icoord Area::virt2phys(vicoord virt) const { return icoord(virt.x, virt.y, depthIndex(virt.z)); } icoord Area::virt2phys(rcoord virt) const { return icoord( (int)(virt.x / tileDim.x), (int)(virt.y / tileDim.y), depthIndex(virt.z) ); } rcoord Area::virt2virt(vicoord virt) const { return rcoord( (double)virt.x * tileDim.x, (double)virt.y * tileDim.y, virt.z ); } vicoord Area::virt2virt(rcoord virt) const { return vicoord( (int)virt.x / tileDim.x, (int)virt.y / tileDim.y, virt.z ); } int Area::depthIndex(double depth) const { return depth2idx.find(depth)->second; } double Area::indexDepth(int idx) const { return idx2depth[idx]; } void Area::runOnLoads() { Resourcer* rc = Resourcer::instance(); World* world = World::instance(); std::string onAreaLoadScript = world->getAreaLoadScript(); if (onAreaLoadScript.size()) { pythonSetGlobal("Area", this); rc->runPythonScript(onAreaLoadScript); } BOOST_FOREACH(const std::string& script, onLoadScripts) { pythonSetGlobal("Area", this); rc->runPythonScript(script); } } void Area::updateTileAnimations() { const int millis = GameWindow::instance().time(); BOOST_FOREACH(TileType& type, tileTypes) type.anim.updateFrame(millis); } void Area::drawTiles() const { const icube_t tiles = visibleTiles(); for (int z = tiles.z1; z < tiles.z2; z++) { double depth = idx2depth[z]; for (int y = tiles.y1; y < tiles.y2; y++) { for (int x = tiles.x1; x < tiles.x2; x++) { const Tile& tile = getTile(x, y, z); drawTile(tile, x, y, depth); } } } } void Area::drawTile(const Tile& tile, int x, int y, double depth) const { const TileType* type = (TileType*)tile.parent; if (type) { const Gosu::Image* img = type->anim.frame(); if (img) img->draw((double)x*img->width(), (double)y*img->height(), depth); } } void Area::drawEntities() { player->draw(); } void Area::drawColorOverlay() { if (colorOverlay.alpha() != 0) { GameWindow& window = GameWindow::instance(); Gosu::Color c = colorOverlay; int x = window.width(); int y = window.height(); window.graphics().drawQuad( 0, 0, c, x, 0, c, x, y, c, 0, y, c, 750 ); } } boost::python::tuple Area::pyGetDimensions() { using namespace boost::python; list zs; BOOST_FOREACH(double dep, idx2depth) { zs.append(dep); } return boost::python::make_tuple(dim.x, dim.y, zs); } void exportArea() { boost::python::class_<Area>("Area", boost::python::no_init) .add_property("descriptor", &Area::getDescriptor) .add_property("dimensions", &Area::pyGetDimensions) .def("request_redraw", &Area::requestRedraw) .def("tiles", static_cast<Tile& (Area::*) (int, int, double)> (&Area::getTile), boost::python::return_value_policy< boost::python::reference_existing_object >()) .def("in_bounds", static_cast<bool (Area::*) (int, int, double) const> (&Area::inBounds)) .def("get_tile_type", &Area::getTileType, boost::python::return_value_policy< boost::python::reference_existing_object >() ) .def("reset", &Area::reset) .def("color_overlay", &Area::setColorOverlay) ; } <commit_msg>cleanup exportArea<commit_after>/********************************* ** Tsunagari Tile Engine ** ** area.cpp ** ** Copyright 2011-2012 OmegaSDG ** *********************************/ #include <algorithm> #include <math.h> #include <vector> #include <boost/foreach.hpp> #include <boost/shared_ptr.hpp> #include <Gosu/Graphics.hpp> #include <Gosu/Image.hpp> #include <Gosu/Math.hpp> #include <Gosu/Timing.hpp> #include "area.h" #include "common.h" #include "entity.h" #include "log.h" #include "python.h" #include "resourcer.h" #include "tile.h" #include "window.h" #include "world.h" #define ASSERT(x) if (!(x)) return false /* NOTE: In the TMX map format used by Tiled, tileset tiles start counting their Y-positions from 0, while layer tiles start counting from 1. I can't imagine why the author did this, but we have to take it into account. */ Area::Area(Viewport* view, Player* player, Music* music, const std::string& descriptor) : view(view), player(player), music(music), colorOverlay(0, 0, 0, 0), dim(0, 0, 0), tileDim(0, 0), loopX(false), loopY(false), beenFocused(false), redraw(true), descriptor(descriptor) { } Area::~Area() { } bool Area::init() { // Abstract method. return false; } void Area::focus() { if (!beenFocused) { beenFocused = true; runOnLoads(); } music->setIntro(musicIntro); music->setLoop(musicLoop); if (onFocusScripts.size()) { BOOST_FOREACH(const std::string& script, onFocusScripts) { pythonSetGlobal("Area", this); Resourcer* rc = Resourcer::instance(); rc->runPythonScript(script); } } } void Area::buttonDown(const Gosu::Button btn) { if (btn == Gosu::kbRight) player->startMovement(ivec2(1, 0)); else if (btn == Gosu::kbLeft) player->startMovement(ivec2(-1, 0)); else if (btn == Gosu::kbUp) player->startMovement(ivec2(0, -1)); else if (btn == Gosu::kbDown) player->startMovement(ivec2(0, 1)); else if (btn == Gosu::kbSpace) player->useTile(); } void Area::buttonUp(const Gosu::Button btn) { if (btn == Gosu::kbRight) player->stopMovement(ivec2(1, 0)); else if (btn == Gosu::kbLeft) player->stopMovement(ivec2(-1, 0)); else if (btn == Gosu::kbUp) player->stopMovement(ivec2(0, -1)); else if (btn == Gosu::kbDown) player->stopMovement(ivec2(0, 1)); } void Area::draw() { updateTileAnimations(); drawTiles(); drawEntities(); drawColorOverlay(); redraw = false; } bool Area::needsRedraw() const { if (redraw) return true; if (player->needsRedraw()) return true; // Do any on-screen tile types need to update their animations? const icube_t tiles = visibleTiles(); for (int z = tiles.z1; z < tiles.z2; z++) { for (int y = tiles.y1; y < tiles.y2; y++) { for (int x = tiles.x1; x < tiles.x2; x++) { const Tile& tile = getTile(x, y, z); const TileType* type = tile.getType(); if (type && type->needsRedraw()) return true; } } } return false; } void Area::requestRedraw() { redraw = true; } void Area::update(unsigned long dt) { pythonSetGlobal("Area", this); player->update(dt); if (onUpdateScripts.size()) { BOOST_FOREACH(const std::string& script, onUpdateScripts) { pythonSetGlobal("Area", this); Resourcer* rc = Resourcer::instance(); rc->runPythonScript(script); } } view->update(dt); music->update(); } AreaPtr Area::reset() { World* world = World::instance(); AreaPtr newSelf = world->getArea(descriptor, GETAREA_ALWAYS_CREATE); if (world->getFocusedArea().get() == this) { vicoord c = player->getTileCoords_vi(); world->focusArea(newSelf, c); } return newSelf; } void Area::setColorOverlay(int r, int g, int b, int a) { using namespace Gosu; if (0 <= r && r < 256 && 0 <= g && g < 256 && 0 <= b && b < 256 && 0 <= a && a < 256) { Color::Channel ac = (Color::Channel)a; Color::Channel rc = (Color::Channel)r; Color::Channel gc = (Color::Channel)g; Color::Channel bc = (Color::Channel)b; colorOverlay = Color(ac, rc, gc, bc); redraw = true; } else { PyErr_Format(PyExc_ValueError, "Area::color_overlay() arguments must be " "between 0 and 255"); } } const Tile& Area::getTile(int x, int y, int z) const { if (loopX) x = wrap(0, x, dim.x); if (loopY) y = wrap(0, y, dim.y); return map[z][y][x]; } const Tile& Area::getTile(int x, int y, double z) const { return getTile(x, y, depthIndex(z)); } const Tile& Area::getTile(icoord phys) const { return getTile(phys.x, phys.y, phys.z); } const Tile& Area::getTile(vicoord virt) const { return getTile(virt2phys(virt)); } Tile& Area::getTile(int x, int y, int z) { if (loopX) x = wrap(0, x, dim.x); if (loopY) y = wrap(0, y, dim.y); return map[z][y][x]; } Tile& Area::getTile(int x, int y, double z) { return getTile(x, y, depthIndex(z)); } Tile& Area::getTile(icoord phys) { return getTile(phys.x, phys.y, phys.z); } Tile& Area::getTile(vicoord virt) { return getTile(virt2phys(virt)); } TileType& Area::getTileType(int idx) { return tileTypes[idx]; } ivec3 Area::getDimensions() const { return dim; } ivec2 Area::getTileDimensions() const { return tileDim; } icube_t Area::visibleTileBounds() const { rvec2 screen = view->getVirtRes(); rvec2 off = view->getMapOffset(); int x1 = (int)floor(off.x / tileDim.x); int y1 = (int)floor(off.y / tileDim.y); int x2 = (int)ceil((screen.x + off.x) / tileDim.x); int y2 = (int)ceil((screen.y + off.y) / tileDim.y); return icube(x1, y1, 0, x2, y2, dim.z); } icube_t Area::visibleTiles() const { icube_t cube = visibleTileBounds(); if (!loopX) { cube.x1 = std::max(cube.x1, 0); cube.x2 = std::min(cube.x2, dim.x); } if (!loopY) { cube.y1 = std::max(cube.y1, 0); cube.y2 = std::min(cube.y2, dim.y); } return cube; } bool Area::inBounds(int x, int y, int z) const { return ((loopX || (0 <= x && x < dim.x)) && (loopY || (0 <= y && y < dim.y)) && 0 <= z && z < dim.z); } bool Area::inBounds(int x, int y, double z) const { return inBounds(x, y, depthIndex(z)); } bool Area::inBounds(icoord phys) const { return inBounds(phys.x, phys.y, phys.z); } bool Area::inBounds(vicoord virt) const { return inBounds(virt2phys(virt)); } bool Area::loopsInX() const { return loopX; } bool Area::loopsInY() const { return loopY; } const std::string Area::getDescriptor() const { return descriptor; } vicoord Area::phys2virt_vi(icoord phys) const { return vicoord(phys.x, phys.y, indexDepth(phys.z)); } rcoord Area::phys2virt_r(icoord phys) const { return rcoord( (double)phys.x * tileDim.x, (double)phys.y * tileDim.y, indexDepth(phys.z) ); } icoord Area::virt2phys(vicoord virt) const { return icoord(virt.x, virt.y, depthIndex(virt.z)); } icoord Area::virt2phys(rcoord virt) const { return icoord( (int)(virt.x / tileDim.x), (int)(virt.y / tileDim.y), depthIndex(virt.z) ); } rcoord Area::virt2virt(vicoord virt) const { return rcoord( (double)virt.x * tileDim.x, (double)virt.y * tileDim.y, virt.z ); } vicoord Area::virt2virt(rcoord virt) const { return vicoord( (int)virt.x / tileDim.x, (int)virt.y / tileDim.y, virt.z ); } int Area::depthIndex(double depth) const { return depth2idx.find(depth)->second; } double Area::indexDepth(int idx) const { return idx2depth[idx]; } void Area::runOnLoads() { Resourcer* rc = Resourcer::instance(); World* world = World::instance(); std::string onAreaLoadScript = world->getAreaLoadScript(); if (onAreaLoadScript.size()) { pythonSetGlobal("Area", this); rc->runPythonScript(onAreaLoadScript); } BOOST_FOREACH(const std::string& script, onLoadScripts) { pythonSetGlobal("Area", this); rc->runPythonScript(script); } } void Area::updateTileAnimations() { const int millis = GameWindow::instance().time(); BOOST_FOREACH(TileType& type, tileTypes) type.anim.updateFrame(millis); } void Area::drawTiles() const { const icube_t tiles = visibleTiles(); for (int z = tiles.z1; z < tiles.z2; z++) { double depth = idx2depth[z]; for (int y = tiles.y1; y < tiles.y2; y++) { for (int x = tiles.x1; x < tiles.x2; x++) { const Tile& tile = getTile(x, y, z); drawTile(tile, x, y, depth); } } } } void Area::drawTile(const Tile& tile, int x, int y, double depth) const { const TileType* type = (TileType*)tile.parent; if (type) { const Gosu::Image* img = type->anim.frame(); if (img) img->draw((double)x*img->width(), (double)y*img->height(), depth); } } void Area::drawEntities() { player->draw(); } void Area::drawColorOverlay() { if (colorOverlay.alpha() != 0) { GameWindow& window = GameWindow::instance(); Gosu::Color c = colorOverlay; int x = window.width(); int y = window.height(); window.graphics().drawQuad( 0, 0, c, x, 0, c, x, y, c, 0, y, c, 750 ); } } boost::python::tuple Area::pyGetDimensions() { using namespace boost::python; list zs; BOOST_FOREACH(double dep, idx2depth) zs.append(dep); return make_tuple(dim.x, dim.y, zs); } void exportArea() { using namespace boost::python; class_<Area>("Area", no_init) .add_property("descriptor", &Area::getDescriptor) .add_property("dimensions", &Area::pyGetDimensions) .def("request_redraw", &Area::requestRedraw) .def("tiles", static_cast<Tile& (Area::*) (int, int, double)> (&Area::getTile), return_value_policy<reference_existing_object>()) .def("in_bounds", static_cast<bool (Area::*) (int, int, double) const> (&Area::inBounds)) .def("get_tile_type", &Area::getTileType, return_value_policy<reference_existing_object>()) .def("reset", &Area::reset) .def("color_overlay", &Area::setColorOverlay) ; } <|endoftext|>
<commit_before>// builds all boost.asio source as a separate compilation unit #include <boost/version.hpp> #ifndef BOOST_ASIO_SOURCE #define BOOST_ASIO_SOURCE #endif #ifdef _MSC_VER // on windows; including timer_queue.hpp results in an // actual link-time dependency on boost.date_time, even // though it's never referenced. So, avoid that on windows. // on Mac OS X and Linux, not including it results in // missing symbols. For some reason, this current setup // works, at least across windows, Linux and Mac OS X. // In the future this hack can be fixed by disabling // use of boost.date_time in boost.asio #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # error Do not compile Asio library source with BOOST_ASIO_HEADER_ONLY defined #endif #include <boost/asio/impl/error.ipp> #include <boost/asio/impl/io_service.ipp> #include <boost/asio/impl/serial_port_base.ipp> #include <boost/asio/detail/impl/descriptor_ops.ipp> #include <boost/asio/detail/impl/dev_poll_reactor.ipp> #include <boost/asio/detail/impl/epoll_reactor.ipp> #include <boost/asio/detail/impl/eventfd_select_interrupter.ipp> #if BOOST_VERSION >= 104700 #include <boost/asio/detail/impl/handler_tracking.ipp> #include <boost/asio/detail/impl/signal_set_service.ipp> #include <boost/asio/detail/impl/win_static_mutex.ipp> #endif #include <boost/asio/detail/impl/kqueue_reactor.ipp> #include <boost/asio/detail/impl/pipe_select_interrupter.ipp> #include <boost/asio/detail/impl/posix_event.ipp> #include <boost/asio/detail/impl/posix_mutex.ipp> #include <boost/asio/detail/impl/posix_thread.ipp> #include <boost/asio/detail/impl/posix_tss_ptr.ipp> #include <boost/asio/detail/impl/reactive_descriptor_service.ipp> #include <boost/asio/detail/impl/reactive_serial_port_service.ipp> #include <boost/asio/detail/impl/reactive_socket_service_base.ipp> #include <boost/asio/detail/impl/resolver_service_base.ipp> #include <boost/asio/detail/impl/select_reactor.ipp> #include <boost/asio/detail/impl/service_registry.ipp> #include <boost/asio/detail/impl/socket_ops.ipp> #include <boost/asio/detail/impl/socket_select_interrupter.ipp> #include <boost/asio/detail/impl/strand_service.ipp> #include <boost/asio/detail/impl/task_io_service.ipp> #include <boost/asio/detail/impl/throw_error.ipp> //#include <boost/asio/detail/impl/timer_queue.ipp> #include <boost/asio/detail/impl/timer_queue_set.ipp> #include <boost/asio/detail/impl/win_iocp_handle_service.ipp> #include <boost/asio/detail/impl/win_iocp_io_service.ipp> #include <boost/asio/detail/impl/win_iocp_serial_port_service.ipp> #include <boost/asio/detail/impl/win_iocp_socket_service_base.ipp> #include <boost/asio/detail/impl/win_event.ipp> #include <boost/asio/detail/impl/win_mutex.ipp> #include <boost/asio/detail/impl/win_thread.ipp> #include <boost/asio/detail/impl/win_tss_ptr.ipp> #include <boost/asio/detail/impl/winsock_init.ipp> #include <boost/asio/ip/impl/address.ipp> #include <boost/asio/ip/impl/address_v4.ipp> #include <boost/asio/ip/impl/address_v6.ipp> #include <boost/asio/ip/impl/host_name.ipp> #include <boost/asio/ip/detail/impl/endpoint.ipp> #include <boost/asio/local/detail/impl/endpoint.ipp> #if BOOST_VERSION >= 104900 #include <boost/asio/detail/impl/win_object_handle_service.ipp> #endif #else // _MSC_VER #if BOOST_VERSION >= 104500 #include <boost/asio/impl/src.hpp> #elif BOOST_VERSION >= 104400 #include <boost/asio/impl/src.cpp> #endif #endif <commit_msg>asio include fix<commit_after>// builds all boost.asio source as a separate compilation unit #include <boost/version.hpp> #ifndef BOOST_ASIO_SOURCE #define BOOST_ASIO_SOURCE #endif #ifdef _MSC_VER > 1310 // on windows; including timer_queue.hpp results in an // actual link-time dependency on boost.date_time, even // though it's never referenced. So, avoid that on windows. // on Mac OS X and Linux, not including it results in // missing symbols. For some reason, this current setup // works, at least across windows, Linux and Mac OS X. // In the future this hack can be fixed by disabling // use of boost.date_time in boost.asio #include <boost/asio/detail/config.hpp> #if defined(BOOST_ASIO_HEADER_ONLY) # error Do not compile Asio library source with BOOST_ASIO_HEADER_ONLY defined #endif #include <boost/asio/impl/error.ipp> #include <boost/asio/impl/io_service.ipp> #include <boost/asio/impl/serial_port_base.ipp> #include <boost/asio/detail/impl/descriptor_ops.ipp> #include <boost/asio/detail/impl/dev_poll_reactor.ipp> #include <boost/asio/detail/impl/epoll_reactor.ipp> #include <boost/asio/detail/impl/eventfd_select_interrupter.ipp> #if BOOST_VERSION >= 104700 #include <boost/asio/detail/impl/handler_tracking.ipp> #include <boost/asio/detail/impl/signal_set_service.ipp> #include <boost/asio/detail/impl/win_static_mutex.ipp> #endif #include <boost/asio/detail/impl/kqueue_reactor.ipp> #include <boost/asio/detail/impl/pipe_select_interrupter.ipp> #include <boost/asio/detail/impl/posix_event.ipp> #include <boost/asio/detail/impl/posix_mutex.ipp> #include <boost/asio/detail/impl/posix_thread.ipp> #include <boost/asio/detail/impl/posix_tss_ptr.ipp> #include <boost/asio/detail/impl/reactive_descriptor_service.ipp> #include <boost/asio/detail/impl/reactive_serial_port_service.ipp> #include <boost/asio/detail/impl/reactive_socket_service_base.ipp> #include <boost/asio/detail/impl/resolver_service_base.ipp> #include <boost/asio/detail/impl/select_reactor.ipp> #include <boost/asio/detail/impl/service_registry.ipp> #include <boost/asio/detail/impl/socket_ops.ipp> #include <boost/asio/detail/impl/socket_select_interrupter.ipp> #include <boost/asio/detail/impl/strand_service.ipp> #include <boost/asio/detail/impl/task_io_service.ipp> #include <boost/asio/detail/impl/throw_error.ipp> //#include <boost/asio/detail/impl/timer_queue.ipp> #include <boost/asio/detail/impl/timer_queue_set.ipp> #include <boost/asio/detail/impl/win_iocp_handle_service.ipp> #include <boost/asio/detail/impl/win_iocp_io_service.ipp> #include <boost/asio/detail/impl/win_iocp_serial_port_service.ipp> #include <boost/asio/detail/impl/win_iocp_socket_service_base.ipp> #include <boost/asio/detail/impl/win_event.ipp> #include <boost/asio/detail/impl/win_mutex.ipp> #include <boost/asio/detail/impl/win_thread.ipp> #include <boost/asio/detail/impl/win_tss_ptr.ipp> #include <boost/asio/detail/impl/winsock_init.ipp> #include <boost/asio/ip/impl/address.ipp> #include <boost/asio/ip/impl/address_v4.ipp> #include <boost/asio/ip/impl/address_v6.ipp> #include <boost/asio/ip/impl/host_name.ipp> #include <boost/asio/ip/detail/impl/endpoint.ipp> #include <boost/asio/local/detail/impl/endpoint.ipp> #if BOOST_VERSION >= 104900 #include <boost/asio/detail/impl/win_object_handle_service.ipp> #endif #else // _MSC_VER #if BOOST_VERSION >= 104500 #include <boost/asio/impl/src.hpp> #elif BOOST_VERSION >= 104400 #include <boost/asio/impl/src.cpp> #endif #endif <|endoftext|>
<commit_before>AliAnalysisTaskPythiaNuclei* AddTaskPythiaNuclei(){ AliAnalysisTaskPythiaNuclei *task = new AliAnalysisTaskPythiaNuclei(""); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { cout<<"AliAnalysisTaskPythiaNuclei","No analysis manager to connect to."<<endl; return NULL; } mgr->AddTask(task); // Create containers for input/output TString outputFileName = AliAnalysisManager::GetCommonFileName(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput = mgr->CreateContainer("fOutputList", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); //connect containers mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, coutput); return task; } <commit_msg>Add subwagon compatibility to the AddTask macro<commit_after>AliAnalysisTaskPythiaNuclei* AddTaskPythiaNuclei(TString suffix = ""){ AliAnalysisTaskPythiaNuclei *task = new AliAnalysisTaskPythiaNuclei(Form("nuclei%s",suffix.Data())); AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { cout<<"AliAnalysisTaskPythiaNuclei","No analysis manager to connect to."<<endl; return NULL; } mgr->AddTask(task); // Create containers for input/output TString outputFileName = AliAnalysisManager::GetCommonFileName(); AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("fOutputList%s",suffix.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName); //connect containers mgr->ConnectInput(task, 0, cinput); mgr->ConnectOutput(task, 1, coutput); return task; } <|endoftext|>
<commit_before>/* base.cpp -*- C++ -*- Rémi Attab ([email protected]), 29 Nov 2013 FreeBSD-style copyright and disclaimer apply Endpoint base implementation. */ #include "base.h" #include "utils.h" #include <cassert> #include <sys/epoll.h> namespace slick { /******************************************************************************/ /* ENDPOINT BASE */ /******************************************************************************/ EndpointBase:: EndpointBase() : pollThread(0) { poller.add(messagesFd.fd()); } EndpointBase:: ~EndpointBase() { // The extra step is required to not invalidate our iterator std::vector<int> toDisconnect; for (const auto& connection : connections) toDisconnect.push_back(connection.first); for (int fd : toDisconnect) disconnect(fd); } void EndpointBase:: poll() { pollThread = threadId(); while(poller.poll()) { struct epoll_event ev = poller.next(); if (connections.count(ev.data.fd)) { if (ev.events & EPOLLERR) connections[ev.data.fd].socket.throwError(); if (ev.events & EPOLLIN) recvPayload(ev.data.fd); if (ev.events & EPOLLRDHUP || ev.events & EPOLLHUP) { disconnect(ev.data.fd); continue; } if (ev.events & EPOLLOUT) flushQueue(ev.data.fd); } else if (ev.data.fd == messagesFd.fd()) { SLICK_CHECK_ERRNO(!(ev.events & EPOLLERR), "EndpointBase.meesageFd.EPOLLERR"); flushMessages(); } else { onPollEvent(ev); } } } void EndpointBase:: connect(Socket&& socket) { poller.add(socket.fd(), EPOLLET | EPOLLIN | EPOLLOUT); int fd = socket.fd(); ConnectionState connection; connection.socket = std::move(socket); connections[connection.socket.fd()] = std::move(connection); if (onNewConnection) onNewConnection(fd); } void EndpointBase:: disconnect(int fd) { poller.del(fd); connections.erase(fd); if (onLostConnection) onLostConnection(fd); } uint8_t* EndpointBase:: processRecvBuffer(int fd, uint8_t* first, uint8_t* last) { uint8_t* it = first; while (it < last) { size_t leftover = last - it; Payload data = proto::fromBuffer(it, leftover); if (!data.packetSize()) { std::copy(it, last, first); return first + leftover; } it += data.packetSize(); onPayload(fd, std::move(data)); } assert(it == last); return last; } void EndpointBase:: recvPayload(int fd) { auto conn = connections.find(fd); assert(conn != connections.end()); enum { bufferLength = 1U << 16 }; uint8_t buffer[bufferLength]; uint8_t* bufferIt = buffer; while (true) { ssize_t read = recv(fd, bufferIt, (buffer + bufferLength) - bufferIt, 0); if (read < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (errno == EINTR) continue; SLICK_CHECK_ERRNO(read != -1, "EndpointBase.recv"); } if (!read) { // indicates that shutdown was called on the connection side. disconnect(fd); break; } conn->second.bytesRecv += read; bufferIt = processRecvBuffer(fd, buffer, bufferIt + read); } } namespace { // This is not part of the class EndpointBase because we don't want to make // it part of the header. template<typename Payload> bool sendTo(EndpointBase::ConnectionState& conn, Payload&& data) { (void) conn; (void) data; if (!conn.writable) { conn.sendQueue.emplace_back(std::forward<Payload>(data)); return true; } ssize_t sent = send( conn.socket.fd(), data.packet(), data.packetSize(), MSG_NOSIGNAL); if (sent >= 0) { assert(size_t(sent) == data.packetSize()); return true; } if (errno == EAGAIN || errno == EWOULDBLOCK) { conn.sendQueue.emplace_back(std::forward<Payload>(data)); return true; } else if (errno == ECONNRESET || errno == EPIPE) return false; SLICK_CHECK_ERRNO(sent >= 0, "EndpointBase.sendTo.send"); conn.bytesSent += sent; return true; } } // namespace anonymous void EndpointBase:: send(int fd, Payload&& msg) { if (threadId() != pollThread) { messages.push(Message(fd, std::move(msg))); messagesFd.signal(); return; } auto it = connections.find(fd); assert(it != connections.end()); if (!sendTo(it->second, std::move(msg))) disconnect(it->first); } void EndpointBase:: broadcast(Payload&& msg) { if (threadId() != pollThread) { messages.push(Message(std::move(msg))); messagesFd.signal(); return; } std::vector<int> toDisconnect; for (auto& connection : connections) { if (!sendTo(connection.second, msg)) toDisconnect.push_back(connection.first); } for (int fd : toDisconnect) disconnect(fd); } void EndpointBase:: flushQueue(int fd) { auto it = connections.find(fd); assert(it != connections.end()); ConnectionState& connection = it->second; connection.writable = true; std::vector<Payload> queue = std::move(connection.sendQueue); for (auto& msg : queue) { if (sendTo(connection, std::move(msg))) continue; disconnect(fd); break; } } void EndpointBase:: flushMessages() { while (messagesFd.poll()) { while (!messages.empty()) { Message msg = messages.pop(); if (msg.isBroadcast()) broadcast(std::move(msg.data)); else send(msg.conn, std::move(msg.data)); } } } } // slick <commit_msg>processRecvBuffer returns the right pointer after having consumed the entire buffer.<commit_after>/* base.cpp -*- C++ -*- Rémi Attab ([email protected]), 29 Nov 2013 FreeBSD-style copyright and disclaimer apply Endpoint base implementation. */ #include "base.h" #include "utils.h" #include <cassert> #include <sys/epoll.h> namespace slick { /******************************************************************************/ /* ENDPOINT BASE */ /******************************************************************************/ EndpointBase:: EndpointBase() : pollThread(0) { poller.add(messagesFd.fd()); } EndpointBase:: ~EndpointBase() { // The extra step is required to not invalidate our iterator std::vector<int> toDisconnect; for (const auto& connection : connections) toDisconnect.push_back(connection.first); for (int fd : toDisconnect) disconnect(fd); } void EndpointBase:: poll() { pollThread = threadId(); while(poller.poll()) { struct epoll_event ev = poller.next(); if (connections.count(ev.data.fd)) { if (ev.events & EPOLLERR) connections[ev.data.fd].socket.throwError(); if (ev.events & EPOLLIN) recvPayload(ev.data.fd); if (ev.events & EPOLLRDHUP || ev.events & EPOLLHUP) { disconnect(ev.data.fd); continue; } if (ev.events & EPOLLOUT) flushQueue(ev.data.fd); } else if (ev.data.fd == messagesFd.fd()) { SLICK_CHECK_ERRNO(!(ev.events & EPOLLERR), "EndpointBase.meesageFd.EPOLLERR"); flushMessages(); } else { onPollEvent(ev); } } } void EndpointBase:: connect(Socket&& socket) { poller.add(socket.fd(), EPOLLET | EPOLLIN | EPOLLOUT); int fd = socket.fd(); ConnectionState connection; connection.socket = std::move(socket); connections[connection.socket.fd()] = std::move(connection); if (onNewConnection) onNewConnection(fd); } void EndpointBase:: disconnect(int fd) { poller.del(fd); connections.erase(fd); if (onLostConnection) onLostConnection(fd); } uint8_t* EndpointBase:: processRecvBuffer(int fd, uint8_t* first, uint8_t* last) { uint8_t* it = first; while (it < last) { size_t leftover = last - it; Payload data = proto::fromBuffer(it, leftover); if (!data.packetSize()) { std::copy(it, last, first); return first + leftover; } it += data.packetSize(); onPayload(fd, std::move(data)); } assert(it == last); return first; } void EndpointBase:: recvPayload(int fd) { auto conn = connections.find(fd); assert(conn != connections.end()); enum { bufferLength = 1U << 16 }; uint8_t buffer[bufferLength]; uint8_t* bufferIt = buffer; while (true) { ssize_t read = recv(fd, bufferIt, (buffer + bufferLength) - bufferIt, 0); if (read < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) break; if (errno == EINTR) continue; SLICK_CHECK_ERRNO(read != -1, "EndpointBase.recv"); } if (!read) { // indicates that shutdown was called on the connection side. disconnect(fd); break; } conn->second.bytesRecv += read; bufferIt = processRecvBuffer(fd, buffer, bufferIt + read); } } namespace { // This is not part of the class EndpointBase because we don't want to make // it part of the header. template<typename Payload> bool sendTo(EndpointBase::ConnectionState& conn, Payload&& data) { (void) conn; (void) data; if (!conn.writable) { conn.sendQueue.emplace_back(std::forward<Payload>(data)); return true; } ssize_t sent = send( conn.socket.fd(), data.packet(), data.packetSize(), MSG_NOSIGNAL); if (sent >= 0) { assert(size_t(sent) == data.packetSize()); return true; } if (errno == EAGAIN || errno == EWOULDBLOCK) { conn.sendQueue.emplace_back(std::forward<Payload>(data)); return true; } else if (errno == ECONNRESET || errno == EPIPE) return false; SLICK_CHECK_ERRNO(sent >= 0, "EndpointBase.sendTo.send"); conn.bytesSent += sent; return true; } } // namespace anonymous void EndpointBase:: send(int fd, Payload&& msg) { if (threadId() != pollThread) { messages.push(Message(fd, std::move(msg))); messagesFd.signal(); return; } auto it = connections.find(fd); assert(it != connections.end()); if (!sendTo(it->second, std::move(msg))) disconnect(it->first); } void EndpointBase:: broadcast(Payload&& msg) { if (threadId() != pollThread) { messages.push(Message(std::move(msg))); messagesFd.signal(); return; } std::vector<int> toDisconnect; for (auto& connection : connections) { if (!sendTo(connection.second, msg)) toDisconnect.push_back(connection.first); } for (int fd : toDisconnect) disconnect(fd); } void EndpointBase:: flushQueue(int fd) { auto it = connections.find(fd); assert(it != connections.end()); ConnectionState& connection = it->second; connection.writable = true; std::vector<Payload> queue = std::move(connection.sendQueue); for (auto& msg : queue) { if (sendTo(connection, std::move(msg))) continue; disconnect(fd); break; } } void EndpointBase:: flushMessages() { while (messagesFd.poll()) { while (!messages.empty()) { Message msg = messages.pop(); if (msg.isBroadcast()) broadcast(std::move(msg.data)); else send(msg.conn, std::move(msg.data)); } } } } // slick <|endoftext|>
<commit_before>#include <string.h> #include "s_object.h" #include "s_runtime.h" #include "s_gc.h" #include "u_new.h" #include "u_assert.h" #include "u_log.h" namespace s { // TODO(daleweiler): make this part of the virtual machine state Object *Object::m_lastAllocated; size_t Object::m_numAllocated; size_t Object::m_nextGCRun = 10000; ///! Table Object **Table::lookupReference(const char *key, Table::Entry **first) { if (!m_entry.m_name) { if (first) *first = &m_entry; return nullptr; } Entry *entry = &m_entry; Entry *prev; while (entry) { if (strcmp(key, entry->m_name) == 0) return &entry->m_value; prev = entry; entry = entry->m_next; } if (first) { Entry *next = (Entry *)neoCalloc(sizeof *next, 1); prev->m_next = next; *first = next; } return nullptr; }; Object *Table::lookup(const char *key, bool *found) { Object **find = lookupReference(key, nullptr); if (!find) { if (found) *found = false; return nullptr; } if (found) *found = true; return *find; } Object *Object::lookup(const char *key, bool *found) { Object *object = this; while (object) { bool keyFound; Object *value = object->m_table.lookup(key, &keyFound); if (keyFound) { if (found) *found = true; return value; } object = object->m_parent; } if (found) *found = false; return nullptr; } ///! Object void Object::mark(Object *context, Object *object) { // break cycles if (!object || object->m_flags & kMarked) return; object->m_flags |= kMarked; // mark parent object mark(context, object->m_parent); // mark all entries in the table Table::Entry *entry = &object->m_table.m_entry; while (entry) { mark(context, entry->m_value); entry = entry->m_next; } // check for mark function and call it if exists bool markFunctionFound; Object *markFunction = object->lookup("mark", &markFunctionFound); if (markFunctionFound) { FunctionObject *markFunctionObject = (FunctionObject *)markFunction; markFunctionObject->m_function(context, object, markFunction, nullptr, 0); } } void Object::free(Object *object) { Table::Entry *entry = object->m_table.m_entry.m_next; while (entry) { Table::Entry *next = entry->m_next; neoFree(entry); entry = next; } neoFree(object); } Object *Object::instanceOf(Object *object, Object *prototype) { // search the prototype chain to see if 'object' is an instance of 'prototype' while (object) { if (object->m_parent == prototype) return object; object = object->m_parent; } return nullptr; } // changes a propery in place void Object::setExisting(const char *key, Object *value) { Object *current = this; while (current) { Object **find = current->m_table.lookupReference(key, nullptr); if (find) { U_ASSERT(!(m_flags & kImmutable)); *find = value; return; } current = current->m_parent; } U_UNREACHABLE(); } // change a propery only if it exists somewhere in the prototype chain void Object::setShadowing(const char *key, Object *value) { Object *current = this; while (current) { Object **find = current->m_table.lookupReference(key, nullptr); if (find) { // Create it in the object setNormal(key, value); return; } current = current->m_parent; } U_UNREACHABLE(); } // set property void Object::setNormal(const char *key, Object *value) { Table::Entry *free = nullptr; Object **find = m_table.lookupReference(key, &free); if (find) { U_ASSERT(!(m_flags & kImmutable)); } else { U_ASSERT(!(m_flags & kClosed)); free->m_name = key; find = &free->m_value; } *find = value; } void *Object::alloc(Object *context, size_t size) { if (m_numAllocated > m_nextGCRun) { GarbageCollector::run(context); // TODO(daleweiler): cleanup in vm state ? m_nextGCRun = m_numAllocated * 1.2f; } Object *result = (Object *)neoCalloc(size, 1); result->m_prev = m_lastAllocated; m_lastAllocated = result; m_numAllocated++; return result; } Object *Object::newObject(Object *context, Object *parent) { Object *object = (Object *)alloc(context, sizeof(Object)); object->m_parent = parent; return object; } Object *Object::newInt(Object *context, int value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *intBase = root->lookup("int", nullptr); auto *object = (IntObject *)alloc(context, sizeof(IntObject)); object->m_parent = intBase; object->m_value = value; return (Object *)object; } Object *Object::newFloat(Object *context, float value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *floatBase = root->lookup("float", nullptr); auto *object = (FloatObject *)alloc(context, sizeof(FloatObject)); object->m_parent = floatBase; object->m_flags = kImmutable | kClosed; object->m_value = value; return (Object *)object; } Object *Object::newBoolean(Object *context, bool value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *boolBase = root->lookup("bool", nullptr); auto *object = (BooleanObject *)alloc(context, sizeof(BooleanObject)); object->m_parent = boolBase; object->m_flags = kImmutable | kClosed; object->m_value = value; return (Object *)object; } Object *Object::newString(Object *context, const char *value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *stringBase = root->lookup("string", nullptr); size_t length = strlen(value); // string gets allocated as part of the object auto *object = (StringObject *)alloc(context, sizeof(StringObject) + length + 1); object->m_parent = stringBase; object->m_flags = kImmutable | kClosed; object->m_value = ((char *)object) + sizeof(StringObject); strncpy(object->m_value, value, length + 1); return (Object *)object; } Object *Object::newArray(Object *context, Object **contents, size_t length) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *arrayBase = root->lookup("array", nullptr); auto *object = (ArrayObject *)alloc(context, sizeof(ArrayObject)); object->m_parent = arrayBase; object->m_contents = contents; object->m_length = length; ((Object *)object)->setNormal("length", newInt(context, length)); return (Object *)object; } Object *Object::newFunction(Object *context, FunctionPointer function) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *functionBase = root->lookup("function", nullptr); auto *object = (FunctionObject*)alloc(context, sizeof(FunctionObject)); object->m_parent = functionBase; object->m_function = function; return (Object *)object; } Object *Object::newClosure(Object *context, UserFunction *function) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *closureBase = root->lookup("closure", nullptr); auto *object = (ClosureObject*)alloc(context, sizeof(ClosureObject)); object->m_parent = closureBase; if (function->m_isMethod) object->m_function = methodHandler; else object->m_function = functionHandler; object->m_context = context; object->m_userFunction = *function; return (Object *)object; } } <commit_msg>Pin when setting length property of array since newInt may trigger GC<commit_after>#include <string.h> #include "s_object.h" #include "s_runtime.h" #include "s_gc.h" #include "u_new.h" #include "u_assert.h" #include "u_log.h" namespace s { // TODO(daleweiler): make this part of the virtual machine state Object *Object::m_lastAllocated; size_t Object::m_numAllocated; size_t Object::m_nextGCRun = 10000; ///! Table Object **Table::lookupReference(const char *key, Table::Entry **first) { if (!m_entry.m_name) { if (first) *first = &m_entry; return nullptr; } Entry *entry = &m_entry; Entry *prev; while (entry) { if (strcmp(key, entry->m_name) == 0) return &entry->m_value; prev = entry; entry = entry->m_next; } if (first) { Entry *next = (Entry *)neoCalloc(sizeof *next, 1); prev->m_next = next; *first = next; } return nullptr; }; Object *Table::lookup(const char *key, bool *found) { Object **find = lookupReference(key, nullptr); if (!find) { if (found) *found = false; return nullptr; } if (found) *found = true; return *find; } Object *Object::lookup(const char *key, bool *found) { Object *object = this; while (object) { bool keyFound; Object *value = object->m_table.lookup(key, &keyFound); if (keyFound) { if (found) *found = true; return value; } object = object->m_parent; } if (found) *found = false; return nullptr; } ///! Object void Object::mark(Object *context, Object *object) { // break cycles if (!object || object->m_flags & kMarked) return; object->m_flags |= kMarked; // mark parent object mark(context, object->m_parent); // mark all entries in the table Table::Entry *entry = &object->m_table.m_entry; while (entry) { mark(context, entry->m_value); entry = entry->m_next; } // check for mark function and call it if exists bool markFunctionFound; Object *markFunction = object->lookup("mark", &markFunctionFound); if (markFunctionFound) { FunctionObject *markFunctionObject = (FunctionObject *)markFunction; markFunctionObject->m_function(context, object, markFunction, nullptr, 0); } } void Object::free(Object *object) { Table::Entry *entry = object->m_table.m_entry.m_next; while (entry) { Table::Entry *next = entry->m_next; neoFree(entry); entry = next; } neoFree(object); } Object *Object::instanceOf(Object *object, Object *prototype) { // search the prototype chain to see if 'object' is an instance of 'prototype' while (object) { if (object->m_parent == prototype) return object; object = object->m_parent; } return nullptr; } // changes a propery in place void Object::setExisting(const char *key, Object *value) { Object *current = this; while (current) { Object **find = current->m_table.lookupReference(key, nullptr); if (find) { U_ASSERT(!(m_flags & kImmutable)); *find = value; return; } current = current->m_parent; } U_UNREACHABLE(); } // change a propery only if it exists somewhere in the prototype chain void Object::setShadowing(const char *key, Object *value) { Object *current = this; while (current) { Object **find = current->m_table.lookupReference(key, nullptr); if (find) { // Create it in the object setNormal(key, value); return; } current = current->m_parent; } U_UNREACHABLE(); } // set property void Object::setNormal(const char *key, Object *value) { Table::Entry *free = nullptr; Object **find = m_table.lookupReference(key, &free); if (find) { U_ASSERT(!(m_flags & kImmutable)); } else { U_ASSERT(!(m_flags & kClosed)); free->m_name = key; find = &free->m_value; } *find = value; } void *Object::alloc(Object *context, size_t size) { if (m_numAllocated > m_nextGCRun) { GarbageCollector::run(context); // TODO(daleweiler): cleanup in vm state ? m_nextGCRun = m_numAllocated * 1.2f; } Object *result = (Object *)neoCalloc(size, 1); result->m_prev = m_lastAllocated; m_lastAllocated = result; m_numAllocated++; return result; } Object *Object::newObject(Object *context, Object *parent) { Object *object = (Object *)alloc(context, sizeof(Object)); object->m_parent = parent; return object; } Object *Object::newInt(Object *context, int value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *intBase = root->lookup("int", nullptr); auto *object = (IntObject *)alloc(context, sizeof(IntObject)); object->m_parent = intBase; object->m_value = value; return (Object *)object; } Object *Object::newFloat(Object *context, float value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *floatBase = root->lookup("float", nullptr); auto *object = (FloatObject *)alloc(context, sizeof(FloatObject)); object->m_parent = floatBase; object->m_flags = kImmutable | kClosed; object->m_value = value; return (Object *)object; } Object *Object::newBoolean(Object *context, bool value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *boolBase = root->lookup("bool", nullptr); auto *object = (BooleanObject *)alloc(context, sizeof(BooleanObject)); object->m_parent = boolBase; object->m_flags = kImmutable | kClosed; object->m_value = value; return (Object *)object; } Object *Object::newString(Object *context, const char *value) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *stringBase = root->lookup("string", nullptr); size_t length = strlen(value); // string gets allocated as part of the object auto *object = (StringObject *)alloc(context, sizeof(StringObject) + length + 1); object->m_parent = stringBase; object->m_flags = kImmutable | kClosed; object->m_value = ((char *)object) + sizeof(StringObject); strncpy(object->m_value, value, length + 1); return (Object *)object; } Object *Object::newArray(Object *context, Object **contents, size_t length) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *arrayBase = root->lookup("array", nullptr); auto *object = (ArrayObject *)alloc(context, sizeof(ArrayObject)); object->m_parent = arrayBase; object->m_contents = contents; object->m_length = length; // pin this since newInt may trigger the garbage collector void *pinned = GarbageCollector::addRoots(u::unsafe_cast<Object **>(&object), 1); ((Object *)object)->setNormal("length", newInt(context, length)); GarbageCollector::delRoots(pinned); return (Object *)object; } Object *Object::newFunction(Object *context, FunctionPointer function) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *functionBase = root->lookup("function", nullptr); auto *object = (FunctionObject*)alloc(context, sizeof(FunctionObject)); object->m_parent = functionBase; object->m_function = function; return (Object *)object; } Object *Object::newClosure(Object *context, UserFunction *function) { Object *root = context; while (root->m_parent) root = root->m_parent; Object *closureBase = root->lookup("closure", nullptr); auto *object = (ClosureObject*)alloc(context, sizeof(ClosureObject)); object->m_parent = closureBase; if (function->m_isMethod) object->m_function = methodHandler; else object->m_function = functionHandler; object->m_context = context; object->m_userFunction = *function; return (Object *)object; } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP #define STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP #include <stan/math/rev/core/chainable.hpp> #include <stan/math/rev/core/chainable_alloc.hpp> #include <stan/math/rev/core/chainablestack.hpp> namespace stan { namespace math { /** * Reset all adjoint values in the top nested portion of the stack * to zero. */ static void set_zero_all_adjoints_nested() { if (empty_nested()) throw std::logic_error("empty_nested() must be false before calling" " set_zero_all_adjoints_nested()"); size_t start1 = ChainableStack::nested_var_stack_sizes_.back(); for (size_t i = start1 - 1; i < ChainableStack::var_stack_.size(); ++i) ChainableStack::var_stack_[i]->set_zero_adjoint(); size_t start2 = ChainableStack::nested_var_nochain_stack_sizes_.back(); for (size_t i = start2 - 1; i < ChainableStack::var_nochain_stack_.size(); ++i) ChainableStack::var_nochain_stack_[i]->set_zero_adjoint(); } } } #endif <commit_msg>Update the new adjoint reset function to not use the deprecated chainable base class<commit_after>#ifndef STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP #define STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP #include <stan/math/rev/core/vari.hpp> #include <stan/math/rev/core/chainable_alloc.hpp> #include <stan/math/rev/core/chainablestack.hpp> namespace stan { namespace math { /** * Reset all adjoint values in the top nested portion of the stack * to zero. */ static void set_zero_all_adjoints_nested() { if (empty_nested()) throw std::logic_error("empty_nested() must be false before calling" " set_zero_all_adjoints_nested()"); size_t start1 = ChainableStack::nested_var_stack_sizes_.back(); for (size_t i = start1 - 1; i < ChainableStack::var_stack_.size(); ++i) ChainableStack::var_stack_[i]->set_zero_adjoint(); size_t start2 = ChainableStack::nested_var_nochain_stack_sizes_.back(); for (size_t i = start2 - 1; i < ChainableStack::var_nochain_stack_.size(); ++i) ChainableStack::var_nochain_stack_[i]->set_zero_adjoint(); } } } #endif <|endoftext|>
<commit_before>// Petter Strandmark 2013. #define CATCH_CONFIG_MAIN #include <catch.hpp> #include <spii/string_utils.h> using namespace spii; using namespace std; TEST_CASE("to_string") { CHECK(to_string("Test",12,"test") == "Test12test"); } TEST_CASE("to_string_pair") { pair<int, string> p{123, "Test"}; CHECK(to_string(p) == "(123, Test)"); } TEST_CASE("to_string_pair_pair") { auto p = make_pair(123, "Test"); auto pp = make_pair(12.1, p); CHECK(to_string(pp) == "(12.1, (123, Test))"); } TEST_CASE("to_string_vector") { vector<int> v{1, 2, 3}; CHECK(to_string(v) == "[1, 2, 3]"); v.clear(); CHECK(to_string(v) == "[]"); } TEST_CASE("to_string_vector_pair") { vector<pair<int, string>> v{{1, "P"}, {2, "S"}}; CHECK(to_string(v) == "[(1, P), (2, S)]"); } TEST_CASE("to_string_set") { set<int> v{1, 2, 3}; CHECK(to_string(v) == "{1, 2, 3}"); v.clear(); CHECK(to_string(v) == "{}"); } TEST_CASE("format_string_1") { CHECK(format_string("Test %0!", 12) == "Test 12!"); CHECK(format_string("Test %0", 12) == "Test 12"); } TEST_CASE("format_string_%") { CHECK(format_string("Test %0%%", 12) == "Test 12%"); CHECK(format_string("Test %0%%!", 12) == "Test 12%!"); CHECK(format_string("Test %0 %%", 12) == "Test 12 %"); CHECK(format_string("Test %0 %%!", 12) == "Test 12 %!"); } TEST_CASE("format_string_2") { CHECK(format_string("Test %0 and %1!", 'A', 'O') == "Test A and O!"); CHECK(format_string("Test %1 and %0!", 'A', 'O') == "Test O and A!"); } TEST_CASE("from_string") { CHECK(from_string<int>("42") == 42); CHECK(from_string("asd", 42) == 42); CHECK_THROWS(from_string<int>("abc")); } <commit_msg>Test std:: modifiers for to_string.<commit_after>// Petter Strandmark 2013. #define CATCH_CONFIG_MAIN #include <catch.hpp> #include <spii/string_utils.h> using namespace spii; using namespace std; TEST_CASE("to_string") { CHECK(to_string("Test",12,"test") == "Test12test"); } TEST_CASE("to_string_pair") { pair<int, string> p{123, "Test"}; CHECK(to_string(p) == "(123, Test)"); } TEST_CASE("to_string_pair_pair") { auto p = make_pair(123, "Test"); auto pp = make_pair(12.1, p); CHECK(to_string(pp) == "(12.1, (123, Test))"); } TEST_CASE("to_string_vector") { vector<int> v{1, 2, 3}; CHECK(to_string(v) == "[1, 2, 3]"); v.clear(); CHECK(to_string(v) == "[]"); } TEST_CASE("to_string_vector_pair") { vector<pair<int, string>> v{{1, "P"}, {2, "S"}}; CHECK(to_string(v) == "[(1, P), (2, S)]"); } TEST_CASE("to_string_set") { set<int> v{1, 2, 3}; CHECK(to_string(v) == "{1, 2, 3}"); v.clear(); CHECK(to_string(v) == "{}"); } TEST_CASE("to_string_setprecision") { double d = 1.123456; CHECK(to_string(setprecision(2), d) == "1.1"); } TEST_CASE("to_string_setfill_setw") { CHECK(to_string(setfill('P'), setw(3), 1) == "PP1"); } TEST_CASE("format_string_1") { CHECK(format_string("Test %0!", 12) == "Test 12!"); CHECK(format_string("Test %0", 12) == "Test 12"); } TEST_CASE("format_string_%") { CHECK(format_string("Test %0%%", 12) == "Test 12%"); CHECK(format_string("Test %0%%!", 12) == "Test 12%!"); CHECK(format_string("Test %0 %%", 12) == "Test 12 %"); CHECK(format_string("Test %0 %%!", 12) == "Test 12 %!"); } TEST_CASE("format_string_2") { CHECK(format_string("Test %0 and %1!", 'A', 'O') == "Test A and O!"); CHECK(format_string("Test %1 and %0!", 'A', 'O') == "Test O and A!"); } TEST_CASE("from_string") { CHECK(from_string<int>("42") == 42); CHECK(from_string("asd", 42) == 42); CHECK_THROWS(from_string<int>("abc")); } <|endoftext|>
<commit_before>#include <memory> #include <gtest/gtest.h> #include <parser.h> using namespace lexers; using namespace parser; TEST(LibrariesParsingTest, BasicConsTest) { Scope s; lexers::Lexer lex("(load \"Base.scm\")"); parseExpr(lex)->eval(s); ASSERT_TRUE(s .count("cons")); ASSERT_TRUE(s .count("car")); ASSERT_TRUE(s .count("cdr")); lex.appendExp("(define p (cons 1 2))").appendExp("(cdr p)"); auto res = parseAllExpr(lex)->eval(s); ASSERT_TRUE(std::dynamic_pointer_cast<NumberAST>(res)); auto numPtr = std::dynamic_pointer_cast<NumberAST>(res); ASSERT_EQ(2, numPtr-> getValue() ); lex.appendExp("(car p)"); res = parseAllExpr(lex)->eval(s); ASSERT_TRUE(std::dynamic_pointer_cast<NumberAST>(res)); numPtr = std::dynamic_pointer_cast<NumberAST>(res); ASSERT_EQ(1, numPtr-> getValue() ); } TEST(LibrariesParsingTest, AdvanceConsTest ) { Scope s; lexers::Lexer lex; lex.appendExp("(load \"Base.scm\")") .appendExp("(define p (cons 1 2))") .appendExp("(define pp (cons 3 p))") .appendExp("(car (cdr pp))"); auto res = parseAllExpr(lex)->eval(s); ASSERT_TRUE(std::dynamic_pointer_cast<NumberAST>(res)); auto numPtr = std::dynamic_pointer_cast<NumberAST>(res); ASSERT_EQ(1, numPtr-> getValue() ); } <commit_msg>格式化代码<commit_after>#include <memory> #include <gtest/gtest.h> #include <parser.h> using namespace lexers; using namespace parser; TEST(LibrariesParsingTest, BasicConsTest ) { Scope s; lexers::Lexer lex("(load \"Base.scm\")"); parseExpr(lex)->eval(s); ASSERT_TRUE(s.count("cons")); ASSERT_TRUE(s.count("car")); ASSERT_TRUE(s.count("cdr")); lex.appendExp("(define p (cons 1 2))").appendExp("(cdr p)"); auto res = parseAllExpr(lex)->eval(s); ASSERT_TRUE(std::dynamic_pointer_cast<NumberAST>(res)); auto numPtr = std::dynamic_pointer_cast<NumberAST>(res); ASSERT_EQ(2, numPtr->getValue()); lex.appendExp("(car p)"); res = parseAllExpr(lex)->eval(s); ASSERT_TRUE(std::dynamic_pointer_cast<NumberAST>(res)); numPtr = std::dynamic_pointer_cast<NumberAST>(res); ASSERT_EQ(1, numPtr->getValue()); } TEST(LibrariesParsingTest, AdvanceConsTest ) { Scope s; lexers::Lexer lex; lex.appendExp("(load \"Base.scm\")") .appendExp("(define p (cons 1 2))") .appendExp("(define pp (cons 3 p))") .appendExp("(car (cdr pp))"); auto res = parseAllExpr(lex)->eval(s); ASSERT_TRUE(std::dynamic_pointer_cast<NumberAST>(res)); auto numPtr = std::dynamic_pointer_cast<NumberAST>(res); ASSERT_EQ(1, numPtr->getValue()); } <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> #include <dune/detailed/discretizations/space/interface.hh> namespace Dune { namespace Detailed { namespace Discretizations { template< class ElementType > class ContainerFactoryEigen { public: typedef Dune::Stuff::LA::EigenRowMajorSparseMatrix< ElementType > RowMajorSparseMatrixType; typedef Dune::Stuff::LA::EigenDenseMatrix< ElementType > DenseMatrixType; typedef Dune::Stuff::LA::EigenDenseVector< ElementType > DenseVectorType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; template< class T, class A > static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface< T >& testSpace, const SpaceInterface< A >& ansatzSpace) { const std::shared_ptr< const PatternType > pattern(testSpace.computePattern(ansatzSpace)); return createRowMajorSparseMatrix(testSpace, ansatzSpace, *pattern); } // static ... createRowMajorSparseMatrix(...) template< class T, class A > static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface< T >& testSpace, const SpaceInterface< A >& ansatzSpace, const PatternType& pattern) { return new RowMajorSparseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size(), pattern); } // static ... createRowMajorSparseMatrix(...) template< class T, class A > static DenseMatrixType createDenseMatrix(const SpaceInterface< T >& testSpace, const SpaceInterface< A >& ansatzSpace) { return new DenseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size()); } // static ... createDenseMatrix(...) template< class S > static DenseVectorType* createDenseVector(const SpaceInterface< S >& space) { return new DenseVectorType(space.mapper().size()); } // static ... createDenseVector(const SpaceType& space) }; // class ContainerFactoryEigen } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <commit_msg>[la.containerfactory.eigen] minor fix<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> #include <dune/detailed/discretizations/space/interface.hh> namespace Dune { namespace Detailed { namespace Discretizations { template< class ElementType > class ContainerFactoryEigen { public: typedef Dune::Stuff::LA::EigenRowMajorSparseMatrix< ElementType > RowMajorSparseMatrixType; typedef Dune::Stuff::LA::EigenDenseMatrix< ElementType > DenseMatrixType; typedef Dune::Stuff::LA::EigenDenseVector< ElementType > DenseVectorType; typedef Dune::Stuff::LA::SparsityPatternDefault PatternType; template< class T, class A > static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface< T >& testSpace, const SpaceInterface< A >& ansatzSpace) { const std::shared_ptr< const PatternType > pattern(testSpace.computePattern(ansatzSpace)); return createRowMajorSparseMatrix(testSpace, ansatzSpace, *pattern); } // static ... createRowMajorSparseMatrix(...) template< class T, class A > static RowMajorSparseMatrixType* createRowMajorSparseMatrix(const SpaceInterface< T >& testSpace, const SpaceInterface< A >& ansatzSpace, const PatternType& pattern) { return new RowMajorSparseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size(), pattern); } // static ... createRowMajorSparseMatrix(...) template< class T, class A > static DenseMatrixType *createDenseMatrix(const SpaceInterface< T >& testSpace, const SpaceInterface< A >& ansatzSpace) { return new DenseMatrixType(testSpace.mapper().size(), ansatzSpace.mapper().size()); } // static ... createDenseMatrix(...) template< class S > static DenseVectorType* createDenseVector(const SpaceInterface< S >& space) { return new DenseVectorType(space.mapper().size()); } // static ... createDenseVector(const SpaceType& space) }; // class ContainerFactoryEigen } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/platform_test.h" #include "base/task.h" #include "base/waitable_event.h" #include "base/worker_pool.h" #include "testing/gtest/include/gtest/gtest.h" using base::WaitableEvent; typedef PlatformTest WorkerPoolTest; namespace { class PostTaskTestTask : public Task { public: PostTaskTestTask(WaitableEvent* event) : event_(event) { } void Run() { event_->Signal(); } private: WaitableEvent* event_; }; TEST_F(WorkerPoolTest, PostTask) { WaitableEvent test_event(false, false); WaitableEvent long_test_event(false, false); bool signaled; WorkerPool::PostTask(FROM_HERE, new PostTaskTestTask(&test_event), false); WorkerPool::PostTask(FROM_HERE, new PostTaskTestTask(&long_test_event), true); signaled = test_event.Wait(); EXPECT_TRUE(signaled); signaled = long_test_event.Wait(); EXPECT_TRUE(signaled); } } // namespace <commit_msg>Reading the comments on a later change, it seems I should have only used a copyright of 2008 on this new file, so this fixes it.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/platform_test.h" #include "base/task.h" #include "base/waitable_event.h" #include "base/worker_pool.h" #include "testing/gtest/include/gtest/gtest.h" using base::WaitableEvent; typedef PlatformTest WorkerPoolTest; namespace { class PostTaskTestTask : public Task { public: PostTaskTestTask(WaitableEvent* event) : event_(event) { } void Run() { event_->Signal(); } private: WaitableEvent* event_; }; TEST_F(WorkerPoolTest, PostTask) { WaitableEvent test_event(false, false); WaitableEvent long_test_event(false, false); bool signaled; WorkerPool::PostTask(FROM_HERE, new PostTaskTestTask(&test_event), false); WorkerPool::PostTask(FROM_HERE, new PostTaskTestTask(&long_test_event), true); signaled = test_event.Wait(); EXPECT_TRUE(signaled); signaled = long_test_event.Wait(); EXPECT_TRUE(signaled); } } // namespace <|endoftext|>
<commit_before>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE We have two types of objects in the simulation - Orrery bodies (planets/moons/asteroid) and spaceships. They behave quite differently and are described as separate classes of objects with some elements in common */ #pragma once #include <cstdint> #include <optional> #include <string> #include <unordered_map> #include <vector> #include "naifbody.hpp" #include "vector.hpp" namespace sim { struct RockLike { struct Property { NAIFbody naif; float GM; // GM value for body float r; // Radius of body (for collision tests) uint32_t color; // For display purposes }; struct State { Vector pos; // Position referenced to solar system barycenter double t_s; }; }; struct ShipLike { struct Property { NAIFbody naif; float max_acc; // Maximum acceleration possible for ship m/s^2 float max_fuel; // Maximum fuel reserve (U) float burn_rate; // Fuel consumption rate (U/ (m/s^2)) uint32_t color; // For display purposes }; struct State { Vector pos; // Position referenced to solar system barycenter Vector vel; // Velocity Vector att; // Attitude float fuel; // Current fuel reserve (U) float acc; // Current acceleration km/s^2 double t_s; }; }; template <typename T> struct SnapShot { typename T::Property property; typename T::State state; }; // This allows us to do lazy computation of rock velocities. // Time will tell if we were too clever here template <typename T> struct SnapShotV { SnapShotV(int& N, typename T::Property _property) : _N(N) { property = _property; } typename T::Property property; typename T::State _state[2]; double& t_s() { return _state[_N].t_s; } double t_s() const { return _state[_N].t_s; } Vector& pos() { return _state[_N].pos; } const Vector& pos() const { return _state[_N].pos; } Vector vel() const { return (_state[_N].pos - _state[1 - _N].pos) / (_state[_N].t_s - _state[1 - _N].t_s); } const typename T::State& state() const { return _state[_N]; } int& _N; }; template <typename T> struct BaseCollection { std::vector<T> bodies; std::unordered_map<NAIFbody, size_t> lookup; size_t size() const { return bodies.size(); } T& operator[](size_t idx) { return bodies[idx]; } T& operator[](const NAIFbody& id) { return bodies[lookup[id]]; } const T& operator[](size_t idx) const { return bodies[idx]; } const T& operator[](const NAIFbody& id) const { return bodies[lookup[id]]; } virtual void push_back(const T& body) { bodies.push_back(body); lookup[body.property.naif] = bodies.size() - 1; } }; template <typename T> struct Collection : public BaseCollection<T> { }; // template <> template <typename T> struct Collection<SnapShotV<T>> : public BaseCollection<SnapShotV<T>> { int N = 0; void push_back(const typename T::Property& property) { // using BaseCollection<SnapShotV<T>>::bodies; // using BaseCollection<SnapShotV<T>>::lookup; bodies.push_back({ N, property }); lookup[property.naif] = bodies.size() - 1; } private: using BaseCollection<SnapShotV<T>>::push_back; }; template <template <typename> class Trock, template <typename> class Tship> struct RocksAndShips { Collection<Trock<RockLike>> system; Collection<Tship<ShipLike>> fleet; }; /* // TODO: deprecate // This allows us to do lazy computation of rock velocities. // Time will tell if we were too clever here struct RockSnapShotWithVel { RockSnapShotWithVel(int& N, RockLike::Property _property) : _N(N) { property = _property; } RockLike::Property property; RockLike::State _state[2]; double& t_s() { return _state[_N].t_s; } double t_s() const { return _state[_N].t_s; } Vector& pos() { return _state[_N].pos; } const Vector& pos() const { return _state[_N].pos; } Vector vel() const { return (_state[_N].pos - _state[1 - _N].pos) / (_state[_N].t_s - _state[1 - _N].t_s); } constexpr const RockLike::State& state() const { return _state[_N]; } int& _N; }; template <typename T> struct BaseCollection { std::vector<T> bodies; std::unordered_map<NAIFbody, size_t> lookup; constexpr size_t size() const { return bodies.size(); } constexpr T& operator[](size_t idx) { return bodies[idx]; } constexpr T& operator[](const NAIFbody& id) { return bodies[lookup[id]]; } constexpr const T& operator[](size_t idx) const { return bodies[idx]; } virtual void push_back(const T& body) { bodies.push_back(body); lookup[body.property.naif] = bodies.size() - 1; } }; template <typename T> struct Collection : public BaseCollection<T> { }; template <> struct Collection<RockSnapShotWithVel> : public BaseCollection<RockSnapShotWithVel> { int N = 0; void push_back(const RockLike::Property& property) { bodies.push_back({ N, property }); lookup[property.naif] = bodies.size() - 1; } private: using BaseCollection<RockSnapShotWithVel>::push_back; }; template <template <typename> class T> struct RocksAndShips { Collection<T<RockLike>> system; Collection<T<ShipLike>> fleet; }; */ template <typename T> inline std::optional<size_t> find(const std::vector<T>& bodies, const NAIFbody& naif) { for (size_t i = 0; i < bodies.size(); i++) { if (bodies[i].property.naif == naif) { return i; } } return {}; } } <commit_msg>Fixed template specialization<commit_after>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2017-2018 by Kaushik Ghose. Some rights reserved, see LICENSE We have two types of objects in the simulation - Orrery bodies (planets/moons/asteroid) and spaceships. They behave quite differently and are described as separate classes of objects with some elements in common */ #pragma once #include <cstdint> #include <optional> #include <string> #include <unordered_map> #include <vector> #include "naifbody.hpp" #include "vector.hpp" namespace sim { struct RockLike { struct Property { NAIFbody naif; float GM; // GM value for body float r; // Radius of body (for collision tests) uint32_t color; // For display purposes }; struct State { Vector pos; // Position referenced to solar system barycenter double t_s; }; }; struct ShipLike { struct Property { NAIFbody naif; float max_acc; // Maximum acceleration possible for ship m/s^2 float max_fuel; // Maximum fuel reserve (U) float burn_rate; // Fuel consumption rate (U/ (m/s^2)) uint32_t color; // For display purposes }; struct State { Vector pos; // Position referenced to solar system barycenter Vector vel; // Velocity Vector att; // Attitude float fuel; // Current fuel reserve (U) float acc; // Current acceleration km/s^2 double t_s; }; }; template <typename T> struct SnapShot { typename T::Property property; typename T::State state; }; // This allows us to do lazy computation of rock velocities. // Time will tell if we were too clever here template <typename T> struct SnapShotV { SnapShotV(int& N, typename T::Property _property) : _N(N) { property = _property; } typename T::Property property; typename T::State _state[2]; double& t_s() { return _state[_N].t_s; } double t_s() const { return _state[_N].t_s; } Vector& pos() { return _state[_N].pos; } const Vector& pos() const { return _state[_N].pos; } Vector vel() const { return (_state[_N].pos - _state[1 - _N].pos) / (_state[_N].t_s - _state[1 - _N].t_s); } const typename T::State& state() const { return _state[_N]; } int& _N; }; template <typename T> struct BaseCollection { std::vector<T> bodies; std::unordered_map<NAIFbody, size_t> lookup; size_t size() const { return bodies.size(); } T& operator[](size_t idx) { return bodies[idx]; } T& operator[](const NAIFbody& id) { return bodies[lookup[id]]; } const T& operator[](size_t idx) const { return bodies[idx]; } const T& operator[](const NAIFbody& id) const { return bodies[lookup[id]]; } virtual void push_back(const T& body) { bodies.push_back(body); lookup[body.property.naif] = bodies.size() - 1; } }; template <typename T> struct Collection : public BaseCollection<T> { }; template <typename T> struct Collection<SnapShotV<T>> : public BaseCollection<SnapShotV<T>> { using BaseCollection<SnapShotV<T>>::bodies; using BaseCollection<SnapShotV<T>>::lookup; int N = 0; void push_back(const typename T::Property& property) { bodies.push_back({ N, property }); lookup[property.naif] = bodies.size() - 1; } private: using BaseCollection<SnapShotV<T>>::push_back; }; template <template <typename> class Trock, template <typename> class Tship> struct RocksAndShips { Collection<Trock<RockLike>> system; Collection<Tship<ShipLike>> fleet; }; /* // TODO: deprecate // This allows us to do lazy computation of rock velocities. // Time will tell if we were too clever here struct RockSnapShotWithVel { RockSnapShotWithVel(int& N, RockLike::Property _property) : _N(N) { property = _property; } RockLike::Property property; RockLike::State _state[2]; double& t_s() { return _state[_N].t_s; } double t_s() const { return _state[_N].t_s; } Vector& pos() { return _state[_N].pos; } const Vector& pos() const { return _state[_N].pos; } Vector vel() const { return (_state[_N].pos - _state[1 - _N].pos) / (_state[_N].t_s - _state[1 - _N].t_s); } constexpr const RockLike::State& state() const { return _state[_N]; } int& _N; }; template <typename T> struct BaseCollection { std::vector<T> bodies; std::unordered_map<NAIFbody, size_t> lookup; constexpr size_t size() const { return bodies.size(); } constexpr T& operator[](size_t idx) { return bodies[idx]; } constexpr T& operator[](const NAIFbody& id) { return bodies[lookup[id]]; } constexpr const T& operator[](size_t idx) const { return bodies[idx]; } virtual void push_back(const T& body) { bodies.push_back(body); lookup[body.property.naif] = bodies.size() - 1; } }; template <typename T> struct Collection : public BaseCollection<T> { }; template <> struct Collection<RockSnapShotWithVel> : public BaseCollection<RockSnapShotWithVel> { int N = 0; void push_back(const RockLike::Property& property) { bodies.push_back({ N, property }); lookup[property.naif] = bodies.size() - 1; } private: using BaseCollection<RockSnapShotWithVel>::push_back; }; template <template <typename> class T> struct RocksAndShips { Collection<T<RockLike>> system; Collection<T<ShipLike>> fleet; }; */ template <typename T> inline std::optional<size_t> find(const std::vector<T>& bodies, const NAIFbody& naif) { for (size_t i = 0; i < bodies.size(); i++) { if (bodies[i].property.naif == naif) { return i; } } return {}; } } <|endoftext|>
<commit_before>/** ** \file scheduler/scheduler.cc ** \brief Implementation of scheduler::Scheduler. */ //#define ENABLE_DEBUG_TRACES #include <algorithm> #include <cassert> #include <cstdlib> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/contract.hh> #include <libport/foreach.hh> #include <object/urbi-exception.hh> #include <scheduler/scheduler.hh> #include <scheduler/job.hh> namespace scheduler { Scheduler::Scheduler(boost::function0<libport::utime_t> get_time) : get_time_(get_time) , current_job_(0) , possible_side_effect_(true) , cycle_(0) , ready_to_die_(false) , real_time_behaviour_(false) { ECHO("Initializing main coroutine"); coroutine_initialize_main(&coro_); } Scheduler::~Scheduler() { ECHO("Destroying scheduler"); } // This function is required to start a new job using the libcoroutine. // Its only purpose is to create the context and start the execution // of the new job. static void run_job(Job* job) { job->run(); } void Scheduler::add_job(rJob job) { assert(job); assert(!libport::has(jobs_, job)); assert(!libport::has(pending_, job)); // If we are currently in a job, add it to the pending_ queue so that // the job is started in the course of the current round. To make sure // that it is not started too late even if the creator is located after // the job that is causing the creation (think "at job handler" for // example), insert it right before the job which was right after the // current one. This way, jobs inserted successively will get queued // in the right order. if (current_job_) pending_.insert(next_job_p_, job); else jobs_.push_back(job); } libport::utime_t Scheduler::work() { ++cycle_; ECHO("======================================================== cycle " << cycle_); libport::utime_t deadline = execute_round(); #ifdef ENABLE_DEBUG_TRACES if (deadline) ECHO("Scheduler asking to be woken up in " << (deadline - get_time_()) / 1000000L << " seconds"); else ECHO("Scheduler asking to be woken up ASAP"); #endif return deadline; } static bool prio_gt(const rJob& j1, const rJob& j2) { return j2->prio_get() < j1->prio_get(); } libport::utime_t Scheduler::execute_round() { // Run all the jobs in the run queue once. If any job declares upon entry or // return that it is not side-effect free, we remember that for the next // cycle. pending_.clear(); std::swap(pending_, jobs_); // Sort all the jobs according to their priority. if (real_time_behaviour_) { static std::vector<rJob> tmp; tmp.reserve(pending_.size()); tmp.clear(); foreach(rJob job, pending_) tmp.push_back(job); std::stable_sort(tmp.begin(), tmp.end(), prio_gt); pending_.clear(); foreach(rJob job, tmp) pending_.push_back(job); } // By default, wake us up after one hour and consider that we have no // new job to start. Also, run waiting jobs only if the previous round // may have add a side effect and reset this indication for the current // job. libport::utime_t start_time = get_time_(); libport::utime_t deadline = start_time + 3600000000LL; bool start_waiting = possible_side_effect_; possible_side_effect_ = false; bool at_least_one_started = false; ECHO(pending_.size() << " jobs in the queue for this round"); // Do not use libport::foreach here, as the list of jobs may grow if // add_job() is called during the iteration. for (jobs_type::iterator job_p = pending_.begin(); job_p != pending_.end(); ++job_p) { rJob& job = *job_p; // Store the next job so that insertions happen before it. next_job_p_ = job_p; ++next_job_p_; // If the job has terminated during the previous round, remove the // references we have on it by just skipping it. if (job->terminated()) continue; // Should the job be started? bool start = false; // Save the current time since we will use it several times during this job // analysis. libport::utime_t current_time = get_time_(); ECHO("Considering " << *job << " in state " << state_name(job->state_get())); switch (job->state_get()) { case to_start: { // New job. Start its coroutine but do not start the job as it // would be queued twice otherwise. It will start doing real // work at the next cycle, so set deadline to 0. Note that we // use "continue" here to avoid having the job requeued // because it hasn't been started by setting "start". // // The code below takes care of destroying the rJob reference // to the job, so that it does not stay in the call stack as a // local variable. If it did, the job would never be // destroyed. However, to prevent the job from being // prematurely destroyed, we set current_job_ (global to the // scheduler) to the rJob. ECHO("Starting job " << *job); current_job_ = job; ECHO("Job " << *job << " is starting"); job = 0; coroutine_start(&coro_, current_job_->coro_get(), run_job, current_job_.get()); current_job_ = 0; deadline = SCHED_IMMEDIATE; at_least_one_started = true; continue; } case zombie: abort(); break; case running: start = true; break; case sleeping: { libport::utime_t job_deadline = job->deadline_get(); // If the job has been frozen, extend its deadline by the // corresponding amount of time. The deadline will be adjusted // later when the job is unfrozen using notice_not_frozen(), // but in the meantime we do not want to cause an early wakeup. if (libport::utime_t frozen_since = job->frozen_since_get()) job_deadline += current_time - frozen_since; if (job_deadline <= current_time) start = true; else deadline = std::min(deadline, job_deadline); } break; case waiting: // Since jobs keep their orders in the queue, start waiting jobs if // previous jobs in the run have had a possible side effect or if // the previous run may have had some. Without it, we may miss some // changes if the watching job is after the modifying job in the queue // and the watched condition gets true for only one cycle. start = start_waiting || possible_side_effect_; break; case joining: break; } // Tell the job whether it is frozen or not so that it can remember // since when it has been in this state. if (job->frozen()) job->notice_frozen(current_time); else job->notice_not_frozen(current_time); // A job with an exception will start unconditionally. if (start || job->has_pending_exception()) { at_least_one_started = true; ECHO("will resume job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); possible_side_effect_ |= !job->side_effect_free_get(); assert(!current_job_); coroutine_switch_to(&coro_, job->coro_get()); assert(current_job_); current_job_ = 0; possible_side_effect_ |= !job->side_effect_free_get(); ECHO("back from job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); switch (job->state_get()) { case running: deadline = SCHED_IMMEDIATE; break; case sleeping: deadline = std::min(deadline, job->deadline_get()); break; default: break; } } else jobs_.push_back(job); // Job not started, keep it in queue } // If during this cycle a new job has been created by an existing job, // start it. Also start if a possible side effect happened, it may have // occurred later then the waiting jobs in the cycle. if (possible_side_effect_) deadline = SCHED_IMMEDIATE; // If we are ready to die and there are no jobs left, then die. if (ready_to_die_ && jobs_.empty()) deadline = SCHED_EXIT; // Compute statistics if (at_least_one_started) stats_.add_sample(get_time_() - start_time); return deadline; } void Scheduler::resume_scheduler(rJob job) { // If the job has not terminated and is side-effect free, then we // assume it will not take a long time as we are probably evaluating // a condition. In order to reduce the number of cycles spent to evaluate // the condition, continue until it asks to be suspended in another // way or until it is no longer side-effect free. bool side_effect_free_save = job->side_effect_free_get(); if (job->state_get() == running && side_effect_free_save) return; if (job->state_get() == running && job->prio_get() >= UPRIO_RT_MIN && !job->frozen()) return; // We may have to suspend the job several time in case it makes no sense // to start it back. Let's do it in a loop and we'll break when we want // to resume the job. while (true) { // Add the job at the end of the scheduler queue unless the job has // already terminated. if (!job->terminated()) jobs_.push_back(job); // Switch back to the scheduler. But in the case this job has been // destroyed, erase the local variable first so that it doesn't keep // a reference on it which will never be destroyed. assert(current_job_ == job); ECHO(*job << " has " << (job->terminated() ? "" : "not ") << "terminated\n\t" << "state: " << state_name(job->state_get()) << std::endl); Coro* current_coro = job->coro_get(); if (job->terminated()) job = 0; coroutine_switch_to(current_coro, &coro_); // If we regain control, we are not dead. assert(job); // We regained control, we are again in the context of the job. assert(!current_job_); current_job_ = job; ECHO("job " << *job << " resumed"); // Execute a deferred exception if any; this may break out of this loop job->check_for_pending_exception(); // If we are not frozen, it is time to resume regular execution if (!job->frozen()) break; // Ok, we are frozen. Let's requeue ourselves after setting // the side_effect_free flag, and we will be in waiting mode. job->side_effect_free_set(true); job->state_set(waiting); } // Check that we are not near exhausting the stack space. job->check_stack_space(); // Restore the side_effect_free flag job->side_effect_free_set(side_effect_free_save); // Resume job execution } void Scheduler::killall_jobs() { ECHO("killing all jobs!"); // Mark the scheduler as ready to die when all the jobs are // really dead. ready_to_die_ = true; // Since killing the current job will result in its immediate // termination, kill all other jobs before. foreach (const rJob& job, jobs_get()) if (job != current_job_) job->terminate_now(); if (current_job_) current_job_->terminate_now(); } void Scheduler::signal_stop(const Tag& tag, const boost::any& payload) { // Tell the jobs that a tag has been stopped, ending with // the current job to avoid interrupting this method early. foreach (const rJob& job, jobs_get()) { // Job started at this cycle, reset to avoid stack references. if (!job) continue; // Job to be started during this cycle. if (job->state_get() == to_start) { // Check if this job deserves to be removed. foreach (const rTag& t, job->tags_get()) if (t->derives_from(tag)) { pending_.remove(job); continue; } } // Any other non-current job. else if (job != current_job_) job->register_stopped_tag(tag, payload); } if (current_job_) current_job_->register_stopped_tag(tag, payload); } jobs_type Scheduler::jobs_get() const { // If this method is called from within a job, return the currently // executing jobs (pending_), otherwise return the jobs_ content which // is complete. return current_job_ ? pending_ : jobs_; } const scheduler_stats_type& Scheduler::stats_get() const { return stats_; } } // namespace scheduler <commit_msg>Do not store 0 in jobs list.<commit_after>/** ** \file scheduler/scheduler.cc ** \brief Implementation of scheduler::Scheduler. */ //#define ENABLE_DEBUG_TRACES #include <algorithm> #include <cassert> #include <cstdlib> #include <libport/compiler.hh> #include <libport/containers.hh> #include <libport/contract.hh> #include <libport/foreach.hh> #include <object/urbi-exception.hh> #include <scheduler/scheduler.hh> #include <scheduler/job.hh> namespace scheduler { Scheduler::Scheduler(boost::function0<libport::utime_t> get_time) : get_time_(get_time) , current_job_(0) , possible_side_effect_(true) , cycle_(0) , ready_to_die_(false) , real_time_behaviour_(false) { ECHO("Initializing main coroutine"); coroutine_initialize_main(&coro_); } Scheduler::~Scheduler() { ECHO("Destroying scheduler"); } // This function is required to start a new job using the libcoroutine. // Its only purpose is to create the context and start the execution // of the new job. static void run_job(Job* job) { job->run(); } void Scheduler::add_job(rJob job) { assert(job); assert(!libport::has(jobs_, job)); assert(!libport::has(pending_, job)); // If we are currently in a job, add it to the pending_ queue so that // the job is started in the course of the current round. To make sure // that it is not started too late even if the creator is located after // the job that is causing the creation (think "at job handler" for // example), insert it right before the job which was right after the // current one. This way, jobs inserted successively will get queued // in the right order. if (current_job_) pending_.insert(next_job_p_, job); else jobs_.push_back(job); } libport::utime_t Scheduler::work() { ++cycle_; ECHO("======================================================== cycle " << cycle_); libport::utime_t deadline = execute_round(); #ifdef ENABLE_DEBUG_TRACES if (deadline) ECHO("Scheduler asking to be woken up in " << (deadline - get_time_()) / 1000000L << " seconds"); else ECHO("Scheduler asking to be woken up ASAP"); #endif return deadline; } static bool prio_gt(const rJob& j1, const rJob& j2) { return j2->prio_get() < j1->prio_get(); } libport::utime_t Scheduler::execute_round() { // Run all the jobs in the run queue once. If any job declares upon entry or // return that it is not side-effect free, we remember that for the next // cycle. pending_.clear(); std::swap(pending_, jobs_); // Sort all the jobs according to their priority. if (real_time_behaviour_) { static std::vector<rJob> tmp; tmp.reserve(pending_.size()); tmp.clear(); foreach(rJob job, pending_) tmp.push_back(job); std::stable_sort(tmp.begin(), tmp.end(), prio_gt); pending_.clear(); foreach(rJob job, tmp) pending_.push_back(job); } // By default, wake us up after one hour and consider that we have no // new job to start. Also, run waiting jobs only if the previous round // may have add a side effect and reset this indication for the current // job. libport::utime_t start_time = get_time_(); libport::utime_t deadline = start_time + 3600000000LL; bool start_waiting = possible_side_effect_; possible_side_effect_ = false; bool at_least_one_started = false; ECHO(pending_.size() << " jobs in the queue for this round"); // Do not use libport::foreach here, as the list of jobs may grow if // add_job() is called during the iteration. for (jobs_type::iterator job_p = pending_.begin(); job_p != pending_.end(); ++job_p) { rJob job = *job_p; // Store the next job so that insertions happen before it. next_job_p_ = job_p; ++next_job_p_; // If the job has terminated during the previous round, remove the // references we have on it by just skipping it. if (job->terminated()) continue; // Should the job be started? bool start = false; // Save the current time since we will use it several times during this job // analysis. libport::utime_t current_time = get_time_(); ECHO("Considering " << *job << " in state " << state_name(job->state_get())); switch (job->state_get()) { case to_start: { // New job. Start its coroutine but do not start the job as it // would be queued twice otherwise. It will start doing real // work at the next cycle, so set deadline to 0. Note that we // use "continue" here to avoid having the job requeued // because it hasn't been started by setting "start". // // The code below takes care of destroying the rJob reference // to the job, so that it does not stay in the call stack as a // local variable. If it did, the job would never be // destroyed. However, to prevent the job from being // prematurely destroyed, we set current_job_ (global to the // scheduler) to the rJob. ECHO("Starting job " << *job); current_job_ = job; ECHO("Job " << *job << " is starting"); job = 0; coroutine_start(&coro_, current_job_->coro_get(), run_job, current_job_.get()); current_job_ = 0; deadline = SCHED_IMMEDIATE; at_least_one_started = true; continue; } case zombie: abort(); break; case running: start = true; break; case sleeping: { libport::utime_t job_deadline = job->deadline_get(); // If the job has been frozen, extend its deadline by the // corresponding amount of time. The deadline will be adjusted // later when the job is unfrozen using notice_not_frozen(), // but in the meantime we do not want to cause an early wakeup. if (libport::utime_t frozen_since = job->frozen_since_get()) job_deadline += current_time - frozen_since; if (job_deadline <= current_time) start = true; else deadline = std::min(deadline, job_deadline); } break; case waiting: // Since jobs keep their orders in the queue, start waiting jobs if // previous jobs in the run have had a possible side effect or if // the previous run may have had some. Without it, we may miss some // changes if the watching job is after the modifying job in the queue // and the watched condition gets true for only one cycle. start = start_waiting || possible_side_effect_; break; case joining: break; } // Tell the job whether it is frozen or not so that it can remember // since when it has been in this state. if (job->frozen()) job->notice_frozen(current_time); else job->notice_not_frozen(current_time); // A job with an exception will start unconditionally. if (start || job->has_pending_exception()) { at_least_one_started = true; ECHO("will resume job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); possible_side_effect_ |= !job->side_effect_free_get(); assert(!current_job_); coroutine_switch_to(&coro_, job->coro_get()); assert(current_job_); current_job_ = 0; possible_side_effect_ |= !job->side_effect_free_get(); ECHO("back from job " << *job << (job->side_effect_free_get() ? " (side-effect free)" : "")); switch (job->state_get()) { case running: deadline = SCHED_IMMEDIATE; break; case sleeping: deadline = std::min(deadline, job->deadline_get()); break; default: break; } } else jobs_.push_back(job); // Job not started, keep it in queue } // If during this cycle a new job has been created by an existing job, // start it. Also start if a possible side effect happened, it may have // occurred later then the waiting jobs in the cycle. if (possible_side_effect_) deadline = SCHED_IMMEDIATE; // If we are ready to die and there are no jobs left, then die. if (ready_to_die_ && jobs_.empty()) deadline = SCHED_EXIT; // Compute statistics if (at_least_one_started) stats_.add_sample(get_time_() - start_time); return deadline; } void Scheduler::resume_scheduler(rJob job) { // If the job has not terminated and is side-effect free, then we // assume it will not take a long time as we are probably evaluating // a condition. In order to reduce the number of cycles spent to evaluate // the condition, continue until it asks to be suspended in another // way or until it is no longer side-effect free. bool side_effect_free_save = job->side_effect_free_get(); if (job->state_get() == running && side_effect_free_save) return; if (job->state_get() == running && job->prio_get() >= UPRIO_RT_MIN && !job->frozen()) return; // We may have to suspend the job several time in case it makes no sense // to start it back. Let's do it in a loop and we'll break when we want // to resume the job. while (true) { // Add the job at the end of the scheduler queue unless the job has // already terminated. if (!job->terminated()) jobs_.push_back(job); // Switch back to the scheduler. But in the case this job has been // destroyed, erase the local variable first so that it doesn't keep // a reference on it which will never be destroyed. assert(current_job_ == job); ECHO(*job << " has " << (job->terminated() ? "" : "not ") << "terminated\n\t" << "state: " << state_name(job->state_get()) << std::endl); Coro* current_coro = job->coro_get(); if (job->terminated()) job = 0; coroutine_switch_to(current_coro, &coro_); // If we regain control, we are not dead. assert(job); // We regained control, we are again in the context of the job. assert(!current_job_); current_job_ = job; ECHO("job " << *job << " resumed"); // Execute a deferred exception if any; this may break out of this loop job->check_for_pending_exception(); // If we are not frozen, it is time to resume regular execution if (!job->frozen()) break; // Ok, we are frozen. Let's requeue ourselves after setting // the side_effect_free flag, and we will be in waiting mode. job->side_effect_free_set(true); job->state_set(waiting); } // Check that we are not near exhausting the stack space. job->check_stack_space(); // Restore the side_effect_free flag job->side_effect_free_set(side_effect_free_save); // Resume job execution } void Scheduler::killall_jobs() { ECHO("killing all jobs!"); // Mark the scheduler as ready to die when all the jobs are // really dead. ready_to_die_ = true; // Since killing the current job will result in its immediate // termination, kill all other jobs before. foreach (const rJob& job, jobs_get()) if (job != current_job_) job->terminate_now(); if (current_job_) current_job_->terminate_now(); } void Scheduler::signal_stop(const Tag& tag, const boost::any& payload) { // Tell the jobs that a tag has been stopped, ending with // the current job to avoid interrupting this method early. foreach (const rJob& job, jobs_get()) { // The current job will be handled last. if (job == current_job_) continue; // Job to be started during this cycle. if (job->state_get() == to_start) { // Check if this job deserves to be removed. foreach (const rTag& t, job->tags_get()) if (t->derives_from(tag)) { pending_.remove(job); continue; } } // Any other job. else job->register_stopped_tag(tag, payload); } // Handle the current job situation. if (current_job_) current_job_->register_stopped_tag(tag, payload); } jobs_type Scheduler::jobs_get() const { // If this method is called from within a job, return the currently // executing jobs (pending_), otherwise return the jobs_ content which // is complete. return current_job_ ? pending_ : jobs_; } const scheduler_stats_type& Scheduler::stats_get() const { return stats_; } } // namespace scheduler <|endoftext|>
<commit_before>#include <groupby.hpp> #include <vector> #include <iostream> #include <string> using iter::groupby; int length(std::string s) { return s.length(); } int main() { std::vector<std::string> vec = { "hi", "ab", "ho", "abc", "def", "abcde", "efghi" }; for (auto gb : groupby(vec, &length)) { std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } std::cout << "skipping length of 3\n"; for (auto gb : groupby(vec, &length)) { if (gb.first == 3) { continue; } std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } std::vector<int> ivec = {5, 5, 6, 6, 19, 19, 19, 19, 69, 0, 10, 10}; for (auto gb : groupby(ivec)) { std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } for (auto gb : groupby("aabbccccdd", [] (const char c) {return c < 'c';})){ std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } for (auto gb : groupby({'a', 'a', 'b', 'b', 'c'})) { std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } return 0; } <commit_msg>Adds test with initializer_list and defalt Key<commit_after>#include <groupby.hpp> #include <vector> #include <iostream> #include <string> using iter::groupby; int length(std::string s) { return s.length(); } int main() { std::vector<std::string> vec = { "hi", "ab", "ho", "abc", "def", "abcde", "efghi" }; for (auto gb : groupby(vec, &length)) { std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } std::cout << "skipping length of 3\n"; for (auto gb : groupby(vec, &length)) { if (gb.first == 3) { continue; } std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } std::vector<int> ivec = {5, 5, 6, 6, 19, 19, 19, 19, 69, 0, 10, 10}; for (auto gb : groupby(ivec)) { std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } for (auto gb : groupby("aabbccccdd", [] (const char c) {return c < 'c';})){ std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } for (auto gb : groupby({'a', 'a', 'b', 'b', 'c'})) { std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } for (auto gb : groupby({'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'}, [] (const char c) {return c < 'c'; })) { std::cout << "key: " << gb.first << '\n'; std::cout << "content: "; for (auto s : gb.second) { std::cout << s << " "; } std::cout << '\n'; } return 0; } <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE VectorView #include <boost/test/unit_test.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(vector_view) { const size_t N = 1024; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); std::vector<double> x = random_vector<double>(2 * N); vex::vector<double> X(queue, x); vex::vector<double> Y(queue, N); cl_ulong size = N; cl_long stride = 2; vex::gslice<1> slice(0, &size, &stride); Y = slice(X); check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK(v == x[idx * 2]); }); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Added test for 2D slicing<commit_after>#define BOOST_TEST_MODULE VectorView #include <valarray> #include <boost/test/unit_test.hpp> #include "context_setup.hpp" BOOST_AUTO_TEST_CASE(vector_view_1d) { const size_t N = 1024; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); std::vector<double> x = random_vector<double>(2 * N); vex::vector<double> X(queue, x); vex::vector<double> Y(queue, N); cl_ulong size = N; cl_long stride = 2; vex::gslice<1> slice(0, &size, &stride); Y = slice(X); check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK(v == x[idx * 2]); }); } BOOST_AUTO_TEST_CASE(vector_view_2) { const size_t N = 32; std::vector<cl::CommandQueue> queue(1, ctx.queue(0)); std::valarray<double> x(N * N); std::iota(&x[0], &x[N * N], 0); // Select every even point from sub-block [(2,4) - (10,10)]: size_t start = 2 * N + 4; size_t size[] = {5, 4}; size_t stride[] = {2, 2}; std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2)); std::valarray<double> y = x[std_slice]; vex::vector<double> X(queue, N * N, &x[0]); vex::vector<double> Y(queue, size[0] * size[1]); vex::gslice<2> vex_slice(start, size, stride); Y = vex_slice(X); check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); }); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <eeros/core/PeriodicThread.hpp> #include <sched.h> #include <time.h> #include <sys/mman.h> #define RT_PRIORITY (49) /* we use 49 as the PRREMPT_RT use 50 as the priority of kernel tasklets and interrupt handler by default */ #define MAX_SAFE_STACK (8*1024) /* The maximum stack size which is guaranteed safe to access without faulting */ using namespace eeros; void stack_prefault() { unsigned char dummy[MAX_SAFE_STACK] = {}; } PeriodicThread::PeriodicThread(double period, double delay, bool realtime, status start, int priority) : counter(period), rt(realtime), period(period), delay(delay), s(start), Thread([this, priority]() { struct timespec time; uint64_t period_ns = to_ns(this->period); std::string id = getId(); log.trace() << "Periodic thread '" << id << "' started."; int r = clock_gettime(CLOCK_MONOTONIC, &time); if (r != 0) { log.error() << "failed to get time " << errno; return; } time.tv_nsec += to_ns(this->delay); if(this->rt) { log.trace() << "Periodic thread '" << id << "' configured for realtime scheduling."; struct sched_param schedulingParam; schedulingParam.sched_priority = RT_PRIORITY + priority; // TODO use sched_get_priority_max if(sched_setscheduler(0, SCHED_FIFO, &schedulingParam) == -1) { // TODO add support for SCHED_DEADLINE log.error() << "Periodic thread '" << id << "': failed to set real time scheduler!"; } /* Lock memory */ if(mlockall(MCL_CURRENT | MCL_FUTURE) == -1) { log.error() << "Periodic thread '" << id << "': failed to lock memory allocation!"; } /* Pre-fault our stack */ stack_prefault(); // TODO should we use pthread_attr_setstacksize() ? } while(time.tv_nsec >= to_ns(1)) { time.tv_nsec -= to_ns(1); time.tv_sec++; } while(s != stopping) { do { r = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &time, NULL); } while (r == EINTR); if (r != 0) { log.error() << "failed to sleep " << r; break; } counter.tick(); if(s != paused) this->run(); counter.tock(); time.tv_nsec += period_ns; while(time.tv_nsec >= to_ns(1)) { time.tv_nsec -= to_ns(1); time.tv_sec++; } } log.trace() << "Periodic thread '" << id << "' stopped."; s = stopped; }) { } PeriodicThread::~PeriodicThread() { stop(); join(); } PeriodicThread::status PeriodicThread::getStatus() const { return s; } double PeriodicThread::getPeriod() const { return period; } void PeriodicThread::start() { s = running; } void PeriodicThread::pause() { s = paused; } void PeriodicThread::stop() { s = stopping; } <commit_msg>error message fixed<commit_after>#include <eeros/core/PeriodicThread.hpp> #include <sched.h> #include <time.h> #include <sys/mman.h> #define RT_PRIORITY (49) /* we use 49 as the PRREMPT_RT use 50 as the priority of kernel tasklets and interrupt handler by default */ #define MAX_SAFE_STACK (8*1024) /* The maximum stack size which is guaranteed safe to access without faulting */ using namespace eeros; void stack_prefault() { unsigned char dummy[MAX_SAFE_STACK] = {}; } PeriodicThread::PeriodicThread(double period, double delay, bool realtime, status start, int priority) : counter(period), rt(realtime), period(period), delay(delay), s(start), Thread([this, priority]() { struct timespec time; uint64_t period_ns = to_ns(this->period); std::string id = getId(); log.trace() << "Periodic thread '" << id << "' started."; int r = clock_gettime(CLOCK_MONOTONIC, &time); if (r != 0) { log.error() << "failed to get time " << errno; return; } time.tv_nsec += to_ns(this->delay); if(this->rt) { log.trace() << "Periodic thread '" << id << "' configured for realtime scheduling."; struct sched_param schedulingParam; schedulingParam.sched_priority = RT_PRIORITY + priority; // TODO use sched_get_priority_max if(sched_setscheduler(0, SCHED_FIFO, &schedulingParam) == -1) { // TODO add support for SCHED_DEADLINE log.error() << "Periodic thread '" << id << "': failed to set real time scheduler!"; } /* Lock memory */ if(mlockall(MCL_CURRENT | MCL_FUTURE) == -1) { log.error() << "Periodic thread '" << id << "': failed to lock memory in RAM!"; } /* Pre-fault our stack */ stack_prefault(); // TODO should we use pthread_attr_setstacksize() ? } while(time.tv_nsec >= to_ns(1)) { time.tv_nsec -= to_ns(1); time.tv_sec++; } while(s != stopping) { do { r = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &time, NULL); } while (r == EINTR); if (r != 0) { log.error() << "failed to sleep " << r; break; } counter.tick(); if(s != paused) this->run(); counter.tock(); time.tv_nsec += period_ns; while(time.tv_nsec >= to_ns(1)) { time.tv_nsec -= to_ns(1); time.tv_sec++; } } log.trace() << "Periodic thread '" << id << "' stopped."; s = stopped; }) { } PeriodicThread::~PeriodicThread() { stop(); join(); } PeriodicThread::status PeriodicThread::getStatus() const { return s; } double PeriodicThread::getPeriod() const { return period; } void PeriodicThread::start() { s = running; } void PeriodicThread::pause() { s = paused; } void PeriodicThread::stop() { s = stopping; } <|endoftext|>
<commit_before>#include "../include/tile.hpp" //////////////////////////////////////////////////////////////////////////////// tile::tile(): neighbors_(4, nullptr), adjacents_(4, nullptr), tile_color_(NEUTRAL_TILE_COLOR), tile_type_(tileType::NEUTRAL) {} //////////////////////////////////////////////////////////////////////////////// tile::~tile() {} //////////////////////////////////////////////////////////////////////////////// void tile::addFriend(tile *n, const dir direction) { switch (direction) { case dir::UP: neighbors_[0] = n; break; case dir::DOWN: neighbors_[1] = n; break; case dir::LEFT: neighbors_[2] = n; break; case dir::RIGHT: neighbors_[3] = n; break; case dir::UP_LEFT: adjacents_[0] = n; break; case dir::UP_RIGHT: adjacents_[1] = n; break; case dir::DOWN_LEFT: adjacents_[2] = n; break; case dir::DOWN_RIGHT: adjacents_[3] = n; break; default: break; } } //////////////////////////////////////////////////////////////////////////////// tile* tile::getFriend(const dir direction) const { switch (direction) { case dir::UP: return neighbors_[0]; case dir::DOWN: return neighbors_[1]; case dir::LEFT: return neighbors_[2]; case dir::RIGHT: return neighbors_[3]; case dir::UP_LEFT: return adjacents_[0]; case dir::UP_RIGHT: return adjacents_[1]; case dir::DOWN_LEFT: return adjacents_[2]; case dir::DOWN_RIGHT: return adjacents_[3]; default: return nullptr; } } //////////////////////////////////////////////////////////////////////////////// bool tile::isAdjacentTo(const tile *n) const { for (const tile* i : adjacents_) if (i==n) return true; return false; } //////////////////////////////////////////////////////////////////////////////// void tile::appendVertices(std::vector<ALLEGRO_VERTEX> &v, const double cx, const double cy, const double width, const double border, const double max_x, const double max_y) const { // The tile is drawed using two triangles float border_px = border*width; float width_2 = width/2; ALLEGRO_VERTEX points[4] = { {float((cx - width_2)+border_px), float((cy + width_2)-border_px), 0.0f, 0.0f, 0.0f, tile_color_}, {float((cx + width_2)-border_px), float((cy + width_2)-border_px), 0.0f, 0.0f, 0.0f, tile_color_}, {float((cx + width_2)-border_px), float((cy - width_2)+border_px), 0.0f, 0.0f, 0.0f, tile_color_}, {float((cx - width_2)+border_px), float((cy - width_2)+border_px), 0.0f, 0.0f, 0.0f, tile_color_} }; v.push_back(points[0]); v.push_back(points[1]); v.push_back(points[3]); v.push_back(points[2]); v.push_back(points[1]); v.push_back(points[3]); } //////////////////////////////////////////////////////////////////////////////// void tile::setType(const tileType type) { tile_type_ = type; switch (type) { case tileType::WATER: tile_color_ = WATER_TILE_COLOR; break; default: tile_color_ = NEUTRAL_TILE_COLOR; break; } } //////////////////////////////////////////////////////////////////////////////// bool tile::isBorder() const { return isAdjacentTo(nullptr); } //////////////////////////////////////////////////////////////////////////////// bool tile::isWater() const { return tile_type_ == tileType::WATER; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Comprobar vertices<commit_after>#include "../include/tile.hpp" //////////////////////////////////////////////////////////////////////////////// tile::tile(): neighbors_(4, nullptr), adjacents_(4, nullptr), tile_color_(NEUTRAL_TILE_COLOR), tile_type_(tileType::NEUTRAL) {} //////////////////////////////////////////////////////////////////////////////// tile::~tile() {} //////////////////////////////////////////////////////////////////////////////// void tile::addFriend(tile *n, const dir direction) { switch (direction) { case dir::UP: neighbors_[0] = n; break; case dir::DOWN: neighbors_[1] = n; break; case dir::LEFT: neighbors_[2] = n; break; case dir::RIGHT: neighbors_[3] = n; break; case dir::UP_LEFT: adjacents_[0] = n; break; case dir::UP_RIGHT: adjacents_[1] = n; break; case dir::DOWN_LEFT: adjacents_[2] = n; break; case dir::DOWN_RIGHT: adjacents_[3] = n; break; default: break; } } //////////////////////////////////////////////////////////////////////////////// tile* tile::getFriend(const dir direction) const { switch (direction) { case dir::UP: return neighbors_[0]; case dir::DOWN: return neighbors_[1]; case dir::LEFT: return neighbors_[2]; case dir::RIGHT: return neighbors_[3]; case dir::UP_LEFT: return adjacents_[0]; case dir::UP_RIGHT: return adjacents_[1]; case dir::DOWN_LEFT: return adjacents_[2]; case dir::DOWN_RIGHT: return adjacents_[3]; default: return nullptr; } } //////////////////////////////////////////////////////////////////////////////// bool tile::isAdjacentTo(const tile *n) const { for (const tile* i : adjacents_) if (i==n) return true; return false; } //////////////////////////////////////////////////////////////////////////////// void tile::appendVertices(std::vector<ALLEGRO_VERTEX> &v, const double cx, const double cy, const double width, const double border, const double max_x, const double max_y) const { // The tile is drawed using two triangles float border_px = border*width; float width_2 = width/2; ALLEGRO_VERTEX points[4] = { {float((cx - width_2)+border_px), float((cy + width_2)-border_px), 0.0f, 0.0f, 0.0f, tile_color_}, {float((cx + width_2)-border_px), float((cy + width_2)-border_px), 0.0f, 0.0f, 0.0f, tile_color_}, {float((cx + width_2)-border_px), float((cy - width_2)+border_px), 0.0f, 0.0f, 0.0f, tile_color_}, {float((cx - width_2)+border_px), float((cy - width_2)+border_px), 0.0f, 0.0f, 0.0f, tile_color_} }; if (points[0].y >= 0 && points[1].y <= max_y && points[0].x <= max_x && points[3].x >= 0){ v.push_back(points[0]); v.push_back(points[1]); v.push_back(points[3]); } if (points[2].y >= 0 && points[1].y <= max_y && points[2].x <= max_x && points[3].x >= 0){ v.push_back(points[2]); v.push_back(points[1]); v.push_back(points[3]); } } //////////////////////////////////////////////////////////////////////////////// void tile::setType(const tileType type) { tile_type_ = type; switch (type) { case tileType::WATER: tile_color_ = WATER_TILE_COLOR; break; default: tile_color_ = NEUTRAL_TILE_COLOR; break; } } //////////////////////////////////////////////////////////////////////////////// bool tile::isBorder() const { return isAdjacentTo(nullptr); } //////////////////////////////////////////////////////////////////////////////// bool tile::isWater() const { return tile_type_ == tileType::WATER; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include "ghost/config.h" #include "ghost/types.h" #include "ghost/densemat.h" #include "ghost/util.h" #include "ghost/math.h" #include "ghost/tsmm.h" #include "ghost/tsmm_gen.h" #include "ghost/tsmm_avx_gen.h" #include "ghost/tsmm_sse_gen.h" #include "ghost/tsmm_cu_gen.h" #include "ghost/timing.h" #include <map> using namespace std; static bool operator<(const ghost_tsmm_parameters_t &a, const ghost_tsmm_parameters_t &b) { return ghost_hash(a.dt,a.xcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,a.alignment))) < ghost_hash(b.dt,b.xcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,b.alignment))); } static map<ghost_tsmm_parameters_t, ghost_tsmm_kernel_t> ghost_tsmm_kernels; ghost_error_t ghost_tsmm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv, ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror) { if (x->traits.datatype != v->traits.datatype || x->traits.datatype != w->traits.datatype) { if (printerror) { ERROR_LOG("Different data types!"); } return GHOST_ERR_INVALID_ARG; } if (x == v) { if (printerror) { ERROR_LOG("x must not be equal to v!"); } return GHOST_ERR_INVALID_ARG; } if ((x->traits.flags & GHOST_DENSEMAT_SCATTERED) || (v->traits.flags & GHOST_DENSEMAT_SCATTERED) || (w->traits.flags & GHOST_DENSEMAT_SCATTERED)) { if (printerror) { ERROR_LOG("Scattered views not supported!"); } return GHOST_ERR_INVALID_ARG; } if (reduce != GHOST_GEMM_NO_REDUCE) { if (printerror) { ERROR_LOG("Only NO_REDUCE valid!"); } return GHOST_ERR_INVALID_ARG; } if (strncasecmp(transv,"N",1)) { if (printerror) { ERROR_LOG("v must not be transposed!"); } return GHOST_ERR_INVALID_ARG; } if (strncasecmp(transw,"N",1)) { if (printerror) { ERROR_LOG("w must not be transposed!"); } return GHOST_ERR_INVALID_ARG; } UNUSED(alpha); UNUSED(beta); return GHOST_SUCCESS; } ghost_error_t ghost_tsmm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta) { GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH); ghost_error_t ret; if ((ret = ghost_tsmm_valid(x,v,"N",w,"N",alpha,beta,GHOST_GEMM_NO_REDUCE,1)) != GHOST_SUCCESS) { INFO_LOG("TSMM cannot be applied. Checking whether GEMM is fine!"); if ((ret = ghost_gemm_valid(x,v,"N",w,"N",alpha,beta,GHOST_GEMM_NO_REDUCE,GHOST_GEMM_DEFAULT,1)) != GHOST_SUCCESS) { ERROR_LOG("GEMM cannot be applied!"); return ret; } else { return ghost_gemm(x,v,"N",w,"N",alpha,beta,GHOST_GEMM_NO_REDUCE,GHOST_GEMM_NOT_SPECIAL); } } if (ghost_tsmm_kernels.empty()) { #include "tsmm.def" #include "tsmm_avx.def" #include "tsmm_sse.def" #ifdef GHOST_HAVE_CUDA #include "tsmm_cu.def" #endif } ghost_tsmm_parameters_t p; p.dt = x->traits.datatype; p.alignment = GHOST_ALIGNED; ghost_tsmm_kernel_t kernel = NULL; #ifdef GHOST_HAVE_MIC p.impl = GHOST_IMPLEMENTATION_MIC; #elif defined(GHOST_HAVE_AVX) p.impl = GHOST_IMPLEMENTATION_AVX; #elif defined(GHOST_HAVE_SSE) p.impl = GHOST_IMPLEMENTATION_SSE; #else p.impl = GHOST_IMPLEMENTATION_PLAIN; #endif #ifdef GHOST_HAVE_CUDA if (x->traits.location & GHOST_LOCATION_DEVICE) { p.impl = GHOST_IMPLEMENTATION_CUDA; p.dt = GHOST_DT_ANY; p.alignment = GHOST_UNALIGNED; } #endif p.xstor = x->traits.storage; p.wstor = w->traits.storage; p.xcols = x->traits.ncols; p.vcols = v->traits.ncols; if (p.vcols < 4 || p.xcols < 4) { p.impl = GHOST_IMPLEMENTATION_PLAIN; } else if (p.vcols % 4 || p.xcols % 4) { if (!(x->traits.flags & GHOST_DENSEMAT_VIEW) && (!(v->traits.ncolspadded % 4) && !(x->traits.ncolspadded % 4))) { p.vcols = v->traits.ncolspadded; p.xcols = x->traits.ncolspadded; } else { if (p.xcols == 2) { #ifdef GHOST_HAVE_SSE PERFWARNING_LOG("Use SSE for ncols==2"); p.impl = GHOST_IMPLEMENTATION_SSE; #endif } if (p.xcols == 1) { PERFWARNING_LOG("Use plain for ncols==1"); p.impl = GHOST_IMPLEMENTATION_PLAIN; } if ((p.xcols % 4 || p.vcols % 4) && (p.impl != GHOST_IMPLEMENTATION_CUDA)) { PERFWARNING_LOG("Use SSE for non-multiple of four"); p.impl = GHOST_IMPLEMENTATION_SSE; } if ((p.xcols % 2 || p.vcols % 2) && (p.impl != GHOST_IMPLEMENTATION_CUDA)) { PERFWARNING_LOG("Use plain for non-even column count"); p.impl = GHOST_IMPLEMENTATION_PLAIN; } } } if (p.impl == GHOST_IMPLEMENTATION_SSE) { if (!IS_ALIGNED(x->val,16) || !IS_ALIGNED(v->val,16) || !IS_ALIGNED(w->val,16) || (x->stride*x->elSize)%16 || (v->stride*v->elSize)%16 || (w->stride*w->elSize)%16) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } } if (p.impl == GHOST_IMPLEMENTATION_AVX) { if (!IS_ALIGNED(x->val,32) || !IS_ALIGNED(v->val,32) || !IS_ALIGNED(w->val,32) || (x->stride*x->elSize)%32 || (v->stride*v->elSize)%32 || (w->stride*w->elSize)%32) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } } if (p.impl == GHOST_IMPLEMENTATION_PLAIN || p.impl == GHOST_IMPLEMENTATION_MIC) { if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || !IS_ALIGNED(w->val,64) || (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64 || (w->stride*w->elSize)%64) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } } INFO_LOG("Initial search for kernel %d %d %d %d %d %d %d!",p.alignment,p.impl,p.dt,p.xcols,p.vcols,p.xstor,p.wstor); kernel = ghost_tsmm_kernels[p]; if (!kernel) { PERFWARNING_LOG("Try kernel with fixed xcols and arbitrary vcols"); p.xcols = x->traits.ncols; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with fixed vcols and arbitrary xcols"); p.xcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.xcols = -1; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try plain implementation"); p.impl = GHOST_IMPLEMENTATION_PLAIN; if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || !IS_ALIGNED(w->val,64) || (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64 || (w->stride*w->elSize)%64) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } else { p.alignment = GHOST_ALIGNED; } p.xcols = x->traits.ncols; p.vcols = v->traits.ncols; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with fixed xcols and arbitrary vcols"); p.xcols = x->traits.ncols; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with fixed vcols and arbitrary xcols"); p.xcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.xcols = -1; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try unaligned kernel"); p.alignment = GHOST_UNALIGNED; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { INFO_LOG("Could not find TSMM kernel with %d %d %d %d %d %d %d!",p.alignment,p.impl,p.dt,p.xcols,p.vcols,p.xstor,p.wstor); return GHOST_ERR_INVALID_ARG; } ret = kernel(x,v,w,alpha,beta); #ifdef GHOST_HAVE_INSTR_TIMING ghost_gemm_perf_args_t tsmm_perfargs; tsmm_perfargs.n = p.xcols; tsmm_perfargs.k = p.vcols; if (v->context) { tsmm_perfargs.m = v->context->gnrows; } else { tsmm_perfargs.m = v->traits.nrows; } tsmm_perfargs.dt = x->traits.datatype; tsmm_perfargs.betaiszero = ghost_iszero(beta,p.dt); tsmm_perfargs.alphaisone = ghost_isone(alpha,p.dt); ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GBs,(void *)&tsmm_perfargs,sizeof(tsmm_perfargs),"GB/s"); ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmm_perfargs,sizeof(tsmm_perfargs),"GF/s"); #endif GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH); return ret; } <commit_msg>the small matrix does not have to be aligned as we can do this in the kernel.<commit_after>#include "ghost/config.h" #include "ghost/types.h" #include "ghost/densemat.h" #include "ghost/util.h" #include "ghost/math.h" #include "ghost/tsmm.h" #include "ghost/tsmm_gen.h" #include "ghost/tsmm_avx_gen.h" #include "ghost/tsmm_sse_gen.h" #include "ghost/tsmm_cu_gen.h" #include "ghost/timing.h" #include <map> using namespace std; static bool operator<(const ghost_tsmm_parameters_t &a, const ghost_tsmm_parameters_t &b) { return ghost_hash(a.dt,a.xcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,a.alignment))) < ghost_hash(b.dt,b.xcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,b.alignment))); } static map<ghost_tsmm_parameters_t, ghost_tsmm_kernel_t> ghost_tsmm_kernels; ghost_error_t ghost_tsmm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv, ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror) { if (x->traits.datatype != v->traits.datatype || x->traits.datatype != w->traits.datatype) { if (printerror) { ERROR_LOG("Different data types!"); } return GHOST_ERR_INVALID_ARG; } if (x == v) { if (printerror) { ERROR_LOG("x must not be equal to v!"); } return GHOST_ERR_INVALID_ARG; } if ((x->traits.flags & GHOST_DENSEMAT_SCATTERED) || (v->traits.flags & GHOST_DENSEMAT_SCATTERED) || (w->traits.flags & GHOST_DENSEMAT_SCATTERED)) { if (printerror) { ERROR_LOG("Scattered views not supported!"); } return GHOST_ERR_INVALID_ARG; } if (reduce != GHOST_GEMM_NO_REDUCE) { if (printerror) { ERROR_LOG("Only NO_REDUCE valid!"); } return GHOST_ERR_INVALID_ARG; } if (strncasecmp(transv,"N",1)) { if (printerror) { ERROR_LOG("v must not be transposed!"); } return GHOST_ERR_INVALID_ARG; } if (strncasecmp(transw,"N",1)) { if (printerror) { ERROR_LOG("w must not be transposed!"); } return GHOST_ERR_INVALID_ARG; } UNUSED(alpha); UNUSED(beta); return GHOST_SUCCESS; } ghost_error_t ghost_tsmm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta) { GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH); ghost_error_t ret; if ((ret = ghost_tsmm_valid(x,v,"N",w,"N",alpha,beta,GHOST_GEMM_NO_REDUCE,1)) != GHOST_SUCCESS) { INFO_LOG("TSMM cannot be applied. Checking whether GEMM is fine!"); if ((ret = ghost_gemm_valid(x,v,"N",w,"N",alpha,beta,GHOST_GEMM_NO_REDUCE,GHOST_GEMM_DEFAULT,1)) != GHOST_SUCCESS) { ERROR_LOG("GEMM cannot be applied!"); return ret; } else { return ghost_gemm(x,v,"N",w,"N",alpha,beta,GHOST_GEMM_NO_REDUCE,GHOST_GEMM_NOT_SPECIAL); } } if (ghost_tsmm_kernels.empty()) { #include "tsmm.def" #include "tsmm_avx.def" #include "tsmm_sse.def" #ifdef GHOST_HAVE_CUDA #include "tsmm_cu.def" #endif } ghost_tsmm_parameters_t p; p.dt = x->traits.datatype; p.alignment = GHOST_ALIGNED; ghost_tsmm_kernel_t kernel = NULL; #ifdef GHOST_HAVE_MIC p.impl = GHOST_IMPLEMENTATION_MIC; #elif defined(GHOST_HAVE_AVX) p.impl = GHOST_IMPLEMENTATION_AVX; #elif defined(GHOST_HAVE_SSE) p.impl = GHOST_IMPLEMENTATION_SSE; #else p.impl = GHOST_IMPLEMENTATION_PLAIN; #endif #ifdef GHOST_HAVE_CUDA if (x->traits.location & GHOST_LOCATION_DEVICE) { p.impl = GHOST_IMPLEMENTATION_CUDA; p.dt = GHOST_DT_ANY; p.alignment = GHOST_UNALIGNED; } #endif p.xstor = x->traits.storage; p.wstor = w->traits.storage; p.xcols = x->traits.ncols; p.vcols = v->traits.ncols; if (p.vcols < 4 || p.xcols < 4) { p.impl = GHOST_IMPLEMENTATION_PLAIN; } else if (p.vcols % 4 || p.xcols % 4) { if (!(x->traits.flags & GHOST_DENSEMAT_VIEW) && (!(v->traits.ncolspadded % 4) && !(x->traits.ncolspadded % 4))) { p.vcols = v->traits.ncolspadded; p.xcols = x->traits.ncolspadded; } else { if (p.xcols == 2) { #ifdef GHOST_HAVE_SSE PERFWARNING_LOG("Use SSE for ncols==2"); p.impl = GHOST_IMPLEMENTATION_SSE; #endif } if (p.xcols == 1) { PERFWARNING_LOG("Use plain for ncols==1"); p.impl = GHOST_IMPLEMENTATION_PLAIN; } if ((p.xcols % 4 || p.vcols % 4) && (p.impl != GHOST_IMPLEMENTATION_CUDA)) { PERFWARNING_LOG("Use SSE for non-multiple of four"); p.impl = GHOST_IMPLEMENTATION_SSE; } if ((p.xcols % 2 || p.vcols % 2) && (p.impl != GHOST_IMPLEMENTATION_CUDA)) { PERFWARNING_LOG("Use plain for non-even column count"); p.impl = GHOST_IMPLEMENTATION_PLAIN; } } } if (p.impl == GHOST_IMPLEMENTATION_SSE) { if (!IS_ALIGNED(x->val,16) || !IS_ALIGNED(v->val,16) || !IS_ALIGNED(w->val,16) || (x->stride*x->elSize)%16 || (v->stride*v->elSize)%16 || (w->stride*w->elSize)%16) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } } if (p.impl == GHOST_IMPLEMENTATION_AVX) { if (!IS_ALIGNED(x->val,32) || !IS_ALIGNED(v->val,32) || !IS_ALIGNED(w->val,32) || (x->stride*x->elSize)%32 || (v->stride*v->elSize)%32 || (w->stride*w->elSize)%32) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } } if (p.impl == GHOST_IMPLEMENTATION_PLAIN || p.impl == GHOST_IMPLEMENTATION_MIC) { if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } } INFO_LOG("Initial search for kernel %d %d %d %d %d %d %d!",p.alignment,p.impl,p.dt,p.xcols,p.vcols,p.xstor,p.wstor); kernel = ghost_tsmm_kernels[p]; if (!kernel) { PERFWARNING_LOG("Try kernel with fixed xcols and arbitrary vcols"); p.xcols = x->traits.ncols; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with fixed vcols and arbitrary xcols"); p.xcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.xcols = -1; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try plain implementation"); p.impl = GHOST_IMPLEMENTATION_PLAIN; if (!IS_ALIGNED(x->val,64) || !IS_ALIGNED(v->val,64) || !IS_ALIGNED(w->val,64) || (x->stride*x->elSize)%64 || (v->stride*v->elSize)%64 || (w->stride*w->elSize)%64) { p.alignment = GHOST_UNALIGNED; PERFWARNING_LOG("Switching to the unaligned kernel!"); } else { p.alignment = GHOST_ALIGNED; } p.xcols = x->traits.ncols; p.vcols = v->traits.ncols; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with fixed xcols and arbitrary vcols"); p.xcols = x->traits.ncols; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with fixed vcols and arbitrary xcols"); p.xcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.xcols = -1; p.vcols = -1; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try unaligned kernel"); p.alignment = GHOST_UNALIGNED; kernel = ghost_tsmm_kernels[p]; } if (!kernel) { INFO_LOG("Could not find TSMM kernel with %d %d %d %d %d %d %d!",p.alignment,p.impl,p.dt,p.xcols,p.vcols,p.xstor,p.wstor); return GHOST_ERR_INVALID_ARG; } ret = kernel(x,v,w,alpha,beta); #ifdef GHOST_HAVE_INSTR_TIMING ghost_gemm_perf_args_t tsmm_perfargs; tsmm_perfargs.n = p.xcols; tsmm_perfargs.k = p.vcols; if (v->context) { tsmm_perfargs.m = v->context->gnrows; } else { tsmm_perfargs.m = v->traits.nrows; } tsmm_perfargs.dt = x->traits.datatype; tsmm_perfargs.betaiszero = ghost_iszero(beta,p.dt); tsmm_perfargs.alphaisone = ghost_isone(alpha,p.dt); ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GBs,(void *)&tsmm_perfargs,sizeof(tsmm_perfargs),"GB/s"); ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmm_perfargs,sizeof(tsmm_perfargs),"GF/s"); #endif GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH); return ret; } <|endoftext|>
<commit_before>/* * StringUtils.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/StringUtils.hpp> #include <tests/TestThat.hpp> namespace core { namespace string_utils { test_that("isSubsequence works") { expect_true(isSubsequence("", "")); } } // end namespace string_utils } // end namespace core <commit_msg>add a couple more simple tests<commit_after>/* * StringUtils.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include <core/StringUtils.hpp> #include <tests/TestThat.hpp> namespace core { namespace string_utils { test_that("isSubsequence works") { expect_true(isSubsequence("", "")); expect_true(isSubsequence("annnbnnnc", "abc")); expect_false(isSubsequence("abcdef", "abdcef")); expect_true(isSubsequence("abcdef", "AeF", true)); } } // end namespace string_utils } // end namespace core <|endoftext|>
<commit_before>#ifndef VEXCL_SYMBOLIC_HPP #define VEXCL_SYMBOLIC_HPP #include <iostream> #include <string> #include <sstream> #include <map> #include <exception> #include <type_traits> #include <vexcl/util.hpp> namespace vex { namespace generator { template <bool dummy = true> class recorder { public: static void set(std::ostream &s) { os = &s; } static std::ostream& get() { return os ? *os : std::cout; } private: static std::ostream *os; }; template <bool dummy> std::ostream* recorder<dummy>::os = 0; inline void set_recorder(std::ostream &os) { recorder<>::set(os); } inline std::ostream& get_recorder() { return recorder<>::get(); } template <class T, class Enable = void> struct terminal { static std::string get(const T &v) { std::ostringstream s; s << std::scientific << std::setprecision(18) << v; return s.str(); } }; template <class T> struct terminal< T, typename std::enable_if<T::is_symbolic>::type > { static std::string get(const T &v) { return v.get_string(); } }; template <typename T> class symbolic { public: enum scope_type { LocalVar = 0, Parameter = 1 }; enum dimension_type { Scalar = 0, Vector = 1 }; enum constness_type { NonConst = 0, Const = 1 }; static const bool is_symbolic = true; symbolic( scope_type scope = LocalVar, dimension_type dimension = Vector, constness_type constness = Const ) : num(index++), scope(scope), dimension(dimension), constness(constness) { if (scope == LocalVar) { get_recorder() << type_name<T>() << " " << get_string() << ";\n"; } } symbolic(const symbolic &s) : num(index++) { get_recorder() << type_name<T>() << " " << get_string() << " = " << s.get_string() << ";\n"; } std::string get_string() const { std::ostringstream s; s << "var" << num; return s.str(); } const symbolic& operator=(const symbolic &s) { get_recorder() << get_string() << " = " << s.get_string() << ";\n"; return *this; } template <class Expr> const symbolic& operator=(const Expr &expr) const { get_recorder() << get_string() << " = " << terminal<Expr>::get(expr) << ";\n"; return *this; } #define COMPOUND_ASSIGNMENT(cop, op) \ template <class Expr> \ const symbolic& operator cop(const Expr &expr) { \ return *this = *this op expr; \ } COMPOUND_ASSIGNMENT(+=, +); COMPOUND_ASSIGNMENT(-=, -); COMPOUND_ASSIGNMENT(*=, *); COMPOUND_ASSIGNMENT(/=, /); COMPOUND_ASSIGNMENT(%=, %); COMPOUND_ASSIGNMENT(&=, &); COMPOUND_ASSIGNMENT(|=, |); COMPOUND_ASSIGNMENT(^=, ^); COMPOUND_ASSIGNMENT(<<=, <<); COMPOUND_ASSIGNMENT(>>=, >>); #undef COMPOUND_ASSIGNMENT std::string read() const { std::ostringstream s; s << type_name<T>() << " " << get_string() << " = p_" << get_string(); switch (dimension) { case Vector: s << "[idx];\n"; break; case Scalar: s << ";\n"; break; } return s.str(); } std::string write() const { std::ostringstream s; if (dimension == Vector && constness == NonConst) s << "p_" << get_string() << "[idx] = " << get_string() << ";\n"; return s.str(); } std::string prmdecl() const { std::ostringstream s; if (dimension == Vector) s << "global "; if (constness == Const) s << "const "; s << type_name<T>(); if (dimension == Vector) s << "* "; s << "p_" << get_string(); return s.str(); } private: static size_t index; size_t num; scope_type scope; dimension_type dimension; constness_type constness; }; template <typename T> size_t symbolic<T>::index = 0; template <class LHS, binop::kind OP, class RHS> struct symbolic_expression { static const bool is_symbolic = true; symbolic_expression(const LHS &lhs, const RHS &rhs) : lhs(lhs), rhs(rhs) {} const LHS &lhs; const RHS &rhs; std::string get_string() const { std::ostringstream s; s << "(" << terminal<LHS>::get(lhs) << " " << binop::traits<OP>::oper() << " " << terminal<RHS>::get(rhs) << ")"; return s.str(); } }; template <class T, class Enable = void> struct valid_symb : public std::false_type {}; template <class T> struct valid_symb<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> : std::true_type {}; template <class T> struct valid_symb<T, typename std::enable_if<T::is_symbolic>::type> : std::true_type {}; #define DEFINE_BINARY_OP(kind, oper) \ template <class LHS, class RHS> \ typename std::enable_if<valid_symb<LHS>::value && valid_symb<RHS>::value, \ symbolic_expression<LHS, kind, RHS> \ >::type \ operator oper(const LHS &lhs, const RHS &rhs) { \ return symbolic_expression<LHS, kind, RHS>(lhs, rhs); \ } DEFINE_BINARY_OP(binop::Add, + ) DEFINE_BINARY_OP(binop::Subtract, - ) DEFINE_BINARY_OP(binop::Multiply, * ) DEFINE_BINARY_OP(binop::Divide, / ) DEFINE_BINARY_OP(binop::Remainder, % ) DEFINE_BINARY_OP(binop::Greater, > ) DEFINE_BINARY_OP(binop::Less, < ) DEFINE_BINARY_OP(binop::GreaterEqual, >=) DEFINE_BINARY_OP(binop::LessEqual, <=) DEFINE_BINARY_OP(binop::Equal, ==) DEFINE_BINARY_OP(binop::NotEqual, !=) DEFINE_BINARY_OP(binop::BitwiseAnd, & ) DEFINE_BINARY_OP(binop::BitwiseOr, | ) DEFINE_BINARY_OP(binop::BitwiseXor, ^ ) DEFINE_BINARY_OP(binop::LogicalAnd, &&) DEFINE_BINARY_OP(binop::LogicalOr, ||) DEFINE_BINARY_OP(binop::RightShift, >>) DEFINE_BINARY_OP(binop::LeftShift, <<) #undef DEFINE_BINARY_OP template <class... Args> class Kernel { public: Kernel( const std::vector<cl::CommandQueue> &queue, const std::string &name, const std::string &body, const Args&... args ) : queue(queue) { std::ostringstream source; source << standard_kernel_header << "kernel void " << name << "(\n" << "\t" << type_name<size_t>() << " n"; declare_params(source, args...); source << "\n\t)\n{\n" << "size_t idx = get_global_id(0);\n" << "if (idx < n) {\n"; read_params(source, args...); source << body; write_params(source, args...); source << "}\n}\n"; #ifdef VEXCL_SHOW_KERNELS std::cout << source.str() << std::endl; #endif for(auto q = queue.begin(); q != queue.end(); q++) { cl::Context context = q->getInfo<CL_QUEUE_CONTEXT>(); cl::Device device = q->getInfo<CL_QUEUE_DEVICE>(); auto program = build_sources(context, source.str()); krn[context()] = cl::Kernel(program, name.c_str()); wgs[context()] = kernel_workgroup_size(krn[context()], device); } } template <class... Param> void operator()(const Param&... param) { static_assert( sizeof...(Param) == sizeof...(Args), "Wrong number of kernel parameters" ); for(uint d = 0; d < queue.size(); d++) { if (size_t psize = prm_size(d, param...)) { cl::Context context = queue[d].getInfo<CL_QUEUE_CONTEXT>(); uint pos = 0; krn[context()].setArg(pos++, psize); set_params(krn[context()], d, pos, param...); queue[d].enqueueNDRangeKernel( krn[context()], cl::NullRange, alignup(psize, wgs[context()]), wgs[context()] ); } } } private: std::vector<cl::CommandQueue> queue; std::map<cl_context, cl::Kernel> krn; std::map<cl_context, uint> wgs; void declare_params(std::ostream &os) const {} template <class Head, class... Tail> void declare_params(std::ostream &os, const Head &head, const Tail&... tail) { os << ",\n\t" << head.prmdecl(); declare_params(os, tail...); } void read_params(std::ostream &os) const {} template <class Head, class... Tail> void read_params(std::ostream &os, const Head &head, const Tail&... tail) { os << head.read(); read_params(os, tail...); } void write_params(std::ostream &os) const {} template <class Head, class... Tail> void write_params(std::ostream &os, const Head &head, const Tail&... tail) { os << head.write(); write_params(os, tail...); } size_t prm_size(uint d) const { throw std::logic_error( "Kernel has to have at least one vector parameter" ); } template <class Head, class... Tail> size_t prm_size(uint d, const Head &head, const Tail&... tail) const { if (std::is_arithmetic<Head>::value) return prm_size(d, tail...); else return KernelGenerator<Head>(head).part_size(d); } void set_params(cl::Kernel &k, uint d, uint &p) const {} template <class Head, class... Tail> void set_params(cl::Kernel &k, uint d, uint &p, const Head &head, const Tail&... tail) const { KernelGenerator<Head>(head).kernel_args(k, d, p); set_params(k, d, p, tail...); } }; template <class... Args> Kernel<Args...> build_kernel( const std::vector<cl::CommandQueue> &queue, const std::string &name, const std::string& body, const Args&... args ) { return Kernel<Args...>(queue, name, body, args...); } } // namespace generator; } // namespace vex; #endif <commit_msg>nonconst symbolic by default<commit_after>#ifndef VEXCL_SYMBOLIC_HPP #define VEXCL_SYMBOLIC_HPP #include <iostream> #include <string> #include <sstream> #include <map> #include <exception> #include <type_traits> #include <vexcl/util.hpp> namespace vex { namespace generator { template <bool dummy = true> class recorder { public: static void set(std::ostream &s) { os = &s; } static std::ostream& get() { return os ? *os : std::cout; } private: static std::ostream *os; }; template <bool dummy> std::ostream* recorder<dummy>::os = 0; inline void set_recorder(std::ostream &os) { recorder<>::set(os); } inline std::ostream& get_recorder() { return recorder<>::get(); } template <class T, class Enable = void> struct terminal { static std::string get(const T &v) { std::ostringstream s; s << std::scientific << std::setprecision(18) << v; return s.str(); } }; template <class T> struct terminal< T, typename std::enable_if<T::is_symbolic>::type > { static std::string get(const T &v) { return v.get_string(); } }; template <typename T> class symbolic { public: enum scope_type { LocalVar = 0, Parameter = 1 }; enum dimension_type { Scalar = 0, Vector = 1 }; enum constness_type { NonConst = 0, Const = 1 }; static const bool is_symbolic = true; symbolic( scope_type scope = LocalVar, dimension_type dimension = Vector, constness_type constness = NonConst ) : num(index++), scope(scope), dimension(dimension), constness(constness) { if (scope == LocalVar) { get_recorder() << type_name<T>() << " " << get_string() << ";\n"; } } symbolic(const symbolic &s) : num(index++) { get_recorder() << type_name<T>() << " " << get_string() << " = " << s.get_string() << ";\n"; } std::string get_string() const { std::ostringstream s; s << "var" << num; return s.str(); } const symbolic& operator=(const symbolic &s) { get_recorder() << get_string() << " = " << s.get_string() << ";\n"; return *this; } template <class Expr> const symbolic& operator=(const Expr &expr) const { get_recorder() << get_string() << " = " << terminal<Expr>::get(expr) << ";\n"; return *this; } #define COMPOUND_ASSIGNMENT(cop, op) \ template <class Expr> \ const symbolic& operator cop(const Expr &expr) { \ return *this = *this op expr; \ } COMPOUND_ASSIGNMENT(+=, +); COMPOUND_ASSIGNMENT(-=, -); COMPOUND_ASSIGNMENT(*=, *); COMPOUND_ASSIGNMENT(/=, /); COMPOUND_ASSIGNMENT(%=, %); COMPOUND_ASSIGNMENT(&=, &); COMPOUND_ASSIGNMENT(|=, |); COMPOUND_ASSIGNMENT(^=, ^); COMPOUND_ASSIGNMENT(<<=, <<); COMPOUND_ASSIGNMENT(>>=, >>); #undef COMPOUND_ASSIGNMENT std::string read() const { std::ostringstream s; s << type_name<T>() << " " << get_string() << " = p_" << get_string(); switch (dimension) { case Vector: s << "[idx];\n"; break; case Scalar: s << ";\n"; break; } return s.str(); } std::string write() const { std::ostringstream s; if (dimension == Vector && constness == NonConst) s << "p_" << get_string() << "[idx] = " << get_string() << ";\n"; return s.str(); } std::string prmdecl() const { std::ostringstream s; if (dimension == Vector) s << "global "; if (constness == Const) s << "const "; s << type_name<T>(); if (dimension == Vector) s << "* "; s << "p_" << get_string(); return s.str(); } private: static size_t index; size_t num; scope_type scope; dimension_type dimension; constness_type constness; }; template <typename T> size_t symbolic<T>::index = 0; template <class LHS, binop::kind OP, class RHS> struct symbolic_expression { static const bool is_symbolic = true; symbolic_expression(const LHS &lhs, const RHS &rhs) : lhs(lhs), rhs(rhs) {} const LHS &lhs; const RHS &rhs; std::string get_string() const { std::ostringstream s; s << "(" << terminal<LHS>::get(lhs) << " " << binop::traits<OP>::oper() << " " << terminal<RHS>::get(rhs) << ")"; return s.str(); } }; template <class T, class Enable = void> struct valid_symb : public std::false_type {}; template <class T> struct valid_symb<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> : std::true_type {}; template <class T> struct valid_symb<T, typename std::enable_if<T::is_symbolic>::type> : std::true_type {}; #define DEFINE_BINARY_OP(kind, oper) \ template <class LHS, class RHS> \ typename std::enable_if<valid_symb<LHS>::value && valid_symb<RHS>::value, \ symbolic_expression<LHS, kind, RHS> \ >::type \ operator oper(const LHS &lhs, const RHS &rhs) { \ return symbolic_expression<LHS, kind, RHS>(lhs, rhs); \ } DEFINE_BINARY_OP(binop::Add, + ) DEFINE_BINARY_OP(binop::Subtract, - ) DEFINE_BINARY_OP(binop::Multiply, * ) DEFINE_BINARY_OP(binop::Divide, / ) DEFINE_BINARY_OP(binop::Remainder, % ) DEFINE_BINARY_OP(binop::Greater, > ) DEFINE_BINARY_OP(binop::Less, < ) DEFINE_BINARY_OP(binop::GreaterEqual, >=) DEFINE_BINARY_OP(binop::LessEqual, <=) DEFINE_BINARY_OP(binop::Equal, ==) DEFINE_BINARY_OP(binop::NotEqual, !=) DEFINE_BINARY_OP(binop::BitwiseAnd, & ) DEFINE_BINARY_OP(binop::BitwiseOr, | ) DEFINE_BINARY_OP(binop::BitwiseXor, ^ ) DEFINE_BINARY_OP(binop::LogicalAnd, &&) DEFINE_BINARY_OP(binop::LogicalOr, ||) DEFINE_BINARY_OP(binop::RightShift, >>) DEFINE_BINARY_OP(binop::LeftShift, <<) #undef DEFINE_BINARY_OP template <class... Args> class Kernel { public: Kernel( const std::vector<cl::CommandQueue> &queue, const std::string &name, const std::string &body, const Args&... args ) : queue(queue) { std::ostringstream source; source << standard_kernel_header << "kernel void " << name << "(\n" << "\t" << type_name<size_t>() << " n"; declare_params(source, args...); source << "\n\t)\n{\n" << "size_t idx = get_global_id(0);\n" << "if (idx < n) {\n"; read_params(source, args...); source << body; write_params(source, args...); source << "}\n}\n"; #ifdef VEXCL_SHOW_KERNELS std::cout << source.str() << std::endl; #endif for(auto q = queue.begin(); q != queue.end(); q++) { cl::Context context = q->getInfo<CL_QUEUE_CONTEXT>(); cl::Device device = q->getInfo<CL_QUEUE_DEVICE>(); auto program = build_sources(context, source.str()); krn[context()] = cl::Kernel(program, name.c_str()); wgs[context()] = kernel_workgroup_size(krn[context()], device); } } template <class... Param> void operator()(const Param&... param) { static_assert( sizeof...(Param) == sizeof...(Args), "Wrong number of kernel parameters" ); for(uint d = 0; d < queue.size(); d++) { if (size_t psize = prm_size(d, param...)) { cl::Context context = queue[d].getInfo<CL_QUEUE_CONTEXT>(); uint pos = 0; krn[context()].setArg(pos++, psize); set_params(krn[context()], d, pos, param...); queue[d].enqueueNDRangeKernel( krn[context()], cl::NullRange, alignup(psize, wgs[context()]), wgs[context()] ); } } } private: std::vector<cl::CommandQueue> queue; std::map<cl_context, cl::Kernel> krn; std::map<cl_context, uint> wgs; void declare_params(std::ostream &os) const {} template <class Head, class... Tail> void declare_params(std::ostream &os, const Head &head, const Tail&... tail) { os << ",\n\t" << head.prmdecl(); declare_params(os, tail...); } void read_params(std::ostream &os) const {} template <class Head, class... Tail> void read_params(std::ostream &os, const Head &head, const Tail&... tail) { os << head.read(); read_params(os, tail...); } void write_params(std::ostream &os) const {} template <class Head, class... Tail> void write_params(std::ostream &os, const Head &head, const Tail&... tail) { os << head.write(); write_params(os, tail...); } size_t prm_size(uint d) const { throw std::logic_error( "Kernel has to have at least one vector parameter" ); } template <class Head, class... Tail> size_t prm_size(uint d, const Head &head, const Tail&... tail) const { if (std::is_arithmetic<Head>::value) return prm_size(d, tail...); else return KernelGenerator<Head>(head).part_size(d); } void set_params(cl::Kernel &k, uint d, uint &p) const {} template <class Head, class... Tail> void set_params(cl::Kernel &k, uint d, uint &p, const Head &head, const Tail&... tail) const { KernelGenerator<Head>(head).kernel_args(k, d, p); set_params(k, d, p, tail...); } }; template <class... Args> Kernel<Args...> build_kernel( const std::vector<cl::CommandQueue> &queue, const std::string &name, const std::string& body, const Args&... args ) { return Kernel<Args...>(queue, name, body, args...); } } // namespace generator; } // namespace vex; #endif <|endoftext|>
<commit_before>/*************************************************************************** Copyright (C) 2007 by Marco Gulino <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ***************************************************************************/ #include "calendar_jobs.h" #include "engine.h" #include "kmobiletoolsat_engine.h" #include <qregexp.h> #include <qstring.h> #include <qdatetime.h> #include <libkcal/alarm.h> #include <kdeversion.h> FetchCalendar::FetchCalendar(KMobileTools::Job *pjob, KMobileTools::SerialManager *device, kmobiletoolsAT_engine* parent) : kmobiletoolsATJob(pjob, device, parent) { p_calendar=engine->engineData()->calendar(); p_calendar->clear(); } void FetchCalendar::run() { engine->suspendStatusJobs(true ); if(engine->getATAbilities().isMotorola()) { fetchMotorolaCalendar(); return; } } void FetchCalendar::fetchMotorolaCalendar() { kDebug() <<"void FetchCalendar::fetchMotorolaCalendar()"; QString buffer; QRegExp regexp; buffer=p_device->sendATCommand(this, "AT+MDBL=1\r" ); if(KMobileTools::SerialManager::ATError(buffer)) return; buffer=p_device->sendATCommand(this, "AT+MDBR=?\r" ); if(KMobileTools::SerialManager::ATError(buffer)) { p_device->sendATCommand(this, "AT+MDBL=0\r" ); return; } buffer=formatBuffer(buffer).grep("MDBR").first(); regexp.setPattern( "^[+]MDBR:[\\s]*([\\d]*),.*"); regexp.search(buffer); int maxcal=regexp.cap(1).toInt(); kDebug() <<"Max number of calendar entries:" << maxcal; QStringList entries; for(int i=0; i<maxcal; i+=10) { buffer=p_device->sendATCommand(this, QString("AT+MDBR=%1,%2\r") .arg(i).arg( (i+10 < maxcal) ? (i+10) : (maxcal ) ) , 200 ); entries+= formatBuffer(buffer).grep("MDBR"); } QStringList::Iterator it; int index; QString text; bool timed; bool enabled; KDateTime startDT, alDT; int duration, repeat; QDate tempDate; int tempyear, tempmonth, tempday; for(it=entries.begin(); it!=entries.end(); ++it) { regexp.setPattern("^[+]MDBR:[\\s]*([\\d]),(\"[^\"]*[^,]*|[\\dA-F]*),([\\d]*),([\\d]*)"); regexp.search(*it); index=regexp.cap(1).toInt(); text=decodeString(regexp.cap(2)); timed=(bool) regexp.cap(3).toInt(); enabled=(bool) regexp.cap(4).toInt(); kDebug() <<"Index=" << index <<"|| Text=" << text <<"|| Timed=" << timed <<"|| Enabled=" << enabled <<"||end"; buffer=(*it).replace(regexp.cap(0), ""); regexp.setPattern(",\"([\\d:]*)\",\"([\\d-]*)\",([\\d]*),\"([\\d:]*)\",\"([\\d-]*)\",([\\d]*)"); regexp.search(buffer); startDT.setTime( QTime::fromString(regexp.cap(1) ) ); alDT.setTime( QTime::fromString(regexp.cap(4) ) ); repeat=regexp.cap(6).toInt(); duration=regexp.cap(3).toInt(); buffer=regexp.cap(2); tempyear=buffer.section('-',2,2).toInt(); tempyear= (tempyear < 100) ? (tempyear+2000) : tempyear; tempmonth=buffer.section('-',0,0).toInt(); tempday=buffer.section('-',1,1).toInt(); tempDate.setYMD( tempyear, tempmonth, tempday ); startDT.setDate(tempDate); kDebug() <<"Setdate args for" << buffer <<":" << tempyear <<"," << tempmonth <<"," << tempday; buffer=regexp.cap(5); tempyear=buffer.section('-',2,2).toInt(); tempyear= (tempyear < 100) ? (tempyear+2000) : tempyear; tempmonth=buffer.section('-',0,0).toInt(); tempday=buffer.section('-',1,1).toInt(); tempDate.setYMD( tempyear, tempmonth, tempday ); alDT.setDate(tempDate); kDebug() <<"Setdate args for" << buffer <<":" << tempyear <<"," << tempmonth <<"," << tempday; kDebug() <<"Start time=" << startDT.time() <<"|| Start Date=" << startDT.date() << "|| Duration=" << duration << "|| Alarm time=" << alDT.time() << "|| Alarm date=" << alDT.date() << "|| Repeat=" << repeat << "|| End\n"; KCal::Event *event=new KCal::Event(); if( startDT.isValid () && duration!=1440 ) event->setFloats(false); else event->setFloats(true); event->setDtStart(startDT); event->setDuration( duration*60); #if KDE_IS_VERSION( 3, 5, 0 ) switch( repeat ){ case 1: event->recurrence ()->setDaily(1); break; case 2: event->recurrence()->setWeekly(1); break; case 3: event->recurrence()->setMonthly(1); break; case 4: event->recurrence()->setWeekly(4); break; case 5: event->recurrence()->setYearly(1); break; default: event->recurrence()->clear(); } #else switch( repeat ){ case 1: event->recurrence ()->setDaily(1,0); break; case 2: event->recurrence()->setWeekly(1,0,0,0); break; case 3: event->recurrence()->setMonthly(1,0,0); break; case 4: event->recurrence()->setWeekly(4,0,0,0); break; case 5: event->recurrence()->setYearly(1,0,0); break; //default: // event->recurrence()->clear(); } #endif event->setDescription(text); if(enabled) { KCal::Alarm *alarm=event->newAlarm(); // if( alDT.isValid () ) alarm->setFloats(false); else alarm->setFloats(true); alarm->setText(text); alarm->setDisplayAlarm(text); alarm->setTime(alDT); alarm->setStartOffset(KCal::Duration(startDT, alDT) ); alarm->setType(KCal::Alarm::Display); alarm->setEnabled(true); // event->addAlarm(alarm); } p_calendar->append(event); } p_calendar->dump(); p_device->sendATCommand(this, "AT+MDBL=0\r", 100 ); } #include "calendar_jobs.moc" <commit_msg>now we use kde4<commit_after>/*************************************************************************** Copyright (C) 2007 by Marco Gulino <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ***************************************************************************/ #include "calendar_jobs.h" #include "engine.h" #include "kmobiletoolsat_engine.h" #include <qregexp.h> #include <qstring.h> #include <qdatetime.h> #include <libkcal/alarm.h> #include <kdeversion.h> FetchCalendar::FetchCalendar(KMobileTools::Job *pjob, KMobileTools::SerialManager *device, kmobiletoolsAT_engine* parent) : kmobiletoolsATJob(pjob, device, parent) { p_calendar=engine->engineData()->calendar(); p_calendar->clear(); } void FetchCalendar::run() { engine->suspendStatusJobs(true ); if(engine->getATAbilities().isMotorola()) { fetchMotorolaCalendar(); return; } } void FetchCalendar::fetchMotorolaCalendar() { kDebug() <<"void FetchCalendar::fetchMotorolaCalendar()"; QString buffer; QRegExp regexp; buffer=p_device->sendATCommand(this, "AT+MDBL=1\r" ); if(KMobileTools::SerialManager::ATError(buffer)) return; buffer=p_device->sendATCommand(this, "AT+MDBR=?\r" ); if(KMobileTools::SerialManager::ATError(buffer)) { p_device->sendATCommand(this, "AT+MDBL=0\r" ); return; } buffer=formatBuffer(buffer).grep("MDBR").first(); regexp.setPattern( "^[+]MDBR:[\\s]*([\\d]*),.*"); regexp.search(buffer); int maxcal=regexp.cap(1).toInt(); kDebug() <<"Max number of calendar entries:" << maxcal; QStringList entries; for(int i=0; i<maxcal; i+=10) { buffer=p_device->sendATCommand(this, QString("AT+MDBR=%1,%2\r") .arg(i).arg( (i+10 < maxcal) ? (i+10) : (maxcal ) ) , 200 ); entries+= formatBuffer(buffer).grep("MDBR"); } QStringList::Iterator it; int index; QString text; bool timed; bool enabled; KDateTime startDT, alDT; int duration, repeat; QDate tempDate; int tempyear, tempmonth, tempday; for(it=entries.begin(); it!=entries.end(); ++it) { regexp.setPattern("^[+]MDBR:[\\s]*([\\d]),(\"[^\"]*[^,]*|[\\dA-F]*),([\\d]*),([\\d]*)"); regexp.search(*it); index=regexp.cap(1).toInt(); text=decodeString(regexp.cap(2)); timed=(bool) regexp.cap(3).toInt(); enabled=(bool) regexp.cap(4).toInt(); kDebug() <<"Index=" << index <<"|| Text=" << text <<"|| Timed=" << timed <<"|| Enabled=" << enabled <<"||end"; buffer=(*it).replace(regexp.cap(0), ""); regexp.setPattern(",\"([\\d:]*)\",\"([\\d-]*)\",([\\d]*),\"([\\d:]*)\",\"([\\d-]*)\",([\\d]*)"); regexp.search(buffer); startDT.setTime( QTime::fromString(regexp.cap(1) ) ); alDT.setTime( QTime::fromString(regexp.cap(4) ) ); repeat=regexp.cap(6).toInt(); duration=regexp.cap(3).toInt(); buffer=regexp.cap(2); tempyear=buffer.section('-',2,2).toInt(); tempyear= (tempyear < 100) ? (tempyear+2000) : tempyear; tempmonth=buffer.section('-',0,0).toInt(); tempday=buffer.section('-',1,1).toInt(); tempDate.setYMD( tempyear, tempmonth, tempday ); startDT.setDate(tempDate); kDebug() <<"Setdate args for" << buffer <<":" << tempyear <<"," << tempmonth <<"," << tempday; buffer=regexp.cap(5); tempyear=buffer.section('-',2,2).toInt(); tempyear= (tempyear < 100) ? (tempyear+2000) : tempyear; tempmonth=buffer.section('-',0,0).toInt(); tempday=buffer.section('-',1,1).toInt(); tempDate.setYMD( tempyear, tempmonth, tempday ); alDT.setDate(tempDate); kDebug() <<"Setdate args for" << buffer <<":" << tempyear <<"," << tempmonth <<"," << tempday; kDebug() <<"Start time=" << startDT.time() <<"|| Start Date=" << startDT.date() << "|| Duration=" << duration << "|| Alarm time=" << alDT.time() << "|| Alarm date=" << alDT.date() << "|| Repeat=" << repeat << "|| End\n"; KCal::Event *event=new KCal::Event(); if( startDT.isValid () && duration!=1440 ) event->setFloats(false); else event->setFloats(true); event->setDtStart(startDT); event->setDuration( duration*60); switch( repeat ){ case 1: event->recurrence ()->setDaily(1); break; case 2: event->recurrence()->setWeekly(1); break; case 3: event->recurrence()->setMonthly(1); break; case 4: event->recurrence()->setWeekly(4); break; case 5: event->recurrence()->setYearly(1); break; default: event->recurrence()->clear(); } event->setDescription(text); if(enabled) { KCal::Alarm *alarm=event->newAlarm(); // if( alDT.isValid () ) alarm->setFloats(false); else alarm->setFloats(true); alarm->setText(text); alarm->setDisplayAlarm(text); alarm->setTime(alDT); alarm->setStartOffset(KCal::Duration(startDT, alDT) ); alarm->setType(KCal::Alarm::Display); alarm->setEnabled(true); // event->addAlarm(alarm); } p_calendar->append(event); } p_calendar->dump(); p_device->sendATCommand(this, "AT+MDBL=0\r", 100 ); } #include "calendar_jobs.moc" <|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <memseries.h> #include <ctime> #include <limits> #include <cmath> #include <chrono> int main(int argc, char *argv[]) { auto ms = new memseries::storage::MemoryStorage{ 2000000 }; auto m = memseries::Meas::empty(); std::vector<memseries::Time> deltas{ 50,255,1024,2050 }; auto now=std::chrono::system_clock::now(); memseries::Time t =memseries::timeutil::from_chrono(now); const size_t ids_count = 2; auto start = clock(); const size_t K = 2; for (size_t i = 0; i < K*1000000; i++) { m.id = i%ids_count; m.flag = 0xff; t += deltas[i%deltas.size()]; m.time = t; m.value = i; ms->append(m); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"memorystorage insert : "<<elapsed/K<<std::endl; start = clock(); auto reader=ms->readInTimePoint(ms->maxTime()); memseries::Meas::MeasList mlist{}; reader->readAll(&mlist); elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"memorystorage read: "<<elapsed/K<<std::endl; std::cout<<"raded: "<<mlist.size()<<std::endl; delete ms; } <commit_msg>storage benchmark.<commit_after>#include <ctime> #include <iostream> #include <cstdlib> #include <iterator> #include <memseries.h> #include <ctime> #include <limits> #include <cmath> #include <chrono> int main(int argc, char *argv[]) { auto ms = new memseries::storage::MemoryStorage{ 2000000 }; auto m = memseries::Meas::empty(); std::vector<memseries::Time> deltas{ 50,255,1024,2050 }; auto now=std::chrono::system_clock::now(); memseries::Time t =memseries::timeutil::from_chrono(now); const size_t ids_count = 2; auto start = clock(); const size_t K = 2; for (size_t i = 0; i < K*1000000; i++) { m.id = i%ids_count; m.flag = 0xff; t += deltas[i%deltas.size()]; m.time = t; m.value = i; ms->append(m); } auto elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"memorystorage insert : "<<elapsed<<std::endl; start = clock(); auto reader = ms->readInTimePoint(ms->maxTime()); memseries::Meas::MeasList mlist{}; reader->readAll(&mlist); elapsed = ((float)clock() - start) / CLOCKS_PER_SEC; std::cout << "memorystorage readTimePoint last: " << elapsed / K << std::endl; std::cout << "raded: " << mlist.size() << std::endl; start = clock(); auto reader_int = ms->readInterval(memseries::timeutil::from_chrono(now), t); mlist.clear(); reader_int->readAll(&mlist); elapsed=((float)clock()-start)/ CLOCKS_PER_SEC; std::cout<<"memorystorage readIntarval all: "<<elapsed/K<<std::endl; std::cout<<"raded: "<<mlist.size()<<std::endl; delete ms; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/browser/android/external_video_surface_container_impl.h" #include "base/android/jni_android.h" #include "content/public/browser/android/content_view_core.h" #include "jni/ExternalVideoSurfaceContainer_jni.h" #include "ui/gfx/geometry/rect_f.h" namespace chromecast { namespace shell { ExternalVideoSurfaceContainerImpl::ExternalVideoSurfaceContainerImpl( content::WebContents* web_contents) { content::ContentViewCore* cvc = content::ContentViewCore::FromWebContents(web_contents); if (cvc) { JNIEnv* env = base::android::AttachCurrentThread(); jobject_.Reset( Java_ExternalVideoSurfaceContainer_create( env, reinterpret_cast<intptr_t>(this), cvc->GetJavaObject().obj())); } } ExternalVideoSurfaceContainerImpl::~ExternalVideoSurfaceContainerImpl() { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_destroy(env, jobject_.obj()); jobject_.Reset(); } void ExternalVideoSurfaceContainerImpl::RequestExternalVideoSurface( int player_id, const SurfaceCreatedCB& surface_created_cb, const SurfaceDestroyedCB& surface_destroyed_cb) { surface_created_cb_ = surface_created_cb; surface_destroyed_cb_ = surface_destroyed_cb; JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_requestExternalVideoSurface( env, jobject_.obj(), static_cast<jint>(player_id)); } int ExternalVideoSurfaceContainerImpl::GetCurrentPlayerId() { JNIEnv* env = AttachCurrentThread(); int current_player = static_cast<int>( Java_ExternalVideoSurfaceContainer_getCurrentPlayerId( env, jobject_.obj())); if (current_player < 0) return kInvalidPlayerId; else return current_player; } void ExternalVideoSurfaceContainerImpl::ReleaseExternalVideoSurface( int player_id) { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_releaseExternalVideoSurface( env, jobject_.obj(), static_cast<jint>(player_id)); surface_created_cb_.Reset(); surface_destroyed_cb_.Reset(); } void ExternalVideoSurfaceContainerImpl::OnFrameInfoUpdated() { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_onFrameInfoUpdated(env, jobject_.obj()); } void ExternalVideoSurfaceContainerImpl::OnExternalVideoSurfacePositionChanged( int player_id, const gfx::RectF& rect) { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_onExternalVideoSurfacePositionChanged( env, jobject_.obj(), static_cast<jint>(player_id), static_cast<jfloat>(rect.x()), static_cast<jfloat>(rect.y()), static_cast<jfloat>(rect.x() + rect.width()), static_cast<jfloat>(rect.y() + rect.height())); } // Methods called from Java. void ExternalVideoSurfaceContainerImpl::SurfaceCreated( JNIEnv* env, jobject obj, jint player_id, jobject jsurface) { if (!surface_created_cb_.is_null()) surface_created_cb_.Run(static_cast<int>(player_id), jsurface); } void ExternalVideoSurfaceContainerImpl::SurfaceDestroyed( JNIEnv* env, jobject obj, jint player_id) { if (!surface_destroyed_cb_.is_null()) surface_destroyed_cb_.Run(static_cast<int>(player_id)); } bool RegisterExternalVideoSurfaceContainer(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace shell } // namespace chromecast <commit_msg>Chromecast Android buildfix: fully-qualify AttachCurrentThread.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/browser/android/external_video_surface_container_impl.h" #include "base/android/jni_android.h" #include "content/public/browser/android/content_view_core.h" #include "jni/ExternalVideoSurfaceContainer_jni.h" #include "ui/gfx/geometry/rect_f.h" namespace chromecast { namespace shell { ExternalVideoSurfaceContainerImpl::ExternalVideoSurfaceContainerImpl( content::WebContents* web_contents) { content::ContentViewCore* cvc = content::ContentViewCore::FromWebContents(web_contents); if (cvc) { JNIEnv* env = base::android::AttachCurrentThread(); jobject_.Reset( Java_ExternalVideoSurfaceContainer_create( env, reinterpret_cast<intptr_t>(this), cvc->GetJavaObject().obj())); } } ExternalVideoSurfaceContainerImpl::~ExternalVideoSurfaceContainerImpl() { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_destroy(env, jobject_.obj()); jobject_.Reset(); } void ExternalVideoSurfaceContainerImpl::RequestExternalVideoSurface( int player_id, const SurfaceCreatedCB& surface_created_cb, const SurfaceDestroyedCB& surface_destroyed_cb) { surface_created_cb_ = surface_created_cb; surface_destroyed_cb_ = surface_destroyed_cb; JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_requestExternalVideoSurface( env, jobject_.obj(), static_cast<jint>(player_id)); } int ExternalVideoSurfaceContainerImpl::GetCurrentPlayerId() { JNIEnv* env = base::android::AttachCurrentThread(); int current_player = static_cast<int>( Java_ExternalVideoSurfaceContainer_getCurrentPlayerId( env, jobject_.obj())); if (current_player < 0) return kInvalidPlayerId; else return current_player; } void ExternalVideoSurfaceContainerImpl::ReleaseExternalVideoSurface( int player_id) { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_releaseExternalVideoSurface( env, jobject_.obj(), static_cast<jint>(player_id)); surface_created_cb_.Reset(); surface_destroyed_cb_.Reset(); } void ExternalVideoSurfaceContainerImpl::OnFrameInfoUpdated() { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_onFrameInfoUpdated(env, jobject_.obj()); } void ExternalVideoSurfaceContainerImpl::OnExternalVideoSurfacePositionChanged( int player_id, const gfx::RectF& rect) { JNIEnv* env = base::android::AttachCurrentThread(); Java_ExternalVideoSurfaceContainer_onExternalVideoSurfacePositionChanged( env, jobject_.obj(), static_cast<jint>(player_id), static_cast<jfloat>(rect.x()), static_cast<jfloat>(rect.y()), static_cast<jfloat>(rect.x() + rect.width()), static_cast<jfloat>(rect.y() + rect.height())); } // Methods called from Java. void ExternalVideoSurfaceContainerImpl::SurfaceCreated( JNIEnv* env, jobject obj, jint player_id, jobject jsurface) { if (!surface_created_cb_.is_null()) surface_created_cb_.Run(static_cast<int>(player_id), jsurface); } void ExternalVideoSurfaceContainerImpl::SurfaceDestroyed( JNIEnv* env, jobject obj, jint player_id) { if (!surface_destroyed_cb_.is_null()) surface_destroyed_cb_.Run(static_cast<int>(player_id)); } bool RegisterExternalVideoSurfaceContainer(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace shell } // namespace chromecast <|endoftext|>
<commit_before>#include "util.hpp" namespace util { bool createDir(QString dirname, bool remove_if_exists) { // remove the dir if it does exist QDir dir(dirname); if (remove_if_exists && dir.exists()) { if (!dir.removeRecursively()) { qCritical() << QString("Can't remove dir %1").arg(dirname); return false; } } // go up from the dir so that we can create it if (!dir.cdUp()) { qCritical() << QString("Can't cd up from dir %1").arg(dirname); return false; } if (!dir.mkdir(dirname)) { qCritical() << QString("Can't mkdir dir %1").arg(dirname); return false; } return true; } //// See https://code.woboq.org/qt5/qtbase/src/gui/image/qimage.cpp.html#_ZN6QImage8setPixelEiij //// Set pixel without detach void copyBlock(const QImage& dst_image, const QImage& block, int start_x, int start_y) { // No detach for you bits() ;) auto dst_bits = const_cast<uchar*>(dst_image.constBits()); auto bytes_line = dst_image.bytesPerLine(); auto block_bits = const_cast<uchar*>(block.constBits()); if (dst_image.bytesPerLine() != block.bytesPerLine()) { qWarning() << "util::copyBlock: dst_image.bytesPerLine() == block.bytesPerLine()"; return; } // auto dst_pos = dst_bits + start_x; // auto src_pos = block_bits + start_x; // auto column = constants::BLOCK_WIDTH * sizeof(QRgb) * sizeof(QRgb); // lines are the same for (int i = 0; i < constants::BLOCK_WIDTH; i++) { // auto line = (i + start_y) * bytes_line; auto dst_line = reinterpret_cast<QRgb*>(dst_bits + (i + start_y) * bytes_line); auto src_line = reinterpret_cast<QRgb*>(block_bits + (i + start_y) * bytes_line); for (int j = 0; j < constants::BLOCK_WIDTH; j++) { // auto pos = start_x + j + (i + start_y) * bytes_line; // Q_ASSERT(pos < dst_image.byteCount()); dst_line[start_x + j] = src_line[start_x + j]; // dst_bits[pos] = block_bits[pos]; } // copy line by line, TODO use memcpy // memcpy(dst_pos + line, src_pos + line, column + 1); } } void copyBlockColor(const QImage& dst_image, QRgb color, int start_x, int start_y) { // use QRgb auto dst_bits = reinterpret_cast<QRgb*>(const_cast<uchar*>(dst_image.constBits())); auto bytes_line = dst_image.bytesPerLine() / sizeof(QRgb); for (int i = 0; i < constants::BLOCK_WIDTH; i++) { // line y = (i + start_y) * bytes_line // column x on line y = start_x // std::fill_n(dst_bits + (i + start_y) * bytes_line + start_x, constants::BLOCK_WIDTH, color); // memset works with bytes, FIXME why black? // memset(dst_bits + (i + start_y) * bytes_line + start_x, color, sizeof(QRgb) * constants::BLOCK_WIDTH); for (int j = 0; j < constants::BLOCK_WIDTH; j++) { dst_bits[(i + start_y) * bytes_line + start_x + j] = color; } } } } <commit_msg>Try to optimize more the copyBlock functions<commit_after>#include "util.hpp" namespace util { bool createDir(QString dirname, bool remove_if_exists) { // remove the dir if it does exist QDir dir(dirname); if (remove_if_exists && dir.exists()) { if (!dir.removeRecursively()) { qCritical() << QString("Can't remove dir %1").arg(dirname); return false; } } // go up from the dir so that we can create it if (!dir.cdUp()) { qCritical() << QString("Can't cd up from dir %1").arg(dirname); return false; } if (!dir.mkdir(dirname)) { qCritical() << QString("Can't mkdir dir %1").arg(dirname); return false; } return true; } // See https://code.woboq.org/qt5/qtbase/src/gui/image/qimage.cpp.html#_ZN6QImage8setPixelEiij // Set pixel without detach void copyBlock(const QImage& dst_image, const QImage& block, int start_x, int start_y) { // No detach for you bits() ;) auto dst_bits = const_cast<uchar*>(dst_image.constBits()); auto bytes_line = dst_image.bytesPerLine(); auto block_bits = const_cast<uchar*>(block.constBits()); if (bytes_line != block.bytesPerLine()) { qWarning() << "util::copyBlock: dst_image.bytesPerLine() != block.bytesPerLine()"; return; } // start_x and start_y are relative to a QRgb (4 bytes) Image, // convert so that they are relative to uchar image (1 byte) // NOTE: start_y does not need to be converted start_x *= sizeof(QRgb); auto dst_pos = dst_bits + start_x; auto src_pos = block_bits + start_x; // iterate over lines, lines are the same for (auto i = 0; i < constants::BLOCK_WIDTH; i++) { auto line_pos = (i + start_y) * bytes_line; // copy line by line memcpy(dst_pos + line_pos, src_pos + line_pos, sizeof(QRgb) * constants::BLOCK_WIDTH); } } void copyBlockColor(const QImage& dst_image, QRgb set_color, int start_x, int start_y) { // use QRgb auto dst_bits = reinterpret_cast<QRgb*>(const_cast<uchar*>(dst_image.constBits())); auto bytes_line = dst_image.bytesPerLine() / sizeof(QRgb); // start from column x auto dst_start = dst_bits + start_x; // iterate over lines for (auto i = 0; i < constants::BLOCK_WIDTH; i++) { // line y = (i + start_y) * bytes_line // column x on line y = start_x std::fill_n(dst_start + (i + start_y) * bytes_line, constants::BLOCK_WIDTH, set_color); // DOES NOT WORK because it uses conversion to unsigned char, sigh // memset(dst_start + (i + start_y) * bytes_line, set_color, sizeof(QRgb) * constants::BLOCK_WIDTH); } } } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/devtools/devtools_window_testing.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" class InterstitialUITest : public InProcessBrowserTest { public: InterstitialUITest() {} virtual ~InterstitialUITest() {} protected: void TestInterstitial(GURL url, const std::string& page_title) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ( base::ASCIIToUTF16(page_title), browser()->tab_strip_model()->GetActiveWebContents()->GetTitle()); // Should also be able to open and close devtools. DevToolsWindow* window = DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), true); EXPECT_TRUE(window); DevToolsWindowTesting::CloseDevToolsWindowSync(window); } }; IN_PROC_BROWSER_TEST_F(InterstitialUITest, OpenInterstitial) { TestInterstitial( GURL("chrome://interstitials"), "Interstitials"); // Invalid path should open the main page: TestInterstitial( GURL("chrome://interstitials/--invalid--"), "Interstitials"); TestInterstitial( GURL("chrome://interstitials/ssl"), "Privacy error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=malware"), "Security error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=phishing"), "Security error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_malware"), "Security error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_phishing"), "Security error"); } <commit_msg>OpenIntersitital test is marked as FLAKY.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/devtools/devtools_window_testing.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/web_contents.h" class InterstitialUITest : public InProcessBrowserTest { public: InterstitialUITest() {} virtual ~InterstitialUITest() {} protected: void TestInterstitial(GURL url, const std::string& page_title) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ( base::ASCIIToUTF16(page_title), browser()->tab_strip_model()->GetActiveWebContents()->GetTitle()); // Should also be able to open and close devtools. DevToolsWindow* window = DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), true); EXPECT_TRUE(window); DevToolsWindowTesting::CloseDevToolsWindowSync(window); } }; IN_PROC_BROWSER_TEST_F(InterstitialUITest, FLAKY_OpenInterstitial) { TestInterstitial( GURL("chrome://interstitials"), "Interstitials"); // Invalid path should open the main page: TestInterstitial( GURL("chrome://interstitials/--invalid--"), "Interstitials"); TestInterstitial( GURL("chrome://interstitials/ssl"), "Privacy error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=malware"), "Security error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=phishing"), "Security error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_malware"), "Security error"); TestInterstitial( GURL("chrome://interstitials/safebrowsing?type=clientside_phishing"), "Security error"); } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2016-2021 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "smithwaterman_common.h" int32_t fast_itoa(char * ptr, int32_t number){ bool is_neg = false; if(number < 0){ number = -number; is_neg = true; } int32_t cp_number = number; int32_t digits = 0; while (cp_number > 0){ cp_number /= 10; digits++; } if (ptr == NULL){ // if the number is negative add 1 for the minus sign, 0 otherwise return digits + (int) is_neg; } if(is_neg){ *(ptr++) = '-'; } for(int i = digits-1; i >= 0; i--){ *(ptr + i) = '0' + (number % 10); number /= 10; } // if the number is negative add 1 for the minus sign, 0 otherwise return digits + (int) is_neg; } <commit_msg>Fix compilation warning (#156)<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2016-2021 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "smithwaterman_common.h" int32_t fast_itoa(char * ptr, int32_t number){ bool is_neg = false; if(number < 0){ number = -number; is_neg = true; } int32_t cp_number = number; int32_t digits = 0; while (cp_number > 0){ cp_number /= 10; digits++; } if (ptr == NULL){ // if the number is negative add 1 for the minus sign, 0 otherwise return digits + (int) is_neg; } if(is_neg){ *(ptr++) = '-'; } for(int i = digits-1; i >= 0; i--){ *(ptr + i) = (char)((int)'0' + (number % 10)); number /= 10; } // if the number is negative add 1 for the minus sign, 0 otherwise return digits + (int) is_neg; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkUSVideoDevice.h" #include "mitkTestingMacros.h" #include "mitkUSImageToUSImageFilter.h" #include "mitkPadImageFilter.h" // START TESTFILER // This is an specialization of the USImageToUSImageFIlter class TestUSFilter : public mitk::USImageToUSImageFilter { protected: TestUSFilter() : mitk::USImageToUSImageFilter(){}; virtual ~TestUSFilter(){}; public: mitkClassMacro(TestUSFilter, mitk::USImageToUSImageFilter); itkNewMacro(Self); virtual void GenerateOutputInformation() { MITK_INFO << "GenerateOutputInformation called in Testfilter!"; mitk::Image::Pointer inputImage = (mitk::Image*) this->GetInput(0); mitk::Image::Pointer output = this->GetOutput(0); itkDebugMacro(<<"GenerateOutputInformation()"); if(inputImage.IsNull()) return; }; void GenerateData() { MITK_INFO << "GenerateData called in Testfilter!"; //mitk::Image::Pointer ni = const_cast<mitk::Image*>(this->GetInput(0)); mitk::USImage::Pointer ni = this->GetInput(0); mitk::USImage::Pointer result = mitk::USImage::New(); result->Initialize(ni); result->SetImportVolume(ni->GetData()); mitk::USImageMetadata::Pointer meta = ni->GetMetadata(); meta->SetDeviceComment("Test"); result->SetMetadata(meta); SetNthOutput(0, result); MITK_INFO << "GenerateData completed in Testfilter!"; }; }; // END TESTFILTER class mitkUSPipelineTestClass { public: static void TestPipelineUS(std::string videoFilePath) { // Set up a pipeline mitk::USVideoDevice::Pointer videoDevice = mitk::USVideoDevice::New("C:\\Users\\maerz\\Videos\\Debut\\us.avi", "Manufacturer", "Model"); TestUSFilter::Pointer filter = TestUSFilter::New(); videoDevice->Update(); filter->SetInput(videoDevice->GetOutput()); filter->Update(); MITK_TEST_CONDITION_REQUIRED(videoDevice.IsNotNull(), "videoDevice should not be null after instantiation"); //mitk::USImage::Pointer result = dynamic_cast<mitk::USImage *> (filter->GetOutput(0)); mitk::USImage::Pointer result = filter->GetOutput(0); MITK_TEST_CONDITION_REQUIRED(result.IsNotNull(), "resulting images should not be null"); std::string model = result->GetMetadata()->GetDeviceModel(); MITK_TEST_CONDITION_REQUIRED(model.compare("Model") == 0 , "Resulting images should have their metadata set correctly"); } }; /** * This function is setting up a pipeline and checks the output for validity. */ int mitkUSPipelineTest(int argc , char* argv[]) { MITK_TEST_BEGIN("mitkUSPipelineTest"); mitkUSPipelineTestClass::TestPipelineUS(argv[1]); MITK_TEST_END(); }<commit_msg>Removed Debug Messages, fixed cast failing under Linux<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkUSVideoDevice.h" #include "mitkTestingMacros.h" #include "mitkUSImageToUSImageFilter.h" #include "mitkPadImageFilter.h" // START TESTFILER // This is an specialization of the USImageToUSImageFIlter class TestUSFilter : public mitk::USImageToUSImageFilter { protected: TestUSFilter() : mitk::USImageToUSImageFilter(){}; virtual ~TestUSFilter(){}; public: mitkClassMacro(TestUSFilter, mitk::USImageToUSImageFilter); itkNewMacro(Self); virtual void GenerateOutputInformation() { mitk::Image::Pointer inputImage = (mitk::Image*) this->GetInput(0); mitk::Image::Pointer output = (mitk::Image*) this->GetOutput(0); if(inputImage.IsNull()) return; }; void GenerateData() { MITK_INFO << "GenerateData called in Testfilter!"; //mitk::Image::Pointer ni = const_cast<mitk::Image*>(this->GetInput(0)); mitk::USImage::Pointer ni = this->GetInput(0); mitk::USImage::Pointer result = mitk::USImage::New(); result->Initialize(ni); result->SetImportVolume(ni->GetData()); mitk::USImageMetadata::Pointer meta = ni->GetMetadata(); meta->SetDeviceComment("Test"); result->SetMetadata(meta); SetNthOutput(0, result); MITK_INFO << "GenerateData completed in Testfilter!"; }; }; // END TESTFILTER class mitkUSPipelineTestClass { public: static void TestPipelineUS(std::string videoFilePath) { // Set up a pipeline mitk::USVideoDevice::Pointer videoDevice = mitk::USVideoDevice::New("C:\\Users\\maerz\\Videos\\Debut\\us.avi", "Manufacturer", "Model"); TestUSFilter::Pointer filter = TestUSFilter::New(); videoDevice->Update(); filter->SetInput(videoDevice->GetOutput()); filter->Update(); MITK_TEST_CONDITION_REQUIRED(videoDevice.IsNotNull(), "videoDevice should not be null after instantiation"); //mitk::USImage::Pointer result = dynamic_cast<mitk::USImage *> (filter->GetOutput(0)); mitk::USImage::Pointer result = filter->GetOutput(0); MITK_TEST_CONDITION_REQUIRED(result.IsNotNull(), "resulting images should not be null"); std::string model = result->GetMetadata()->GetDeviceModel(); MITK_TEST_CONDITION_REQUIRED(model.compare("Model") == 0 , "Resulting images should have their metadata set correctly"); } }; /** * This function is setting up a pipeline and checks the output for validity. */ int mitkUSPipelineTest(int argc , char* argv[]) { MITK_TEST_BEGIN("mitkUSPipelineTest"); mitkUSPipelineTestClass::TestPipelineUS(argv[1]); MITK_TEST_END(); }<|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file vdev_posix.cpp * * POSIX-like API for virtual character device */ #include <px4_log.h> #include <px4_posix.h> #include <px4_time.h> #include "device.h" #include "vfile.h" #include <hrt_work.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> using namespace device; pthread_mutex_t filemutex = PTHREAD_MUTEX_INITIALIZER; extern "C" { static void timer_cb(void *data) { px4_sem_t *p_sem = (px4_sem_t *)data; px4_sem_post(p_sem); PX4_DEBUG("timer_handler: Timer expired"); } #define PX4_MAX_FD 200 static device::file_t *filemap[PX4_MAX_FD] = {}; int px4_errno; inline bool valid_fd(int fd) { pthread_mutex_lock(&filemutex); bool ret = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != NULL); pthread_mutex_unlock(&filemutex); return ret; } inline VDev *get_vdev(int fd) { pthread_mutex_lock(&filemutex); bool valid = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != NULL); VDev *dev; if (valid) { dev = (VDev *)(filemap[fd]->vdev); } else { dev = nullptr; } pthread_mutex_unlock(&filemutex); return dev; } int px4_open(const char *path, int flags, ...) { PX4_DEBUG("px4_open"); VDev *dev = VDev::getDev(path); int ret = 0; int i; mode_t mode; if (!dev && (flags & (PX4_F_WRONLY | PX4_F_CREAT)) != 0 && strncmp(path, "/obj/", 5) != 0 && strncmp(path, "/dev/", 5) != 0) { va_list p; va_start(p, flags); mode = va_arg(p, mode_t); va_end(p); // Create the file PX4_DEBUG("Creating virtual file %s", path); dev = VFile::createFile(path, mode); } if (dev) { pthread_mutex_lock(&filemutex); for (i = 0; i < PX4_MAX_FD; ++i) { if (filemap[i] == 0) { filemap[i] = new device::file_t(flags, dev, i); break; } } pthread_mutex_unlock(&filemutex); if (i < PX4_MAX_FD) { ret = dev->open(filemap[i]); } else { PX4_WARN("exceeded maximum number of file descriptors!"); ret = -ENOENT; } } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; return -1; } PX4_DEBUG("px4_open fd = %d", filemap[i]->fd); return filemap[i]->fd; } int px4_close(int fd) { int ret; VDev *dev = get_vdev(fd); if (dev) { pthread_mutex_lock(&filemutex); ret = dev->close(filemap[fd]); filemap[fd] = nullptr; pthread_mutex_unlock(&filemutex); PX4_DEBUG("px4_close fd = %d", fd); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_read(int fd, void *buffer, size_t buflen) { int ret; VDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_read fd = %d", fd); ret = dev->read(filemap[fd], (char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_write(int fd, const void *buffer, size_t buflen) { int ret; VDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_write fd = %d", fd); ret = dev->write(filemap[fd], (const char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } int px4_ioctl(int fd, int cmd, unsigned long arg) { PX4_DEBUG("px4_ioctl fd = %d", fd); int ret = 0; VDev *dev = get_vdev(fd); if (dev) { ret = dev->ioctl(filemap[fd], cmd, arg); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; } return ret; } int px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout) { px4_sem_t sem; int count = 0; int ret = -1; unsigned int i; PX4_DEBUG("Called px4_poll timeout = %d", timeout); px4_sem_init(&sem, 0, 0); // For each fd for (i = 0; i < nfds; ++i) { fds[i].sem = &sem; fds[i].revents = 0; fds[i].priv = NULL; VDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("px4_poll: VDev->poll(setup) %d", fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], true); if (ret < 0) { break; } } } if (ret >= 0) { if (timeout > 0) { // Use a work queue task work_s _hpwork = {}; hrt_work_queue(&_hpwork, (worker_t)&timer_cb, (void *)&sem, 1000 * timeout); px4_sem_wait(&sem); // Make sure timer thread is killed before sem goes // out of scope hrt_work_cancel(&_hpwork); } else if (timeout < 0) { px4_sem_wait(&sem); } // For each fd for (i = 0; i < nfds; ++i) { VDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("px4_poll: VDev->poll(teardown) %d", fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], false); if (ret < 0) { break; } if (fds[i].revents) { count += 1; } } } } px4_sem_destroy(&sem); return count; } int px4_fsync(int fd) { return 0; } int px4_access(const char *pathname, int mode) { if (mode != F_OK) { errno = EINVAL; return -1; } VDev *dev = VDev::getDev(pathname); return (dev != nullptr) ? 0 : -1; } void px4_show_devices() { VDev::showDevices(); } void px4_show_topics() { VDev::showTopics(); } void px4_show_files() { VDev::showFiles(); } const char *px4_get_device_names(unsigned int *handle) { return VDev::devList(handle); } const char *px4_get_topic_names(unsigned int *handle) { return VDev::topicList(handle); } } <commit_msg>VDev: Switch to a timed wait semaphore<commit_after>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file vdev_posix.cpp * * POSIX-like API for virtual character device */ #include <px4_log.h> #include <px4_posix.h> #include <px4_time.h> #include "device.h" #include "vfile.h" #include <hrt_work.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> using namespace device; pthread_mutex_t filemutex = PTHREAD_MUTEX_INITIALIZER; extern "C" { #define PX4_MAX_FD 200 static device::file_t *filemap[PX4_MAX_FD] = {}; int px4_errno; inline bool valid_fd(int fd) { pthread_mutex_lock(&filemutex); bool ret = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != NULL); pthread_mutex_unlock(&filemutex); return ret; } inline VDev *get_vdev(int fd) { pthread_mutex_lock(&filemutex); bool valid = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd] != NULL); VDev *dev; if (valid) { dev = (VDev *)(filemap[fd]->vdev); } else { dev = nullptr; } pthread_mutex_unlock(&filemutex); return dev; } int px4_open(const char *path, int flags, ...) { PX4_DEBUG("px4_open"); VDev *dev = VDev::getDev(path); int ret = 0; int i; mode_t mode; if (!dev && (flags & (PX4_F_WRONLY | PX4_F_CREAT)) != 0 && strncmp(path, "/obj/", 5) != 0 && strncmp(path, "/dev/", 5) != 0) { va_list p; va_start(p, flags); mode = va_arg(p, mode_t); va_end(p); // Create the file PX4_DEBUG("Creating virtual file %s", path); dev = VFile::createFile(path, mode); } if (dev) { pthread_mutex_lock(&filemutex); for (i = 0; i < PX4_MAX_FD; ++i) { if (filemap[i] == 0) { filemap[i] = new device::file_t(flags, dev, i); break; } } pthread_mutex_unlock(&filemutex); if (i < PX4_MAX_FD) { ret = dev->open(filemap[i]); } else { PX4_WARN("exceeded maximum number of file descriptors!"); ret = -ENOENT; } } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; return -1; } PX4_DEBUG("px4_open fd = %d", filemap[i]->fd); return filemap[i]->fd; } int px4_close(int fd) { int ret; VDev *dev = get_vdev(fd); if (dev) { pthread_mutex_lock(&filemutex); ret = dev->close(filemap[fd]); filemap[fd] = nullptr; pthread_mutex_unlock(&filemutex); PX4_DEBUG("px4_close fd = %d", fd); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_read(int fd, void *buffer, size_t buflen) { int ret; VDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_read fd = %d", fd); ret = dev->read(filemap[fd], (char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_write(int fd, const void *buffer, size_t buflen) { int ret; VDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_write fd = %d", fd); ret = dev->write(filemap[fd], (const char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } int px4_ioctl(int fd, int cmd, unsigned long arg) { PX4_DEBUG("px4_ioctl fd = %d", fd); int ret = 0; VDev *dev = get_vdev(fd); if (dev) { ret = dev->ioctl(filemap[fd], cmd, arg); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; } return ret; } int px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout) { px4_sem_t sem; int count = 0; int ret = -1; unsigned int i; PX4_DEBUG("Called px4_poll timeout = %d", timeout); px4_sem_init(&sem, 0, 0); // For each fd for (i = 0; i < nfds; ++i) { fds[i].sem = &sem; fds[i].revents = 0; fds[i].priv = NULL; VDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("px4_poll: VDev->poll(setup) %d", fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], true); if (ret < 0) { break; } } } if (ret >= 0) { if (timeout > 0) { struct timespec ts; px4_clock_gettime(CLOCK_REALTIME, &ts); ts.tv_sec += timeout / 1000; ts.tv_nsec += (1000 * 1000 * timeout) % (1000 * 1000 * 1000); px4_sem_timedwait(&sem, &ts); } else if (timeout < 0) { px4_sem_wait(&sem); } // For each fd for (i = 0; i < nfds; ++i) { VDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("px4_poll: VDev->poll(teardown) %d", fds[i].fd); ret = dev->poll(filemap[fds[i].fd], &fds[i], false); if (ret < 0) { break; } if (fds[i].revents) { count += 1; } } } } px4_sem_destroy(&sem); return count; } int px4_fsync(int fd) { return 0; } int px4_access(const char *pathname, int mode) { if (mode != F_OK) { errno = EINVAL; return -1; } VDev *dev = VDev::getDev(pathname); return (dev != nullptr) ? 0 : -1; } void px4_show_devices() { VDev::showDevices(); } void px4_show_topics() { VDev::showTopics(); } void px4_show_files() { VDev::showFiles(); } const char *px4_get_device_names(unsigned int *handle) { return VDev::devList(handle); } const char *px4_get_topic_names(unsigned int *handle) { return VDev::topicList(handle); } } <|endoftext|>
<commit_before>/* * Copyright 2012 Matthew McCormick * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstdlib> // EXIT_SUCCESS #include "argParse/argParse.h" // Tmux color lookup tables for the different metrics. #include "luts.h" #include "version.h" #if defined(__APPLE__) && defined(__MACH__) // Apple osx system #include "osx/cpu.h" #include "osx/memory.h" #include "osx/load.h" #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) // BSD system // TODO: Includes and *BSD support #define BSD_BASED 1 // include _get_cpu_percentage (see osx/cpu.cc) // include cpu_percentage (see osx/cpu.cc) #else // assume linux system #include "linux/cpu.h" #include "linux/memory.h" #include "linux/load.h" #endif #include "graph.h" // Function declarations. // TODO: those should stay in separate headers // LINUX: DONE/partial // OSX: DONE/partial // BSD: TODO std::string cpu_string(unsigned int cpu_usage_delay, unsigned int graph_lines, bool use_colors = false) { float percentage; //output stuff std::ostringstream oss; oss.precision( 1 ); oss.setf( std::ios::fixed | std::ios::right ); // get % percentage = cpu_percentage( cpu_usage_delay ); if( use_colors ) oss << cpu_percentage_lut[static_cast<unsigned int>( percentage )]; oss << "["; oss << getGraphByPercentage( unsigned(percentage), graph_lines ); oss << "]"; oss.width( 5 ); oss << percentage; oss << "%"; if( use_colors ) oss << "#[fg=default,bg=default]"; return oss.str(); } int main(int argc, char** argv) { using namespace ArgvParse; unsigned cpu_usage_delay = 1000000; unsigned short graph_lines = 10; // max 65535 should be enough bool use_colors = false; // Argv parser ArgvParser arg; // ugly, I know std::string intro = "tmux-mem-cpu-load v"; intro += std::to_string(VERSION_MAJOR) + "." + std::to_string(VERSION_MINOR); intro += "." + std::to_string(VERSION_PATCH) + "\n"; intro += "Usage: tmux-mem-cpu-load [OPTIONS]"; arg.setIntroduction(intro); arg.setHelpOption("h", "help", "Prints this help message"); // define actual options arg.defineOption("colors", "Use tmux colors in output", ArgvParser::NoAttribute); arg.defineOption("i", "interval", "set tmux status refresh interval in " "seconds. Default: 1 second", ArgvParser::RequiresValue); arg.defineOption("g", "graph-lines", "Set how many lines should be drawn in " "a graph. Default: 10", ArgvParser::RequiresValue); int result = arg.parse(argc, argv); if (result != ArgvParser::Success) { std::cerr << arg.parseErrorDescription(result); return EXIT_FAILURE; } // mangle arguments std::istringstream iss; iss.exceptions ( std::ifstream::failbit | std::ifstream::badbit ); if (arg.foundOption("colors")) use_colors = true; if (arg.foundOption("interval")){ iss.str(arg.optionValue("interval")); iss >> cpu_usage_delay; if (cpu_usage_delay < 1) { std::cerr << "Status interval argument must be one or greater.\n"; return EXIT_FAILURE; } cpu_usage_delay *= 1000000; } if (arg.foundOption("graph-lines")) { iss.str( arg.optionValue("graph-lines") ); iss.clear(); iss >> graph_lines; if( graph_lines < 1 ) { std::cerr << "Graph lines argument must be one or greater.\n"; return EXIT_FAILURE; } } std::cout << mem_string( use_colors ) << ' ' << cpu_string( cpu_usage_delay, graph_lines, use_colors ) << ' ' << load_string( use_colors ); return EXIT_SUCCESS; } <commit_msg>instead of using istringstream to convert form strin to int use stoi() function<commit_after>/* * Copyright 2012 Matthew McCormick * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstdlib> // EXIT_SUCCESS #include "argParse/argParse.h" // Tmux color lookup tables for the different metrics. #include "luts.h" #include "version.h" #if defined(__APPLE__) && defined(__MACH__) // Apple osx system #include "osx/cpu.h" #include "osx/memory.h" #include "osx/load.h" #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) // BSD system // TODO: Includes and *BSD support #define BSD_BASED 1 // include _get_cpu_percentage (see osx/cpu.cc) // include cpu_percentage (see osx/cpu.cc) #else // assume linux system #include "linux/cpu.h" #include "linux/memory.h" #include "linux/load.h" #endif #include "graph.h" // Function declarations. // TODO: those should stay in separate headers // LINUX: DONE/partial // OSX: DONE/partial // BSD: TODO std::string cpu_string(unsigned int cpu_usage_delay, unsigned int graph_lines, bool use_colors = false) { float percentage; //output stuff std::ostringstream oss; oss.precision( 1 ); oss.setf( std::ios::fixed | std::ios::right ); // get % percentage = cpu_percentage( cpu_usage_delay ); if( use_colors ) oss << cpu_percentage_lut[static_cast<unsigned int>( percentage )]; oss << "["; oss << getGraphByPercentage( unsigned(percentage), graph_lines ); oss << "]"; oss.width( 5 ); oss << percentage; oss << "%"; if( use_colors ) oss << "#[fg=default,bg=default]"; return oss.str(); } int main(int argc, char** argv) { using namespace ArgvParse; unsigned cpu_usage_delay = 1000000; short graph_lines = 10; // max 32767 should be enough bool use_colors = false; // Argv parser ArgvParser arg; // ugly, I know std::string intro = "tmux-mem-cpu-load v"; intro += std::to_string(VERSION_MAJOR) + "." + std::to_string(VERSION_MINOR); intro += "." + std::to_string(VERSION_PATCH) + "\n"; intro += "Usage: tmux-mem-cpu-load [OPTIONS]"; arg.setIntroduction(intro); arg.setHelpOption("h", "help", "Prints this help message"); // define actual options arg.defineOption("colors", "Use tmux colors in output", ArgvParser::NoAttribute); arg.defineOption("i", "interval", "set tmux status refresh interval in " "seconds. Default: 1 second", ArgvParser::RequiresValue); arg.defineOption("g", "graph-lines", "Set how many lines should be drawn in " "a graph. Default: 10", ArgvParser::RequiresValue); int result = arg.parse(argc, argv); if (result != ArgvParser::Success) { std::cerr << arg.parseErrorDescription(result); return EXIT_FAILURE; } // mangle arguments if (arg.foundOption("colors")) use_colors = true; if (arg.foundOption("interval")) { int delay = std::stoi(arg.optionValue("interval")); if (delay < 1) { std::cerr << "Status interval argument must be one or greater.\n"; return EXIT_FAILURE; } cpu_usage_delay = delay * 1000000; } if (arg.foundOption("graph-lines")) { graph_lines = std::stoi(arg.optionValue("graph-lines")); if( graph_lines < 1 ) { std::cerr << "Graph lines argument must be one or greater.\n"; return EXIT_FAILURE; } } std::cout << mem_string( use_colors ) << ' ' << cpu_string( cpu_usage_delay, graph_lines, use_colors ) << ' ' << load_string( use_colors ); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File : fbxmain.cpp // Version : 1.35 // Modified : 27. Dec 2003. // Author : Milan Babuskov ([email protected]) // Purpose : This file contains main() function for command-line version // and some functions specific to cmdline version // // Note : Uses version 2 of IBPP library (also released under MPL) // Check http://ibpp.sourceforge.net for more info // /////////////////////////////////////////////////////////////////////////////// // // The contents of this file are subject to the Mozilla Public License // Version 1.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is "FBExport 1.35" and all its associated documentation. // // The Initial Developer of the Original Code is Milan Babuskov. // // Contributor(s): ______________________________________. // /////////////////////////////////////////////////////////////////////////////// #ifdef IBPP_WINDOWS #include <windows.h> #endif #ifdef IBPP_LINUX #define __cdecl /**/ #include "stdarg.h" #endif #include "ibpp.h" #ifdef HAS_HDRSTOP #pragma hdrstop #endif #include <stdio.h> #include "ParseArgs.h" #include "FBExport.h" //--------------------------------------------------------------------------------------- int __cdecl main(int argc, char* argv[]) { if (! IBPP::CheckVersion(IBPP::Version)) { printf("\nThis program got linked to an incompatible version of the library.\nCan't execute safely.\n"); return 2; } // parse command-line args into Argument class Arguments ar(argc, argv); FBExport F; return F.Init(&ar); // Init() is used since ctor can't return values } //--------------------------------------------------------------------------------------- void FBExport::Printf(const char *format, ...) { va_list argptr; va_start(argptr, format); vfprintf(stderr, format, argptr); va_end(argptr); } //--------------------------------------------------------------------------------------- <commit_msg>Update cli-main.cpp<commit_after>/////////////////////////////////////////////////////////////////////////////// // Author : Milan Babuskov ([email protected]) // Purpose : This file contains main() function for command-line version // and some functions specific to cmdline version // // Note : Uses version 2 of IBPP library (also released under MPL) // Check http://ibpp.sourceforge.net for more info // /////////////////////////////////////////////////////////////////////////////// // // The contents of this file are subject to the Mozilla Public License // Version 1.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is "FBExport 1.35" and all its associated documentation. // // The Initial Developer of the Original Code is Milan Babuskov. // // Contributor(s): ______________________________________. // /////////////////////////////////////////////////////////////////////////////// #ifdef IBPP_WINDOWS #include <windows.h> #endif #ifdef IBPP_LINUX #define __cdecl /**/ #include "stdarg.h" #endif #include "ibpp.h" #ifdef HAS_HDRSTOP #pragma hdrstop #endif #include <stdio.h> #include "ParseArgs.h" #include "FBExport.h" int __cdecl main(int argc, char* argv[]) { if (! IBPP::CheckVersion(IBPP::Version)) { printf("\nThis program got linked to an incompatible version of the library.\nCan't execute safely.\n"); return 2; } // parse command-line args into Argument class Arguments ar(argc, argv); FBExport F; return F.Init(&ar); // Init() is used since ctor can't return values } void FBExport::Printf(const char *format, ...) { va_list argptr; va_start(argptr, format); vfprintf(stderr, format, argptr); va_end(argptr); } <|endoftext|>
<commit_before>/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "firestore/src/android/load_bundle_task_progress_android.h" #include "firestore/src/jni/env.h" #include "firestore/src/jni/loader.h" #include "firestore/src/jni/string.h" namespace firebase { namespace firestore { namespace { using jni::Class; using jni::Constructor; using jni::Env; using jni::Local; using jni::Method; using jni::Object; using jni::StaticField; using jni::String; constexpr char kClassName[] = PROGUARD_KEEP_CLASS "com/google/firebase/firestore/LoadBundleTaskProgress"; Method<int32_t> kGetDocumentsLoaded("getDocumentsLoaded", "()I"); Method<int32_t> kGetTotalDocuments("getTotalDocuments", "()I"); Method<int64_t> kGetBytesLoaded("getBytesLoaded", "()J"); Method<int64_t> kGetTotalBytes("getTotalBytes", "()J"); Method<Object> kGetTaskState( "getTaskState", "()Lcom/google/firebase/firestore/LoadBundleTaskProgress$TaskState;"); constexpr char kStateEnumName[] = PROGUARD_KEEP_CLASS "com/google/firebase/firestore/LoadBundleTaskProgress$TaskState"; StaticField<Object> kTaskStateSuccess( "SUCCESS", "Lcom/google/firebase/firestore/LoadBundleTaskProgress$TaskState;"); StaticField<Object> kTaskStateRunning( "RUNNING", "Lcom/google/firebase/firestore/LoadBundleTaskProgress$TaskState;"); Method<String> kName("name", "()Ljava/lang/String;"); jclass g_clazz = nullptr; } // namespace void LoadBundleTaskProgressInternal::Initialize(jni::Loader& loader) { g_clazz = loader.LoadClass(kClassName, kGetDocumentsLoaded, kGetTotalDocuments, kGetBytesLoaded, kGetTotalBytes, kGetTaskState); loader.LoadClass(kStateEnumName, kTaskStateSuccess, kTaskStateRunning); } Class LoadBundleTaskProgressInternal::GetClass() { return Class(g_clazz); } int32_t LoadBundleTaskProgressInternal::documents_loaded() const { Env env = GetEnv(); return env.Call(obj_, kGetDocumentsLoaded); } int32_t LoadBundleTaskProgressInternal::total_documents() const { Env env = GetEnv(); return env.Call(obj_, kGetTotalDocuments); } int64_t LoadBundleTaskProgressInternal::bytes_loaded() const { Env env = GetEnv(); return env.Call(obj_, kGetBytesLoaded); } int64_t LoadBundleTaskProgressInternal::total_bytes() const { Env env = GetEnv(); return env.Call(obj_, kGetTotalBytes); } LoadBundleTaskProgress::State LoadBundleTaskProgressInternal::state() const { Env env = GetEnv(); Local<Object> state = env.Call(obj_, kGetTaskState); Local<Object> running_state = env.Get(kTaskStateRunning); Local<Object> success_state = env.Get(kTaskStateSuccess); if (Object::Equals(env, state, success_state)) { return LoadBundleTaskProgress::State::kSuccess; } else if (Object::Equals(env, state, running_state)) { return LoadBundleTaskProgress::State::kInProgress; } else { // "ERROR" return LoadBundleTaskProgress::State::kError; } } } // namespace firestore } // namespace firebase <commit_msg>Remove unused field, since it can cause warnings<commit_after>/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "firestore/src/android/load_bundle_task_progress_android.h" #include "firestore/src/jni/env.h" #include "firestore/src/jni/loader.h" #include "firestore/src/jni/string.h" namespace firebase { namespace firestore { namespace { using jni::Class; using jni::Constructor; using jni::Env; using jni::Local; using jni::Method; using jni::Object; using jni::StaticField; using jni::String; constexpr char kClassName[] = PROGUARD_KEEP_CLASS "com/google/firebase/firestore/LoadBundleTaskProgress"; Method<int32_t> kGetDocumentsLoaded("getDocumentsLoaded", "()I"); Method<int32_t> kGetTotalDocuments("getTotalDocuments", "()I"); Method<int64_t> kGetBytesLoaded("getBytesLoaded", "()J"); Method<int64_t> kGetTotalBytes("getTotalBytes", "()J"); Method<Object> kGetTaskState( "getTaskState", "()Lcom/google/firebase/firestore/LoadBundleTaskProgress$TaskState;"); constexpr char kStateEnumName[] = PROGUARD_KEEP_CLASS "com/google/firebase/firestore/LoadBundleTaskProgress$TaskState"; StaticField<Object> kTaskStateSuccess( "SUCCESS", "Lcom/google/firebase/firestore/LoadBundleTaskProgress$TaskState;"); StaticField<Object> kTaskStateRunning( "RUNNING", "Lcom/google/firebase/firestore/LoadBundleTaskProgress$TaskState;"); jclass g_clazz = nullptr; } // namespace void LoadBundleTaskProgressInternal::Initialize(jni::Loader& loader) { g_clazz = loader.LoadClass(kClassName, kGetDocumentsLoaded, kGetTotalDocuments, kGetBytesLoaded, kGetTotalBytes, kGetTaskState); loader.LoadClass(kStateEnumName, kTaskStateSuccess, kTaskStateRunning); } Class LoadBundleTaskProgressInternal::GetClass() { return Class(g_clazz); } int32_t LoadBundleTaskProgressInternal::documents_loaded() const { Env env = GetEnv(); return env.Call(obj_, kGetDocumentsLoaded); } int32_t LoadBundleTaskProgressInternal::total_documents() const { Env env = GetEnv(); return env.Call(obj_, kGetTotalDocuments); } int64_t LoadBundleTaskProgressInternal::bytes_loaded() const { Env env = GetEnv(); return env.Call(obj_, kGetBytesLoaded); } int64_t LoadBundleTaskProgressInternal::total_bytes() const { Env env = GetEnv(); return env.Call(obj_, kGetTotalBytes); } LoadBundleTaskProgress::State LoadBundleTaskProgressInternal::state() const { Env env = GetEnv(); Local<Object> state = env.Call(obj_, kGetTaskState); Local<Object> running_state = env.Get(kTaskStateRunning); Local<Object> success_state = env.Get(kTaskStateSuccess); if (Object::Equals(env, state, success_state)) { return LoadBundleTaskProgress::State::kSuccess; } else if (Object::Equals(env, state, running_state)) { return LoadBundleTaskProgress::State::kInProgress; } else { // "ERROR" return LoadBundleTaskProgress::State::kError; } } } // namespace firestore } // namespace firebase <|endoftext|>
<commit_before>//============================================================================ // Name : HelloWorld2.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { cout << "!!!Hello World 2!!!" << endl; // prints !!!Hello World!!! return 0; } <commit_msg>Fixed Typo<commit_after>//============================================================================ // Name : HelloWorld2.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; int main() { cout << "!!!Hello World Two!!!" << endl; // prints !!!Hello World!!! return 0; } <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnordmetric/environment.h> #include <fnordmetric/sql/backends/mysql/mysqlconnection.h> namespace fnordmetric { namespace query { namespace mysql_backend { std::unique_ptr<MySQLConnection> MySQLConnection::openConnection( const util::URI& uri) { std::unique_ptr<MySQLConnection> conn(new MySQLConnection()); conn->connect(uri); return conn; } MySQLConnection::MySQLConnection() : mysql_(nullptr) { #ifdef FNORD_ENABLE_MYSQL mysql_ = mysql_init(NULL); if (mysql_ == nullptr) { RAISE(kRuntimeError, "mysql_init() failed\n"); } #else RAISE(kRuntimeError, "fnordmetric was compiled without libmysqlclient"); #endif } MySQLConnection::~MySQLConnection() { #ifdef FNORD_ENABLE_MYSQL mysql_close(mysql_); #else RAISE(kRuntimeError, "fnordmetric was compiled without libmysqlclient"); #endif } void MySQLConnection::connect(const util::URI& uri) { unsigned int port = 3306; std::string host = uri.host(); std::string username; std::string password; std::string database; if (host.size() == 0) { RAISE( kRuntimeError, "invalid mysql:// URI: has no hostname (URI: '%s')", uri.toString().c_str()); } if (uri.port() > 0) { port = uri.port(); } if (uri.path().size() < 2 || uri.path()[0] != '/') { RAISE( kRuntimeError, "invalid mysql:// URI: missing database, format is: mysql://host/db " " (URI: %s)", uri.toString().c_str()); } database = uri.path().substr(1); for (const auto& param : uri.queryParams()) { if (param.first == "username" || param.first == "user") { username = param.second; continue; } if (param.first == "password" || param.first == "pass") { password = param.second; continue; } RAISE( kRuntimeError, "invalid parameter for mysql:// URI: '%s=%s'", param.first.c_str(), param.second.c_str()); } connect(host, port, database, username, password); } void MySQLConnection::connect( const std::string& host, unsigned int port, const std::string& database, const std::string& username, const std::string& password) { #ifdef FNORD_ENABLE_MYSQL auto ret = mysql_real_connect( mysql_, host.c_str(), username.size() > 0 ? username.c_str() : NULL, password.size() > 0 ? password.c_str() : NULL, database.size() > 0 ? database.c_str() : NULL, port, NULL, CLIENT_COMPRESS); if (ret != mysql_) { RAISE( kRuntimeError, "mysql_real_connect() failed: %s\n", mysql_error(mysql_)); } #else RAISE(kRuntimeError, "fnordmetric was compiled without libmysqlclient"); #endif } std::vector<std::string> MySQLConnection::describeTable( const std::string& table_name) { std::vector<std::string> columns; #ifdef FNORD_ENABLE_MYSQL MYSQL_RES* res = mysql_list_fields(mysql_, table_name.c_str(), NULL); if (res == nullptr) { RAISE( kRuntimeError, "mysql_list_fields() failed: %s\n", mysql_error(mysql_)); } auto num_cols = mysql_num_fields(res); for (int i = 0; i < num_cols; ++i) { MYSQL_FIELD* col = mysql_fetch_field_direct(res, i); columns.emplace_back(col->name); } mysql_free_result(res); #else RAISE(kRuntimeError, "fnordmetric was compiled without libmysqlclient"); #endif return columns; } void MySQLConnection::executeQuery( const std::string& query, std::function<bool (const std::vector<std::string>&)> row_callback) { #ifdef FNORD_ENABLE_MYSQL if (env()->verbose()) { fnord::util::LogEntry entry; entry.append("__severity__", "DEBUG"); entry.append("__message__", "Executing MySQL query"); entry.append("query", query); env()->logger()->log(entry); } MYSQL_RES* result = nullptr; if (mysql_real_query(mysql_, query.c_str(), query.size()) == 0) { result = mysql_use_result(mysql_); } if (result == nullptr) { RAISE( kRuntimeError, "mysql query failed: %s -- error: %s\n", query.c_str(), mysql_error(mysql_)); } MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { auto col_lens = mysql_fetch_lengths(result); if (col_lens == nullptr) { break; } std::vector<std::string> row_vec; auto row_len = mysql_num_fields(result); for (int i = 0; i < row_len; ++i) { row_vec.emplace_back(row[i], col_lens[i]); } try { if (!row_callback(row_vec)) { break; } } catch (const std::exception& e) { mysql_free_result(result); try { auto rte = dynamic_cast<const util::RuntimeException&>(e); throw rte; } catch (std::bad_cast bce) { throw e; } } } mysql_free_result(result); #else RAISE(kRuntimeError, "fnordmetric was compiled without libmysqlclient"); #endif } } } } <commit_msg>improve MySQL detection<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <fnordmetric/environment.h> #include <fnordmetric/sql/backends/mysql/mysqlconnection.h> namespace fnordmetric { namespace query { namespace mysql_backend { std::unique_ptr<MySQLConnection> MySQLConnection::openConnection( const util::URI& uri) { std::unique_ptr<MySQLConnection> conn(new MySQLConnection()); conn->connect(uri); return conn; } MySQLConnection::MySQLConnection() : mysql_(nullptr) { #ifdef FNORD_ENABLE_MYSQL mysql_ = mysql_init(NULL); if (mysql_ == nullptr) { RAISE(kRuntimeError, "mysql_init() failed\n"); } #else RAISE(kRuntimeError, "FnordMetric was compiled without libmysqlclient"); #endif } MySQLConnection::~MySQLConnection() { #ifdef FNORD_ENABLE_MYSQL mysql_close(mysql_); #else RAISE(kRuntimeError, "FnordMetric was compiled without libmysqlclient"); #endif } void MySQLConnection::connect(const util::URI& uri) { unsigned int port = 3306; std::string host = uri.host(); std::string username; std::string password; std::string database; if (host.size() == 0) { RAISE( kRuntimeError, "invalid mysql:// URI: has no hostname (URI: '%s')", uri.toString().c_str()); } if (uri.port() > 0) { port = uri.port(); } if (uri.path().size() < 2 || uri.path()[0] != '/') { RAISE( kRuntimeError, "invalid mysql:// URI: missing database, format is: mysql://host/db " " (URI: %s)", uri.toString().c_str()); } database = uri.path().substr(1); for (const auto& param : uri.queryParams()) { if (param.first == "username" || param.first == "user") { username = param.second; continue; } if (param.first == "password" || param.first == "pass") { password = param.second; continue; } RAISE( kRuntimeError, "invalid parameter for mysql:// URI: '%s=%s'", param.first.c_str(), param.second.c_str()); } connect(host, port, database, username, password); } void MySQLConnection::connect( const std::string& host, unsigned int port, const std::string& database, const std::string& username, const std::string& password) { #ifdef FNORD_ENABLE_MYSQL auto ret = mysql_real_connect( mysql_, host.c_str(), username.size() > 0 ? username.c_str() : NULL, password.size() > 0 ? password.c_str() : NULL, database.size() > 0 ? database.c_str() : NULL, port, NULL, CLIENT_COMPRESS); if (ret != mysql_) { RAISE( kRuntimeError, "mysql_real_connect() failed: %s\n", mysql_error(mysql_)); } #else RAISE(kRuntimeError, "FnordMetric was compiled without libmysqlclient"); #endif } std::vector<std::string> MySQLConnection::describeTable( const std::string& table_name) { std::vector<std::string> columns; #ifdef FNORD_ENABLE_MYSQL MYSQL_RES* res = mysql_list_fields(mysql_, table_name.c_str(), NULL); if (res == nullptr) { RAISE( kRuntimeError, "mysql_list_fields() failed: %s\n", mysql_error(mysql_)); } auto num_cols = mysql_num_fields(res); for (int i = 0; i < num_cols; ++i) { MYSQL_FIELD* col = mysql_fetch_field_direct(res, i); columns.emplace_back(col->name); } mysql_free_result(res); #else RAISE(kRuntimeError, "FnordMetric was compiled without libmysqlclient"); #endif return columns; } void MySQLConnection::executeQuery( const std::string& query, std::function<bool (const std::vector<std::string>&)> row_callback) { #ifdef FNORD_ENABLE_MYSQL if (env()->verbose()) { fnord::util::LogEntry entry; entry.append("__severity__", "DEBUG"); entry.append("__message__", "Executing MySQL query"); entry.append("query", query); env()->logger()->log(entry); } MYSQL_RES* result = nullptr; if (mysql_real_query(mysql_, query.c_str(), query.size()) == 0) { result = mysql_use_result(mysql_); } if (result == nullptr) { RAISE( kRuntimeError, "mysql query failed: %s -- error: %s\n", query.c_str(), mysql_error(mysql_)); } MYSQL_ROW row; while ((row = mysql_fetch_row(result))) { auto col_lens = mysql_fetch_lengths(result); if (col_lens == nullptr) { break; } std::vector<std::string> row_vec; auto row_len = mysql_num_fields(result); for (int i = 0; i < row_len; ++i) { row_vec.emplace_back(row[i], col_lens[i]); } try { if (!row_callback(row_vec)) { break; } } catch (const std::exception& e) { mysql_free_result(result); try { auto rte = dynamic_cast<const util::RuntimeException&>(e); throw rte; } catch (std::bad_cast bce) { throw e; } } } mysql_free_result(result); #else RAISE(kRuntimeError, "FnordMetric was compiled without libmysqlclient"); #endif } } } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #define NOMINMAX // for Windows #include "tools.h" #include <core/loghelper.h> #include <core/openssl_wrapper.h> #include <limits> using namespace std; void Tools::getRandNumber(int start, int end, int howMany, int* randArray, bool different, int* bad) { int r = end-start+1; unsigned char rand_buf[4]; unsigned int randNumber; int i,j; if (!different) { for (i=0; i<howMany; i++) { if(!RAND_bytes(rand_buf, 4)) { LOG_MSG("RAND_bytes failed!"); } randNumber = 0; for(j=0; j<4; j++) { randNumber += (rand_buf[j] << 8*j); } if(randNumber < ( (unsigned int) ( ((double)numeric_limits<unsigned int>::max()) / r ) ) * r) { randArray[i] = start + (randNumber % r); } } } else { int *tempArray = new int[end-start+1]; for (i=0; i<(end-start+1); i++) tempArray[i]=1; if(bad) { for(i=0;i<(sizeof(bad)/sizeof(int));i++) { tempArray[bad[i]]=0; } } int counter(0); while (counter < howMany) { if(!RAND_bytes(rand_buf, 4)) { LOG_MSG("RAND_bytes failed!"); } randNumber = 0; for(j=0; j<4; j++) { randNumber += (rand_buf[j] << 8*j); } if(randNumber < ( (unsigned int) ( ((double)numeric_limits<unsigned int>::max()) / r ) ) * r) { randNumber = randNumber % r; if (tempArray[randNumber] == 1) { randArray[counter] = start + randNumber; tempArray[randNumber] = 0; counter++; } } } delete[] tempArray; } } <commit_msg>calcHandsChance<commit_after>/*************************************************************************** * Copyright (C) 2006 by FThauer FHammer * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #define NOMINMAX // for Windows #include "tools.h" #include <core/loghelper.h> #include <core/openssl_wrapper.h> #include <limits> using namespace std; void Tools::getRandNumber(int start, int end, int howMany, int* randArray, bool different, int* bad) { int r = end-start+1; unsigned char rand_buf[4]; unsigned int randNumber; int i,j; if (!different) { for (i=0; i<howMany; i++) { if(!RAND_bytes(rand_buf, 4)) { LOG_MSG("RAND_bytes failed!"); } randNumber = 0; for(j=0; j<4; j++) { randNumber += (rand_buf[j] << 8*j); } if(randNumber < ( (unsigned int) ( ((double)numeric_limits<unsigned int>::max()) / r ) ) * r) { randArray[i] = start + (randNumber % r); } } } else { int *tempArray = new int[end-start+1]; for (i=0; i<(end-start+1); i++) tempArray[i]=1; if(bad) { for(i=0;i<(int)(sizeof(bad)/sizeof(int));i++) { tempArray[bad[i]]=0; } } int counter(0); while (counter < howMany) { if(!RAND_bytes(rand_buf, 4)) { LOG_MSG("RAND_bytes failed!"); } randNumber = 0; for(j=0; j<4; j++) { randNumber += (rand_buf[j] << 8*j); } if(randNumber < ( (unsigned int) ( ((double)numeric_limits<unsigned int>::max()) / r ) ) * r) { randNumber = randNumber % r; if (tempArray[randNumber] == 1) { randArray[counter] = start + randNumber; tempArray[randNumber] = 0; counter++; } } } delete[] tempArray; } } <|endoftext|>
<commit_before> #ifndef NETWORK_IDENTIFIERS_HPP #define NETWORK_IDENTIFIERS_HPP #define GAME_PROTOCOL_ID 1357924680 #define GAME_PORT 12084 #define HEARTBEAT_MILLISECONDS 1500 #define PACKET_LOST_TIMEOUT_MILLISECONDS 1000 #define SENT_PACKET_LIST_MAX_SIZE 33 #define CONNECTION_TIMEOUT_MILLISECONDS 10000 #define NETWORK_GOOD_MODE_SEND_INTERVAL 1.0f/30.0f #define NETWORK_BAD_MODE_SEND_INTERVAL 1.0f/10.0f #include <list> #include <SFML/Config.hpp> #include <SFML/Network.hpp> #include <SFML/System.hpp> struct PacketInfo { PacketInfo(); PacketInfo(sf::Packet packet); PacketInfo(sf::Packet packet, sf::Uint32 address); PacketInfo(sf::Packet packet, sf::Uint32 address, sf::Uint32 ID); PacketInfo(sf::Packet packet, sf::Uint32 address, sf::Uint32 ID, bool isResending); sf::Packet packet; sf::Clock sentTime; sf::Uint32 address; sf::Uint32 ID; bool isResending; }; struct ConnectionData { ConnectionData(); ConnectionData(sf::Uint32 ID, sf::Uint32 lSequence); sf::Clock elapsedTime; sf::Uint32 ID; sf::Uint32 lSequence; sf::Uint32 rSequence; sf::Uint32 ackBitfield; std::list<PacketInfo> sentPackets; std::list<PacketInfo> sendPacketQueue; sf::Time rtt; bool triggerSend; float timer; bool isGood; bool isGoodRtt; float toggleTime; float toggleTimer; float toggledTimer; bool operator== (const ConnectionData& other) const; }; namespace std { template<> struct hash<ConnectionData> { std::size_t operator() (const ConnectionData& connectionData) const; }; } namespace network { enum SpecialIDs { CONNECT = 0xFFFFFFFF, PING = 0xFFFFFFFE }; bool moreRecent(sf::Uint32 current, sf::Uint32 previous); bool isSpecialID(sf::Uint32 ID); } #endif <commit_msg>Added seemingly necessary include<commit_after> #ifndef NETWORK_IDENTIFIERS_HPP #define NETWORK_IDENTIFIERS_HPP #define GAME_PROTOCOL_ID 1357924680 #define GAME_PORT 12084 #define HEARTBEAT_MILLISECONDS 1500 #define PACKET_LOST_TIMEOUT_MILLISECONDS 1000 #define SENT_PACKET_LIST_MAX_SIZE 33 #define CONNECTION_TIMEOUT_MILLISECONDS 10000 #define NETWORK_GOOD_MODE_SEND_INTERVAL 1.0f/30.0f #define NETWORK_BAD_MODE_SEND_INTERVAL 1.0f/10.0f #include <list> #include <cstdlib> #include <SFML/Config.hpp> #include <SFML/Network.hpp> #include <SFML/System.hpp> struct PacketInfo { PacketInfo(); PacketInfo(sf::Packet packet); PacketInfo(sf::Packet packet, sf::Uint32 address); PacketInfo(sf::Packet packet, sf::Uint32 address, sf::Uint32 ID); PacketInfo(sf::Packet packet, sf::Uint32 address, sf::Uint32 ID, bool isResending); sf::Packet packet; sf::Clock sentTime; sf::Uint32 address; sf::Uint32 ID; bool isResending; }; struct ConnectionData { ConnectionData(); ConnectionData(sf::Uint32 ID, sf::Uint32 lSequence); sf::Clock elapsedTime; sf::Uint32 ID; sf::Uint32 lSequence; sf::Uint32 rSequence; sf::Uint32 ackBitfield; std::list<PacketInfo> sentPackets; std::list<PacketInfo> sendPacketQueue; sf::Time rtt; bool triggerSend; float timer; bool isGood; bool isGoodRtt; float toggleTime; float toggleTimer; float toggledTimer; bool operator== (const ConnectionData& other) const; }; namespace std { template<> struct hash<ConnectionData> { std::size_t operator() (const ConnectionData& connectionData) const; }; } namespace network { enum SpecialIDs { CONNECT = 0xFFFFFFFF, PING = 0xFFFFFFFE }; bool moreRecent(sf::Uint32 current, sf::Uint32 previous); bool isSpecialID(sf::Uint32 ID); } #endif <|endoftext|>
<commit_before>/* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LCB_NO_DEPR_CXX_CTORS #include "config.h" #include <sys/types.h> #include <libcouchbase/couchbase.h> #include <libcouchbase/api3.h> #include <libcouchbase/n1ql.h> #include <libcouchbase/vbucket.h> #include <iostream> #include <list> #include <cassert> #include <cstdio> #include <cstdlib> #include <cerrno> #include <fstream> #include <algorithm> // random_shuffle #include <stdexcept> #include <sstream> #ifndef WIN32 #include <pthread.h> #include <unistd.h> // isatty() #endif #include "common/options.h" #include "common/histogram.h" using namespace cbc; using namespace cliopts; using std::vector; using std::string; using std::cerr; using std::endl; #ifndef _WIN32 static bool use_ansi_codes = true; #else static bool use_ansi_codes = false; #endif static void do_or_die(lcb_error_t rc) { if (rc != LCB_SUCCESS) { std::stringstream ss; ss << "[" << std::hex << rc << "] " << lcb_strerror(NULL, rc); throw std::runtime_error(ss.str()); } } class Metrics { public: Metrics() : n_rows(0), n_queries(0), n_errors(0), last_update(time(NULL)), hg(NULL) { #ifndef _WIN32 if (pthread_mutex_init(&m_lock, NULL) != 0) { abort(); } #endif start_time = last_update; } size_t nerrors() { return n_errors; } void update_row(size_t n = 1) { n_rows += n; update_display(); } void update_done(size_t n = 1) { n_queries += n; update_display(); } void update_error(size_t n = 1) { n_errors += n; update_display(); } void update_timings(lcb_U64 duration) { if (hg != NULL) { hg->record(duration); } } #ifndef _WIN32 bool is_tty() const { return isatty(STDOUT_FILENO); } void lock() { pthread_mutex_lock(&m_lock); } void unlock() { pthread_mutex_unlock(&m_lock); } #else void lock(){} void unlock(){} bool is_tty() const { return false; } #endif void prepare_screen() { if (is_tty() && use_ansi_codes) { printf("\n\n\n"); } } void prepare_timings() { if (hg == NULL) { hg = new Histogram(); hg->installStandalone(stdout); } } private: void update_display() { time_t now = time(NULL); time_t duration = now - last_update; if (!duration) { return; } last_update = now; const char *prefix; const char *final_suffix; // Only use "ticker" style updates if we're a TTY and we have no // following timings. if (use_ansi_codes && is_tty() && hg == NULL) { // Move up 3 cursors printf("\x1B[2A"); prefix = "\x1B[K"; final_suffix = "\r"; } else { // Determine the total number of time unsigned total_duration = now - start_time; printf("\n"); // Clear line.. printf("+%us\n", total_duration); prefix = ""; final_suffix = "\n"; } printf("%sQUERIES/SEC: %lu\n", prefix, (unsigned long)(n_queries / duration)); printf("%sROWS/SEC: %lu\n", prefix, (unsigned long)(n_rows / duration)); printf("%sERRORS: %lu%s", prefix, (unsigned long)n_errors, final_suffix); if (hg != NULL) { hg->write(); } fflush(stdout); n_queries = 0; n_rows = 0; } size_t n_rows; size_t n_queries; size_t n_errors; time_t last_update; time_t start_time; cbc::Histogram *hg; #ifndef _WIN32 pthread_mutex_t m_lock; #endif }; Metrics GlobalMetrics; class Configuration { public: Configuration() : o_file("queryfile"), o_threads("num-threads"), o_errlog("error-log"), m_errlog(NULL) { o_file.mandatory(true); o_file.description( "Path to a file containing all the queries to execute. " "Each line should contain the full query body"); o_file.abbrev('f'); o_threads.description("Number of threads to run"); o_threads.abbrev('t'); o_threads.setDefault(1); o_errlog.description( "Path to a file containing failed queries"); o_errlog.abbrev('e'); o_errlog.setDefault(""); } ~Configuration() { if (m_errlog != NULL) { delete m_errlog; m_errlog = NULL; } } void addToParser(Parser& parser) { parser.addOption(o_file); parser.addOption(o_threads); parser.addOption(o_errlog); m_params.addToParser(parser); } void processOptions() { std::ifstream ifs(o_file.const_result().c_str()); if (!ifs.is_open()) { int ec_save = errno; string errstr(o_file.const_result()); errstr += ": "; errstr += strerror(ec_save); throw std::runtime_error(errstr); } string curline; while (std::getline(ifs, curline).good() && !ifs.eof()) { if (!curline.empty()) { m_queries.push_back(curline); } } if (m_params.useTimings()) { GlobalMetrics.prepare_timings(); } if (o_errlog.passed()) { m_errlog = new std::ofstream(o_errlog.const_result().c_str()); if (!m_errlog->is_open()) { int ec_save = errno; string errstr(o_file.const_result()); errstr += ": "; errstr += strerror(ec_save); throw std::runtime_error(errstr); } } } void set_cropts(lcb_create_st &opts) { m_params.fillCropts(opts); } const vector<string>& queries() const { return m_queries; } size_t nthreads() { return o_threads.result(); } std::ofstream* errlog() { return m_errlog; } private: vector<string> m_queries; StringOption o_file; UIntOption o_threads; ConnParams m_params; StringOption o_errlog; std::ofstream *m_errlog; }; extern "C" { static void n1qlcb(lcb_t, int, const lcb_RESPN1QL *resp); } extern "C" { static void* pthrfunc(void*); } class ThreadContext; struct QueryContext { lcb_U64 begin; bool received; // whether any row was received ThreadContext *ctx; // Parent QueryContext(ThreadContext *tctx) : begin(lcb_nstime()), received(false), ctx(tctx) {} }; class ThreadContext { public: void run() { while (!m_cancelled) { vector<string>::const_iterator ii = m_queries.begin(); for (; ii != m_queries.end(); ++ii) { run_one_query(*ii); } } } #ifndef _WIN32 void start() { assert(m_thr == NULL); m_thr = new pthread_t; int rc = pthread_create(m_thr, NULL, pthrfunc, this); if (rc != 0) { throw std::runtime_error(strerror(rc)); } } void join() { assert(m_thr != NULL); void *arg = NULL; pthread_join(*m_thr, &arg); } ~ThreadContext() { if (m_thr != NULL) { join(); delete m_thr; m_thr = NULL; } } #else void start() { run(); } void join() {} #endif void handle_response(const lcb_RESPN1QL *resp, QueryContext *ctx) { if (!ctx->received) { lcb_U64 duration = lcb_nstime() - ctx->begin; m_metrics->lock(); m_metrics->update_timings(duration); m_metrics->unlock(); ctx->received = true; } if (resp->rflags & LCB_RESP_F_FINAL) { if (resp->rc != LCB_SUCCESS) { if (m_errlog != NULL) { std::stringstream ss; ss.write(m_cmd.query, m_cmd.nquery); ss << endl; ss.write(resp->row, resp->nrow); log_error(resp->rc, ss.str().c_str(), ss.str().size()); } else { log_error(resp->rc, NULL, 0); } } } else { last_nrow++; } } ThreadContext(lcb_t instance, const vector<string>& initial_queries, std::ofstream *errlog) : m_instance(instance), last_nerr(0), last_nrow(0), m_metrics(&GlobalMetrics), m_cancelled(false), m_thr(NULL), m_errlog(errlog) { memset(&m_cmd, 0, sizeof m_cmd); m_cmd.content_type = "application/json"; m_cmd.callback = n1qlcb; // Shuffle the list m_queries = initial_queries; std::random_shuffle(m_queries.begin(), m_queries.end()); } private: void log_error(lcb_error_t err, const char* info, size_t ninfo) { size_t erridx; m_metrics->lock(); m_metrics->update_error(); erridx = m_metrics->nerrors(); m_metrics->unlock(); if (m_errlog != NULL) { std::stringstream ss; ss << "[" << erridx << "] 0x" << std::hex << err << ", " << lcb_strerror(NULL, err) << endl; if (ninfo) { ss.write(info, ninfo); ss << endl; } *m_errlog << ss.str(); m_errlog->flush(); } } void run_one_query(const string& txt) { // Reset counters last_nrow = 0; last_nerr = 0; m_cmd.query = txt.c_str(); m_cmd.nquery = txt.size(); // Set up our context QueryContext qctx(this); lcb_error_t rc = lcb_n1ql_query(m_instance, &qctx, &m_cmd); if (rc != LCB_SUCCESS) { log_error(rc, txt.c_str(), txt.size()); } else { lcb_wait(m_instance); m_metrics->lock(); m_metrics->update_row(last_nrow); m_metrics->update_done(1); m_metrics->unlock(); } } lcb_t m_instance; vector<string> m_queries; size_t last_nerr; size_t last_nrow; lcb_CMDN1QL m_cmd; Metrics *m_metrics; volatile bool m_cancelled; #ifndef _WIN32 pthread_t *m_thr; #else void *m_thr; #endif std::ofstream *m_errlog; }; static void n1qlcb(lcb_t, int, const lcb_RESPN1QL *resp) { QueryContext *qctx = reinterpret_cast<QueryContext*>(resp->cookie); qctx->ctx->handle_response(resp, qctx); } static void* pthrfunc(void *arg) { reinterpret_cast<ThreadContext*>(arg)->run(); return NULL; } static bool instance_has_n1ql(lcb_t instance) { // Check that the instance supports N1QL lcbvb_CONFIG *vbc; do_or_die(lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_VBCONFIG, &vbc)); int sslmode = 0; lcbvb_SVCMODE svcmode = LCBVB_SVCMODE_PLAIN; do_or_die(lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_SSL_MODE, &sslmode)); if (sslmode & LCB_SSL_ENABLED) { svcmode = LCBVB_SVCMODE_SSL; } int hix = lcbvb_get_randhost(vbc, LCBVB_SVCTYPE_N1QL, svcmode); return hix > -1; } static void real_main(int argc, char **argv) { Configuration config; Parser parser; config.addToParser(parser); parser.parse(argc, argv); vector<ThreadContext*> threads; vector<lcb_t> instances; lcb_create_st cropts = { 0 }; config.set_cropts(cropts); config.processOptions(); for (size_t ii = 0; ii < config.nthreads(); ii++) { lcb_t instance; do_or_die(lcb_create(&instance, &cropts)); do_or_die(lcb_connect(instance)); lcb_wait(instance); do_or_die(lcb_get_bootstrap_status(instance)); if (ii == 0 && !instance_has_n1ql(instance)) { throw std::runtime_error("Cluster does not support N1QL!"); } ThreadContext* cx = new ThreadContext(instance, config.queries(), config.errlog()); threads.push_back(cx); instances.push_back(instance); } GlobalMetrics.prepare_screen(); for (size_t ii = 0; ii < threads.size(); ++ii) { threads[ii]->start(); } for (size_t ii = 0; ii < threads.size(); ++ii) { threads[ii]->join(); } for (size_t ii = 0; ii < instances.size(); ++ii) { lcb_destroy(instances[ii]); } } int main(int argc, char **argv) { try { real_main(argc, argv); return 0; } catch (std::exception& exc) { cerr << exc.what() << endl; exit(EXIT_FAILURE); } } <commit_msg>CCBC-908: cbc-n1qlback: report number of loaded queries<commit_after>/* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LCB_NO_DEPR_CXX_CTORS #include "config.h" #include <sys/types.h> #include <libcouchbase/couchbase.h> #include <libcouchbase/api3.h> #include <libcouchbase/n1ql.h> #include <libcouchbase/vbucket.h> #include <iostream> #include <list> #include <cassert> #include <cstdio> #include <cstdlib> #include <cerrno> #include <fstream> #include <algorithm> // random_shuffle #include <stdexcept> #include <sstream> #ifndef WIN32 #include <pthread.h> #include <unistd.h> // isatty() #endif #include "common/options.h" #include "common/histogram.h" using namespace cbc; using namespace cliopts; using std::vector; using std::string; using std::cerr; using std::endl; #ifndef _WIN32 static bool use_ansi_codes = true; #else static bool use_ansi_codes = false; #endif static void do_or_die(lcb_error_t rc) { if (rc != LCB_SUCCESS) { std::stringstream ss; ss << "[" << std::hex << rc << "] " << lcb_strerror(NULL, rc); throw std::runtime_error(ss.str()); } } class Metrics { public: Metrics() : n_rows(0), n_queries(0), n_errors(0), last_update(time(NULL)), hg(NULL) { #ifndef _WIN32 if (pthread_mutex_init(&m_lock, NULL) != 0) { abort(); } #endif start_time = last_update; } size_t nerrors() { return n_errors; } void update_row(size_t n = 1) { n_rows += n; update_display(); } void update_done(size_t n = 1) { n_queries += n; update_display(); } void update_error(size_t n = 1) { n_errors += n; update_display(); } void update_timings(lcb_U64 duration) { if (hg != NULL) { hg->record(duration); } } #ifndef _WIN32 bool is_tty() const { return isatty(STDOUT_FILENO); } void lock() { pthread_mutex_lock(&m_lock); } void unlock() { pthread_mutex_unlock(&m_lock); } #else void lock(){} void unlock(){} bool is_tty() const { return false; } #endif void prepare_screen() { if (is_tty() && use_ansi_codes) { printf("\n\n\n"); } } void prepare_timings() { if (hg == NULL) { hg = new Histogram(); hg->installStandalone(stdout); } } private: void update_display() { time_t now = time(NULL); time_t duration = now - last_update; if (!duration) { return; } last_update = now; const char *prefix; const char *final_suffix; // Only use "ticker" style updates if we're a TTY and we have no // following timings. if (use_ansi_codes && is_tty() && hg == NULL) { // Move up 3 cursors printf("\x1B[2A"); prefix = "\x1B[K"; final_suffix = "\r"; } else { // Determine the total number of time unsigned total_duration = now - start_time; printf("\n"); // Clear line.. printf("+%us\n", total_duration); prefix = ""; final_suffix = "\n"; } printf("%sQUERIES/SEC: %lu\n", prefix, (unsigned long)(n_queries / duration)); printf("%sROWS/SEC: %lu\n", prefix, (unsigned long)(n_rows / duration)); printf("%sERRORS: %lu%s", prefix, (unsigned long)n_errors, final_suffix); if (hg != NULL) { hg->write(); } fflush(stdout); n_queries = 0; n_rows = 0; } size_t n_rows; size_t n_queries; size_t n_errors; time_t last_update; time_t start_time; cbc::Histogram *hg; #ifndef _WIN32 pthread_mutex_t m_lock; #endif }; Metrics GlobalMetrics; class Configuration { public: Configuration() : o_file("queryfile"), o_threads("num-threads"), o_errlog("error-log"), m_errlog(NULL) { o_file.mandatory(true); o_file.description( "Path to a file containing all the queries to execute. " "Each line should contain the full query body"); o_file.abbrev('f'); o_threads.description("Number of threads to run"); o_threads.abbrev('t'); o_threads.setDefault(1); o_errlog.description( "Path to a file containing failed queries"); o_errlog.abbrev('e'); o_errlog.setDefault(""); } ~Configuration() { if (m_errlog != NULL) { delete m_errlog; m_errlog = NULL; } } void addToParser(Parser& parser) { parser.addOption(o_file); parser.addOption(o_threads); parser.addOption(o_errlog); m_params.addToParser(parser); } void processOptions() { std::ifstream ifs(o_file.const_result().c_str()); if (!ifs.is_open()) { int ec_save = errno; string errstr(o_file.const_result()); errstr += ": "; errstr += strerror(ec_save); throw std::runtime_error(errstr); } string curline; while (std::getline(ifs, curline).good() && !ifs.eof()) { if (!curline.empty()) { m_queries.push_back(curline); } } std::cerr << "Loaded " << m_queries.size() << " queries " << "from \"" << o_file.const_result() << "\"" << std::endl; if (m_params.useTimings()) { GlobalMetrics.prepare_timings(); } if (o_errlog.passed()) { m_errlog = new std::ofstream(o_errlog.const_result().c_str()); if (!m_errlog->is_open()) { int ec_save = errno; string errstr(o_file.const_result()); errstr += ": "; errstr += strerror(ec_save); throw std::runtime_error(errstr); } } } void set_cropts(lcb_create_st &opts) { m_params.fillCropts(opts); } const vector<string>& queries() const { return m_queries; } size_t nthreads() { return o_threads.result(); } std::ofstream* errlog() { return m_errlog; } private: vector<string> m_queries; StringOption o_file; UIntOption o_threads; ConnParams m_params; StringOption o_errlog; std::ofstream *m_errlog; }; extern "C" { static void n1qlcb(lcb_t, int, const lcb_RESPN1QL *resp); } extern "C" { static void* pthrfunc(void*); } class ThreadContext; struct QueryContext { lcb_U64 begin; bool received; // whether any row was received ThreadContext *ctx; // Parent QueryContext(ThreadContext *tctx) : begin(lcb_nstime()), received(false), ctx(tctx) {} }; class ThreadContext { public: void run() { while (!m_cancelled) { vector<string>::const_iterator ii = m_queries.begin(); for (; ii != m_queries.end(); ++ii) { run_one_query(*ii); } } } #ifndef _WIN32 void start() { assert(m_thr == NULL); m_thr = new pthread_t; int rc = pthread_create(m_thr, NULL, pthrfunc, this); if (rc != 0) { throw std::runtime_error(strerror(rc)); } } void join() { assert(m_thr != NULL); void *arg = NULL; pthread_join(*m_thr, &arg); } ~ThreadContext() { if (m_thr != NULL) { join(); delete m_thr; m_thr = NULL; } } #else void start() { run(); } void join() {} #endif void handle_response(const lcb_RESPN1QL *resp, QueryContext *ctx) { if (!ctx->received) { lcb_U64 duration = lcb_nstime() - ctx->begin; m_metrics->lock(); m_metrics->update_timings(duration); m_metrics->unlock(); ctx->received = true; } if (resp->rflags & LCB_RESP_F_FINAL) { if (resp->rc != LCB_SUCCESS) { if (m_errlog != NULL) { std::stringstream ss; ss.write(m_cmd.query, m_cmd.nquery); ss << endl; ss.write(resp->row, resp->nrow); log_error(resp->rc, ss.str().c_str(), ss.str().size()); } else { log_error(resp->rc, NULL, 0); } } } else { last_nrow++; } } ThreadContext(lcb_t instance, const vector<string>& initial_queries, std::ofstream *errlog) : m_instance(instance), last_nerr(0), last_nrow(0), m_metrics(&GlobalMetrics), m_cancelled(false), m_thr(NULL), m_errlog(errlog) { memset(&m_cmd, 0, sizeof m_cmd); m_cmd.content_type = "application/json"; m_cmd.callback = n1qlcb; // Shuffle the list m_queries = initial_queries; std::random_shuffle(m_queries.begin(), m_queries.end()); } private: void log_error(lcb_error_t err, const char* info, size_t ninfo) { size_t erridx; m_metrics->lock(); m_metrics->update_error(); erridx = m_metrics->nerrors(); m_metrics->unlock(); if (m_errlog != NULL) { std::stringstream ss; ss << "[" << erridx << "] 0x" << std::hex << err << ", " << lcb_strerror(NULL, err) << endl; if (ninfo) { ss.write(info, ninfo); ss << endl; } *m_errlog << ss.str(); m_errlog->flush(); } } void run_one_query(const string& txt) { // Reset counters last_nrow = 0; last_nerr = 0; m_cmd.query = txt.c_str(); m_cmd.nquery = txt.size(); // Set up our context QueryContext qctx(this); lcb_error_t rc = lcb_n1ql_query(m_instance, &qctx, &m_cmd); if (rc != LCB_SUCCESS) { log_error(rc, txt.c_str(), txt.size()); } else { lcb_wait(m_instance); m_metrics->lock(); m_metrics->update_row(last_nrow); m_metrics->update_done(1); m_metrics->unlock(); } } lcb_t m_instance; vector<string> m_queries; size_t last_nerr; size_t last_nrow; lcb_CMDN1QL m_cmd; Metrics *m_metrics; volatile bool m_cancelled; #ifndef _WIN32 pthread_t *m_thr; #else void *m_thr; #endif std::ofstream *m_errlog; }; static void n1qlcb(lcb_t, int, const lcb_RESPN1QL *resp) { QueryContext *qctx = reinterpret_cast<QueryContext*>(resp->cookie); qctx->ctx->handle_response(resp, qctx); } static void* pthrfunc(void *arg) { reinterpret_cast<ThreadContext*>(arg)->run(); return NULL; } static bool instance_has_n1ql(lcb_t instance) { // Check that the instance supports N1QL lcbvb_CONFIG *vbc; do_or_die(lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_VBCONFIG, &vbc)); int sslmode = 0; lcbvb_SVCMODE svcmode = LCBVB_SVCMODE_PLAIN; do_or_die(lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_SSL_MODE, &sslmode)); if (sslmode & LCB_SSL_ENABLED) { svcmode = LCBVB_SVCMODE_SSL; } int hix = lcbvb_get_randhost(vbc, LCBVB_SVCTYPE_N1QL, svcmode); return hix > -1; } static void real_main(int argc, char **argv) { Configuration config; Parser parser; config.addToParser(parser); parser.parse(argc, argv); vector<ThreadContext*> threads; vector<lcb_t> instances; lcb_create_st cropts = { 0 }; config.set_cropts(cropts); config.processOptions(); for (size_t ii = 0; ii < config.nthreads(); ii++) { lcb_t instance; do_or_die(lcb_create(&instance, &cropts)); do_or_die(lcb_connect(instance)); lcb_wait(instance); do_or_die(lcb_get_bootstrap_status(instance)); if (ii == 0 && !instance_has_n1ql(instance)) { throw std::runtime_error("Cluster does not support N1QL!"); } ThreadContext* cx = new ThreadContext(instance, config.queries(), config.errlog()); threads.push_back(cx); instances.push_back(instance); } GlobalMetrics.prepare_screen(); for (size_t ii = 0; ii < threads.size(); ++ii) { threads[ii]->start(); } for (size_t ii = 0; ii < threads.size(); ++ii) { threads[ii]->join(); } for (size_t ii = 0; ii < instances.size(); ++ii) { lcb_destroy(instances[ii]); } } int main(int argc, char **argv) { try { real_main(argc, argv); return 0; } catch (std::exception& exc) { cerr << exc.what() << endl; exit(EXIT_FAILURE); } } <|endoftext|>
<commit_before>int main() { return 0; } <commit_msg>Add license header to no_op.cc.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // No-op main() to provide a dummy executable target. int main() { return 0; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // LLVM 'GCCAS' UTILITY // // This utility is designed to be used by the GCC frontend for creating // bytecode files from it's intermediate llvm assembly. The requirements for // this utility are thus slightly different than that of the standard as util. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Assembly/Parser.h" #include "llvm/Transforms/CleanupGCCOutput.h" #include "llvm/Transforms/LevelChange.h" #include "llvm/Transforms/ConstantMerge.h" #include "llvm/Transforms/ChangeAllocations.h" #include "llvm/Transforms/Scalar/ConstantProp.h" #include "llvm/Transforms/Scalar/DCE.h" #include "llvm/Transforms/Scalar/GCSE.h" #include "llvm/Transforms/Scalar/IndVarSimplify.h" #include "llvm/Transforms/Scalar/InstructionCombining.h" #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> cl::String InputFilename ("", "Parse <arg> file, compile to bytecode", cl::Required, ""); cl::String OutputFilename("o", "Override output filename", cl::NoFlags, ""); cl::Flag StopAtLevelRaise("stopraise", "Stop optimization before level raise", cl::Hidden); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n"); std::auto_ptr<Module> M; try { // Parse the file now... M.reset(ParseAssemblyFile(InputFilename)); } catch (const ParseException &E) { cerr << E.getMessage() << endl; return 1; } if (M.get() == 0) { cerr << "assembly didn't read correctly.\n"; return 1; } if (OutputFilename == "") { // Didn't specify an output filename? std::string IFN = InputFilename; int Len = IFN.length(); if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s? OutputFilename = std::string(IFN.begin(), IFN.end()-2); } else { OutputFilename = IFN; // Append a .o to it } OutputFilename += ".o"; } std::ofstream Out(OutputFilename.c_str(), ios::out); if (!Out.good()) { cerr << "Error opening " << OutputFilename << "!\n"; return 1; } // Make sure that the Out file gets unlink'd from the disk if we get a SIGINT RemoveFileOnSignal(OutputFilename); // In addition to just parsing the input from GCC, we also want to spiff it up // a little bit. Do this now. // PassManager Passes; Passes.add(createFunctionResolvingPass()); // Resolve (...) functions Passes.add(createConstantMergePass()); // Merge dup global constants Passes.add(createDeadInstEliminationPass()); // Remove Dead code/vars Passes.add(createRaiseAllocationsPass()); // call %malloc -> malloc inst Passes.add(createCleanupGCCOutputPass()); // Fix gccisms Passes.add(createIndVarSimplifyPass()); // Simplify indvars if (!StopAtLevelRaise) { Passes.add(createRaisePointerReferencesPass()); // Eliminate casts Passes.add(createPromoteMemoryToRegister()); // Promote alloca's to regs Passes.add(createInstructionCombiningPass()); // Combine silly seq's Passes.add(createSCCPPass()); // Constant prop with SCCP Passes.add(createGCSEPass()); // Remove common subexprs Passes.add(createDeadCodeEliminationPass()); // Remove Dead code/vars } Passes.add(new WriteBytecodePass(&Out)); // Write bytecode to file... // Run our queue of passes all at once now, efficiently. Passes.run(M.get()); return 0; } <commit_msg>Instruction Combination can create a ton of trivially dead instructions. Remove them with an DIE pass before more expensive optimizations are run.<commit_after>//===----------------------------------------------------------------------===// // LLVM 'GCCAS' UTILITY // // This utility is designed to be used by the GCC frontend for creating // bytecode files from it's intermediate llvm assembly. The requirements for // this utility are thus slightly different than that of the standard as util. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Assembly/Parser.h" #include "llvm/Transforms/CleanupGCCOutput.h" #include "llvm/Transforms/LevelChange.h" #include "llvm/Transforms/ConstantMerge.h" #include "llvm/Transforms/ChangeAllocations.h" #include "llvm/Transforms/Scalar/ConstantProp.h" #include "llvm/Transforms/Scalar/DCE.h" #include "llvm/Transforms/Scalar/GCSE.h" #include "llvm/Transforms/Scalar/IndVarSimplify.h" #include "llvm/Transforms/Scalar/InstructionCombining.h" #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> cl::String InputFilename ("", "Parse <arg> file, compile to bytecode", cl::Required, ""); cl::String OutputFilename("o", "Override output filename", cl::NoFlags, ""); cl::Flag StopAtLevelRaise("stopraise", "Stop optimization before level raise", cl::Hidden); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n"); std::auto_ptr<Module> M; try { // Parse the file now... M.reset(ParseAssemblyFile(InputFilename)); } catch (const ParseException &E) { cerr << E.getMessage() << endl; return 1; } if (M.get() == 0) { cerr << "assembly didn't read correctly.\n"; return 1; } if (OutputFilename == "") { // Didn't specify an output filename? std::string IFN = InputFilename; int Len = IFN.length(); if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s? OutputFilename = std::string(IFN.begin(), IFN.end()-2); } else { OutputFilename = IFN; // Append a .o to it } OutputFilename += ".o"; } std::ofstream Out(OutputFilename.c_str(), ios::out); if (!Out.good()) { cerr << "Error opening " << OutputFilename << "!\n"; return 1; } // Make sure that the Out file gets unlink'd from the disk if we get a SIGINT RemoveFileOnSignal(OutputFilename); // In addition to just parsing the input from GCC, we also want to spiff it up // a little bit. Do this now. // PassManager Passes; Passes.add(createFunctionResolvingPass()); // Resolve (...) functions Passes.add(createConstantMergePass()); // Merge dup global constants Passes.add(createDeadInstEliminationPass()); // Remove Dead code/vars Passes.add(createRaiseAllocationsPass()); // call %malloc -> malloc inst Passes.add(createCleanupGCCOutputPass()); // Fix gccisms Passes.add(createIndVarSimplifyPass()); // Simplify indvars if (!StopAtLevelRaise) { Passes.add(createRaisePointerReferencesPass()); // Eliminate casts Passes.add(createPromoteMemoryToRegister()); // Promote alloca's to regs Passes.add(createInstructionCombiningPass()); // Combine silly seq's Passes.add(createDeadInstEliminationPass()); // Kill InstCombine remnants Passes.add(createSCCPPass()); // Constant prop with SCCP Passes.add(createGCSEPass()); // Remove common subexprs Passes.add(createDeadCodeEliminationPass()); // Remove Dead code/vars } Passes.add(new WriteBytecodePass(&Out)); // Write bytecode to file... // Run our queue of passes all at once now, efficiently. Passes.run(M.get()); return 0; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // LLVM 'GCCAS' UTILITY // // This utility is designed to be used by the GCC frontend for creating // bytecode files from it's intermediate llvm assembly. The requirements for // this utility are thus slightly different than that of the standard as util. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Assembly/Parser.h" #include "llvm/Transforms/RaisePointerReferences.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Target/TargetData.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> namespace { // FIXME: This should eventually be parameterized... TargetData TD("gccas target"); cl::opt<std::string> InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-")); cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::value_desc("filename")); cl::opt<int> RunNPasses("stopAfterNPasses", cl::desc("Only run the first N passes of gccas"), cl::Hidden, cl::value_desc("# passes")); cl::opt<bool> Verify("verify", cl::desc("Verify each pass result")); } static inline void addPass(PassManager &PM, Pass *P) { static int NumPassesCreated = 0; // If we haven't already created the number of passes that was requested... if (RunNPasses == 0 || RunNPasses > NumPassesCreated) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (Verify) PM.add(createVerifierPass()); // Keep track of how many passes we made for -stopAfterNPasses ++NumPassesCreated; } else { delete P; // We don't want this pass to run, just delete it now } } void AddConfiguredTransformationPasses(PassManager &PM) { if (Verify) PM.add(createVerifierPass()); addPass(PM, createFunctionResolvingPass()); // Resolve (...) functions addPass(PM, createGlobalDCEPass()); // Kill unused uinit g-vars addPass(PM, createDeadTypeEliminationPass()); // Eliminate dead types addPass(PM, createConstantMergePass()); // Merge dup global constants addPass(PM, createVerifierPass()); // Verify that input is correct addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createDeadInstEliminationPass()); // Remove Dead code/vars addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst addPass(PM, createIndVarSimplifyPass()); // Simplify indvars addPass(PM, createRaisePointerReferencesPass(TD));// Recover type information addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createPromoteMemoryToRegister()); // Promote alloca's to regs addPass(PM, createReassociatePass()); // Reassociate expressions //addPass(PM, createCorrelatedExpressionEliminationPass());// Kill corr branches addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createLICMPass()); // Hoist loop invariants addPass(PM, createLoadValueNumberingPass()); // GVN for load instructions addPass(PM, createGCSEPass()); // Remove common subexprs addPass(PM, createSCCPPass()); // Constant prop with SCCP // Run instcombine after redundancy elimination to exploit opportunities // opened up by them. addPass(PM, createInstructionCombiningPass()); addPass(PM, createAggressiveDCEPass()); // SSA based 'Agressive DCE' addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n"); std::auto_ptr<Module> M; try { // Parse the file now... M.reset(ParseAssemblyFile(InputFilename)); } catch (const ParseException &E) { std::cerr << argv[0] << ": " << E.getMessage() << "\n"; return 1; } if (M.get() == 0) { std::cerr << argv[0] << ": assembly didn't read correctly.\n"; return 1; } std::ostream *Out = 0; if (OutputFilename == "") { // Didn't specify an output filename? if (InputFilename == "-") { OutputFilename = "-"; } else { std::string IFN = InputFilename; int Len = IFN.length(); if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s? OutputFilename = std::string(IFN.begin(), IFN.end()-2); } else { OutputFilename = IFN; // Append a .o to it } OutputFilename += ".o"; } } if (OutputFilename == "-") Out = &std::cout; else { Out = new std::ofstream(OutputFilename.c_str(), std::ios::out); // Make sure that the Out file gets unlink'd from the disk if we get a // signal RemoveFileOnSignal(OutputFilename); } if (!Out->good()) { std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; return 1; } // In addition to just parsing the input from GCC, we also want to spiff it up // a little bit. Do this now. // PassManager Passes; // Add all of the transformation passes to the pass manager to do the cleanup // and optimization of the GCC output. // AddConfiguredTransformationPasses(Passes); // Write bytecode to file... Passes.add(new WriteBytecodePass(Out)); // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); if (Out != &std::cout) delete Out; return 0; } <commit_msg>LevelRaise now gets target data from passmanager<commit_after>//===----------------------------------------------------------------------===// // LLVM 'GCCAS' UTILITY // // This utility is designed to be used by the GCC frontend for creating // bytecode files from it's intermediate llvm assembly. The requirements for // this utility are thus slightly different than that of the standard as util. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Assembly/Parser.h" #include "llvm/Transforms/RaisePointerReferences.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Analysis/LoadValueNumbering.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Bytecode/WriteBytecodePass.h" #include "llvm/Target/TargetData.h" #include "Support/CommandLine.h" #include "Support/Signals.h" #include <memory> #include <fstream> namespace { cl::opt<std::string> InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-")); cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::value_desc("filename")); cl::opt<int> RunNPasses("stopAfterNPasses", cl::desc("Only run the first N passes of gccas"), cl::Hidden, cl::value_desc("# passes")); cl::opt<bool> Verify("verify", cl::desc("Verify each pass result")); } static inline void addPass(PassManager &PM, Pass *P) { static int NumPassesCreated = 0; // If we haven't already created the number of passes that was requested... if (RunNPasses == 0 || RunNPasses > NumPassesCreated) { // Add the pass to the pass manager... PM.add(P); // If we are verifying all of the intermediate steps, add the verifier... if (Verify) PM.add(createVerifierPass()); // Keep track of how many passes we made for -stopAfterNPasses ++NumPassesCreated; } else { delete P; // We don't want this pass to run, just delete it now } } void AddConfiguredTransformationPasses(PassManager &PM) { if (Verify) PM.add(createVerifierPass()); addPass(PM, createFunctionResolvingPass()); // Resolve (...) functions addPass(PM, createGlobalDCEPass()); // Kill unused uinit g-vars addPass(PM, createDeadTypeEliminationPass()); // Eliminate dead types addPass(PM, createConstantMergePass()); // Merge dup global constants addPass(PM, createVerifierPass()); // Verify that input is correct addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createDeadInstEliminationPass()); // Remove Dead code/vars addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst addPass(PM, createIndVarSimplifyPass()); // Simplify indvars addPass(PM, createRaisePointerReferencesPass());// Recover type information addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createPromoteMemoryToRegister()); // Promote alloca's to regs addPass(PM, createReassociatePass()); // Reassociate expressions //addPass(PM, createCorrelatedExpressionEliminationPass());// Kill corr branches addPass(PM, createInstructionCombiningPass()); // Combine silly seq's addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs addPass(PM, createLICMPass()); // Hoist loop invariants addPass(PM, createLoadValueNumberingPass()); // GVN for load instructions addPass(PM, createGCSEPass()); // Remove common subexprs addPass(PM, createSCCPPass()); // Constant prop with SCCP // Run instcombine after redundancy elimination to exploit opportunities // opened up by them. addPass(PM, createInstructionCombiningPass()); addPass(PM, createAggressiveDCEPass()); // SSA based 'Agressive DCE' addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n"); // FIXME: This should eventually be parameterized... TargetData TD("gccas target"); std::auto_ptr<Module> M; try { // Parse the file now... M.reset(ParseAssemblyFile(InputFilename)); } catch (const ParseException &E) { std::cerr << argv[0] << ": " << E.getMessage() << "\n"; return 1; } if (M.get() == 0) { std::cerr << argv[0] << ": assembly didn't read correctly.\n"; return 1; } std::ostream *Out = 0; if (OutputFilename == "") { // Didn't specify an output filename? if (InputFilename == "-") { OutputFilename = "-"; } else { std::string IFN = InputFilename; int Len = IFN.length(); if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s? OutputFilename = std::string(IFN.begin(), IFN.end()-2); } else { OutputFilename = IFN; // Append a .o to it } OutputFilename += ".o"; } } if (OutputFilename == "-") Out = &std::cout; else { Out = new std::ofstream(OutputFilename.c_str(), std::ios::out); // Make sure that the Out file gets unlink'd from the disk if we get a // signal RemoveFileOnSignal(OutputFilename); } if (!Out->good()) { std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; return 1; } // In addition to just parsing the input from GCC, we also want to spiff it up // a little bit. Do this now. // PassManager Passes; // Add all of the transformation passes to the pass manager to do the cleanup // and optimization of the GCC output. // AddConfiguredTransformationPasses(Passes); // Write bytecode to file... Passes.add(new WriteBytecodePass(Out)); // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); if (Out != &std::cout) delete Out; return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/protocol/types.hpp> namespace graphene { namespace chain { /** * @ingroup operations * @brief Generate an deflation * * This operation is used to generate a deflation */ struct deflation_operation : public base_operation { struct fee_parameters_type {uint64_t fee = 0; }; deflation_operation() {} account_id_type issuer; uint32_t rate; asset fee; //this is virtual operation, no fee is charged account_id_type fee_payer() const { return GRAPHENE_TEMP_ACCOUNT; } void validate() const; /// This is a virtual operation; there is no fee share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; /** * @ingroup operations * @brief Generate an accout deflation * * This operation is used to generate a deflation for a specified account */ struct account_deflation_operation : public base_operation { struct fee_parameters_type {uint64_t fee = 0; }; account_deflation_operation() {} deflation_id_type deflation_id; account_id_type owner; asset fee; //this is virtual operation, no fee is charged share_type amount; // only for history detail account_id_type fee_payer() const { return GRAPHENE_TEMP_ACCOUNT; } void validate() const; /// This is a virtual operation; there is no fee share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; }} // graphene::chain FC_REFLECT( graphene::chain::deflation_operation::fee_parameters_type, (fee) ) FC_REFLECT( graphene::chain::deflation_operation, (issuer)(rate)(fee) ) FC_REFLECT( graphene::chain::account_deflation_operation::fee_parameters_type, (fee) ) FC_REFLECT( graphene::chain::account_deflation_operation, (deflation_id)(owner)(fee)(amount) )<commit_msg>deflation<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #include <graphene/chain/protocol/base.hpp> #include <graphene/chain/protocol/types.hpp> namespace graphene { namespace chain { /** * @ingroup operations * @brief Generate an deflation * * This operation is used to generate a deflation */ struct deflation_operation : public base_operation { struct fee_parameters_type {uint64_t fee = 0; }; deflation_operation() {} asset fee; //this is virtual operation, no fee is charged account_id_type issuer; uint32_t rate; account_id_type fee_payer() const { return issuer; } void validate() const; /// This is a virtual operation; there is no fee share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; /** * @ingroup operations * @brief Generate an accout deflation * * This operation is used to generate a deflation for a specified account */ struct account_deflation_operation : public base_operation { struct fee_parameters_type {uint64_t fee = 0; }; account_deflation_operation() {} asset fee; //this is virtual operation, no fee is charged deflation_id_type deflation_id; account_id_type owner; share_type amount; // only for history detail account_id_type fee_payer() const { return GRAPHENE_TEMP_ACCOUNT; } void validate() const; /// This is a virtual operation; there is no fee share_type calculate_fee(const fee_parameters_type& k)const { return 0; } }; }} // graphene::chain FC_REFLECT( graphene::chain::deflation_operation::fee_parameters_type, (fee) ) FC_REFLECT( graphene::chain::deflation_operation, (fee)(issuer)(rate) ) FC_REFLECT( graphene::chain::account_deflation_operation::fee_parameters_type, (fee) ) FC_REFLECT( graphene::chain::account_deflation_operation, (fee)(deflation_id)(owner)(amount) )<|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file MulticopterLandDetector.cpp * * @author Johan Jansen <[email protected]> * @author Morten Lysgaard <[email protected]> * @author Julian Oes <[email protected]> */ #include <cmath> #include <drivers/drv_hrt.h> #include <mathlib/mathlib.h> #include "MulticopterLandDetector.h" namespace land_detector { MulticopterLandDetector::MulticopterLandDetector() : LandDetector(), _paramHandle(), _params(), _vehicleLocalPositionSub(-1), _actuatorsSub(-1), _armingSub(-1), _attitudeSub(-1), _manualSub(-1), _ctrl_state_sub(-1), _vehicle_control_mode_sub(-1), _vehicleLocalPosition{}, _actuators{}, _arming{}, _vehicleAttitude{}, _manual{}, _ctrl_state{}, _control_mode{}, _min_trust_start(0), _arming_time(0) { _paramHandle.maxRotation = param_find("LNDMC_ROT_MAX"); _paramHandle.maxVelocity = param_find("LNDMC_XY_VEL_MAX"); _paramHandle.maxClimbRate = param_find("LNDMC_Z_VEL_MAX"); _paramHandle.minThrottle = param_find("MPC_THR_MIN"); _paramHandle.minManThrottle = param_find("MPC_MANTHR_MIN"); _paramHandle.freefall_acc_threshold = param_find("LNDMC_FFALL_THR"); _paramHandle.freefall_trigger_time = param_find("LNDMC_FFALL_TTRI"); } void MulticopterLandDetector::_initialize_topics() { // subscribe to position, attitude, arming and velocity changes _vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position)); _attitudeSub = orb_subscribe(ORB_ID(vehicle_attitude)); _actuatorsSub = orb_subscribe(ORB_ID(actuator_controls_0)); _armingSub = orb_subscribe(ORB_ID(actuator_armed)); _parameterSub = orb_subscribe(ORB_ID(parameter_update)); _manualSub = orb_subscribe(ORB_ID(manual_control_setpoint)); _ctrl_state_sub = orb_subscribe(ORB_ID(control_state)); _vehicle_control_mode_sub = orb_subscribe(ORB_ID(vehicle_control_mode)); } void MulticopterLandDetector::_update_topics() { _orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition); _orb_update(ORB_ID(vehicle_attitude), _attitudeSub, &_vehicleAttitude); _orb_update(ORB_ID(actuator_controls_0), _actuatorsSub, &_actuators); _orb_update(ORB_ID(actuator_armed), _armingSub, &_arming); _orb_update(ORB_ID(manual_control_setpoint), _manualSub, &_manual); _orb_update(ORB_ID(control_state), _ctrl_state_sub, &_ctrl_state); _orb_update(ORB_ID(vehicle_control_mode), _vehicle_control_mode_sub, &_control_mode); } void MulticopterLandDetector::_update_params() { param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate); param_get(_paramHandle.maxVelocity, &_params.maxVelocity); param_get(_paramHandle.maxRotation, &_params.maxRotation_rad_s); _params.maxRotation_rad_s = math::radians(_params.maxRotation_rad_s); param_get(_paramHandle.minThrottle, &_params.minThrottle); param_get(_paramHandle.minManThrottle, &_params.minManThrottle); param_get(_paramHandle.freefall_acc_threshold, &_params.freefall_acc_threshold); param_get(_paramHandle.freefall_trigger_time, &_params.freefall_trigger_time); _freefall_hysteresis.set_hysteresis_time_from(false, 1e6f * _params.freefall_trigger_time); } bool MulticopterLandDetector::_get_freefall_state() { if (_params.freefall_acc_threshold < 0.1f || _params.freefall_acc_threshold > 10.0f) { //if parameter is set to zero or invalid, disable free-fall detection. return false; } if (_ctrl_state.timestamp == 0) { // _ctrl_state is not valid yet, we have to assume we're not falling. return false; } float acc_norm = _ctrl_state.x_acc * _ctrl_state.x_acc + _ctrl_state.y_acc * _ctrl_state.y_acc + _ctrl_state.z_acc * _ctrl_state.z_acc; acc_norm = sqrtf(acc_norm); //norm of specific force. Should be close to 9.8 m/s^2 when landed. return (acc_norm < _params.freefall_acc_threshold); //true if we are currently falling } bool MulticopterLandDetector::_get_landed_state() { // Time base for this function const uint64_t now = hrt_absolute_time(); float sys_min_throttle = (_params.minThrottle + 0.01f); // Determine the system min throttle based on flight mode if (!_control_mode.flag_control_altitude_enabled) { sys_min_throttle = (_params.minManThrottle + 0.01f); } // Check if thrust output is less than the minimum auto throttle param. bool minimalThrust = (_actuators.control[3] <= sys_min_throttle); if (minimalThrust && _min_trust_start == 0) { _min_trust_start = now; } else if (!minimalThrust) { _min_trust_start = 0; } // only trigger flight conditions if we are armed if (!_arming.armed) { _arming_time = 0; return true; } else if (_arming_time == 0) { _arming_time = now; } const bool manual_control_present = _control_mode.flag_control_manual_enabled && _manual.timestamp > 0; // If we control manually and are still landed, we want to stay idle until the pilot rises the throttle if (_state == LandDetectionState::LANDED && manual_control_present && _manual.z < get_takeoff_throttle()) { return true; } // If in manual flight mode never report landed if the user has more than idle throttle // Check if user commands throttle and if so, report not landed based on // the user intent to take off (even if the system might physically still have // ground contact at this point). if (manual_control_present && _manual.z > 0.15f) { return false; } // Return status based on armed state and throttle if no position lock is available. if (_vehicleLocalPosition.timestamp == 0 || hrt_elapsed_time(&_vehicleLocalPosition.timestamp) > 500000 || !_vehicleLocalPosition.xy_valid || !_vehicleLocalPosition.z_valid) { // The system has minimum trust set (manual or in failsafe) // if this persists for 8 seconds AND the drone is not // falling consider it to be landed. This should even sustain // quite acrobatic flight. if ((_min_trust_start > 0) && (hrt_elapsed_time(&_min_trust_start) > 8000000)) { return true; } else { return false; } } float armThresholdFactor = 1.0f; // Widen acceptance thresholds for landed state right after arming // so that motor spool-up and other effects do not trigger false negatives. if (hrt_elapsed_time(&_arming_time) < LAND_DETECTOR_ARM_PHASE_TIME_US) { armThresholdFactor = 2.5f; } // Check if we are moving vertically - this might see a spike after arming due to // throttle-up vibration. If accelerating fast the throttle thresholds will still give // an accurate in-air indication. bool verticalMovement = fabsf(_vehicleLocalPosition.vz) > _params.maxClimbRate * armThresholdFactor; // Check if we are moving horizontally. bool horizontalMovement = sqrtf(_vehicleLocalPosition.vx * _vehicleLocalPosition.vx + _vehicleLocalPosition.vy * _vehicleLocalPosition.vy) > _params.maxVelocity; // Next look if all rotation angles are not moving. float maxRotationScaled = _params.maxRotation_rad_s * armThresholdFactor; bool rotating = (fabsf(_vehicleAttitude.rollspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.pitchspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.yawspeed) > maxRotationScaled); if (verticalMovement || rotating || !minimalThrust || horizontalMovement) { // Sensed movement or thottle high, so reset the land detector. return false; } return true; } float MulticopterLandDetector::get_takeoff_throttle() { /* Position mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_position_enabled) { /* Should be above 0.5 because below that we do not gain altitude and won't take off. * Also it should be quite high such that we don't accidentally take off when using * a spring loaded throttle and have a useful vertical speed to start with. */ return 0.75f; } /* Manual/attitude mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_attitude_enabled) { /* Should be quite low and certainly below hover throttle because pilot controls throttle manually. */ return 0.15f; } /* As default for example in acro mode we do not want to stay landed. */ return 0.0f; } } <commit_msg>land detector: changed minimum throttle threshold to have useful landing detection in real world scenarios<commit_after>/**************************************************************************** * * Copyright (c) 2013-2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file MulticopterLandDetector.cpp * * @author Johan Jansen <[email protected]> * @author Morten Lysgaard <[email protected]> * @author Julian Oes <[email protected]> */ #include <cmath> #include <drivers/drv_hrt.h> #include <mathlib/mathlib.h> #include "MulticopterLandDetector.h" namespace land_detector { MulticopterLandDetector::MulticopterLandDetector() : LandDetector(), _paramHandle(), _params(), _vehicleLocalPositionSub(-1), _actuatorsSub(-1), _armingSub(-1), _attitudeSub(-1), _manualSub(-1), _ctrl_state_sub(-1), _vehicle_control_mode_sub(-1), _vehicleLocalPosition{}, _actuators{}, _arming{}, _vehicleAttitude{}, _manual{}, _ctrl_state{}, _control_mode{}, _min_trust_start(0), _arming_time(0) { _paramHandle.maxRotation = param_find("LNDMC_ROT_MAX"); _paramHandle.maxVelocity = param_find("LNDMC_XY_VEL_MAX"); _paramHandle.maxClimbRate = param_find("LNDMC_Z_VEL_MAX"); _paramHandle.minThrottle = param_find("MPC_THR_MIN"); _paramHandle.minManThrottle = param_find("MPC_MANTHR_MIN"); _paramHandle.freefall_acc_threshold = param_find("LNDMC_FFALL_THR"); _paramHandle.freefall_trigger_time = param_find("LNDMC_FFALL_TTRI"); } void MulticopterLandDetector::_initialize_topics() { // subscribe to position, attitude, arming and velocity changes _vehicleLocalPositionSub = orb_subscribe(ORB_ID(vehicle_local_position)); _attitudeSub = orb_subscribe(ORB_ID(vehicle_attitude)); _actuatorsSub = orb_subscribe(ORB_ID(actuator_controls_0)); _armingSub = orb_subscribe(ORB_ID(actuator_armed)); _parameterSub = orb_subscribe(ORB_ID(parameter_update)); _manualSub = orb_subscribe(ORB_ID(manual_control_setpoint)); _ctrl_state_sub = orb_subscribe(ORB_ID(control_state)); _vehicle_control_mode_sub = orb_subscribe(ORB_ID(vehicle_control_mode)); } void MulticopterLandDetector::_update_topics() { _orb_update(ORB_ID(vehicle_local_position), _vehicleLocalPositionSub, &_vehicleLocalPosition); _orb_update(ORB_ID(vehicle_attitude), _attitudeSub, &_vehicleAttitude); _orb_update(ORB_ID(actuator_controls_0), _actuatorsSub, &_actuators); _orb_update(ORB_ID(actuator_armed), _armingSub, &_arming); _orb_update(ORB_ID(manual_control_setpoint), _manualSub, &_manual); _orb_update(ORB_ID(control_state), _ctrl_state_sub, &_ctrl_state); _orb_update(ORB_ID(vehicle_control_mode), _vehicle_control_mode_sub, &_control_mode); } void MulticopterLandDetector::_update_params() { param_get(_paramHandle.maxClimbRate, &_params.maxClimbRate); param_get(_paramHandle.maxVelocity, &_params.maxVelocity); param_get(_paramHandle.maxRotation, &_params.maxRotation_rad_s); _params.maxRotation_rad_s = math::radians(_params.maxRotation_rad_s); param_get(_paramHandle.minThrottle, &_params.minThrottle); param_get(_paramHandle.minManThrottle, &_params.minManThrottle); param_get(_paramHandle.freefall_acc_threshold, &_params.freefall_acc_threshold); param_get(_paramHandle.freefall_trigger_time, &_params.freefall_trigger_time); _freefall_hysteresis.set_hysteresis_time_from(false, 1e6f * _params.freefall_trigger_time); } bool MulticopterLandDetector::_get_freefall_state() { if (_params.freefall_acc_threshold < 0.1f || _params.freefall_acc_threshold > 10.0f) { //if parameter is set to zero or invalid, disable free-fall detection. return false; } if (_ctrl_state.timestamp == 0) { // _ctrl_state is not valid yet, we have to assume we're not falling. return false; } float acc_norm = _ctrl_state.x_acc * _ctrl_state.x_acc + _ctrl_state.y_acc * _ctrl_state.y_acc + _ctrl_state.z_acc * _ctrl_state.z_acc; acc_norm = sqrtf(acc_norm); //norm of specific force. Should be close to 9.8 m/s^2 when landed. return (acc_norm < _params.freefall_acc_threshold); //true if we are currently falling } bool MulticopterLandDetector::_get_landed_state() { // Time base for this function const uint64_t now = hrt_absolute_time(); float sys_min_throttle = (_params.minThrottle + 0.2f); // Determine the system min throttle based on flight mode if (!_control_mode.flag_control_altitude_enabled) { sys_min_throttle = (_params.minManThrottle + 0.01f); } // Check if thrust output is less than the minimum auto throttle param. bool minimalThrust = (_actuators.control[3] <= sys_min_throttle); if (minimalThrust && _min_trust_start == 0) { _min_trust_start = now; } else if (!minimalThrust) { _min_trust_start = 0; } // only trigger flight conditions if we are armed if (!_arming.armed) { _arming_time = 0; return true; } else if (_arming_time == 0) { _arming_time = now; } const bool manual_control_present = _control_mode.flag_control_manual_enabled && _manual.timestamp > 0; // If we control manually and are still landed, we want to stay idle until the pilot rises the throttle if (_state == LandDetectionState::LANDED && manual_control_present && _manual.z < get_takeoff_throttle()) { return true; } // If in manual flight mode never report landed if the user has more than idle throttle // Check if user commands throttle and if so, report not landed based on // the user intent to take off (even if the system might physically still have // ground contact at this point). if (manual_control_present && _manual.z > 0.15f) { return false; } // Return status based on armed state and throttle if no position lock is available. if (_vehicleLocalPosition.timestamp == 0 || hrt_elapsed_time(&_vehicleLocalPosition.timestamp) > 500000 || !_vehicleLocalPosition.xy_valid || !_vehicleLocalPosition.z_valid) { // The system has minimum trust set (manual or in failsafe) // if this persists for 8 seconds AND the drone is not // falling consider it to be landed. This should even sustain // quite acrobatic flight. if ((_min_trust_start > 0) && (hrt_elapsed_time(&_min_trust_start) > 8000000)) { return true; } else { return false; } } float armThresholdFactor = 1.0f; // Widen acceptance thresholds for landed state right after arming // so that motor spool-up and other effects do not trigger false negatives. if (hrt_elapsed_time(&_arming_time) < LAND_DETECTOR_ARM_PHASE_TIME_US) { armThresholdFactor = 2.5f; } // Check if we are moving vertically - this might see a spike after arming due to // throttle-up vibration. If accelerating fast the throttle thresholds will still give // an accurate in-air indication. bool verticalMovement = fabsf(_vehicleLocalPosition.vz) > _params.maxClimbRate * armThresholdFactor; // Check if we are moving horizontally. bool horizontalMovement = sqrtf(_vehicleLocalPosition.vx * _vehicleLocalPosition.vx + _vehicleLocalPosition.vy * _vehicleLocalPosition.vy) > _params.maxVelocity; // Next look if all rotation angles are not moving. float maxRotationScaled = _params.maxRotation_rad_s * armThresholdFactor; bool rotating = (fabsf(_vehicleAttitude.rollspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.pitchspeed) > maxRotationScaled) || (fabsf(_vehicleAttitude.yawspeed) > maxRotationScaled); if (verticalMovement || rotating || !minimalThrust || horizontalMovement) { // Sensed movement or thottle high, so reset the land detector. return false; } return true; } float MulticopterLandDetector::get_takeoff_throttle() { /* Position mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_position_enabled) { /* Should be above 0.5 because below that we do not gain altitude and won't take off. * Also it should be quite high such that we don't accidentally take off when using * a spring loaded throttle and have a useful vertical speed to start with. */ return 0.75f; } /* Manual/attitude mode */ if (_control_mode.flag_control_manual_enabled && _control_mode.flag_control_attitude_enabled) { /* Should be quite low and certainly below hover throttle because pilot controls throttle manually. */ return 0.15f; } /* As default for example in acro mode we do not want to stay landed. */ return 0.0f; } } <|endoftext|>
<commit_before>#include "core.hpp" #include <ncurses.h> #include <string> #include "config.hpp" #include "draw.hpp" #include "todolist.hpp" using std::string; // ===================| // internal variables | // ===================| TodoList *backup_; // ===================| // internal functions | // ===================| void backup(TodoList *list); void restore(TodoList *&list); ////////////////////////////////////////////// // initiate things such as the mouse listener void Core::init() { if (USE_MOUSE){ mousemask(ALL_MOUSE_EVENTS, NULL); } backup_ = nullptr; } /////////////////////////////////////////// // cleanup everything and prepare to exit void Core::stop() { delete backup_; } ////////////////////////////////// // create and load the to-do list TodoList* Core::list(string name) { TodoList *list = new TodoList(name); list->load(); return list; } ////////////////////////////////////////// // intercept keyboard input and act on it // returns true if the program should exit // and false if it should continue bool Core::handleInput(int c, TodoList *&todoList, unsigned &position) { std::string newTask; switch(c){ case EXIT_KEY: return true; case TOGGLE_CHECK_KEY: if (todoList->size() != 0){ todoList->at(position).toggleComplete(); } break; case NEW_KEY: backup(todoList); newTask = Draw::getInput(); if (!newTask.empty()){ todoList->add(Task(newTask), position); } break; case EDIT_KEY: { backup(todoList); string base = todoList->at(position).raw(); string editTask = Draw::getInput(base); if (!editTask.empty()) todoList->at(position) = Task(editTask); break; } case REMOVE_KEY: backup(todoList); todoList->remove(position); if (todoList->size() != 0){ if (position >= todoList->size()){ position = todoList->size() - 1; } } break; case UNDO_KEY: restore(todoList); break; case MOVE_UP_KEY: if (todoList->swap(position - 1)){ --position; if (autoSave){ todoList->save(); } } break; case MOVE_DOWN_KEY: if(todoList->swap(position)){ ++position; if (autoSave){ todoList->save(); } } break; case DIV_KEY: backup(todoList); newTask = Draw::getInput(); if (!newTask.empty()){ newTask ="[" + newTask + "]"; } newTask = DIV_CODE + newTask; todoList->add(Task(newTask), position); break; case UP_KEY: if (position != 0){ --position; } break; case DOWN_KEY: if (todoList->size() != 0){ ++position; if (position >= todoList->size()){ position = todoList->size() - 1; } } break; case SORT_KEY: backup(todoList); todoList->sort(); if (autoSave){ todoList->save(); } break; case KEY_RESIZE: Draw::stop(); Draw::init(); break; case KEY_MOUSE: MEVENT event; if (getmouse(&event) == OK){ if (event.bstate & BUTTON1_PRESSED){ Draw::mouse(event, todoList, position, false); } else if (event.bstate & BUTTON3_PRESSED){ Draw::mouse(event, todoList, position, true); } else if (event.bstate & BUTTON4_PRESSED){ if (position != 0){ --position; } } } else { // ncurses is weird and returns ERR ++position; // on mouse wheel down events if (position >= todoList->size()){ position = todoList->size() - 1; } } break; } return false; } /////////////////// // backup todolist void backup(TodoList *list) { delete backup_; backup_ = new TodoList(list); } //////////////////////////////// // restore to-do list from backup void restore(TodoList *&list) { if (!backup_) return; delete list; list = new TodoList(backup_); } <commit_msg>fixed positioning of new items<commit_after>#include "core.hpp" #include <ncurses.h> #include <string> #include "config.hpp" #include "draw.hpp" #include "todolist.hpp" using std::string; // ===================| // internal variables | // ===================| TodoList *backup_; // ===================| // internal functions | // ===================| void backup(TodoList *list); void restore(TodoList *&list); ////////////////////////////////////////////// // initiate things such as the mouse listener void Core::init() { if (USE_MOUSE){ mousemask(ALL_MOUSE_EVENTS, NULL); } backup_ = nullptr; } /////////////////////////////////////////// // cleanup everything and prepare to exit void Core::stop() { delete backup_; } ////////////////////////////////// // create and load the to-do list TodoList* Core::list(string name) { TodoList *list = new TodoList(name); list->load(); return list; } ////////////////////////////////////////// // intercept keyboard input and act on it // returns true if the program should exit // and false if it should continue bool Core::handleInput(int c, TodoList *&todoList, unsigned &position) { std::string newTask; switch(c){ case EXIT_KEY: return true; case TOGGLE_CHECK_KEY: if (todoList->size() != 0){ todoList->at(position).toggleComplete(); } break; case NEW_KEY: backup(todoList); newTask = Draw::getInput(); if (!newTask.empty()){ todoList->add(Task(newTask), position + 1); } break; case EDIT_KEY: { backup(todoList); string base = todoList->at(position).raw(); string editTask = Draw::getInput(base); if (!editTask.empty()) todoList->at(position) = Task(editTask); break; } case REMOVE_KEY: backup(todoList); todoList->remove(position); if (todoList->size() != 0){ if (position >= todoList->size()){ position = todoList->size() - 1; } } break; case UNDO_KEY: restore(todoList); break; case MOVE_UP_KEY: if (todoList->swap(position - 1)){ --position; if (autoSave){ todoList->save(); } } break; case MOVE_DOWN_KEY: if(todoList->swap(position)){ ++position; if (autoSave){ todoList->save(); } } break; case DIV_KEY: backup(todoList); newTask = Draw::getInput(); if (!newTask.empty()){ newTask ="[" + newTask + "]"; } newTask = DIV_CODE + newTask; todoList->add(Task(newTask), position + 1); break; case UP_KEY: if (position != 0){ --position; } break; case DOWN_KEY: if (todoList->size() != 0){ ++position; if (position >= todoList->size()){ position = todoList->size() - 1; } } break; case SORT_KEY: backup(todoList); todoList->sort(); if (autoSave){ todoList->save(); } break; case KEY_RESIZE: Draw::stop(); Draw::init(); break; case KEY_MOUSE: MEVENT event; if (getmouse(&event) == OK){ if (event.bstate & BUTTON1_PRESSED){ Draw::mouse(event, todoList, position, false); } else if (event.bstate & BUTTON3_PRESSED){ Draw::mouse(event, todoList, position, true); } else if (event.bstate & BUTTON4_PRESSED){ if (position != 0){ --position; } } } else { // ncurses is weird and returns ERR ++position; // on mouse wheel down events if (position >= todoList->size()){ position = todoList->size() - 1; } } break; } return false; } /////////////////// // backup todolist void backup(TodoList *list) { delete backup_; backup_ = new TodoList(list); } //////////////////////////////// // restore to-do list from backup void restore(TodoList *&list) { if (!backup_) return; delete list; list = new TodoList(backup_); } <|endoftext|>
<commit_before>/** @file @brief Hurwitz zeta function and polylogarithm. For implemenation, see <a href="http://fredrikj.net/math/hurwitz_zeta.pdf"> Fredrik Johansson.</a> */ #include <zeta.h> #include <bernoulli.h> #include <gsl/gsl_sf.h> #include <gsl/gsl_math.h> #include <complex> #include <stdexcept> cdouble S(double s, cdouble a, int N) { /** @returns \f$S\f$ part of zeta function @param s @param a @param N */ cdouble sum = 0.; for (int k = 0; k <= N - 1; k += 1) { sum += pow(a + static_cast<cdouble>(k), -s); } return sum; } cdouble I(double s, cdouble a, int N) { /** @returns \f$I\f$ part of zeta function @param s @param a @param N */ return pow(a + static_cast<cdouble>(N), 1. - s) / (s - 1.); } cdouble T(double s, cdouble a, int N, int M) { /** @returns \f$T\f$ part of zeta function @param s @param a @param N @param M */ const cdouble d = a + static_cast<cdouble>(N); const cdouble factor = pow(d, -s); if (M > B_2n_fact_size) { #ifdef DEBUG printf("M = %d > B_2n_fact_size = %d. Using M = B_2n_fact_size\n", M, B_2n_fact_size); #endif #ifdef THROW throw std::invalid_argument("Bernoulli numbers out of bounds"); #endif M = B_2n_fact_size; } cdouble sum = 0.; for (int k = 1; k <= M; k += 1) { sum += B_2n_fact[k] * gsl_sf_poch(s, 2. * k - 1.) / pow(d, 2 * k - 1); } return factor * (0.5 + sum); } cdouble hurwitz_zeta(double s, cdouble a, int N) { /** @returns Hurwitz zeta function, \f$\zeta_s(a)\f$ @param s @param a @param N */ if (N > B_2n_fact_size) { #ifdef DEBUG printf("N = %d > B_2n_fact_size = %d. Using N = B_2n_fact_size\n", N, B_2n_fact_size); #endif #ifdef THROW throw std::invalid_argument("Bernoulli numbers out of bounds"); #endif N = B_2n_fact_size; } return S(s, a, N) + I(s, a, N) + T(s, a, N, N); } cdouble polylog(double s, cdouble a, int N) { /** @returns Polylogarithm function, \f$\textrm{Li}_s(a)\f$ @param s @param a @param N */ if (s > 1 && std::abs(a) <= 1) { cdouble term = a; cdouble sum = term; for (int i = 2; i <= N; i += 1) { const double x = (i - 1) / static_cast<double>(i); term *= a * gsl_pow_2(x) * sqrt(x); sum += term; } return sum; } const cdouble j(0., 1.); const cdouble factor = pow(0.5 * j * M_1_PI, 1. - s) * gsl_sf_gamma(1. - s); const cdouble arg = 0.5 * j * log(a) * M_1_PI; const cdouble zeta = - pow(j, 2. * s) * hurwitz_zeta(1. - s, arg, N) + hurwitz_zeta(1. - s, 1. - arg, N); return factor * zeta; } <commit_msg>use pow for pow(double, double)<commit_after>/** @file @brief Hurwitz zeta function and polylogarithm. For implemenation, see <a href="http://fredrikj.net/math/hurwitz_zeta.pdf"> Fredrik Johansson.</a> */ #include <zeta.h> #include <bernoulli.h> #include <gsl/gsl_sf.h> #include <complex> #include <stdexcept> cdouble S(double s, cdouble a, int N) { /** @returns \f$S\f$ part of zeta function @param s @param a @param N */ cdouble sum = 0.; for (int k = 0; k <= N - 1; k += 1) { sum += pow(a + static_cast<cdouble>(k), -s); } return sum; } cdouble I(double s, cdouble a, int N) { /** @returns \f$I\f$ part of zeta function @param s @param a @param N */ return pow(a + static_cast<cdouble>(N), 1. - s) / (s - 1.); } cdouble T(double s, cdouble a, int N, int M) { /** @returns \f$T\f$ part of zeta function @param s @param a @param N @param M */ const cdouble d = a + static_cast<cdouble>(N); const cdouble factor = pow(d, -s); if (M > B_2n_fact_size) { #ifdef DEBUG printf("M = %d > B_2n_fact_size = %d. Using M = B_2n_fact_size\n", M, B_2n_fact_size); #endif #ifdef THROW throw std::invalid_argument("Bernoulli numbers out of bounds"); #endif M = B_2n_fact_size; } cdouble sum = 0.; for (int k = 1; k <= M; k += 1) { sum += B_2n_fact[k] * gsl_sf_poch(s, 2. * k - 1.) / pow(d, 2 * k - 1); } return factor * (0.5 + sum); } cdouble hurwitz_zeta(double s, cdouble a, int N) { /** @returns Hurwitz zeta function, \f$\zeta_s(a)\f$ @param s @param a @param N */ if (N > B_2n_fact_size) { #ifdef DEBUG printf("N = %d > B_2n_fact_size = %d. Using N = B_2n_fact_size\n", N, B_2n_fact_size); #endif #ifdef THROW throw std::invalid_argument("Bernoulli numbers out of bounds"); #endif N = B_2n_fact_size; } return S(s, a, N) + I(s, a, N) + T(s, a, N, N); } cdouble polylog(double s, cdouble a, int N) { /** @returns Polylogarithm function, \f$\textrm{Li}_s(a)\f$ @param s @param a @param N */ if (s > 1 && std::abs(a) <= 1) { cdouble term = a; cdouble sum = term; for (int i = 2; i <= N; i += 1) { const double x = (i - 1) / static_cast<double>(i); term *= a * pow(x, 2.5); sum += term; } return sum; } const cdouble j(0., 1.); const cdouble factor = pow(0.5 * j * M_1_PI, 1. - s) * gsl_sf_gamma(1. - s); const cdouble arg = 0.5 * j * log(a) * M_1_PI; const cdouble zeta = - pow(j, 2. * s) * hurwitz_zeta(1. - s, arg, N) + hurwitz_zeta(1. - s, 1. - arg, N); return factor * zeta; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Christoph Schulz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "zxing.h" #include "image.h" #include "util.h" #include <zxing/LuminanceSource.h> #include <zxing/Binarizer.h> #include <zxing/BinaryBitmap.h> #include <zxing/common/HybridBinarizer.h> #include <zxing/common/HybridBinarizer.h> #include <zxing/Result.h> #include <zxing/ReaderException.h> #include <zxing/MultiFormatReader.h> #include <zxing/multi/GenericMultipleBarcodeReader.h> #include <sstream> using namespace v8; using namespace node; class PixSource : public zxing::LuminanceSource { public: PixSource(Pix* pix, bool take = false); ~PixSource(); int getWidth() const; int getHeight() const; unsigned char* getRow(int y, unsigned char* row); unsigned char* getMatrix(); bool isCropSupported() const; zxing::Ref<zxing::LuminanceSource> crop(int left, int top, int width, int height); bool isRotateSupported() const; zxing::Ref<zxing::LuminanceSource> rotateCounterClockwise(); int getStraightLine(unsigned char *line, int nLengthMax, int x1,int y1,int x2,int y2); private: PIX* pix_; }; PixSource::PixSource(Pix* pix, bool take) { if (take) { assert(pix->d == 8); pix_ = pix; } else { pix_ = pixConvertTo8(pix, 0); } } PixSource::~PixSource() { pixDestroy(&pix_); } int PixSource::getWidth() const { return pix_->w; } int PixSource::getHeight() const { return pix_->h; } unsigned char* PixSource::getRow(int y, unsigned char* row) { row = row ? row : new unsigned char[pix_->w]; if (static_cast<uint32_t>(y) < pix_->h) { uint32_t *line = pix_->data + (pix_->wpl * y); unsigned char *r = row; for (uint32_t x = 0; x < pix_->w; ++x) { *r = GET_DATA_BYTE(line, x); ++r; } } return row; } unsigned char* PixSource::getMatrix() { unsigned char* matrix = new unsigned char[pix_->w * pix_->h]; unsigned char* m = matrix; uint32_t *line = pix_->data; for (uint32_t y = 0; y < pix_->h; ++y) { for (uint32_t x = 0; x < pix_->w; ++x) { *m = GET_DATA_BYTE(line, x); ++m; } line += pix_->wpl; } return matrix; } bool PixSource::isRotateSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::rotateCounterClockwise() { // Rotate 90 degree counterclockwise. if (pix_->w != 0 && pix_->h != 0) { Pix *rotatedPix = pixRotate90(pix_, -1); return zxing::Ref<PixSource>(new PixSource(rotatedPix, true)); } else { return zxing::Ref<PixSource>(new PixSource(pix_)); } } bool PixSource::isCropSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::crop(int left, int top, int width, int height) { BOX *box = boxCreate(left, top, width, height); PIX *croppedPix = pixClipRectangle(pix_, box, 0); boxDestroy(&box); return zxing::Ref<PixSource>(new PixSource(croppedPix, true)); } //TODO: clean this code someday (more or less copied). int PixSource::getStraightLine(unsigned char *line, int nLengthMax, int x1,int y1,int x2,int y2) { int width = pix_->w; int height = pix_->h; int x,y,xDiff,yDiff,xDiffAbs,yDiffAbs,nMigr,dX,dY; int cnt; int nLength = nLengthMax; int nMigrGlob; if(x1 < 0 || x1 >= 0 + width || x2 < 0 || x2 >= 0 + width || y1 < 0 || y1 >= height || y2 < 0 || y2 >= 0 + height) return 0; x = x1; y = y1; cnt = 0; xDiff = x2 - x1; yDiff = y2 - y1; xDiffAbs = std::abs(xDiff); yDiffAbs = std::abs(yDiff); dX = dY = 1; if (xDiff < 0) dX = -1; if (yDiff < 0) dY = -1; nMigrGlob = nLength / 2; unsigned char* matrix = getMatrix(); // horizontal dimension greater than vertical? if (xDiffAbs > yDiffAbs) { nMigr = xDiffAbs / 2; // distributes regularly <nLength> points of the straight line to line[]: while(cnt < nLength) { while(cnt < nLength && nMigrGlob > 0) { line[cnt] = matrix[(0 + y) * width + 0 + x]; nMigrGlob -= xDiffAbs; cnt++; } while(nMigrGlob <= 0) { nMigrGlob += nLength; x += dX; nMigr -= yDiffAbs; if (nMigr < 0) { nMigr += xDiffAbs; y += dY; } } } } else { // vertical dimension greater than horizontal: nMigr = yDiffAbs / 2; while(cnt < nLength) { while(cnt < nLength && nMigrGlob > 0) { line[cnt] = matrix[(0 + y) * width + 0 + x]; nMigrGlob -= yDiffAbs; cnt++; } while(nMigrGlob <= 0) { nMigrGlob += nLength; y += dY; nMigr -= xDiffAbs; if (nMigr < 0) { nMigr += yDiffAbs; x += dX; } } } } // last point? if (cnt < nLengthMax) { line[cnt] = matrix[(0 + y) * width + 0 + x]; cnt++; } delete matrix; return cnt; } void ZXing::Init(Handle<Object> target) { Local<FunctionTemplate> constructor_template = FunctionTemplate::New(New); constructor_template->SetClassName(String::NewSymbol("ZXing")); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = constructor_template->PrototypeTemplate(); proto->SetAccessor(String::NewSymbol("image"), GetImage, SetImage); proto->SetAccessor(String::NewSymbol("tryHarder"), GetTryHarder, SetTryHarder); proto->Set(String::NewSymbol("findCode"), FunctionTemplate::New(FindCode)->GetFunction()); proto->Set(String::NewSymbol("findCodes"), FunctionTemplate::New(FindCodes)->GetFunction()); target->Set(String::NewSymbol("ZXing"), Persistent<Function>::New(constructor_template->GetFunction())); } Handle<Value> ZXing::New(const Arguments &args) { HandleScope scope; Local<Object> image; if (args.Length() == 1 && Image::HasInstance(args[0])) { image = args[0]->ToObject(); } else if (args.Length() != 0) { return THROW(TypeError, "cannot convert argument list to " "() or " "(image: Image)"); } ZXing* obj = new ZXing(); if (!image.IsEmpty()) { obj->image_ = Persistent<Object>::New(image->ToObject()); } obj->Wrap(args.This()); return args.This(); } Handle<Value> ZXing::GetImage(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return obj->image_; } void ZXing::SetImage(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (Image::HasInstance(value)) { if (!obj->image_.IsEmpty()) { obj->image_.Dispose(); obj->image_.Clear(); } obj->image_ = Persistent<Object>::New(value->ToObject()); } else { THROW(TypeError, "value must be of type Image"); } } Handle<Value> ZXing::GetTryHarder(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return Boolean::New(obj->hints_.getTryHarder()); } void ZXing::SetTryHarder(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (value->IsBoolean()) { obj->hints_.setTryHarder(value->BooleanValue()); } else { THROW(TypeError, "value must be of type bool"); } } Handle<Value> ZXing::FindCode(const Arguments &args) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(args.This()); try { zxing::Ref<PixSource> source(new PixSource(Image::Pixels(obj->image_))); zxing::Ref<zxing::Binarizer> binarizer(new zxing::HybridBinarizer(source)); zxing::Ref<zxing::BinaryBitmap> binary(new zxing::BinaryBitmap(binarizer)); zxing::Ref<zxing::Result> result(obj->reader_->decodeWithState(binary)); Local<Object> object = Object::New(); object->Set(String::NewSymbol("type"), String::New(zxing::barcodeFormatNames[result->getBarcodeFormat()])); object->Set(String::NewSymbol("data"), String::New(result->getText()->getText().c_str())); Local<Array> points = Array::New(); for (size_t i = 0; i < result->getResultPoints().size(); ++i) { Local<Object> point = Object::New(); point->Set(String::NewSymbol("x"), Number::New(result->getResultPoints()[i]->getX())); point->Set(String::NewSymbol("y"), Number::New(result->getResultPoints()[i]->getY())); points->Set(i, point); } object->Set(String::NewSymbol("points"), points); return scope.Close(object); } catch (const zxing::ReaderException& e) { if (strcmp(e.what(), "No code detected") == 0) { return scope.Close(Null()); } else { return THROW(Error, e.what()); } } catch (const zxing::IllegalArgumentException& e) { return THROW(Error, e.what()); } catch (const zxing::Exception& e) { return THROW(Error, e.what()); } catch (const std::exception& e) { return THROW(Error, e.what()); } catch (...) { return THROW(Error, "Uncaught exception"); } } Handle<Value> ZXing::FindCodes(const Arguments &args) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(args.This()); try { zxing::Ref<PixSource> source(new PixSource(Image::Pixels(obj->image_))); zxing::Ref<zxing::Binarizer> binarizer(new zxing::HybridBinarizer(source)); zxing::Ref<zxing::BinaryBitmap> binary(new zxing::BinaryBitmap(binarizer)); std::vector< zxing::Ref<zxing::Result> > result = obj->multiReader_->decodeMultiple(binary, obj->hints_); Local<Array> objects = Array::New(); for (size_t i = 0; i < result.size(); ++i) { Local<Object> object = Object::New(); object->Set(String::NewSymbol("type"), String::New(zxing::barcodeFormatNames[result[i]->getBarcodeFormat()])); object->Set(String::NewSymbol("data"), String::New(result[i]->getText()->getText().c_str())); Local<Array> points = Array::New(); for (size_t j = 0; j < result[i]->getResultPoints().size(); ++j) { Local<Object> point = Object::New(); point->Set(String::NewSymbol("x"), Number::New(result[i]->getResultPoints()[j]->getX())); point->Set(String::NewSymbol("y"), Number::New(result[i]->getResultPoints()[j]->getY())); points->Set(j, point); } object->Set(String::NewSymbol("points"), points); objects->Set(i, object); } return scope.Close(objects); } catch (const zxing::ReaderException& e) { if (strcmp(e.what(), "No code detected") == 0) { return scope.Close(Array::New()); } else { return THROW(Error, e.what()); } } catch (const zxing::IllegalArgumentException& e) { return THROW(Error, e.what()); } catch (const zxing::Exception& e) { return THROW(Error, e.what()); } catch (const std::exception& e) { return THROW(Error, e.what()); } catch (...) { return THROW(Error, "Uncaught exception"); } } ZXing::ZXing() : hints_(zxing::DecodeHints::DEFAULT_HINT), reader_(new zxing::MultiFormatReader), multiReader_(new zxing::multi::GenericMultipleBarcodeReader(*reader_)) { //TODO: implement getters/setters for hints //hints_.addFormat(...) reader_->setHints(hints_); } ZXing::~ZXing() { } <commit_msg>Fix gcc compile error<commit_after>/* * Copyright (c) 2012 Christoph Schulz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "zxing.h" #include "image.h" #include "util.h" #include <zxing/LuminanceSource.h> #include <zxing/Binarizer.h> #include <zxing/BinaryBitmap.h> #include <zxing/common/HybridBinarizer.h> #include <zxing/common/HybridBinarizer.h> #include <zxing/Result.h> #include <zxing/ReaderException.h> #include <zxing/MultiFormatReader.h> #include <zxing/multi/GenericMultipleBarcodeReader.h> #include <cstdlib> #include <sstream> using namespace v8; using namespace node; class PixSource : public zxing::LuminanceSource { public: PixSource(Pix* pix, bool take = false); ~PixSource(); int getWidth() const; int getHeight() const; unsigned char* getRow(int y, unsigned char* row); unsigned char* getMatrix(); bool isCropSupported() const; zxing::Ref<zxing::LuminanceSource> crop(int left, int top, int width, int height); bool isRotateSupported() const; zxing::Ref<zxing::LuminanceSource> rotateCounterClockwise(); int getStraightLine(unsigned char *line, int nLengthMax, int x1,int y1,int x2,int y2); private: PIX* pix_; }; PixSource::PixSource(Pix* pix, bool take) { if (take) { assert(pix->d == 8); pix_ = pix; } else { pix_ = pixConvertTo8(pix, 0); } } PixSource::~PixSource() { pixDestroy(&pix_); } int PixSource::getWidth() const { return pix_->w; } int PixSource::getHeight() const { return pix_->h; } unsigned char* PixSource::getRow(int y, unsigned char* row) { row = row ? row : new unsigned char[pix_->w]; if (static_cast<uint32_t>(y) < pix_->h) { uint32_t *line = pix_->data + (pix_->wpl * y); unsigned char *r = row; for (uint32_t x = 0; x < pix_->w; ++x) { *r = GET_DATA_BYTE(line, x); ++r; } } return row; } unsigned char* PixSource::getMatrix() { unsigned char* matrix = new unsigned char[pix_->w * pix_->h]; unsigned char* m = matrix; uint32_t *line = pix_->data; for (uint32_t y = 0; y < pix_->h; ++y) { for (uint32_t x = 0; x < pix_->w; ++x) { *m = GET_DATA_BYTE(line, x); ++m; } line += pix_->wpl; } return matrix; } bool PixSource::isRotateSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::rotateCounterClockwise() { // Rotate 90 degree counterclockwise. if (pix_->w != 0 && pix_->h != 0) { Pix *rotatedPix = pixRotate90(pix_, -1); return zxing::Ref<PixSource>(new PixSource(rotatedPix, true)); } else { return zxing::Ref<PixSource>(new PixSource(pix_)); } } bool PixSource::isCropSupported() const { return true; } zxing::Ref<zxing::LuminanceSource> PixSource::crop(int left, int top, int width, int height) { BOX *box = boxCreate(left, top, width, height); PIX *croppedPix = pixClipRectangle(pix_, box, 0); boxDestroy(&box); return zxing::Ref<PixSource>(new PixSource(croppedPix, true)); } //TODO: clean this code someday (more or less copied). int PixSource::getStraightLine(unsigned char *line, int nLengthMax, int x1,int y1,int x2,int y2) { int width = pix_->w; int height = pix_->h; int x,y,xDiff,yDiff,xDiffAbs,yDiffAbs,nMigr,dX,dY; int cnt; int nLength = nLengthMax; int nMigrGlob; if(x1 < 0 || x1 >= 0 + width || x2 < 0 || x2 >= 0 + width || y1 < 0 || y1 >= height || y2 < 0 || y2 >= 0 + height) return 0; x = x1; y = y1; cnt = 0; xDiff = x2 - x1; yDiff = y2 - y1; xDiffAbs = std::abs(xDiff); yDiffAbs = std::abs(yDiff); dX = dY = 1; if (xDiff < 0) dX = -1; if (yDiff < 0) dY = -1; nMigrGlob = nLength / 2; unsigned char* matrix = getMatrix(); // horizontal dimension greater than vertical? if (xDiffAbs > yDiffAbs) { nMigr = xDiffAbs / 2; // distributes regularly <nLength> points of the straight line to line[]: while(cnt < nLength) { while(cnt < nLength && nMigrGlob > 0) { line[cnt] = matrix[(0 + y) * width + 0 + x]; nMigrGlob -= xDiffAbs; cnt++; } while(nMigrGlob <= 0) { nMigrGlob += nLength; x += dX; nMigr -= yDiffAbs; if (nMigr < 0) { nMigr += xDiffAbs; y += dY; } } } } else { // vertical dimension greater than horizontal: nMigr = yDiffAbs / 2; while(cnt < nLength) { while(cnt < nLength && nMigrGlob > 0) { line[cnt] = matrix[(0 + y) * width + 0 + x]; nMigrGlob -= yDiffAbs; cnt++; } while(nMigrGlob <= 0) { nMigrGlob += nLength; y += dY; nMigr -= xDiffAbs; if (nMigr < 0) { nMigr += yDiffAbs; x += dX; } } } } // last point? if (cnt < nLengthMax) { line[cnt] = matrix[(0 + y) * width + 0 + x]; cnt++; } delete matrix; return cnt; } void ZXing::Init(Handle<Object> target) { Local<FunctionTemplate> constructor_template = FunctionTemplate::New(New); constructor_template->SetClassName(String::NewSymbol("ZXing")); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = constructor_template->PrototypeTemplate(); proto->SetAccessor(String::NewSymbol("image"), GetImage, SetImage); proto->SetAccessor(String::NewSymbol("tryHarder"), GetTryHarder, SetTryHarder); proto->Set(String::NewSymbol("findCode"), FunctionTemplate::New(FindCode)->GetFunction()); proto->Set(String::NewSymbol("findCodes"), FunctionTemplate::New(FindCodes)->GetFunction()); target->Set(String::NewSymbol("ZXing"), Persistent<Function>::New(constructor_template->GetFunction())); } Handle<Value> ZXing::New(const Arguments &args) { HandleScope scope; Local<Object> image; if (args.Length() == 1 && Image::HasInstance(args[0])) { image = args[0]->ToObject(); } else if (args.Length() != 0) { return THROW(TypeError, "cannot convert argument list to " "() or " "(image: Image)"); } ZXing* obj = new ZXing(); if (!image.IsEmpty()) { obj->image_ = Persistent<Object>::New(image->ToObject()); } obj->Wrap(args.This()); return args.This(); } Handle<Value> ZXing::GetImage(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return obj->image_; } void ZXing::SetImage(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (Image::HasInstance(value)) { if (!obj->image_.IsEmpty()) { obj->image_.Dispose(); obj->image_.Clear(); } obj->image_ = Persistent<Object>::New(value->ToObject()); } else { THROW(TypeError, "value must be of type Image"); } } Handle<Value> ZXing::GetTryHarder(Local<String> prop, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); return Boolean::New(obj->hints_.getTryHarder()); } void ZXing::SetTryHarder(Local<String> prop, Local<Value> value, const AccessorInfo &info) { ZXing* obj = ObjectWrap::Unwrap<ZXing>(info.This()); if (value->IsBoolean()) { obj->hints_.setTryHarder(value->BooleanValue()); } else { THROW(TypeError, "value must be of type bool"); } } Handle<Value> ZXing::FindCode(const Arguments &args) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(args.This()); try { zxing::Ref<PixSource> source(new PixSource(Image::Pixels(obj->image_))); zxing::Ref<zxing::Binarizer> binarizer(new zxing::HybridBinarizer(source)); zxing::Ref<zxing::BinaryBitmap> binary(new zxing::BinaryBitmap(binarizer)); zxing::Ref<zxing::Result> result(obj->reader_->decodeWithState(binary)); Local<Object> object = Object::New(); object->Set(String::NewSymbol("type"), String::New(zxing::barcodeFormatNames[result->getBarcodeFormat()])); object->Set(String::NewSymbol("data"), String::New(result->getText()->getText().c_str())); Local<Array> points = Array::New(); for (size_t i = 0; i < result->getResultPoints().size(); ++i) { Local<Object> point = Object::New(); point->Set(String::NewSymbol("x"), Number::New(result->getResultPoints()[i]->getX())); point->Set(String::NewSymbol("y"), Number::New(result->getResultPoints()[i]->getY())); points->Set(i, point); } object->Set(String::NewSymbol("points"), points); return scope.Close(object); } catch (const zxing::ReaderException& e) { if (strcmp(e.what(), "No code detected") == 0) { return scope.Close(Null()); } else { return THROW(Error, e.what()); } } catch (const zxing::IllegalArgumentException& e) { return THROW(Error, e.what()); } catch (const zxing::Exception& e) { return THROW(Error, e.what()); } catch (const std::exception& e) { return THROW(Error, e.what()); } catch (...) { return THROW(Error, "Uncaught exception"); } } Handle<Value> ZXing::FindCodes(const Arguments &args) { HandleScope scope; ZXing* obj = ObjectWrap::Unwrap<ZXing>(args.This()); try { zxing::Ref<PixSource> source(new PixSource(Image::Pixels(obj->image_))); zxing::Ref<zxing::Binarizer> binarizer(new zxing::HybridBinarizer(source)); zxing::Ref<zxing::BinaryBitmap> binary(new zxing::BinaryBitmap(binarizer)); std::vector< zxing::Ref<zxing::Result> > result = obj->multiReader_->decodeMultiple(binary, obj->hints_); Local<Array> objects = Array::New(); for (size_t i = 0; i < result.size(); ++i) { Local<Object> object = Object::New(); object->Set(String::NewSymbol("type"), String::New(zxing::barcodeFormatNames[result[i]->getBarcodeFormat()])); object->Set(String::NewSymbol("data"), String::New(result[i]->getText()->getText().c_str())); Local<Array> points = Array::New(); for (size_t j = 0; j < result[i]->getResultPoints().size(); ++j) { Local<Object> point = Object::New(); point->Set(String::NewSymbol("x"), Number::New(result[i]->getResultPoints()[j]->getX())); point->Set(String::NewSymbol("y"), Number::New(result[i]->getResultPoints()[j]->getY())); points->Set(j, point); } object->Set(String::NewSymbol("points"), points); objects->Set(i, object); } return scope.Close(objects); } catch (const zxing::ReaderException& e) { if (strcmp(e.what(), "No code detected") == 0) { return scope.Close(Array::New()); } else { return THROW(Error, e.what()); } } catch (const zxing::IllegalArgumentException& e) { return THROW(Error, e.what()); } catch (const zxing::Exception& e) { return THROW(Error, e.what()); } catch (const std::exception& e) { return THROW(Error, e.what()); } catch (...) { return THROW(Error, "Uncaught exception"); } } ZXing::ZXing() : hints_(zxing::DecodeHints::DEFAULT_HINT), reader_(new zxing::MultiFormatReader), multiReader_(new zxing::multi::GenericMultipleBarcodeReader(*reader_)) { //TODO: implement getters/setters for hints //hints_.addFormat(...) reader_->setHints(hints_); } ZXing::~ZXing() { } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ #include <random> #include <memory> #include <cstdio> #include <iostream> #include <climits> #include <stdexcept> #include <cmath> #include "error.h" #include "bpmf.h" #include "io.h" static const bool measure_perf = false; std::ostream *Sys::os; std::ostream *Sys::dbgs; int Sys::procid = -1; int Sys::nprocs = -1; int Sys::nsims; int Sys::burnin; int Sys::update_freq; double Sys::alpha = 2.0; std::string Sys::odirname = ""; bool Sys::permute = true; bool Sys::verbose = false; // verifies that A has the same non-zero structure as B void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B) { assert(A.cols() == B.cols()); assert(A.rows() == B.rows()); for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros()); } // // Does predictions for prediction matrix T // Computes RMSE (Root Means Square Error) // void Sys::predict(Sys& other, bool all) { int n = (iter < burnin) ? 0 : (iter - burnin); double se(0.0); // squared err double se_avg(0.0); // squared avg err int nump = 0; // number of predictions int lo = from(); int hi = to(); if (all) { #ifdef BPMF_REDUCE Sys::cout() << "WARNING: predict all items in test set not available in BPMF_REDUCE mode" << std::endl; #else lo = 0; hi = num(); #endif } #pragma omp parallel for reduction(+:se,se_avg,nump) for(int k = lo; k<hi; k++) { for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it) { #ifdef BPMF_REDUCE if (it.row() >= other.to() || it.row() < other.from()) continue; #endif auto m = items().col(it.col()); auto u = other.items().col(it.row()); assert(m.norm() > 0.0); assert(u.norm() > 0.0); const double pred = m.dot(u) + mean_rating; se += sqr(it.value() - pred); // update average prediction double &avg = Pavg.coeffRef(it.row(), it.col()); double delta = pred - avg; avg = (n == 0) ? pred : (avg + delta/n); double &m2 = Pm2.coeffRef(it.row(), it.col()); m2 = (n == 0) ? 0 : m2 + delta * (pred - avg); se_avg += sqr(it.value() - avg); nump++; } } rmse = sqrt( se / num_predict ); rmse_avg = sqrt( se_avg / num_predict ); num_predict = nump; } // // Prints sampling progress // void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) { char buf[1024]; std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling"; sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n", Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6); Sys::cout() << buf; } // // Constructor with that reads MTX files // Sys::Sys(std::string name, std::string fname, std::string probename) : name(name), iter(-1), assigned(false), dom(nprocs+1) { read_matrix(fname, M); read_matrix(probename, T); auto rows = std::max(M.rows(), T.rows()); auto cols = std::max(M.cols(), T.cols()); M.conservativeResize(rows,cols); T.conservativeResize(rows,cols); Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); assert(Sys::nprocs <= (int)Sys::max_procs); } // // Constructs Sys as transpose of existing Sys // Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) { M = Mt.transpose(); Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); } Sys::~Sys() { if (measure_perf) { Sys::cout() << " --------------------\n"; Sys::cout() << name << ": sampling times on " << procid << "\n"; for(int i = from(); i<to(); ++i) { Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n"; } Sys::cout() << " --------------------\n\n"; } } bool Sys::has_prop_posterior() const { return propMu.nonZeros() > 0; } void Sys::add_prop_posterior(std::string fnames) { if (fnames.empty()) return; std::size_t pos = fnames.find_first_of(","); std::string mu_name = fnames.substr(0, pos); std::string lambda_name = fnames.substr(pos+1); read_matrix(mu_name, propMu); read_matrix(lambda_name, propLambda); assert(propMu.cols() == num()); assert(propLambda.cols() == num()); assert(propMu.rows() == num_latent); assert(propLambda.rows() == num_latent * num_latent); } // // Intializes internal Matrices and Vectors // void Sys::init() { //-- M assert(M.rows() > 0 && M.cols() > 0); mean_rating = M.sum() / M.nonZeros(); items().setZero(); sum.setZero(); cov.setZero(); norm = 0.; col_permutation.setIdentity(num()); #ifdef BPMF_REDUCE precMu = MatrixNXd::Zero(num_latent, num()); precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); #endif if (Sys::odirname.size()) { aggrMu = Eigen::MatrixXd::Zero(num_latent, num()); aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); } int count_larger_bp1 = 0; int count_larger_bp2 = 0; int count_sum = 0; for(int k = 0; k<M.cols(); k++) { int count = M.col(k).nonZeros(); count_sum += count; if (count > breakpoint1) count_larger_bp1++; if (count > breakpoint2) count_larger_bp2++; } Sys::cout() << "mean rating: " << mean_rating << std::endl; Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl; Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl; Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl; Sys::cout() << "num " << name << ": " << num() << std::endl; if (has_prop_posterior()) { Sys::cout() << "with propagated posterior" << std::endl; } if (measure_perf) sample_time.resize(num(), .0); } class PrecomputedLLT : public Eigen::LLT<MatrixNNd> { public: void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; } }; void Sys::preComputeMuLambda(const Sys &other) { BPMF_COUNTER("preComputeMuLambda"); #pragma omp parallel for schedule(guided) for (int i = 0; i < num(); ++i) { VectorNd mu = VectorNd::Zero(); MatrixNNd Lambda = MatrixNNd::Zero(); computeMuLambda(i, other, mu, Lambda, true); precLambdaMatrix(i) = Lambda; precMu.col(i) = mu; } } void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM, bool local_only) const { BPMF_COUNTER("computeMuLambda"); for (SparseMatrixD::InnerIterator it(M, idx); it; ++it) { if (local_only && (it.row() < other.from() || it.row() >= other.to())) continue; auto col = other.items().col(it.row()); MM.triangularView<Eigen::Upper>() += col * col.transpose(); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } } // // Update ONE movie or one user // VectorNd Sys::sample(long idx, Sys &other) { auto start = tick(); rng.set_pos((idx+1) * num_latent * (iter+1)); Sys::dbg() << "-- original start name: " << name << " iter: " << iter << " idx: " << idx << ": " << rng.counter << std::endl; VectorNd hp_mu; MatrixNNd hp_LambdaF; MatrixNNd hp_LambdaL; if (has_prop_posterior()) { hp_mu = propMu.col(idx); hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data()); hp_LambdaL = hp_LambdaF.llt().matrixL(); } else { hp_mu = hp.mu; hp_LambdaF = hp.LambdaF; hp_LambdaL = hp.LambdaL; } VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper MatrixNNd MM(MatrixNNd::Zero()); PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14) #ifdef BPMF_REDUCE rr += precMu.col(idx); MM += precLambdaMatrix(idx); #else computeMuLambda(idx, other, rr, MM, false); #endif // copy upper -> lower part, matrix is symmetric. MM.triangularView<Eigen::Lower>() = MM.transpose(); chol.compute(hp_LambdaF + alpha * MM); if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed"); // now we should calculate formula (14) from the paper // u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) = // = mu_i with * + s * [U]^-1, // where // s is a random vector with N(0, I), // mu_i with * is a vector num_latent x 1, // mu_i with * = [lambda_i with *]^-1 * rr, // lambda_i with * = L * U // Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like: chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector rr += nrandn(num_latent); // rr=s+(L\rr), we store result again in rr vector chol.matrixU().solveInPlace(rr); // u_i=U\rr items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix) auto stop = tick(); register_time(idx, 1e6 * (stop - start)); //Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl; assert(rr.norm() > .0); SHOW(rr.transpose()); Sys::dbg() << "-- original done name: " << name << " iter: " << iter << " idx: " << idx << ": " << rng.counter << std::endl; return rr; } // // update ALL movies / users in parallel // void Sys::sample(Sys &other) { iter++; thread_vector<VectorNd> sums(VectorNd::Zero()); // sum thread_vector<double> norms(0.0); // squared norm thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod rng.set_pos(iter); // make this consistent sample_hp(); SHOW(hp.mu.transpose()); #ifdef BPMF_REDUCE other.precMu.setZero(); other.precLambda.setZero(); #endif #pragma omp parallel for schedule(guided) for (int i = from(); i < to(); ++i) { #pragma omp task { auto r = sample(i, other); MatrixNNd cov = (r * r.transpose()); prods.local() += cov; sums.local() += r; norms.local() += r.squaredNorm(); if (iter >= burnin && Sys::odirname.size()) { aggrMu.col(i) += r; aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent); } send_item(i); } } #pragma omp taskwait #ifdef BPMF_REDUCE other.preComputeMuLambda(*this); #endif VectorNd sum = sums.combine(); MatrixNNd prod = prods.combine(); norm = norms.combine(); const int N = num(); cov = (prod - (sum * sum.transpose() / N)) / (N-1); } void Sys::register_time(int i, double t) { if (measure_perf) sample_time.at(i) += t; }<commit_msg>WIP: only diagonal - no covariance<commit_after>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ #include <random> #include <memory> #include <cstdio> #include <iostream> #include <climits> #include <stdexcept> #include <cmath> #include "error.h" #include "bpmf.h" #include "io.h" static const bool measure_perf = false; std::ostream *Sys::os; std::ostream *Sys::dbgs; int Sys::procid = -1; int Sys::nprocs = -1; int Sys::nsims; int Sys::burnin; int Sys::update_freq; double Sys::alpha = 2.0; std::string Sys::odirname = ""; bool Sys::permute = true; bool Sys::verbose = false; // verifies that A has the same non-zero structure as B void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B) { assert(A.cols() == B.cols()); assert(A.rows() == B.rows()); for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros()); } // // Does predictions for prediction matrix T // Computes RMSE (Root Means Square Error) // void Sys::predict(Sys& other, bool all) { int n = (iter < burnin) ? 0 : (iter - burnin); double se(0.0); // squared err double se_avg(0.0); // squared avg err int nump = 0; // number of predictions int lo = from(); int hi = to(); if (all) { #ifdef BPMF_REDUCE Sys::cout() << "WARNING: predict all items in test set not available in BPMF_REDUCE mode" << std::endl; #else lo = 0; hi = num(); #endif } #pragma omp parallel for reduction(+:se,se_avg,nump) for(int k = lo; k<hi; k++) { for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it) { #ifdef BPMF_REDUCE if (it.row() >= other.to() || it.row() < other.from()) continue; #endif auto m = items().col(it.col()); auto u = other.items().col(it.row()); assert(m.norm() > 0.0); assert(u.norm() > 0.0); const double pred = m.dot(u) + mean_rating; se += sqr(it.value() - pred); // update average prediction double &avg = Pavg.coeffRef(it.row(), it.col()); double delta = pred - avg; avg = (n == 0) ? pred : (avg + delta/n); double &m2 = Pm2.coeffRef(it.row(), it.col()); m2 = (n == 0) ? 0 : m2 + delta * (pred - avg); se_avg += sqr(it.value() - avg); nump++; } } rmse = sqrt( se / num_predict ); rmse_avg = sqrt( se_avg / num_predict ); num_predict = nump; } // // Prints sampling progress // void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) { char buf[1024]; std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling"; sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n", Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6); Sys::cout() << buf; } // // Constructor with that reads MTX files // Sys::Sys(std::string name, std::string fname, std::string probename) : name(name), iter(-1), assigned(false), dom(nprocs+1) { read_matrix(fname, M); read_matrix(probename, T); auto rows = std::max(M.rows(), T.rows()); auto cols = std::max(M.cols(), T.cols()); M.conservativeResize(rows,cols); T.conservativeResize(rows,cols); Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); assert(Sys::nprocs <= (int)Sys::max_procs); } // // Constructs Sys as transpose of existing Sys // Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) { M = Mt.transpose(); Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); } Sys::~Sys() { if (measure_perf) { Sys::cout() << " --------------------\n"; Sys::cout() << name << ": sampling times on " << procid << "\n"; for(int i = from(); i<to(); ++i) { Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n"; } Sys::cout() << " --------------------\n\n"; } } bool Sys::has_prop_posterior() const { return propMu.nonZeros() > 0; } void Sys::add_prop_posterior(std::string fnames) { if (fnames.empty()) return; std::size_t pos = fnames.find_first_of(","); std::string mu_name = fnames.substr(0, pos); std::string lambda_name = fnames.substr(pos+1); read_matrix(mu_name, propMu); read_matrix(lambda_name, propLambda); assert(propMu.cols() == num()); assert(propLambda.cols() == num()); assert(propMu.rows() == num_latent); assert(propLambda.rows() == num_latent * num_latent); } // // Intializes internal Matrices and Vectors // void Sys::init() { //-- M assert(M.rows() > 0 && M.cols() > 0); mean_rating = M.sum() / M.nonZeros(); items().setZero(); sum.setZero(); cov.setZero(); norm = 0.; col_permutation.setIdentity(num()); #ifdef BPMF_REDUCE precMu = MatrixNXd::Zero(num_latent, num()); precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); #endif if (Sys::odirname.size()) { aggrMu = Eigen::MatrixXd::Zero(num_latent, num()); aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); } int count_larger_bp1 = 0; int count_larger_bp2 = 0; int count_sum = 0; for(int k = 0; k<M.cols(); k++) { int count = M.col(k).nonZeros(); count_sum += count; if (count > breakpoint1) count_larger_bp1++; if (count > breakpoint2) count_larger_bp2++; } Sys::cout() << "mean rating: " << mean_rating << std::endl; Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl; Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl; Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl; Sys::cout() << "num " << name << ": " << num() << std::endl; if (has_prop_posterior()) { Sys::cout() << "with propagated posterior" << std::endl; } if (measure_perf) sample_time.resize(num(), .0); } class PrecomputedLLT : public Eigen::LLT<MatrixNNd> { public: void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; } }; void Sys::preComputeMuLambda(const Sys &other) { BPMF_COUNTER("preComputeMuLambda"); #pragma omp parallel for schedule(guided) for (int i = 0; i < num(); ++i) { VectorNd mu = VectorNd::Zero(); MatrixNNd Lambda = MatrixNNd::Zero(); computeMuLambda(i, other, mu, Lambda, true); precLambdaMatrix(i) = Lambda; precMu.col(i) = mu; } } void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM, bool local_only) const { BPMF_COUNTER("computeMuLambda"); for (SparseMatrixD::InnerIterator it(M, idx); it; ++it) { if (local_only && (it.row() < other.from() || it.row() >= other.to())) continue; auto col = other.items().col(it.row()); MM.triangularView<Eigen::Upper>() += col * col.transpose(); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } } // // Update ONE movie or one user // VectorNd Sys::sample(long idx, Sys &other) { auto start = tick(); rng.set_pos((idx+1) * num_latent * (iter+1)); Sys::dbg() << "-- original start name: " << name << " iter: " << iter << " idx: " << idx << ": " << rng.counter << std::endl; VectorNd hp_mu; MatrixNNd hp_LambdaF; MatrixNNd hp_LambdaL; if (has_prop_posterior()) { hp_mu = propMu.col(idx); hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data()); hp_LambdaL = hp_LambdaF.llt().matrixL(); } else { hp_mu = hp.mu; hp_LambdaF = hp.LambdaF; hp_LambdaL = hp.LambdaL; } VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper MatrixNNd MM(MatrixNNd::Zero()); PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14) #ifdef BPMF_REDUCE rr += precMu.col(idx); MM += precLambdaMatrix(idx); #else computeMuLambda(idx, other, rr, MM, false); #endif #ifdef BPMF_NO_COVARIANCE // only keep diagonal -- MM = MM.diagonal().asDiagonal(); #else // copy upper -> lower part, matrix is symmetric. MM.triangularView<Eigen::Lower>() = MM.transpose(); #endif chol.compute(hp_LambdaF + alpha * MM); if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed"); // now we should calculate formula (14) from the paper // u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) = // = mu_i with * + s * [U]^-1, // where // s is a random vector with N(0, I), // mu_i with * is a vector num_latent x 1, // mu_i with * = [lambda_i with *]^-1 * rr, // lambda_i with * = L * U // Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like: chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector rr += nrandn(num_latent); // rr=s+(L\rr), we store result again in rr vector chol.matrixU().solveInPlace(rr); // u_i=U\rr items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix) auto stop = tick(); register_time(idx, 1e6 * (stop - start)); //Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl; assert(rr.norm() > .0); SHOW(rr.transpose()); Sys::dbg() << "-- original done name: " << name << " iter: " << iter << " idx: " << idx << ": " << rng.counter << std::endl; return rr; } // // update ALL movies / users in parallel // void Sys::sample(Sys &other) { iter++; thread_vector<VectorNd> sums(VectorNd::Zero()); // sum thread_vector<double> norms(0.0); // squared norm thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod rng.set_pos(iter); // make this consistent sample_hp(); SHOW(hp.mu.transpose()); #ifdef BPMF_REDUCE other.precMu.setZero(); other.precLambda.setZero(); #endif #pragma omp parallel for schedule(guided) for (int i = from(); i < to(); ++i) { #pragma omp task { auto r = sample(i, other); MatrixNNd cov = (r * r.transpose()); prods.local() += cov; sums.local() += r; norms.local() += r.squaredNorm(); if (iter >= burnin && Sys::odirname.size()) { aggrMu.col(i) += r; aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent); } send_item(i); } } #pragma omp taskwait #ifdef BPMF_REDUCE other.preComputeMuLambda(*this); #endif VectorNd sum = sums.combine(); MatrixNNd prod = prods.combine(); norm = norms.combine(); const int N = num(); cov = (prod - (sum * sum.transpose() / N)) / (N-1); } void Sys::register_time(int i, double t) { if (measure_perf) sample_time.at(i) += t; }<|endoftext|>
<commit_before>#pragma once #include <eosio/chain/block_state.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain/genesis_state.hpp> #include <chainbase/pinnable_mapped_file.hpp> #include <boost/signals2/signal.hpp> #include <eosio/chain/abi_serializer.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/snapshot.hpp> #include <eosio/chain/protocol_feature_manager.hpp> namespace chainbase { class database; } namespace boost { namespace asio { class thread_pool; }} namespace eosio { namespace chain { class authorization_manager; namespace resource_limits { class resource_limits_manager; }; struct controller_impl; using chainbase::database; using chainbase::pinnable_mapped_file; using boost::signals2::signal; class dynamic_global_property_object; class global_property_object; class permission_object; class account_object; using resource_limits::resource_limits_manager; using apply_handler = std::function<void(apply_context&)>; using unapplied_transactions_type = map<transaction_id_type, transaction_metadata_ptr, sha256_less>; class fork_database; enum class db_read_mode { SPECULATIVE, HEAD, READ_ONLY, IRREVERSIBLE }; enum class validation_mode { FULL, LIGHT }; class controller { public: struct config { flat_set<account_name> sender_bypass_whiteblacklist; flat_set<account_name> actor_whitelist; flat_set<account_name> actor_blacklist; flat_set<account_name> contract_whitelist; flat_set<account_name> contract_blacklist; flat_set< pair<account_name, action_name> > action_blacklist; flat_set<public_key_type> key_blacklist; path blocks_dir = chain::config::default_blocks_dir_name; path state_dir = chain::config::default_state_dir_name; uint64_t state_size = chain::config::default_state_size; uint64_t state_guard_size = chain::config::default_state_guard_size; uint64_t reversible_cache_size = chain::config::default_reversible_cache_size; uint64_t reversible_guard_size = chain::config::default_reversible_guard_size; uint32_t sig_cpu_bill_pct = chain::config::default_sig_cpu_bill_pct; uint16_t thread_pool_size = chain::config::default_controller_thread_pool_size; bool read_only = false; bool force_all_checks = false; bool disable_replay_opts = false; bool contracts_console = false; bool allow_ram_billing_in_notify = false; bool disable_all_subjective_mitigations = false; //< for testing purposes only genesis_state genesis; wasm_interface::vm_type wasm_runtime = chain::config::default_wasm_runtime; db_read_mode read_mode = db_read_mode::SPECULATIVE; validation_mode block_validation_mode = validation_mode::FULL; pinnable_mapped_file::map_mode db_map_mode = pinnable_mapped_file::map_mode::mapped; vector<string> db_hugepage_paths; flat_set<account_name> resource_greylist; flat_set<account_name> trusted_producers; uint32_t greylist_limit = chain::config::maximum_elastic_resource_multiplier; }; enum class block_status { irreversible = 0, ///< this block has already been applied before by this node and is considered irreversible validated = 1, ///< this is a complete block signed by a valid producer and has been previously applied by this node and therefore validated but it is not yet irreversible complete = 2, ///< this is a complete block signed by a valid producer but is not yet irreversible nor has it yet been applied by this node incomplete = 3, ///< this is an incomplete block (either being produced by a producer or speculatively produced by a node) }; explicit controller( const config& cfg ); controller( const config& cfg, protocol_feature_set&& pfs ); ~controller(); void add_indices(); void startup( std::function<bool()> shutdown, const snapshot_reader_ptr& snapshot = nullptr ); void preactivate_feature( const digest_type& feature_digest ); vector<digest_type> get_preactivated_protocol_features()const; void validate_protocol_features( const vector<digest_type>& features_to_activate )const; /** * Starts a new pending block session upon which new transactions can * be pushed. * * Will only activate protocol features that have been pre-activated. */ void start_block( block_timestamp_type time = block_timestamp_type(), uint16_t confirm_block_count = 0 ); /** * Starts a new pending block session upon which new transactions can * be pushed. */ void start_block( block_timestamp_type time, uint16_t confirm_block_count, const vector<digest_type>& new_protocol_feature_activations ); void abort_block(); /** * These transactions were previously pushed by have since been unapplied, recalling push_transaction * with the transaction_metadata_ptr will remove them from the source of this data IFF it succeeds. * * The caller is responsible for calling drop_unapplied_transaction on a failing transaction that * they never intend to retry * * @return map of transactions which have been unapplied */ unapplied_transactions_type& get_unapplied_transactions(); /** * */ transaction_trace_ptr push_transaction( const transaction_metadata_ptr& trx, fc::time_point deadline, uint32_t billed_cpu_time_us = 0 ); /** * Attempt to execute a specific transaction in our deferred trx database * */ transaction_trace_ptr push_scheduled_transaction( const transaction_id_type& scheduled, fc::time_point deadline, uint32_t billed_cpu_time_us = 0 ); block_state_ptr finalize_block( const std::function<signature_type( const digest_type& )>& signer_callback ); void sign_block( const std::function<signature_type( const digest_type& )>& signer_callback ); void commit_block(); void pop_block(); std::future<block_state_ptr> create_block_state_future( const signed_block_ptr& b ); void push_block( std::future<block_state_ptr>& block_state_future ); boost::asio::io_context& get_thread_pool(); const chainbase::database& db()const; const fork_database& fork_db()const; const account_object& get_account( account_name n )const; const global_property_object& get_global_properties()const; const dynamic_global_property_object& get_dynamic_global_properties()const; const resource_limits_manager& get_resource_limits_manager()const; resource_limits_manager& get_mutable_resource_limits_manager(); const authorization_manager& get_authorization_manager()const; authorization_manager& get_mutable_authorization_manager(); const protocol_feature_manager& get_protocol_feature_manager()const; const flat_set<account_name>& get_actor_whitelist() const; const flat_set<account_name>& get_actor_blacklist() const; const flat_set<account_name>& get_contract_whitelist() const; const flat_set<account_name>& get_contract_blacklist() const; const flat_set< pair<account_name, action_name> >& get_action_blacklist() const; const flat_set<public_key_type>& get_key_blacklist() const; void set_actor_whitelist( const flat_set<account_name>& ); void set_actor_blacklist( const flat_set<account_name>& ); void set_contract_whitelist( const flat_set<account_name>& ); void set_contract_blacklist( const flat_set<account_name>& ); void set_action_blacklist( const flat_set< pair<account_name, action_name> >& ); void set_key_blacklist( const flat_set<public_key_type>& ); uint32_t head_block_num()const; time_point head_block_time()const; block_id_type head_block_id()const; account_name head_block_producer()const; const block_header& head_block_header()const; block_state_ptr head_block_state()const; uint32_t fork_db_head_block_num()const; block_id_type fork_db_head_block_id()const; time_point fork_db_head_block_time()const; account_name fork_db_head_block_producer()const; uint32_t fork_db_pending_head_block_num()const; block_id_type fork_db_pending_head_block_id()const; time_point fork_db_pending_head_block_time()const; account_name fork_db_pending_head_block_producer()const; time_point pending_block_time()const; account_name pending_block_producer()const; public_key_type pending_block_signing_key()const; optional<block_id_type> pending_producer_block_id()const; const vector<transaction_receipt>& get_pending_trx_receipts()const; const producer_schedule_type& active_producers()const; const producer_schedule_type& pending_producers()const; optional<producer_schedule_type> proposed_producers()const; uint32_t last_irreversible_block_num() const; block_id_type last_irreversible_block_id() const; signed_block_ptr fetch_block_by_number( uint32_t block_num )const; signed_block_ptr fetch_block_by_id( block_id_type id )const; block_state_ptr fetch_block_state_by_number( uint32_t block_num )const; block_state_ptr fetch_block_state_by_id( block_id_type id )const; block_id_type get_block_id_for_num( uint32_t block_num )const; sha256 calculate_integrity_hash()const; void write_snapshot( const snapshot_writer_ptr& snapshot )const; bool sender_avoids_whitelist_blacklist_enforcement( account_name sender )const; void check_actor_list( const flat_set<account_name>& actors )const; void check_contract_list( account_name code )const; void check_action_list( account_name code, action_name action )const; void check_key_list( const public_key_type& key )const; bool is_building_block()const; bool is_producing_block()const; bool is_ram_billing_in_notify_allowed()const; void add_resource_greylist(const account_name &name); void remove_resource_greylist(const account_name &name); bool is_resource_greylisted(const account_name &name) const; const flat_set<account_name> &get_resource_greylist() const; void validate_expiration( const transaction& t )const; void validate_tapos( const transaction& t )const; void validate_db_available_size() const; void validate_reversible_available_size() const; bool is_protocol_feature_activated( const digest_type& feature_digest )const; bool is_builtin_activated( builtin_protocol_feature_t f )const; bool is_known_unexpired_transaction( const transaction_id_type& id) const; int64_t set_proposed_producers( vector<producer_key> producers ); bool light_validation_allowed(bool replay_opts_disabled_by_policy) const; bool skip_auth_check()const; bool skip_db_sessions( )const; bool skip_db_sessions( block_status bs )const; bool skip_trx_checks()const; bool contracts_console()const; chain_id_type get_chain_id()const; db_read_mode get_read_mode()const; validation_mode get_validation_mode()const; void set_subjective_cpu_leeway(fc::microseconds leeway); void set_greylist_limit( uint32_t limit ); uint32_t get_greylist_limit()const; void add_to_ram_correction( account_name account, uint64_t ram_bytes ); bool all_subjective_mitigations_disabled()const; static fc::optional<uint64_t> convert_exception_to_error_code( const fc::exception& e ); signal<void(const signed_block_ptr&)> pre_accepted_block; signal<void(const block_state_ptr&)> accepted_block_header; signal<void(const block_state_ptr&)> accepted_block; signal<void(const block_state_ptr&)> irreversible_block; signal<void(const transaction_metadata_ptr&)> accepted_transaction; signal<void(std::tuple<const transaction_trace_ptr&, const signed_transaction&>)> applied_transaction; signal<void(const int&)> bad_alloc; /* signal<void()> pre_apply_block; signal<void()> post_apply_block; signal<void()> abort_apply_block; signal<void(const transaction_metadata_ptr&)> pre_apply_transaction; signal<void(const transaction_trace_ptr&)> post_apply_transaction; signal<void(const transaction_trace_ptr&)> pre_apply_action; signal<void(const transaction_trace_ptr&)> post_apply_action; */ const apply_handler* find_apply_handler( account_name contract, scope_name scope, action_name act )const; wasm_interface& get_wasm_interface(); optional<abi_serializer> get_abi_serializer( account_name n, const fc::microseconds& max_serialization_time )const { if( n.good() ) { try { const auto& a = get_account( n ); abi_def abi; if( abi_serializer::to_abi( a.abi, abi )) return abi_serializer( abi, max_serialization_time ); } FC_CAPTURE_AND_LOG((n)) } return optional<abi_serializer>(); } template<typename T> fc::variant to_variant_with_abi( const T& obj, const fc::microseconds& max_serialization_time ) { fc::variant pretty_output; abi_serializer::to_variant( obj, pretty_output, [&]( account_name n ){ return get_abi_serializer( n, max_serialization_time ); }, max_serialization_time); return pretty_output; } private: friend class apply_context; friend class transaction_context; chainbase::database& mutable_db()const; std::unique_ptr<controller_impl> my; }; } } /// eosio::chain FC_REFLECT( eosio::chain::controller::config, (actor_whitelist) (actor_blacklist) (contract_whitelist) (contract_blacklist) (blocks_dir) (state_dir) (state_size) (reversible_cache_size) (read_only) (force_all_checks) (disable_replay_opts) (contracts_console) (genesis) (wasm_runtime) (resource_greylist) (trusted_producers) ) <commit_msg>remove unnecessary reflection of controller::config<commit_after>#pragma once #include <eosio/chain/block_state.hpp> #include <eosio/chain/trace.hpp> #include <eosio/chain/genesis_state.hpp> #include <chainbase/pinnable_mapped_file.hpp> #include <boost/signals2/signal.hpp> #include <eosio/chain/abi_serializer.hpp> #include <eosio/chain/account_object.hpp> #include <eosio/chain/snapshot.hpp> #include <eosio/chain/protocol_feature_manager.hpp> namespace chainbase { class database; } namespace boost { namespace asio { class thread_pool; }} namespace eosio { namespace chain { class authorization_manager; namespace resource_limits { class resource_limits_manager; }; struct controller_impl; using chainbase::database; using chainbase::pinnable_mapped_file; using boost::signals2::signal; class dynamic_global_property_object; class global_property_object; class permission_object; class account_object; using resource_limits::resource_limits_manager; using apply_handler = std::function<void(apply_context&)>; using unapplied_transactions_type = map<transaction_id_type, transaction_metadata_ptr, sha256_less>; class fork_database; enum class db_read_mode { SPECULATIVE, HEAD, READ_ONLY, IRREVERSIBLE }; enum class validation_mode { FULL, LIGHT }; class controller { public: struct config { flat_set<account_name> sender_bypass_whiteblacklist; flat_set<account_name> actor_whitelist; flat_set<account_name> actor_blacklist; flat_set<account_name> contract_whitelist; flat_set<account_name> contract_blacklist; flat_set< pair<account_name, action_name> > action_blacklist; flat_set<public_key_type> key_blacklist; path blocks_dir = chain::config::default_blocks_dir_name; path state_dir = chain::config::default_state_dir_name; uint64_t state_size = chain::config::default_state_size; uint64_t state_guard_size = chain::config::default_state_guard_size; uint64_t reversible_cache_size = chain::config::default_reversible_cache_size; uint64_t reversible_guard_size = chain::config::default_reversible_guard_size; uint32_t sig_cpu_bill_pct = chain::config::default_sig_cpu_bill_pct; uint16_t thread_pool_size = chain::config::default_controller_thread_pool_size; bool read_only = false; bool force_all_checks = false; bool disable_replay_opts = false; bool contracts_console = false; bool allow_ram_billing_in_notify = false; bool disable_all_subjective_mitigations = false; //< for testing purposes only genesis_state genesis; wasm_interface::vm_type wasm_runtime = chain::config::default_wasm_runtime; db_read_mode read_mode = db_read_mode::SPECULATIVE; validation_mode block_validation_mode = validation_mode::FULL; pinnable_mapped_file::map_mode db_map_mode = pinnable_mapped_file::map_mode::mapped; vector<string> db_hugepage_paths; flat_set<account_name> resource_greylist; flat_set<account_name> trusted_producers; uint32_t greylist_limit = chain::config::maximum_elastic_resource_multiplier; }; enum class block_status { irreversible = 0, ///< this block has already been applied before by this node and is considered irreversible validated = 1, ///< this is a complete block signed by a valid producer and has been previously applied by this node and therefore validated but it is not yet irreversible complete = 2, ///< this is a complete block signed by a valid producer but is not yet irreversible nor has it yet been applied by this node incomplete = 3, ///< this is an incomplete block (either being produced by a producer or speculatively produced by a node) }; explicit controller( const config& cfg ); controller( const config& cfg, protocol_feature_set&& pfs ); ~controller(); void add_indices(); void startup( std::function<bool()> shutdown, const snapshot_reader_ptr& snapshot = nullptr ); void preactivate_feature( const digest_type& feature_digest ); vector<digest_type> get_preactivated_protocol_features()const; void validate_protocol_features( const vector<digest_type>& features_to_activate )const; /** * Starts a new pending block session upon which new transactions can * be pushed. * * Will only activate protocol features that have been pre-activated. */ void start_block( block_timestamp_type time = block_timestamp_type(), uint16_t confirm_block_count = 0 ); /** * Starts a new pending block session upon which new transactions can * be pushed. */ void start_block( block_timestamp_type time, uint16_t confirm_block_count, const vector<digest_type>& new_protocol_feature_activations ); void abort_block(); /** * These transactions were previously pushed by have since been unapplied, recalling push_transaction * with the transaction_metadata_ptr will remove them from the source of this data IFF it succeeds. * * The caller is responsible for calling drop_unapplied_transaction on a failing transaction that * they never intend to retry * * @return map of transactions which have been unapplied */ unapplied_transactions_type& get_unapplied_transactions(); /** * */ transaction_trace_ptr push_transaction( const transaction_metadata_ptr& trx, fc::time_point deadline, uint32_t billed_cpu_time_us = 0 ); /** * Attempt to execute a specific transaction in our deferred trx database * */ transaction_trace_ptr push_scheduled_transaction( const transaction_id_type& scheduled, fc::time_point deadline, uint32_t billed_cpu_time_us = 0 ); block_state_ptr finalize_block( const std::function<signature_type( const digest_type& )>& signer_callback ); void sign_block( const std::function<signature_type( const digest_type& )>& signer_callback ); void commit_block(); void pop_block(); std::future<block_state_ptr> create_block_state_future( const signed_block_ptr& b ); void push_block( std::future<block_state_ptr>& block_state_future ); boost::asio::io_context& get_thread_pool(); const chainbase::database& db()const; const fork_database& fork_db()const; const account_object& get_account( account_name n )const; const global_property_object& get_global_properties()const; const dynamic_global_property_object& get_dynamic_global_properties()const; const resource_limits_manager& get_resource_limits_manager()const; resource_limits_manager& get_mutable_resource_limits_manager(); const authorization_manager& get_authorization_manager()const; authorization_manager& get_mutable_authorization_manager(); const protocol_feature_manager& get_protocol_feature_manager()const; const flat_set<account_name>& get_actor_whitelist() const; const flat_set<account_name>& get_actor_blacklist() const; const flat_set<account_name>& get_contract_whitelist() const; const flat_set<account_name>& get_contract_blacklist() const; const flat_set< pair<account_name, action_name> >& get_action_blacklist() const; const flat_set<public_key_type>& get_key_blacklist() const; void set_actor_whitelist( const flat_set<account_name>& ); void set_actor_blacklist( const flat_set<account_name>& ); void set_contract_whitelist( const flat_set<account_name>& ); void set_contract_blacklist( const flat_set<account_name>& ); void set_action_blacklist( const flat_set< pair<account_name, action_name> >& ); void set_key_blacklist( const flat_set<public_key_type>& ); uint32_t head_block_num()const; time_point head_block_time()const; block_id_type head_block_id()const; account_name head_block_producer()const; const block_header& head_block_header()const; block_state_ptr head_block_state()const; uint32_t fork_db_head_block_num()const; block_id_type fork_db_head_block_id()const; time_point fork_db_head_block_time()const; account_name fork_db_head_block_producer()const; uint32_t fork_db_pending_head_block_num()const; block_id_type fork_db_pending_head_block_id()const; time_point fork_db_pending_head_block_time()const; account_name fork_db_pending_head_block_producer()const; time_point pending_block_time()const; account_name pending_block_producer()const; public_key_type pending_block_signing_key()const; optional<block_id_type> pending_producer_block_id()const; const vector<transaction_receipt>& get_pending_trx_receipts()const; const producer_schedule_type& active_producers()const; const producer_schedule_type& pending_producers()const; optional<producer_schedule_type> proposed_producers()const; uint32_t last_irreversible_block_num() const; block_id_type last_irreversible_block_id() const; signed_block_ptr fetch_block_by_number( uint32_t block_num )const; signed_block_ptr fetch_block_by_id( block_id_type id )const; block_state_ptr fetch_block_state_by_number( uint32_t block_num )const; block_state_ptr fetch_block_state_by_id( block_id_type id )const; block_id_type get_block_id_for_num( uint32_t block_num )const; sha256 calculate_integrity_hash()const; void write_snapshot( const snapshot_writer_ptr& snapshot )const; bool sender_avoids_whitelist_blacklist_enforcement( account_name sender )const; void check_actor_list( const flat_set<account_name>& actors )const; void check_contract_list( account_name code )const; void check_action_list( account_name code, action_name action )const; void check_key_list( const public_key_type& key )const; bool is_building_block()const; bool is_producing_block()const; bool is_ram_billing_in_notify_allowed()const; void add_resource_greylist(const account_name &name); void remove_resource_greylist(const account_name &name); bool is_resource_greylisted(const account_name &name) const; const flat_set<account_name> &get_resource_greylist() const; void validate_expiration( const transaction& t )const; void validate_tapos( const transaction& t )const; void validate_db_available_size() const; void validate_reversible_available_size() const; bool is_protocol_feature_activated( const digest_type& feature_digest )const; bool is_builtin_activated( builtin_protocol_feature_t f )const; bool is_known_unexpired_transaction( const transaction_id_type& id) const; int64_t set_proposed_producers( vector<producer_key> producers ); bool light_validation_allowed(bool replay_opts_disabled_by_policy) const; bool skip_auth_check()const; bool skip_db_sessions( )const; bool skip_db_sessions( block_status bs )const; bool skip_trx_checks()const; bool contracts_console()const; chain_id_type get_chain_id()const; db_read_mode get_read_mode()const; validation_mode get_validation_mode()const; void set_subjective_cpu_leeway(fc::microseconds leeway); void set_greylist_limit( uint32_t limit ); uint32_t get_greylist_limit()const; void add_to_ram_correction( account_name account, uint64_t ram_bytes ); bool all_subjective_mitigations_disabled()const; static fc::optional<uint64_t> convert_exception_to_error_code( const fc::exception& e ); signal<void(const signed_block_ptr&)> pre_accepted_block; signal<void(const block_state_ptr&)> accepted_block_header; signal<void(const block_state_ptr&)> accepted_block; signal<void(const block_state_ptr&)> irreversible_block; signal<void(const transaction_metadata_ptr&)> accepted_transaction; signal<void(std::tuple<const transaction_trace_ptr&, const signed_transaction&>)> applied_transaction; signal<void(const int&)> bad_alloc; /* signal<void()> pre_apply_block; signal<void()> post_apply_block; signal<void()> abort_apply_block; signal<void(const transaction_metadata_ptr&)> pre_apply_transaction; signal<void(const transaction_trace_ptr&)> post_apply_transaction; signal<void(const transaction_trace_ptr&)> pre_apply_action; signal<void(const transaction_trace_ptr&)> post_apply_action; */ const apply_handler* find_apply_handler( account_name contract, scope_name scope, action_name act )const; wasm_interface& get_wasm_interface(); optional<abi_serializer> get_abi_serializer( account_name n, const fc::microseconds& max_serialization_time )const { if( n.good() ) { try { const auto& a = get_account( n ); abi_def abi; if( abi_serializer::to_abi( a.abi, abi )) return abi_serializer( abi, max_serialization_time ); } FC_CAPTURE_AND_LOG((n)) } return optional<abi_serializer>(); } template<typename T> fc::variant to_variant_with_abi( const T& obj, const fc::microseconds& max_serialization_time ) { fc::variant pretty_output; abi_serializer::to_variant( obj, pretty_output, [&]( account_name n ){ return get_abi_serializer( n, max_serialization_time ); }, max_serialization_time); return pretty_output; } private: friend class apply_context; friend class transaction_context; chainbase::database& mutable_db()const; std::unique_ptr<controller_impl> my; }; } } /// eosio::chain <|endoftext|>
<commit_before>#include <stdlib.h> #include "nan.h" #include "v8-debug.h" namespace nodex { class Debug { public: static NAN_METHOD(Call) { NanScope(); if (args.Length() < 1) { return NanThrowError("Error"); } v8::Handle<v8::Function> fn = v8::Handle<v8::Function>::Cast(args[0]); v8::Debug::Call(fn); NanReturnUndefined(); }; static NAN_METHOD(Signal) { NanScope(); int length = args[0]->ToString()->Length(); const char* msg = *NanUtf8String(args[0]); uint16_t* command = new uint16_t[length + 1]; for (int i = 0; i < length; i++) command[i] = msg[i]; command[length] = '\0'; #if (NODE_MODULE_VERSION > 0x000B) v8::Isolate* debug_isolate = v8::Debug::GetDebugContext()->GetIsolate(); v8::Debug::SendCommand(debug_isolate, command, length); #else v8::Debug::SendCommand(command, length); #endif delete[] command; NanReturnUndefined(); }; static NAN_METHOD(RunScript) { NanScope(); v8::Local<v8::String> script_source(args[0]->ToString()); if (script_source.IsEmpty()) NanReturnUndefined(); v8::Context::Scope context_scope(v8::Debug::GetDebugContext()); v8::Local<v8::Script> script = v8::Script::Compile(script_source); if (script.IsEmpty()) NanReturnUndefined(); NanReturnValue(script->Run()); }; static NAN_METHOD(AllowNatives) { NanScope(); const char allow_natives_syntax[] = "--allow_natives_syntax"; v8::V8::SetFlagsFromString(allow_natives_syntax, sizeof(allow_natives_syntax) - 1); NanReturnUndefined(); } static v8::Handle<v8::Object> createExceptionDetails(v8::Handle<v8::Message> message) { NanEscapableScope(); v8::Handle<v8::Object> exceptionDetails = NanNew<v8::Object>(); exceptionDetails->Set(NanNew<v8::String>("text"), message->Get()); #if (NODE_MODULE_VERSION > 0x000E) exceptionDetails->Set(NanNew<v8::String>("url"), message->GetScriptOrigin().ResourceName()); exceptionDetails->Set(NanNew<v8::String>("scriptId"), NanNew<v8::Integer>(message->GetScriptOrigin().ScriptID()->Value())); #else exceptionDetails->Set(NanNew<v8::String>("url"), message->GetScriptResourceName()); #endif exceptionDetails->Set(NanNew<v8::String>("line"), NanNew<v8::Integer>(message->GetLineNumber())); exceptionDetails->Set(NanNew<v8::String>("column"), NanNew<v8::Integer>(message->GetStartColumn())); if (!message->GetStackTrace().IsEmpty()) exceptionDetails->Set(NanNew<v8::String>("stackTrace"), message->GetStackTrace()->AsArray()); else exceptionDetails->Set(NanNew<v8::String>("stackTrace"), NanUndefined()); return NanEscapeScope(exceptionDetails); }; static NAN_METHOD(EvaluateWithExceptionDetails) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); v8::Local<v8::String> expression = args[0]->ToString(); if (expression.IsEmpty()) return NanThrowTypeError("The argument must be a string."); v8::TryCatch tryCatch; v8::Handle<v8::Value> result = NanRunScript(NanCompileScript(expression)); v8::Local<v8::Object> wrappedResult = NanNew<v8::Object>(); if (tryCatch.HasCaught()) { wrappedResult->Set(NanNew<v8::String>("result"), tryCatch.Exception()); wrappedResult->Set(NanNew<v8::String>("exceptionDetails"), createExceptionDetails(tryCatch.Message())); } else { wrappedResult->Set(NanNew<v8::String>("result"), result); wrappedResult->Set(NanNew<v8::String>("exceptionDetails"), NanUndefined()); } NanReturnValue(wrappedResult); }; static NAN_METHOD(SetNonEnumProperty) { NanScope(); if (args.Length() < 3) return NanThrowError("Three arguments expected."); if (!args[0]->IsObject()) return NanThrowTypeError("Argument 0 must be an object."); if (!args[1]->IsString()) return NanThrowTypeError("Argument 1 must be a string."); v8::Local<v8::Object> object = args[0]->ToObject(); object->ForceSet(args[1], args[2], v8::DontEnum); NanReturnUndefined(); }; static NAN_METHOD(Subtype) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); v8::Handle<v8::Value> value = args[0]; if (value->IsArray()) NanReturnValue(NanNew<v8::String>("array")); #if (NODE_MODULE_VERSION > 0x000B) if (value->IsTypedArray()) NanReturnValue(NanNew<v8::String>("array")); #endif if (value->IsDate()) NanReturnValue(NanNew<v8::String>("date")); if (value->IsRegExp()) NanReturnValue(NanNew<v8::String>("regexp")); if (value->IsNativeError()) NanReturnValue(NanNew<v8::String>("error")); #if (NODE_MODULE_VERSION > 0x000E) if (value->IsArgumentsObject()) NanReturnValue(NanNew<v8::String>("array")); if (value->IsMap() || value->IsWeakMap()) NanReturnValue(NanNew<v8::String>("map")); if (value->IsSet() || value->IsWeakSet()) NanReturnValue(NanNew<v8::String>("set")); if (value->IsMapIterator() || value->IsSetIterator()) NanReturnValue(NanNew<v8::String>("iterator")); #endif NanReturnUndefined(); }; static v8::Local<v8::String> functionDisplayName(v8::Handle<v8::Function> function) { NanEscapableScope(); v8::Handle<v8::Value> value; #if (NODE_MODULE_VERSION > 0x000B) value = function->GetDisplayName(); if (value->IsString() && value->ToString()->Length()) return NanEscapeScope(value->ToString()); #endif value = function->GetName(); if (value->IsString() && value->ToString()->Length()) return NanEscapeScope(value->ToString()); value = function->GetInferredName(); if (value->IsString() && value->ToString()->Length()) return NanEscapeScope(value->ToString()); return NanEscapeScope(NanNew<v8::String>("")); }; static NAN_METHOD(InternalConstructorName) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); if (!args[0]->IsObject()) return NanThrowTypeError("The argument must be an object."); v8::Local<v8::Object> object = args[0]->ToObject(); v8::Local<v8::String> result = object->GetConstructorName(); char* result_type; if (result.IsEmpty() || result->IsNull() || result->IsUndefined()) result_type = ""; else result_type = *NanUtf8String(args[0]); if (!result.IsEmpty() && result_type == "Object") { v8::Local<v8::String> constructorSymbol = NanNew<v8::String>("constructor"); if (object->HasRealNamedProperty(constructorSymbol) && !object->HasRealNamedCallbackProperty(constructorSymbol)) { v8::TryCatch tryCatch; v8::Local<v8::Value> constructor = object->GetRealNamedProperty(constructorSymbol); if (!constructor.IsEmpty() && constructor->IsFunction()) { v8::Local<v8::String> constructorName = functionDisplayName(v8::Handle<v8::Function>::Cast(constructor)); if (!constructorName.IsEmpty() && !tryCatch.HasCaught()) result = constructorName; } } if (result_type == "Object" && object->IsFunction()) result = NanNew<v8::String>("Function"); } NanReturnValue(result); } static NAN_METHOD(FunctionDetailsWithoutScopes) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); if (!args[0]->IsFunction()) return NanThrowTypeError("The argument must be a function."); v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(args[0]); int lineNumber = function->GetScriptLineNumber(); int columnNumber = function->GetScriptColumnNumber(); v8::Local<v8::Object> location = NanNew<v8::Object>(); location->Set(NanNew<v8::String>("lineNumber"), NanNew<v8::Integer>(lineNumber)); location->Set(NanNew<v8::String>("columnNumber"), NanNew<v8::Integer>(columnNumber)); #if (NODE_MODULE_VERSION > 0x000B) location->Set(NanNew<v8::String>("scriptId"), NanNew<v8::Integer>(function->ScriptId())->ToString()); #else location->Set(NanNew<v8::String>("scriptId"), NanNew<v8::Integer>(function->GetScriptId()->ToInt32()->Value())->ToString()); #endif v8::Local<v8::Object> result = NanNew<v8::Object>(); result->Set(NanNew<v8::String>("location"), location); v8::Handle<v8::String> name = functionDisplayName(function); result->Set(NanNew<v8::String>("functionName"), name.IsEmpty() ? NanNew<v8::String>("") : name); NanReturnValue(result); } static NAN_METHOD(CallFunction) { NanScope(); if (args.Length() < 2 || args.Length() > 3) return NanThrowError("Two or three arguments expected."); if (!args[0]->IsFunction()) return NanThrowTypeError("Argument 0 must be a function."); v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(args[0]); #if (NODE_MODULE_VERSION > 0x000B) v8::Handle<v8::Value> receiver = args[1]; #else v8::Handle<v8::Object> receiver = args[1]->ToObject(); #endif if (args.Length() < 3 || args[2]->IsUndefined()) { v8::Local<v8::Value> result = function->Call(receiver, 0, NULL); NanReturnValue(result); } if (!args[2]->IsArray()) return NanThrowTypeError("Argument 2 must be an array."); v8::Handle<v8::Array> arguments = v8::Handle<v8::Array>::Cast(args[2]); size_t argc = arguments->Length(); v8::Handle<v8::Value> *argv = new v8::Handle<v8::Value>[argc]; for (size_t i = 0; i < argc; ++i) argv[i] = arguments->Get(i); v8::Local<v8::Value> result = function->Call(receiver, argc, argv); delete [] argv; NanReturnValue(result); }; static NAN_METHOD(Eval) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); v8::Local<v8::String> expression = args[0]->ToString(); if (expression.IsEmpty()) return NanThrowTypeError("The argument must be a string."); v8::TryCatch tryCatch; v8::Handle<v8::Script> script = v8::Script::Compile(expression); if (tryCatch.HasCaught()) return NanThrowError(tryCatch.ReThrow()); v8::Handle<v8::Value> result = NanRunScript(script); if (tryCatch.HasCaught()) return NanThrowError(tryCatch.ReThrow()); NanReturnValue(result); }; private: Debug() {} ~Debug() {} }; void Initialize(v8::Handle<v8::Object> target) { NanScope(); NODE_SET_METHOD(target, "call", Debug::Call); NODE_SET_METHOD(target, "signal", Debug::Signal); NODE_SET_METHOD(target, "runScript", Debug::RunScript); NODE_SET_METHOD(target, "allowNatives", Debug::RunScript); v8::Local<v8::Object> InjectedScriptHost = NanNew<v8::Object>(); NODE_SET_METHOD(InjectedScriptHost, "eval", Debug::Eval); NODE_SET_METHOD(InjectedScriptHost, "evaluateWithExceptionDetails", Debug::EvaluateWithExceptionDetails); NODE_SET_METHOD(InjectedScriptHost, "setNonEnumProperty", Debug::SetNonEnumProperty); NODE_SET_METHOD(InjectedScriptHost, "subtype", Debug::Subtype); NODE_SET_METHOD(InjectedScriptHost, "internalConstructorName", Debug::InternalConstructorName); NODE_SET_METHOD(InjectedScriptHost, "functionDetailsWithoutScopes", Debug::FunctionDetailsWithoutScopes); NODE_SET_METHOD(InjectedScriptHost, "callFunction", Debug::CallFunction); target->Set(NanNew<v8::String>("InjectedScriptHost"), InjectedScriptHost); } NODE_MODULE(debug, Initialize) } <commit_msg>Fix Linux compatibility<commit_after>#include <stdlib.h> #include "nan.h" #include "v8-debug.h" namespace nodex { class Debug { public: static NAN_METHOD(Call) { NanScope(); if (args.Length() < 1) { return NanThrowError("Error"); } v8::Handle<v8::Function> fn = v8::Handle<v8::Function>::Cast(args[0]); v8::Debug::Call(fn); NanReturnUndefined(); }; static NAN_METHOD(Signal) { NanScope(); v8::String::Value command(args[0]); #if (NODE_MODULE_VERSION > 0x000B) v8::Isolate* debug_isolate = v8::Debug::GetDebugContext()->GetIsolate(); v8::Debug::SendCommand(debug_isolate, *command, command.length()); #else v8::Debug::SendCommand(*command, command.length()); #endif NanReturnUndefined(); }; static NAN_METHOD(RunScript) { NanScope(); v8::Local<v8::String> script_source(args[0]->ToString()); if (script_source.IsEmpty()) NanReturnUndefined(); v8::Context::Scope context_scope(v8::Debug::GetDebugContext()); v8::Local<v8::Script> script = v8::Script::Compile(script_source); if (script.IsEmpty()) NanReturnUndefined(); NanReturnValue(script->Run()); }; static NAN_METHOD(AllowNatives) { NanScope(); const char allow_natives_syntax[] = "--allow_natives_syntax"; v8::V8::SetFlagsFromString(allow_natives_syntax, sizeof(allow_natives_syntax) - 1); NanReturnUndefined(); } static v8::Handle<v8::Object> createExceptionDetails(v8::Handle<v8::Message> message) { NanEscapableScope(); v8::Handle<v8::Object> exceptionDetails = NanNew<v8::Object>(); exceptionDetails->Set(NanNew<v8::String>("text"), message->Get()); #if (NODE_MODULE_VERSION > 0x000E) exceptionDetails->Set(NanNew<v8::String>("url"), message->GetScriptOrigin().ResourceName()); exceptionDetails->Set(NanNew<v8::String>("scriptId"), NanNew<v8::Integer>(message->GetScriptOrigin().ScriptID()->Value())); #else exceptionDetails->Set(NanNew<v8::String>("url"), message->GetScriptResourceName()); #endif exceptionDetails->Set(NanNew<v8::String>("line"), NanNew<v8::Integer>(message->GetLineNumber())); exceptionDetails->Set(NanNew<v8::String>("column"), NanNew<v8::Integer>(message->GetStartColumn())); if (!message->GetStackTrace().IsEmpty()) exceptionDetails->Set(NanNew<v8::String>("stackTrace"), message->GetStackTrace()->AsArray()); else exceptionDetails->Set(NanNew<v8::String>("stackTrace"), NanUndefined()); return NanEscapeScope(exceptionDetails); }; static NAN_METHOD(EvaluateWithExceptionDetails) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); v8::Local<v8::String> expression = args[0]->ToString(); if (expression.IsEmpty()) return NanThrowTypeError("The argument must be a string."); v8::TryCatch tryCatch; v8::Handle<v8::Value> result = NanRunScript(NanCompileScript(expression)); v8::Local<v8::Object> wrappedResult = NanNew<v8::Object>(); if (tryCatch.HasCaught()) { wrappedResult->Set(NanNew<v8::String>("result"), tryCatch.Exception()); wrappedResult->Set(NanNew<v8::String>("exceptionDetails"), createExceptionDetails(tryCatch.Message())); } else { wrappedResult->Set(NanNew<v8::String>("result"), result); wrappedResult->Set(NanNew<v8::String>("exceptionDetails"), NanUndefined()); } NanReturnValue(wrappedResult); }; static NAN_METHOD(SetNonEnumProperty) { NanScope(); if (args.Length() < 3) return NanThrowError("Three arguments expected."); if (!args[0]->IsObject()) return NanThrowTypeError("Argument 0 must be an object."); if (!args[1]->IsString()) return NanThrowTypeError("Argument 1 must be a string."); v8::Local<v8::Object> object = args[0]->ToObject(); object->ForceSet(args[1], args[2], v8::DontEnum); NanReturnUndefined(); }; static NAN_METHOD(Subtype) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); v8::Handle<v8::Value> value = args[0]; if (value->IsArray()) NanReturnValue(NanNew<v8::String>("array")); #if (NODE_MODULE_VERSION > 0x000B) if (value->IsTypedArray()) NanReturnValue(NanNew<v8::String>("array")); #endif if (value->IsDate()) NanReturnValue(NanNew<v8::String>("date")); if (value->IsRegExp()) NanReturnValue(NanNew<v8::String>("regexp")); if (value->IsNativeError()) NanReturnValue(NanNew<v8::String>("error")); #if (NODE_MODULE_VERSION > 0x000E) if (value->IsArgumentsObject()) NanReturnValue(NanNew<v8::String>("array")); if (value->IsMap() || value->IsWeakMap()) NanReturnValue(NanNew<v8::String>("map")); if (value->IsSet() || value->IsWeakSet()) NanReturnValue(NanNew<v8::String>("set")); if (value->IsMapIterator() || value->IsSetIterator()) NanReturnValue(NanNew<v8::String>("iterator")); #endif NanReturnUndefined(); }; static v8::Local<v8::String> functionDisplayName(v8::Handle<v8::Function> function) { NanEscapableScope(); v8::Handle<v8::Value> value; #if (NODE_MODULE_VERSION > 0x000B) value = function->GetDisplayName(); if (value->IsString() && value->ToString()->Length()) return NanEscapeScope(value->ToString()); #endif value = function->GetName(); if (value->IsString() && value->ToString()->Length()) return NanEscapeScope(value->ToString()); value = function->GetInferredName(); if (value->IsString() && value->ToString()->Length()) return NanEscapeScope(value->ToString()); return NanEscapeScope(NanNew<v8::String>("")); }; static NAN_METHOD(InternalConstructorName) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); if (!args[0]->IsObject()) return NanThrowTypeError("The argument must be an object."); v8::Local<v8::Object> object = args[0]->ToObject(); v8::Local<v8::String> result = object->GetConstructorName(); char* result_type; if (result.IsEmpty() || result->IsNull() || result->IsUndefined()) result_type = ""; else result_type = *NanUtf8String(args[0]); if (!result.IsEmpty() && result_type == "Object") { v8::Local<v8::String> constructorSymbol = NanNew<v8::String>("constructor"); if (object->HasRealNamedProperty(constructorSymbol) && !object->HasRealNamedCallbackProperty(constructorSymbol)) { v8::TryCatch tryCatch; v8::Local<v8::Value> constructor = object->GetRealNamedProperty(constructorSymbol); if (!constructor.IsEmpty() && constructor->IsFunction()) { v8::Local<v8::String> constructorName = functionDisplayName(v8::Handle<v8::Function>::Cast(constructor)); if (!constructorName.IsEmpty() && !tryCatch.HasCaught()) result = constructorName; } } if (result_type == "Object" && object->IsFunction()) result = NanNew<v8::String>("Function"); } NanReturnValue(result); } static NAN_METHOD(FunctionDetailsWithoutScopes) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); if (!args[0]->IsFunction()) return NanThrowTypeError("The argument must be a function."); v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(args[0]); int lineNumber = function->GetScriptLineNumber(); int columnNumber = function->GetScriptColumnNumber(); v8::Local<v8::Object> location = NanNew<v8::Object>(); location->Set(NanNew<v8::String>("lineNumber"), NanNew<v8::Integer>(lineNumber)); location->Set(NanNew<v8::String>("columnNumber"), NanNew<v8::Integer>(columnNumber)); #if (NODE_MODULE_VERSION > 0x000B) location->Set(NanNew<v8::String>("scriptId"), NanNew<v8::Integer>(function->ScriptId())->ToString()); #else location->Set(NanNew<v8::String>("scriptId"), NanNew<v8::Integer>(function->GetScriptId()->ToInt32()->Value())->ToString()); #endif v8::Local<v8::Object> result = NanNew<v8::Object>(); result->Set(NanNew<v8::String>("location"), location); v8::Handle<v8::String> name = functionDisplayName(function); result->Set(NanNew<v8::String>("functionName"), name.IsEmpty() ? NanNew<v8::String>("") : name); NanReturnValue(result); } static NAN_METHOD(CallFunction) { NanScope(); if (args.Length() < 2 || args.Length() > 3) return NanThrowError("Two or three arguments expected."); if (!args[0]->IsFunction()) return NanThrowTypeError("Argument 0 must be a function."); v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(args[0]); #if (NODE_MODULE_VERSION > 0x000B) v8::Handle<v8::Value> receiver = args[1]; #else v8::Handle<v8::Object> receiver = args[1]->ToObject(); #endif if (args.Length() < 3 || args[2]->IsUndefined()) { v8::Local<v8::Value> result = function->Call(receiver, 0, NULL); NanReturnValue(result); } if (!args[2]->IsArray()) return NanThrowTypeError("Argument 2 must be an array."); v8::Handle<v8::Array> arguments = v8::Handle<v8::Array>::Cast(args[2]); size_t argc = arguments->Length(); v8::Handle<v8::Value> *argv = new v8::Handle<v8::Value>[argc]; for (size_t i = 0; i < argc; ++i) argv[i] = arguments->Get(i); v8::Local<v8::Value> result = function->Call(receiver, argc, argv); delete [] argv; NanReturnValue(result); }; static NAN_METHOD(Eval) { NanScope(); if (args.Length() < 1) return NanThrowError("One argument expected."); v8::Local<v8::String> expression = args[0]->ToString(); if (expression.IsEmpty()) return NanThrowTypeError("The argument must be a string."); v8::TryCatch tryCatch; v8::Handle<v8::Script> script = v8::Script::Compile(expression); if (tryCatch.HasCaught()) return NanThrowError(tryCatch.ReThrow()); v8::Handle<v8::Value> result = NanRunScript(script); if (tryCatch.HasCaught()) return NanThrowError(tryCatch.ReThrow()); NanReturnValue(result); }; private: Debug() {} ~Debug() {} }; void Initialize(v8::Handle<v8::Object> target) { NanScope(); NODE_SET_METHOD(target, "call", Debug::Call); NODE_SET_METHOD(target, "signal", Debug::Signal); NODE_SET_METHOD(target, "runScript", Debug::RunScript); NODE_SET_METHOD(target, "allowNatives", Debug::RunScript); v8::Local<v8::Object> InjectedScriptHost = NanNew<v8::Object>(); NODE_SET_METHOD(InjectedScriptHost, "eval", Debug::Eval); NODE_SET_METHOD(InjectedScriptHost, "evaluateWithExceptionDetails", Debug::EvaluateWithExceptionDetails); NODE_SET_METHOD(InjectedScriptHost, "setNonEnumProperty", Debug::SetNonEnumProperty); NODE_SET_METHOD(InjectedScriptHost, "subtype", Debug::Subtype); NODE_SET_METHOD(InjectedScriptHost, "internalConstructorName", Debug::InternalConstructorName); NODE_SET_METHOD(InjectedScriptHost, "functionDetailsWithoutScopes", Debug::FunctionDetailsWithoutScopes); NODE_SET_METHOD(InjectedScriptHost, "callFunction", Debug::CallFunction); target->Set(NanNew<v8::String>("InjectedScriptHost"), InjectedScriptHost); } NODE_MODULE(debug, Initialize) } <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // // Demo Borland + vtk Project, // //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- #include "Form_Test.h" // #include "vtkTriangleFilter.h" #include "vtkShrinkPolyData.h" #include "vtkSphereSource.h" #include "vtkElevationFilter.h" #include "vtkPolyDataMapper.h" #include "vtkPolyData.h" #include "vtkActor.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "vtkBorlandRenderWindow" #pragma resource "*.dfm" TVTK_Form *VTK_Form; //--------------------------------------------------------------------------- __fastcall TVTK_Form::TVTK_Form(TComponent* Owner) : TForm(Owner) { shrink = NULL; } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::FormDestroy(TObject *Sender) { vtkRenderer* ren1 = vtkWindow1->GetRenderer(); ren1->GetProps()->RemoveAllItems(); if (shrink) shrink->Delete(); } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::HeaderControl1SectionClick(THeaderControl *HeaderControl, THeaderSection *Section) { if (Section->Text=="Mode") { TPoint p = HeaderControl->ClientToScreen(TPoint(0,0)); ModeMenu->Popup(p.x + Section->Left, p.y - 0); } else if (Section->Text=="Window") { TPoint p = HeaderControl->ClientToScreen(TPoint(0,0)); WindowMenu->Popup(p.x + Section->Left, p.y - 0); } } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::TrackBallMode1Click(TObject *Sender) { if (Sender==JoystickMode1) { vtkWindow1->SetInteractorMode(IM_JoystickCamera); JoystickMode1->Checked = true; } if (Sender==TrackBallMode1) { vtkWindow1->SetInteractorMode(IM_TrackballCamera); TrackBallMode1->Checked = true; } if (Sender==FlightMode1) { vtkWindow1->SetInteractorMode(IM_Flight); FlightMode1->Checked = true; } } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::BackgroundColour1Click(TObject *Sender) { if (!backgroundcolor->Execute()) return; DWORD L = ColorToRGB(backgroundcolor->Color); float rgb[3] = { GetRValue(L)/255.0, GetGValue(L)/255.0, GetBValue(L)/255.0 }; vtkWindow1->GetRenderer()->SetBackground(rgb); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::ResetCamera1Click(TObject *Sender) { vtkWindow1->GetRenderer()->ResetCamera(); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- // // // Here's a demo // // //--------------------------------------------------------------------------- void __fastcall TVTK_Form::bc1Click(TObject *Sender) { if (shrink) return; // vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetThetaResolution(36.0); sphere->SetPhiResolution(18.0); sphere->SetRadius(1.0); shrink = vtkShrinkPolyData::New(); shrink->SetShrinkFactor( ShrinkScroll->Position/100.0 ); shrink->SetInput( sphere->GetOutput() ); vtkElevationFilter *elev = vtkElevationFilter::New(); elev->SetInput( shrink->GetOutput() ); elev->SetLowPoint(-1,-1,-1); elev->SetHighPoint( 1, 1, 1); elev->SetScalarRange(0,1); vtkPolyDataMapper *aMapper = vtkPolyDataMapper::New(); aMapper->SetInput( elev->GetPolyDataOutput() ); aMapper->SetScalarRange(0,1); vtkActor *anActor = vtkActor::New(); anActor->SetMapper(aMapper); // Use these functions to get the actual RenderWindow/Renderers vtkWindow1->GetRenderer()->AddActor(anActor); // we don't need these any more, they are reference counted by the // pipeline and we can delete them, They'll be destructed when everything // finishes anActor->Delete(); aMapper->Delete(); sphere->Delete(); elev->Delete(); // we'll keep a pointer to the shrinkfilter so we can use our scroller vtkWindow1->GetRenderer()->ResetCamera(); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::ShrinkScrollChange(TObject *Sender) { if (!shrink) return; shrink->SetShrinkFactor( ShrinkScroll->Position/100.0 ); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::vtkWindow1Enter(TObject *Sender) { BorderWindow->Color = clMaroon; } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::vtkWindow1Exit(TObject *Sender) { BorderWindow->Color = clBtnFace; } //--------------------------------------------------------------------------- <commit_msg>FIX: additional comments, style changes, two bug fixes<commit_after>//--------------------------------------------------------------------------- // // Demo Borland + vtk Project, // //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- #include "Form_Test.h" // #include "vtkActor.h" #include "vtkAssemblyPath.h" #include "vtkAssemblyNode.h" #include "vtkElevationFilter.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkShrinkPolyData.h" #include "vtkSphereSource.h" #include "vtkTriangleFilter.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "vtkBorlandRenderWindow" #pragma resource "*.dfm" TVTK_Form *VTK_Form; //--------------------------------------------------------------------------- __fastcall TVTK_Form::TVTK_Form(TComponent* Owner) : TForm(Owner) { shrink = NULL; } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::FormDestroy(TObject *Sender) { if (shrink) { shrink->Delete(); } // The release of graphics resources is required here in // the event that an actor is switched between solid // and wireframe representations. This cannot be implemented within // vtkBorlandRenderWindow, since ReleaseGraphicsResources, when called // by a vtkProp's mapper, will cause the internal vtkWin32OpenGLRenderWindow // to fail during MakeCurrent. vtkPropCollection *pc; vtkProp *aProp, *aPart; vtkAssemblyPath *path; vtkRenderer* ren1 = vtkWindow1->GetRenderer(); vtkRenderWindow* renwin = vtkWindow1->GetRenderWindow(); pc = ren1->GetProps(); for (pc->InitTraversal(); (aProp = pc->GetNextProp()); ) { for (aProp->InitPathTraversal(); (path=aProp->GetNextPath()); ) { aPart=(vtkProp *)path->GetLastNode()->GetProp(); aPart->ReleaseGraphicsResources(renwin); } } } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::HeaderControl1SectionClick(THeaderControl *HeaderControl, THeaderSection *Section) { if (Section->Text=="Mode") { TPoint p = HeaderControl->ClientToScreen(TPoint(0,0)); ModeMenu->Popup(p.x + Section->Left, p.y - 0); } else if (Section->Text=="Window") { TPoint p = HeaderControl->ClientToScreen(TPoint(0,0)); WindowMenu->Popup(p.x + Section->Left, p.y - 0); } } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::TrackBallMode1Click(TObject *Sender) { if (Sender==JoystickMode1) { vtkWindow1->SetInteractorMode(IM_JoystickCamera); JoystickMode1->Checked = true; } if (Sender==TrackBallMode1) { vtkWindow1->SetInteractorMode(IM_TrackballCamera); TrackBallMode1->Checked = true; } if (Sender==FlightMode1) { vtkWindow1->SetInteractorMode(IM_Flight); FlightMode1->Checked = true; } } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::BackgroundColour1Click(TObject *Sender) { if (!backgroundcolor->Execute()) { return; } DWORD L = ColorToRGB(backgroundcolor->Color); float rgb[3] = { GetRValue(L)/255.0, GetGValue(L)/255.0, GetBValue(L)/255.0 }; vtkWindow1->GetRenderer()->SetBackground(rgb); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::ResetCamera1Click(TObject *Sender) { vtkWindow1->GetRenderer()->ResetCamera(); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- // // // Here's a demo // // //--------------------------------------------------------------------------- void __fastcall TVTK_Form::bc1Click(TObject *Sender) { if (shrink) { return; } vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetThetaResolution(36.0); sphere->SetPhiResolution(18.0); sphere->SetRadius(1.0); shrink = vtkShrinkPolyData::New(); shrink->SetShrinkFactor( ShrinkScroll->Position/100.0 ); shrink->SetInput( sphere->GetOutput() ); vtkElevationFilter *elev = vtkElevationFilter::New(); elev->SetInput( shrink->GetOutput() ); elev->SetLowPoint(-1,-1,-1); elev->SetHighPoint( 1, 1, 1); elev->SetScalarRange(0,1); vtkPolyDataMapper *aMapper = vtkPolyDataMapper::New(); aMapper->SetInput( elev->GetPolyDataOutput() ); aMapper->SetScalarRange(0,1); vtkActor *anActor = vtkActor::New(); anActor->SetMapper(aMapper); // Use these functions to get the actual RenderWindow/Renderers. vtkWindow1->GetRenderer()->AddActor(anActor); // We don't need these any more, they are reference counted by the // pipeline and we can delete them. They'll be destructed when everything // finishes. We'll keep a pointer to the shrinkfilter so we can use our // scroller. anActor->Delete(); aMapper->Delete(); sphere->Delete(); elev->Delete(); vtkWindow1->GetRenderer()->ResetCamera(); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::ShrinkScrollChange(TObject *Sender) { if (!shrink) { return; } shrink->SetShrinkFactor( ShrinkScroll->Position/100.0 ); vtkWindow1->Invalidate(); } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::vtkWindow1Enter(TObject *Sender) { BorderWindow->Color = clMaroon; } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::vtkWindow1Exit(TObject *Sender) { BorderWindow->Color = clBtnFace; } //--------------------------------------------------------------------------- void __fastcall TVTK_Form::FormShow(TObject *Sender) { // These calls are made to enforce creation of the internal // vtk components of the vtkBorlandRenderWindow. If this were // not done, clicking on the component would attempt to pass // window messages to non-existent entities. This behaviour // could be changed in future. vtkRenderWindowInteractor * iact = vtkWindow1->GetInteractor(); vtkRenderer* ren1 = vtkWindow1->GetRenderer(); } //--------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * Jamoma OSC Receiver * Copyright © 2011, Théo de la Hogue * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTOscSocket.h" TTPtr TTOscSocketListener(TTPtr anArgument) { TTOscSocketPtr anOscSocket= (TTOscSocketPtr) anArgument; anOscSocket->mSocketListener = new UdpListeningReceiveSocket(IpEndpointName(IpEndpointName::ANY_ADDRESS, anOscSocket->mPort), anOscSocket); anOscSocket->mSocketListener->Run(); return NULL; } TTOscSocket::TTOscSocket(const TTObjectBasePtr owner, const TTUInt16 port) { mOwner = owner; mPort = port; mSocketListener = NULL; mSocketListenerThread = new TTThread(TTOscSocketListener, this); mSocketTransmitter = NULL; } TTOscSocket::TTOscSocket(const TTString& address, const TTUInt16 port) { mAddress = address; mPort = port; mSocketTransmitter = new UdpTransmitSocket(IpEndpointName(address.data(), port)); mSocketListener = NULL; } TTOscSocket::~TTOscSocket() { unsigned int usecToStopTheSelect = 20000; if (mSocketListener) { mSocketListener->AsynchronousBreak(); #ifdef TT_PLATFORM_WIN Sleep(usecToStopTheSelect/1000); #else usleep(usecToStopTheSelect); #endif delete mSocketListener; mSocketListener = NULL; } if (mSocketTransmitter) { delete mSocketTransmitter; mSocketTransmitter = NULL; } } void TTOscSocket::ProcessMessage(const osc::ReceivedMessage&m, const IpEndpointName& remoteEndPoint) { TTValue receivedMessage = TTSymbol(m.AddressPattern()); osc::ReceivedMessage::const_iterator arguments = m.ArgumentsBegin(); // get arguments while (arguments != m.ArgumentsEnd()) { if (arguments->IsChar()) receivedMessage.append(arguments->AsChar()); else if (arguments->IsInt32()) { TTInt32 i = arguments->AsInt32(); receivedMessage.append((TTInt64)i); } else if (arguments->IsFloat()) receivedMessage.append(arguments->AsFloat()); else if (arguments->IsString()) receivedMessage.append(TTSymbol(arguments->AsString())); arguments++; } this->mOwner->sendMessage(TTSymbol("oscSocketReceive"), receivedMessage, kTTValNONE); } TTErr TTOscSocket::SendMessage(TTSymbol& message, const TTValue& arguments) { TTUInt32 bufferSize = computeMessageSize(message, arguments); if (!bufferSize) return kTTErrGeneric; #ifdef TT_PLATFORM_WIN char* buffer = (char*)malloc(bufferSize); #else char buffer[bufferSize]; #endif osc::OutboundPacketStream oscStream(buffer, bufferSize); oscStream << osc::BeginMessage(message.c_str()); TTSymbol symValue; TTInt32 intValue; TTFloat64 floatValue; TTBoolean booleanValue; TTDataType valueType; for (TTUInt32 i = 0; i < arguments.getSize(); ++i) { valueType = arguments.getType(i); if (valueType == kTypeSymbol|| arguments.getType(i) == kTypeAddress) { arguments.get(i, symValue); oscStream << symValue.c_str(); } else if (valueType == kTypeBoolean) { arguments.get(i, booleanValue); oscStream << booleanValue; } else if (valueType == kTypeUInt8 || valueType == kTypeUInt16 || valueType == kTypeUInt32 || valueType == kTypeUInt64) { arguments.get(i, intValue); oscStream << intValue; } else if (valueType == kTypeInt8 || valueType == kTypeInt16 || valueType == kTypeInt32 || valueType == kTypeInt64) { arguments.get(i, intValue); oscStream << intValue; } else if (valueType == kTypeFloat32 || valueType == kTypeFloat64) { arguments.get(i, floatValue); oscStream << (float)floatValue; } else return kTTErrGeneric; } oscStream << osc::EndMessage; mSocketTransmitter->Send(oscStream.Data(), oscStream.Size()); oscStream.Clear(); return kTTErrNone; } TTUInt32 TTOscSocket::computeMessageSize(TTSymbol& message, const TTValue& arguments) { TTUInt32 result = 0; result += 8; //#bundle result += 8; //timetag result += 4; //datasize TTUInt32 messageSize = message.string().size(); messageSize += 1; // /0 for end of string result += ((messageSize/4) + 1) * 4; TTUInt32 argumentSize = arguments.getSize(); argumentSize += 1; // , for indicating this is an argument string information result += ((argumentSize/4) + 1) * 4; // ArgumentTag Size for (TTUInt32 i = 0; i < arguments.getSize(); ++i) { if (arguments.getType(i) == kTypeSymbol || arguments.getType(i) == kTypeAddress) { TTSymbol symValue; arguments.get(i, symValue); TTUInt32 stringSize = symValue.string().size(); stringSize += 1; // /0 for end of string result += ((stringSize/4) + 1) * 4; // String Size } else if (arguments.getType(i) == kTypeBoolean) { result += 1; // Boolean size } else if (arguments.getType(i) == kTypeUInt8 || arguments.getType(i) == kTypeInt8) { result += 2; // Int8 size } else if (arguments.getType(i) == kTypeUInt16 || arguments.getType(i) == kTypeInt16) { result += 4; // Int16 size } else if (arguments.getType(i) == kTypeUInt32 || arguments.getType(i) == kTypeInt32 || arguments.getType(i) == kTypeFloat32) { result += 4; // Float32/Int32 size } else if (arguments.getType(i) == kTypeUInt64 || arguments.getType(i) == kTypeInt64 || arguments.getType(i) == kTypeFloat64) { result += 8; // Float64/Int64 size } else return 0; // Error } return result; }<commit_msg>Removing kTypeAddress<commit_after>/* * Jamoma OSC Receiver * Copyright © 2011, Théo de la Hogue * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTOscSocket.h" TTPtr TTOscSocketListener(TTPtr anArgument) { TTOscSocketPtr anOscSocket= (TTOscSocketPtr) anArgument; anOscSocket->mSocketListener = new UdpListeningReceiveSocket(IpEndpointName(IpEndpointName::ANY_ADDRESS, anOscSocket->mPort), anOscSocket); anOscSocket->mSocketListener->Run(); return NULL; } TTOscSocket::TTOscSocket(const TTObjectBasePtr owner, const TTUInt16 port) { mOwner = owner; mPort = port; mSocketListener = NULL; mSocketListenerThread = new TTThread(TTOscSocketListener, this); mSocketTransmitter = NULL; } TTOscSocket::TTOscSocket(const TTString& address, const TTUInt16 port) { mAddress = address; mPort = port; mSocketTransmitter = new UdpTransmitSocket(IpEndpointName(address.data(), port)); mSocketListener = NULL; } TTOscSocket::~TTOscSocket() { unsigned int usecToStopTheSelect = 20000; if (mSocketListener) { mSocketListener->AsynchronousBreak(); #ifdef TT_PLATFORM_WIN Sleep(usecToStopTheSelect/1000); #else usleep(usecToStopTheSelect); #endif delete mSocketListener; mSocketListener = NULL; } if (mSocketTransmitter) { delete mSocketTransmitter; mSocketTransmitter = NULL; } } void TTOscSocket::ProcessMessage(const osc::ReceivedMessage&m, const IpEndpointName& remoteEndPoint) { TTValue receivedMessage = TTSymbol(m.AddressPattern()); osc::ReceivedMessage::const_iterator arguments = m.ArgumentsBegin(); // get arguments while (arguments != m.ArgumentsEnd()) { if (arguments->IsChar()) receivedMessage.append(arguments->AsChar()); else if (arguments->IsInt32()) { TTInt32 i = arguments->AsInt32(); receivedMessage.append((TTInt64)i); } else if (arguments->IsFloat()) receivedMessage.append(arguments->AsFloat()); else if (arguments->IsString()) receivedMessage.append(TTSymbol(arguments->AsString())); arguments++; } this->mOwner->sendMessage(TTSymbol("oscSocketReceive"), receivedMessage, kTTValNONE); } TTErr TTOscSocket::SendMessage(TTSymbol& message, const TTValue& arguments) { TTUInt32 bufferSize = computeMessageSize(message, arguments); if (!bufferSize) return kTTErrGeneric; #ifdef TT_PLATFORM_WIN char* buffer = (char*)malloc(bufferSize); #else char buffer[bufferSize]; #endif osc::OutboundPacketStream oscStream(buffer, bufferSize); oscStream << osc::BeginMessage(message.c_str()); TTSymbol symValue; TTInt32 intValue; TTFloat64 floatValue; TTBoolean booleanValue; TTDataType valueType; for (TTUInt32 i = 0; i < arguments.getSize(); ++i) { valueType = arguments.getType(i); if (valueType == kTypeSymbol) { arguments.get(i, symValue); oscStream << symValue.c_str(); } else if (valueType == kTypeBoolean) { arguments.get(i, booleanValue); oscStream << booleanValue; } else if (valueType == kTypeUInt8 || valueType == kTypeUInt16 || valueType == kTypeUInt32 || valueType == kTypeUInt64) { arguments.get(i, intValue); oscStream << intValue; } else if (valueType == kTypeInt8 || valueType == kTypeInt16 || valueType == kTypeInt32 || valueType == kTypeInt64) { arguments.get(i, intValue); oscStream << intValue; } else if (valueType == kTypeFloat32 || valueType == kTypeFloat64) { arguments.get(i, floatValue); oscStream << (float)floatValue; } else return kTTErrGeneric; } oscStream << osc::EndMessage; mSocketTransmitter->Send(oscStream.Data(), oscStream.Size()); oscStream.Clear(); return kTTErrNone; } TTUInt32 TTOscSocket::computeMessageSize(TTSymbol& message, const TTValue& arguments) { TTUInt32 result = 0; result += 8; //#bundle result += 8; //timetag result += 4; //datasize TTUInt32 messageSize = message.string().size(); messageSize += 1; // /0 for end of string result += ((messageSize/4) + 1) * 4; TTUInt32 argumentSize = arguments.getSize(); argumentSize += 1; // , for indicating this is an argument string information result += ((argumentSize/4) + 1) * 4; // ArgumentTag Size for (TTUInt32 i = 0; i < arguments.getSize(); ++i) { if (arguments.getType(i) == kTypeSymbol) { TTSymbol symValue; arguments.get(i, symValue); TTUInt32 stringSize = symValue.string().size(); stringSize += 1; // /0 for end of string result += ((stringSize/4) + 1) * 4; // String Size } else if (arguments.getType(i) == kTypeBoolean) { result += 1; // Boolean size } else if (arguments.getType(i) == kTypeUInt8 || arguments.getType(i) == kTypeInt8) { result += 2; // Int8 size } else if (arguments.getType(i) == kTypeUInt16 || arguments.getType(i) == kTypeInt16) { result += 4; // Int16 size } else if (arguments.getType(i) == kTypeUInt32 || arguments.getType(i) == kTypeInt32 || arguments.getType(i) == kTypeFloat32) { result += 4; // Float32/Int32 size } else if (arguments.getType(i) == kTypeUInt64 || arguments.getType(i) == kTypeInt64 || arguments.getType(i) == kTypeFloat64) { result += 8; // Float64/Int64 size } else return 0; // Error } return result; }<|endoftext|>
<commit_before>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QDebug> #include <QLocalServer> #include <QLocalSocket> #include <QTcpServer> #include <QTcpSocket> #include "QDjangoFastCgiServer.h" #include "QDjangoFastCgiServer_p.h" #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpRequest_p.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpResponse_p.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" //#define QDJANGO_DEBUG_FCGI #ifdef QDJANGO_DEBUG_FCGI static void hDebug(FCGI_Header *header, const char *dir) { const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0; const quint16 contentLength = (header->contentLengthB1 << 8) | header->contentLengthB0; qDebug("--- FCGI Record %s ---", dir); qDebug("version: %i", header->version); qDebug("type: %i", header->type); qDebug("requestId: %i", requestId); qDebug("contentLength: %i", contentLength); qDebug("paddingLength: %i", header->paddingLength); } #endif /// \cond QDjangoFastCgiConnection::QDjangoFastCgiConnection(QIODevice *device, QDjangoFastCgiServer *server) : QObject(server), m_device(device), m_inputPos(0), m_pendingRequest(0), m_pendingRequestId(0), m_server(server) { bool check; Q_UNUSED(check); m_device->setParent(this); check = connect(m_device, SIGNAL(disconnected()), this, SIGNAL(closed())); Q_ASSERT(check); check = connect(m_device, SIGNAL(bytesWritten(qint64)), this, SLOT(_q_bytesWritten(qint64))); Q_ASSERT(check); check = connect(m_device, SIGNAL(readyRead()), this, SLOT(_q_readyRead())); Q_ASSERT(check); } QDjangoFastCgiConnection::~QDjangoFastCgiConnection() { if (m_pendingRequest) delete m_pendingRequest; } void QDjangoFastCgiConnection::writeResponse(quint16 requestId, QDjangoHttpResponse *response) { // serialise HTTP response QString httpHeader = QString::fromLatin1("Status: %1 %2\r\n").arg(response->d->statusCode).arg(response->d->reasonPhrase); QList<QPair<QString, QString> >::ConstIterator it = response->d->headers.constBegin(); while (it != response->d->headers.constEnd()) { httpHeader += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n"); ++it; } const QByteArray data = httpHeader.toUtf8() + "\r\n" + response->d->body; const char *ptr = data.constData(); FCGI_Header *header = (FCGI_Header*)m_outputBuffer; memset(header, 0, FCGI_HEADER_LEN); header->version = 1; header->requestIdB1 = (requestId >> 8) & 0xff; header->requestIdB0 = (requestId & 0xff); for (qint64 bytesRemaining = data.size(); ; ) { const quint16 contentLength = qMin(bytesRemaining, qint64(32768)); header->type = FCGI_STDOUT; header->contentLengthB1 = (contentLength >> 8) & 0xff; header->contentLengthB0 = (contentLength & 0xff); memcpy(m_outputBuffer + FCGI_HEADER_LEN, ptr, contentLength); m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "sent"); qDebug("[STDOUT]"); #endif if (contentLength > 0) { ptr += contentLength; bytesRemaining -= contentLength; } else { break; } } quint16 contentLength = 8; header->type = FCGI_END_REQUEST; header->contentLengthB1 = (contentLength >> 8) & 0xff; header->contentLengthB0 = (contentLength & 0xff); memset(m_outputBuffer + FCGI_HEADER_LEN, 0, contentLength); m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "sent"); qDebug("[END REQUEST]"); #endif } /** When bytes have been written, check whether we need to close * the connection. * * @param bytes */ void QDjangoFastCgiConnection::_q_bytesWritten(qint64 bytes) { Q_UNUSED(bytes); if (!m_device->bytesToWrite()) { m_device->close(); emit closed(); } } void QDjangoFastCgiConnection::_q_readyRead() { while (m_device->bytesAvailable()) { // read record header if (m_inputPos < FCGI_HEADER_LEN) { const qint64 length = m_device->read(m_inputBuffer + m_inputPos, FCGI_HEADER_LEN - m_inputPos); if (length < 0) { qWarning("Failed to read header from socket"); m_device->close(); emit closed(); return; } m_inputPos += length; if (m_inputPos < FCGI_HEADER_LEN) return; } // read record body FCGI_Header *header = (FCGI_Header*)m_inputBuffer; const quint16 contentLength = (header->contentLengthB1 << 8) | header->contentLengthB0; const quint16 bodyLength = contentLength + header->paddingLength; const qint64 length = m_device->read(m_inputBuffer + m_inputPos, bodyLength + FCGI_HEADER_LEN - m_inputPos); if (length < 0) { qWarning("Failed to read body from socket"); m_device->close(); emit closed(); return; } m_inputPos += length; if (m_inputPos < FCGI_HEADER_LEN + bodyLength) return; m_inputPos = 0; // process record #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "received"); #endif const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0; char *p = m_inputBuffer + FCGI_HEADER_LEN; switch (header->type) { case FCGI_BEGIN_REQUEST: { #ifdef QDJANGO_DEBUG_FCGI const quint16 role = (p[0] << 8) | p[1]; qDebug("[BEGIN REQUEST]"); qDebug("role: %i", role); qDebug("flags: %i", p[2]); #endif if (m_pendingRequest) { qWarning("Received FCGI_BEGIN_REQUEST inside a request"); m_device->close(); emit closed(); break; } m_pendingRequest = new QDjangoHttpRequest; m_pendingRequestId = requestId; break; } case FCGI_ABORT_REQUEST: m_device->close(); emit closed(); break; case FCGI_PARAMS: #ifdef QDJANGO_DEBUG_FCGI qDebug("[PARAMS]"); #endif if (!m_pendingRequest || requestId != m_pendingRequestId) { qWarning("Received FCGI_PARAMS outside a request"); m_device->close(); emit closed(); break; } while (p < m_inputBuffer + FCGI_HEADER_LEN + contentLength) { quint32 nameLength; quint32 valueLength; if (p[0] >> 7) { nameLength = ((p[0] & 0x7f) << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; p += 4; } else { nameLength = p[0]; p++; } if (p[0] >> 7) { valueLength = ((p[0] & 0x7f) << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; p += 4; } else { valueLength = p[0]; p++; } const QByteArray name(p, nameLength); p += nameLength; const QByteArray value(p, valueLength); p += valueLength; #ifdef QDJANGO_DEBUG_FCGI qDebug() << name << ":" << value; #endif if (name == "PATH_INFO") { m_pendingRequest->d->path = QString::fromUtf8(value); } else if (name == "REQUEST_METHOD") { m_pendingRequest->d->method = QString::fromUtf8(value); } m_pendingRequest->d->meta.insert(QString::fromLatin1(name), QString::fromUtf8(value)); } break; case FCGI_STDIN: #ifdef QDJANGO_DEBUG_FCGI qDebug("[STDIN]"); #endif if (!m_pendingRequest || requestId != m_pendingRequestId) { qWarning("Received FCGI_STDIN outside a request"); m_device->close(); emit closed(); break; } if (contentLength) { m_pendingRequest->d->buffer.append(p, contentLength); } else { QDjangoHttpRequest *request = m_pendingRequest; const quint16 requestId = m_pendingRequestId; m_pendingRequest = 0; m_pendingRequestId = 0; QDjangoHttpResponse *response = m_server->urls()->respond(*request, request->path()); writeResponse(requestId, response); } break; default: qWarning("Unhandled request type %i", header->type); break; } } } /// \endcond class QDjangoFastCgiServerPrivate { public: QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq); QLocalServer *localServer; QTcpServer *tcpServer; QDjangoUrlResolver *urlResolver; private: QDjangoFastCgiServer *q; }; QDjangoFastCgiServerPrivate::QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq) : localServer(0), tcpServer(0), q(qq) { urlResolver = new QDjangoUrlResolver(q); } /** Constructs a new FastCGI server. */ QDjangoFastCgiServer::QDjangoFastCgiServer(QObject *parent) : QObject(parent) { d = new QDjangoFastCgiServerPrivate(this); } /** Destroys the FastCGI server. */ QDjangoFastCgiServer::~QDjangoFastCgiServer() { delete d; } /** Closes the server. The server will no longer listen for * incoming connections. */ void QDjangoFastCgiServer::close() { if (d->localServer) d->localServer->close(); if (d->tcpServer) d->tcpServer->close(); } /** Tells the server to listen for incoming connections on the given * local socket. */ bool QDjangoFastCgiServer::listen(const QString &name) { if (!d->localServer) { bool check; Q_UNUSED(check); d->localServer = new QLocalServer(this); check = connect(d->localServer, SIGNAL(newConnection()), this, SLOT(_q_newLocalConnection())); Q_ASSERT(check); } return d->localServer->listen(name); } /** Tells the server to listen for incoming TCP connections on the given * \a address and \a port. */ bool QDjangoFastCgiServer::listen(const QHostAddress &address, quint16 port) { if (!d->tcpServer) { bool check; Q_UNUSED(check); d->tcpServer = new QTcpServer(this); check = connect(d->tcpServer, SIGNAL(newConnection()), this, SLOT(_q_newTcpConnection())); Q_ASSERT(check); } return d->tcpServer->listen(address, port); } /** Returns the root URL resolver for the server, which dispatches * requests to handlers. */ QDjangoUrlResolver* QDjangoFastCgiServer::urls() const { return d->urlResolver; } void QDjangoFastCgiServer::_q_newLocalConnection() { bool check; Q_UNUSED(check); QLocalSocket *socket; while ((socket = d->localServer->nextPendingConnection()) != 0) { #ifdef QDJANGO_DEBUG_FCGI qDebug("New local connection"); #endif QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this); check = connect(connection, SIGNAL(closed()), connection, SLOT(deleteLater())); Q_ASSERT(check); } } void QDjangoFastCgiServer::_q_newTcpConnection() { bool check; Q_UNUSED(check); QTcpSocket *socket; while ((socket = d->tcpServer->nextPendingConnection()) != 0) { #ifdef QDJANGO_DEBUG_FCGI qDebug("New TCP connection"); #endif QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this); check = connect(connection, SIGNAL(closed()), connection, SLOT(deleteLater())); Q_ASSERT(check); } } <commit_msg>make fcgi server support REQUEST_URI<commit_after>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #include <QDebug> #include <QLocalServer> #include <QLocalSocket> #include <QTcpServer> #include <QTcpSocket> #include <QUrl> #include "QDjangoFastCgiServer.h" #include "QDjangoFastCgiServer_p.h" #include "QDjangoHttpController.h" #include "QDjangoHttpRequest.h" #include "QDjangoHttpRequest_p.h" #include "QDjangoHttpResponse.h" #include "QDjangoHttpResponse_p.h" #include "QDjangoHttpServer.h" #include "QDjangoUrlResolver.h" //#define QDJANGO_DEBUG_FCGI #ifdef QDJANGO_DEBUG_FCGI static void hDebug(FCGI_Header *header, const char *dir) { const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0; const quint16 contentLength = (header->contentLengthB1 << 8) | header->contentLengthB0; qDebug("--- FCGI Record %s ---", dir); qDebug("version: %i", header->version); qDebug("type: %i", header->type); qDebug("requestId: %i", requestId); qDebug("contentLength: %i", contentLength); qDebug("paddingLength: %i", header->paddingLength); } #endif /// \cond QDjangoFastCgiConnection::QDjangoFastCgiConnection(QIODevice *device, QDjangoFastCgiServer *server) : QObject(server), m_device(device), m_inputPos(0), m_pendingRequest(0), m_pendingRequestId(0), m_server(server) { bool check; Q_UNUSED(check); m_device->setParent(this); check = connect(m_device, SIGNAL(disconnected()), this, SIGNAL(closed())); Q_ASSERT(check); check = connect(m_device, SIGNAL(bytesWritten(qint64)), this, SLOT(_q_bytesWritten(qint64))); Q_ASSERT(check); check = connect(m_device, SIGNAL(readyRead()), this, SLOT(_q_readyRead())); Q_ASSERT(check); } QDjangoFastCgiConnection::~QDjangoFastCgiConnection() { if (m_pendingRequest) delete m_pendingRequest; } void QDjangoFastCgiConnection::writeResponse(quint16 requestId, QDjangoHttpResponse *response) { // serialise HTTP response QString httpHeader = QString::fromLatin1("Status: %1 %2\r\n").arg(response->d->statusCode).arg(response->d->reasonPhrase); QList<QPair<QString, QString> >::ConstIterator it = response->d->headers.constBegin(); while (it != response->d->headers.constEnd()) { httpHeader += (*it).first + QLatin1String(": ") + (*it).second + QLatin1String("\r\n"); ++it; } const QByteArray data = httpHeader.toUtf8() + "\r\n" + response->d->body; const char *ptr = data.constData(); FCGI_Header *header = (FCGI_Header*)m_outputBuffer; memset(header, 0, FCGI_HEADER_LEN); header->version = 1; header->requestIdB1 = (requestId >> 8) & 0xff; header->requestIdB0 = (requestId & 0xff); for (qint64 bytesRemaining = data.size(); ; ) { const quint16 contentLength = qMin(bytesRemaining, qint64(32768)); header->type = FCGI_STDOUT; header->contentLengthB1 = (contentLength >> 8) & 0xff; header->contentLengthB0 = (contentLength & 0xff); memcpy(m_outputBuffer + FCGI_HEADER_LEN, ptr, contentLength); m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "sent"); qDebug("[STDOUT]"); #endif if (contentLength > 0) { ptr += contentLength; bytesRemaining -= contentLength; } else { break; } } quint16 contentLength = 8; header->type = FCGI_END_REQUEST; header->contentLengthB1 = (contentLength >> 8) & 0xff; header->contentLengthB0 = (contentLength & 0xff); memset(m_outputBuffer + FCGI_HEADER_LEN, 0, contentLength); m_device->write(m_outputBuffer, FCGI_HEADER_LEN + contentLength); #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "sent"); qDebug("[END REQUEST]"); #endif } /** When bytes have been written, check whether we need to close * the connection. * * @param bytes */ void QDjangoFastCgiConnection::_q_bytesWritten(qint64 bytes) { Q_UNUSED(bytes); if (!m_device->bytesToWrite()) { m_device->close(); emit closed(); } } void QDjangoFastCgiConnection::_q_readyRead() { while (m_device->bytesAvailable()) { // read record header if (m_inputPos < FCGI_HEADER_LEN) { const qint64 length = m_device->read(m_inputBuffer + m_inputPos, FCGI_HEADER_LEN - m_inputPos); if (length < 0) { qWarning("Failed to read header from socket"); m_device->close(); emit closed(); return; } m_inputPos += length; if (m_inputPos < FCGI_HEADER_LEN) return; } // read record body FCGI_Header *header = (FCGI_Header*)m_inputBuffer; const quint16 contentLength = (header->contentLengthB1 << 8) | header->contentLengthB0; const quint16 bodyLength = contentLength + header->paddingLength; const qint64 length = m_device->read(m_inputBuffer + m_inputPos, bodyLength + FCGI_HEADER_LEN - m_inputPos); if (length < 0) { qWarning("Failed to read body from socket"); m_device->close(); emit closed(); return; } m_inputPos += length; if (m_inputPos < FCGI_HEADER_LEN + bodyLength) return; m_inputPos = 0; // process record #ifdef QDJANGO_DEBUG_FCGI hDebug(header, "received"); #endif const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0; char *p = m_inputBuffer + FCGI_HEADER_LEN; switch (header->type) { case FCGI_BEGIN_REQUEST: { #ifdef QDJANGO_DEBUG_FCGI const quint16 role = (p[0] << 8) | p[1]; qDebug("[BEGIN REQUEST]"); qDebug("role: %i", role); qDebug("flags: %i", p[2]); #endif if (m_pendingRequest) { qWarning("Received FCGI_BEGIN_REQUEST inside a request"); m_device->close(); emit closed(); break; } m_pendingRequest = new QDjangoHttpRequest; m_pendingRequestId = requestId; break; } case FCGI_ABORT_REQUEST: m_device->close(); emit closed(); break; case FCGI_PARAMS: #ifdef QDJANGO_DEBUG_FCGI qDebug("[PARAMS]"); #endif if (!m_pendingRequest || requestId != m_pendingRequestId) { qWarning("Received FCGI_PARAMS outside a request"); m_device->close(); emit closed(); break; } while (p < m_inputBuffer + FCGI_HEADER_LEN + contentLength) { quint32 nameLength; quint32 valueLength; if (p[0] >> 7) { nameLength = ((p[0] & 0x7f) << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; p += 4; } else { nameLength = p[0]; p++; } if (p[0] >> 7) { valueLength = ((p[0] & 0x7f) << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; p += 4; } else { valueLength = p[0]; p++; } const QByteArray name(p, nameLength); p += nameLength; const QByteArray value(p, valueLength); p += valueLength; #ifdef QDJANGO_DEBUG_FCGI qDebug() << name << ":" << value; #endif if (name == "PATH_INFO") { m_pendingRequest->d->path = QString::fromUtf8(value); } else if (name == "REQUEST_URI") { m_pendingRequest->d->path = QUrl(QString::fromUtf8(value)).path(); } else if (name == "REQUEST_METHOD") { m_pendingRequest->d->method = QString::fromUtf8(value); } m_pendingRequest->d->meta.insert(QString::fromLatin1(name), QString::fromUtf8(value)); } break; case FCGI_STDIN: #ifdef QDJANGO_DEBUG_FCGI qDebug("[STDIN]"); #endif if (!m_pendingRequest || requestId != m_pendingRequestId) { qWarning("Received FCGI_STDIN outside a request"); m_device->close(); emit closed(); break; } if (contentLength) { m_pendingRequest->d->buffer.append(p, contentLength); } else { QDjangoHttpRequest *request = m_pendingRequest; const quint16 requestId = m_pendingRequestId; m_pendingRequest = 0; m_pendingRequestId = 0; QDjangoHttpResponse *response = m_server->urls()->respond(*request, request->path()); writeResponse(requestId, response); } break; default: qWarning("Unhandled request type %i", header->type); break; } } } /// \endcond class QDjangoFastCgiServerPrivate { public: QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq); QLocalServer *localServer; QTcpServer *tcpServer; QDjangoUrlResolver *urlResolver; private: QDjangoFastCgiServer *q; }; QDjangoFastCgiServerPrivate::QDjangoFastCgiServerPrivate(QDjangoFastCgiServer *qq) : localServer(0), tcpServer(0), q(qq) { urlResolver = new QDjangoUrlResolver(q); } /** Constructs a new FastCGI server. */ QDjangoFastCgiServer::QDjangoFastCgiServer(QObject *parent) : QObject(parent) { d = new QDjangoFastCgiServerPrivate(this); } /** Destroys the FastCGI server. */ QDjangoFastCgiServer::~QDjangoFastCgiServer() { delete d; } /** Closes the server. The server will no longer listen for * incoming connections. */ void QDjangoFastCgiServer::close() { if (d->localServer) d->localServer->close(); if (d->tcpServer) d->tcpServer->close(); } /** Tells the server to listen for incoming connections on the given * local socket. */ bool QDjangoFastCgiServer::listen(const QString &name) { if (!d->localServer) { bool check; Q_UNUSED(check); d->localServer = new QLocalServer(this); check = connect(d->localServer, SIGNAL(newConnection()), this, SLOT(_q_newLocalConnection())); Q_ASSERT(check); } return d->localServer->listen(name); } /** Tells the server to listen for incoming TCP connections on the given * \a address and \a port. */ bool QDjangoFastCgiServer::listen(const QHostAddress &address, quint16 port) { if (!d->tcpServer) { bool check; Q_UNUSED(check); d->tcpServer = new QTcpServer(this); check = connect(d->tcpServer, SIGNAL(newConnection()), this, SLOT(_q_newTcpConnection())); Q_ASSERT(check); } return d->tcpServer->listen(address, port); } /** Returns the root URL resolver for the server, which dispatches * requests to handlers. */ QDjangoUrlResolver* QDjangoFastCgiServer::urls() const { return d->urlResolver; } void QDjangoFastCgiServer::_q_newLocalConnection() { bool check; Q_UNUSED(check); QLocalSocket *socket; while ((socket = d->localServer->nextPendingConnection()) != 0) { #ifdef QDJANGO_DEBUG_FCGI qDebug("New local connection"); #endif QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this); check = connect(connection, SIGNAL(closed()), connection, SLOT(deleteLater())); Q_ASSERT(check); } } void QDjangoFastCgiServer::_q_newTcpConnection() { bool check; Q_UNUSED(check); QTcpSocket *socket; while ((socket = d->tcpServer->nextPendingConnection()) != 0) { #ifdef QDJANGO_DEBUG_FCGI qDebug("New TCP connection"); #endif QDjangoFastCgiConnection *connection = new QDjangoFastCgiConnection(socket, this); check = connect(connection, SIGNAL(closed()), connection, SLOT(deleteLater())); Q_ASSERT(check); } } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/qt/widgets/properties/syntaxhighlighter.h> #include <inviwo/core/util/settings/systemsettings.h> #include <inviwo/core/common/inviwomodule.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/settings/systemsettings.h> #include <warn/push> #include <warn/ignore/all> #include <QTextDocument> #include <QTextBlock> #include <warn/pop> static const char* python_keywords[] = { "\\band\\b", "\\bas\\b", "\\bassert\\b", "\\bbreak\\b", "\\bclass\\b", "\\bcontinue\\b", "\\bdef\\b", "\\bdel\\b", "\\belif\\b", "\\belse\\b", "\\bexcept\\b", "\\bexec\\b", "\\bfinally\\b", "\\bfor\\b", "\\bfrom\\b", "\\bglobal\\b", "\\bif\\b", "\\bimport\\b", "\\bin\\b", "\\bis\\b", "\\blambda\\b", "\\bnot\\b", "\\bor\\b", "\\bpass\\b", "\\bprint\\b", "\\braise\\b", "\\breturn\\b", "\\btry\\b", "\\bwhile\\b", "\\bwith\\b", "\\byield\\b"}; namespace inviwo { class PythonCommentFormater : public SyntaxFormater { public: PythonCommentFormater(const QTextCharFormat& format) : format_(format){} virtual Result eval(const QString& text, const int& previousBlockState) override { Result res; res.format = &format_; auto index = text.indexOf('#'); if (index != -1) { res.start.push_back(index); res.length.push_back(text.size() - index); return res; } return res; } private: QTextCharFormat format_; }; class PythonKeywordFormater : public SyntaxFormater { public: virtual Result eval(const QString& text, const int& previousBlockState) override { Result result; result.format = &format_; std::vector<QRegExp>::iterator reg; for (reg = regexps_.begin(); reg != regexps_.end(); ++reg) { int pos = 0; while ((pos = reg->indexIn(text, pos)) != -1) { result.start.push_back(pos); pos += std::max(1, reg->matchedLength()); result.length.push_back(reg->matchedLength()); } } return result; } PythonKeywordFormater(const QTextCharFormat& format, const char** keywords) : format_(format) { int i = -1; while (keywords[++i]) regexps_.push_back(QRegExp(keywords[i])); } private: QTextCharFormat format_; std::vector<QRegExp> regexps_; }; static inline QColor ivec4toQtColor(const ivec4& i) { return QColor(i.r, i.g, i.b, i.a); } template <> void SyntaxHighligther::loadConfig<Python>() { auto sysSettings = InviwoApplication::getPtr()->getSettingsByType<SystemSettings>(); QColor textColor = ivec4toQtColor(sysSettings->pyTextColor_.get()); QColor bgColor = ivec4toQtColor(sysSettings->pyBGColor_.get()); defaultFormat_.setBackground(bgColor); defaultFormat_.setForeground(textColor); QTextCharFormat typeformat, commentformat; typeformat.setBackground(bgColor); typeformat.setForeground(ivec4toQtColor(sysSettings->pyTypeColor_.get())); commentformat.setBackground(bgColor); commentformat.setForeground(ivec4toQtColor(sysSettings->pyCommentsColor_.get())); if (formaters_.empty()) sysSettings->pythonSyntax_.onChange(this, &SyntaxHighligther::loadConfig<Python>); else { while (!formaters_.empty()) { delete formaters_.back(); formaters_.pop_back(); } } formaters_.push_back(new PythonKeywordFormater(typeformat, python_keywords)); formaters_.push_back(new PythonCommentFormater(commentformat)); } } // namespace <commit_msg>Qt: PythonHighlighter: Using vector instead of char* array to prevent crashes, closes inviwo/inviwo-dev#1289<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/qt/widgets/properties/syntaxhighlighter.h> #include <inviwo/core/util/settings/systemsettings.h> #include <inviwo/core/common/inviwomodule.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/settings/systemsettings.h> #include <warn/push> #include <warn/ignore/all> #include <QTextDocument> #include <QTextBlock> #include <warn/pop> static const std::vector<std::string> python_keywords = { "\\band\\b", "\\bas\\b", "\\bassert\\b", "\\bbreak\\b", "\\bclass\\b", "\\bcontinue\\b", "\\bdef\\b", "\\bdel\\b", "\\belif\\b", "\\belse\\b", "\\bexcept\\b", "\\bexec\\b", "\\bfinally\\b", "\\bfor\\b", "\\bfrom\\b", "\\bglobal\\b", "\\bif\\b", "\\bimport\\b", "\\bin\\b", "\\bis\\b", "\\blambda\\b", "\\bnot\\b", "\\bor\\b", "\\bpass\\b", "\\bprint\\b", "\\braise\\b", "\\breturn\\b", "\\btry\\b", "\\bwhile\\b", "\\bwith\\b", "\\byield\\b"}; namespace inviwo { class PythonCommentFormater : public SyntaxFormater { public: PythonCommentFormater(const QTextCharFormat& format) : format_(format){} virtual Result eval(const QString& text, const int& previousBlockState) override { Result res; res.format = &format_; auto index = text.indexOf('#'); if (index != -1) { res.start.push_back(index); res.length.push_back(text.size() - index); return res; } return res; } private: QTextCharFormat format_; }; class PythonKeywordFormater : public SyntaxFormater { public: virtual Result eval(const QString& text, const int& previousBlockState) override { Result result; result.format = &format_; std::vector<QRegExp>::iterator reg; for (reg = regexps_.begin(); reg != regexps_.end(); ++reg) { int pos = 0; while ((pos = reg->indexIn(text, pos)) != -1) { result.start.push_back(pos); pos += std::max(1, reg->matchedLength()); result.length.push_back(reg->matchedLength()); } } return result; } PythonKeywordFormater(const QTextCharFormat& format, const std::vector<std::string> &keywords) : format_(format) { int i = -1; for (const auto &key : keywords) { regexps_.push_back(QRegExp(key.c_str())); } } private: QTextCharFormat format_; std::vector<QRegExp> regexps_; }; static inline QColor ivec4toQtColor(const ivec4& i) { return QColor(i.r, i.g, i.b, i.a); } template <> void SyntaxHighligther::loadConfig<Python>() { auto sysSettings = InviwoApplication::getPtr()->getSettingsByType<SystemSettings>(); QColor textColor = ivec4toQtColor(sysSettings->pyTextColor_.get()); QColor bgColor = ivec4toQtColor(sysSettings->pyBGColor_.get()); defaultFormat_.setBackground(bgColor); defaultFormat_.setForeground(textColor); QTextCharFormat typeformat, commentformat; typeformat.setBackground(bgColor); typeformat.setForeground(ivec4toQtColor(sysSettings->pyTypeColor_.get())); commentformat.setBackground(bgColor); commentformat.setForeground(ivec4toQtColor(sysSettings->pyCommentsColor_.get())); if (formaters_.empty()) sysSettings->pythonSyntax_.onChange(this, &SyntaxHighligther::loadConfig<Python>); else { while (!formaters_.empty()) { delete formaters_.back(); formaters_.pop_back(); } } formaters_.push_back(new PythonKeywordFormater(typeformat, python_keywords)); formaters_.push_back(new PythonCommentFormater(commentformat)); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2011 Seiya Tokui <[email protected]>. All Rights Reserved. // This source code is distributed under MIT License in LICENSE file. #ifndef ELOG_ELOG_HPP_ #define ELOG_ELOG_HPP_ #include <iostream> #include <sstream> #include <stdexcept> #include <type_traits> #include <utility> #ifdef _WIN32 # include <windows.h> #else # include <sys/time.h> #endif namespace LOG { // utility template<typename T, typename U = void> struct enable_if_exist { typedef U type; }; template<typename T> struct identity { typedef T type; }; template<typename T, typename enable_if_exist<typename T::value_type, int>::type = 0, typename enable_if_exist<typename T::iterator, int>::type = 0> std::true_type is_range_fn(int); template<typename T, typename std::enable_if<std::is_array<T>::value, int>::type = 0> std::true_type is_range_fn(int); template<typename> std::false_type is_range_fn(...); template<typename T> struct is_range : identity<decltype(is_range_fn<T>(0))>::type {}; template<typename T, typename enable_if_exist<typename T::first_type>::type = 0, typename enable_if_exist<typename T::second_type>::type = 0> std::true_type is_pair_fn(int); template<typename T> std::false_type is_pair_fn(...); template<typename T> struct is_pair : identity<decltype(is_pair_fn<T>(0))>::type {}; // time inline double gettime_sec() { #ifdef _WIN32 LARGE_INTEGER t, f; QueryPerformanceCounter(&t); QueryPerformanceFrequency(&f); return t.QuadPart * 1.0 / f.QuadPart; #else timeval tv; gettimeofday(&tv, 0); return tv.tv_sec + tv.tv_usec * 1e-6; #endif } template<typename Stream> void pritty_print_time(Stream& stream, double sec) { long long min = sec / 60; sec -= min * 60; long long hour = min / 60; min -= hour * 60; long long day = hour / 24; hour -= day * 24; if (min > 0) { if (hour > 0) { if (day > 0) stream << day << "d "; stream << hour << "h "; } stream << min << "m "; } stream << sec << "s"; } // print value to output stream template<typename T, typename Stream> void pritty_print_internal(const T& t, Stream& stream, ...) { stream << t; } template<typename T, typename Stream, typename std::enable_if<is_pair<T>::value, int>::type = 0> void pritty_print_internal(const T& pair, Stream& stream, int) { stream << '('; pritty_print_internal(pair.first, stream, 0); stream << ", "; pritty_print_internal(pair.second, stream, 0); stream << ')'; } template<typename T, typename Stream, typename std::enable_if<is_range<T>::value, int>::type = 0> void pritty_print_internal(const T& range, Stream& stream, int) { stream << '['; bool is_tail = false; for (const auto& elem : range) { if (is_tail) stream << ", "; is_tail = true; pritty_print_internal(elem, stream, 0); } stream << ']'; } template<typename Stream> void pritty_print_internal(signed char t, Stream& stream, int) { stream << static_cast<int>(t); } template<typename Stream> void pritty_print_internal(unsigned char t, Stream& stream, int) { stream << static_cast<unsigned int>(t); } template<typename T, typename Stream> void pritty_print(const T& t, Stream& stream) { pritty_print_internal(t, stream, 0); } // argument list to stream template<typename Stream> Stream& print_arguments(Stream& stream) { return stream; } template<typename Stream, typename T, typename ... Args> Stream& print_arguments(Stream& stream, const T& t, Args... args) { stream << t; return print_arguments(stream, args...); } // logger struct logger_base { virtual ~logger_base() {}; virtual void write(const std::string& message) const = 0; }; // TODO: Support multi-thread use struct stream_logger : logger_base { stream_logger() : os_(&std::clog) {} void set_stream(std::ostream& os) { os_ = &os; } virtual void write(const std::string& message) const { (*os_) << message; } private: std::ostream* os_; }; enum avoid_odr { AVOID_ODR }; template<typename T, avoid_odr = AVOID_ODR> struct static_holder { static T value; }; template<typename T, avoid_odr A> T static_holder<T, A>::value; struct global_logger_holder { global_logger_holder() : logger(&static_holder<stream_logger>::value) {} logger_base* logger; }; inline logger_base& get_logger() { return *static_holder<global_logger_holder>::value.logger; } inline void set_stream(std::ostream& os) { static_holder<stream_logger>::value.set_stream(os); } // message construction struct message_builder { template<typename T> void operator()(const T& t) { pritty_print(t, oss_); } std::string get() const { return oss_.str(); } private: std::ostringstream oss_; }; struct log_emitter { log_emitter() : logger_(get_logger()) {} explicit log_emitter(logger_base& logger) : logger_(logger) {} template<typename T> log_emitter& operator<<(const T& t) { message_builder_(t); return *this; } log_emitter& self() { return *this; } void emit() const { logger_.write(message_builder_.get()); } private: logger_base& logger_; message_builder message_builder_; }; struct log_emission_trigger { void operator&(const log_emitter& emitter) const { emitter.emit(); } }; struct check_error : std::exception {}; struct check_emission_trigger { void operator&(const log_emitter& emitter) const { emitter.emit(); throw check_error(); } }; // benchmark struct benchmark { benchmark() : logger_(get_logger()), start_sec_(gettime_sec()), done_(false) {} explicit benchmark(logger_base& logger) : logger_(logger), start_sec_(gettime_sec()), done_(false) {} explicit operator bool() const { return false; } ~benchmark() { if (!done_) push_message(); } template<typename T> benchmark& operator<<(const T& t) { title_builder_ << t; return *this; } double gettime() const { return gettime_sec() - start_sec_; } void push_message() { done_ = true; const auto duration = gettime_sec() - start_sec_; log_emitter emitter(logger_); emitter << title_builder_.get() << ": " << duration << " sec"; if (duration >= 60) { emitter << " ("; pritty_print_time(emitter, duration); emitter << ")"; } emitter.emit(); } private: logger_base& logger_; double start_sec_; message_builder title_builder_; bool done_; }; } // namespace LOG #define LOG() ::LOG::log_emission_trigger() & ::LOG::log_emitter().self() #define CHECK(cond) \ (cond) ? (void)0 : \ ::LOG::check_emission_trigger() & ::LOG::log_emitter().self(); #define BENCHMARK(varname, ...) \ if (auto varname = ::LOG::benchmark()); \ else if (!&::LOG::print_arguments(varname, __VA_ARGS__)); else #endif // ELOG_ELOG_HPP_ <commit_msg>fix coding rule<commit_after>// Copyright (c) 2011 Seiya Tokui <[email protected]>. All Rights Reserved. // This source code is distributed under MIT License in LICENSE file. #ifndef ELOG_ELOG_HPP_ #define ELOG_ELOG_HPP_ #include <iostream> #include <sstream> #include <stdexcept> #include <type_traits> #include <utility> #ifdef _WIN32 # include <windows.h> #else # include <sys/time.h> #endif namespace LOG { // utility template<typename T, typename U = void> struct enable_if_exist { typedef U type; }; template<typename T> struct identity { typedef T type; }; template<typename T, typename enable_if_exist<typename T::value_type, int>::type = 0, typename enable_if_exist<typename T::iterator, int>::type = 0> std::true_type is_range_fn(int); template<typename T, typename std::enable_if<std::is_array<T>::value, int>::type = 0> std::true_type is_range_fn(int); template<typename> std::false_type is_range_fn(...); template<typename T> struct is_range : identity<decltype(is_range_fn<T>(0))>::type {}; template<typename T, typename enable_if_exist<typename T::first_type>::type = 0, typename enable_if_exist<typename T::second_type>::type = 0> std::true_type is_pair_fn(int); template<typename T> std::false_type is_pair_fn(...); template<typename T> struct is_pair : identity<decltype(is_pair_fn<T>(0))>::type {}; // time inline double gettime_sec() { #ifdef _WIN32 LARGE_INTEGER t, f; QueryPerformanceCounter(&t); QueryPerformanceFrequency(&f); return t.QuadPart * 1.0 / f.QuadPart; #else timeval tv; gettimeofday(&tv, 0); return tv.tv_sec + tv.tv_usec * 1e-6; #endif } template<typename Stream> void pritty_print_time(Stream& stream, double sec) { long long min = sec / 60; sec -= min * 60; long long hour = min / 60; min -= hour * 60; long long day = hour / 24; hour -= day * 24; if (min > 0) { if (hour > 0) { if (day > 0) stream << day << "d "; stream << hour << "h "; } stream << min << "m "; } stream << sec << "s"; } // print value to output stream template<typename T, typename Stream> void pritty_print_internal(const T& t, Stream& stream, ...) { stream << t; } template<typename T, typename Stream, typename std::enable_if<is_pair<T>::value, int>::type = 0> void pritty_print_internal(const T& pair, Stream& stream, int) { stream << '('; pritty_print_internal(pair.first, stream, 0); stream << ", "; pritty_print_internal(pair.second, stream, 0); stream << ')'; } template<typename T, typename Stream, typename std::enable_if<is_range<T>::value, int>::type = 0> void pritty_print_internal(const T& range, Stream& stream, int) { stream << '['; bool is_tail = false; for (const auto& elem : range) { if (is_tail) stream << ", "; is_tail = true; pritty_print_internal(elem, stream, 0); } stream << ']'; } template<typename Stream> void pritty_print_internal(signed char t, Stream& stream, int) { stream << static_cast<int>(t); } template<typename Stream> void pritty_print_internal(unsigned char t, Stream& stream, int) { stream << static_cast<unsigned int>(t); } template<typename T, typename Stream> void pritty_print(const T& t, Stream& stream) { pritty_print_internal(t, stream, 0); } // argument list to stream template<typename Stream> Stream& print_arguments(Stream& stream) { return stream; } template<typename Stream, typename T, typename ... Args> Stream& print_arguments(Stream& stream, const T& t, Args... args) { stream << t; return print_arguments(stream, args...); } // logger struct logger_base { virtual ~logger_base() {}; virtual void write(const std::string& message) const = 0; }; // TODO: Support multi-thread use struct stream_logger : logger_base { stream_logger() : os_(&std::clog) {} void set_stream(std::ostream& os) { os_ = &os; } virtual void write(const std::string& message) const { (*os_) << message; } private: std::ostream* os_; }; enum avoid_odr { AVOID_ODR }; template<typename T, avoid_odr = AVOID_ODR> struct static_holder { static T value; }; template<typename T, avoid_odr A> T static_holder<T, A>::value; struct global_logger_holder { global_logger_holder() : logger(&static_holder<stream_logger>::value) {} logger_base* logger; }; inline logger_base& get_logger() { return *static_holder<global_logger_holder>::value.logger; } inline void set_stream(std::ostream& os) { static_holder<stream_logger>::value.set_stream(os); } // message construction struct message_builder { template<typename T> void operator()(const T& t) { pritty_print(t, oss_); } std::string get() const { return oss_.str(); } private: std::ostringstream oss_; }; struct log_emitter { log_emitter() : logger_(get_logger()) {} explicit log_emitter(logger_base& logger) : logger_(logger) {} template<typename T> log_emitter& operator<<(const T& t) { message_builder_(t); return *this; } log_emitter& self() { return *this; } void emit() const { logger_.write(message_builder_.get()); } private: logger_base& logger_; message_builder message_builder_; }; struct log_emission_trigger { void operator&(const log_emitter& emitter) const { emitter.emit(); } }; struct check_error : std::exception {}; struct check_emission_trigger { void operator&(const log_emitter& emitter) const { emitter.emit(); throw check_error(); } }; // benchmark struct benchmark { benchmark() : logger_(get_logger()), start_sec_(gettime_sec()), done_(false) {} explicit benchmark(logger_base& logger) : logger_(logger), start_sec_(gettime_sec()), done_(false) {} explicit operator bool() const { return false; } ~benchmark() { if (!done_) push_message(); } template<typename T> benchmark& operator<<(const T& t) { title_builder_ << t; return *this; } double gettime() const { return gettime_sec() - start_sec_; } void push_message() { done_ = true; const auto duration = gettime_sec() - start_sec_; log_emitter emitter(logger_); emitter << title_builder_.get() << ": " << duration << " sec"; if (duration >= 60) { emitter << " ("; pritty_print_time(emitter, duration); emitter << ")"; } emitter.emit(); } private: logger_base& logger_; double start_sec_; message_builder title_builder_; bool done_; }; } // namespace LOG #define LOG() ::LOG::log_emission_trigger() & ::LOG::log_emitter().self() #define CHECK(cond) \ (cond) ? (void)0 : \ ::LOG::check_emission_trigger() & ::LOG::log_emitter().self(); #define BENCHMARK(varname, ...) \ if (auto varname = ::LOG::benchmark()); \ else if (!&::LOG::print_arguments(varname, __VA_ARGS__)); \ else #endif // ELOG_ELOG_HPP_ <|endoftext|>