text
stringlengths
54
60.6k
<commit_before>/** * Created by Liam Huang (Liam0205) on 2018/10/11. */ #ifndef QUEUE_BLOCK_QUEUE_HPP_ #define QUEUE_BLOCK_QUEUE_HPP_ #include <queue> #include <mutex> #include <condition_variable> template <typename T> class BlockQueue { public: using value_type = T; using container_type = std::queue<value_type>; using size_type = typename container_type::size_type; private: size_type capacity_ = 0; container_type container_; mutable std::mutex mutex_; mutable std::condition_variable not_empty_; mutable std::condition_variable not_full_; public: BlockQueue() = delete; BlockQueue(const size_type capacity) : capacity_(capacity) {} BlockQueue(const BlockQueue&) = default; BlockQueue(BlockQueue&&) = default; BlockQueue& operator=(const BlockQueue&) = default; BlockQueue& operator=(BlockQueue&&) = default; private: bool empty() const { return container_.empty(); } bool full() const { return not(container_.size() < capacity_); } public: void put(const value_type& item) { std::unqiue_lock<std::mutex> lock(mutex_); while (full()) { not_full_.wait(lock); } container_.push(item); not_empty_.notify_one(); } void take(value_type& out) { std::unique_lock<std::mutex> lock(mutex_); while (empty()) { not_empty_.wait(lock); } out = container_.front(); container_.pop(); not_full_.notify_one(); } }; #endif // QUEUE_BLOCK_QUEUE_HPP_ <commit_msg>[09_queue] concurrency, block_queue, wait_for, done.<commit_after>/** * Created by Liam Huang (Liam0205) on 2018/10/11. */ #ifndef QUEUE_BLOCK_QUEUE_HPP_ #define QUEUE_BLOCK_QUEUE_HPP_ #include <queue> #include <mutex> #include <condition_variable> template <typename T> class BlockQueue { public: using value_type = T; using container_type = std::queue<value_type>; using size_type = typename container_type::size_type; private: size_type capacity_ = 0; container_type container_; mutable std::mutex mutex_; mutable std::condition_variable not_empty_; mutable std::condition_variable not_full_; public: BlockQueue() = delete; BlockQueue(const size_type capacity) : capacity_(capacity) {} BlockQueue(const BlockQueue&) = default; BlockQueue(BlockQueue&&) = default; BlockQueue& operator=(const BlockQueue&) = default; BlockQueue& operator=(BlockQueue&&) = default; private: bool empty() const { return container_.empty(); } bool full() const { return not(container_.size() < capacity_); } public: void put(const value_type& item) { std::unqiue_lock<std::mutex> lock(mutex_); while (full()) { not_full_.wait(lock); } container_.push(item); not_empty_.notify_one(); } void take(value_type& out) { std::unique_lock<std::mutex> lock(mutex_); while (empty()) { not_empty_.wait(lock); } out = container_.front(); container_.pop(); not_full_.notify_one(); } template <typename Duration> bool put_for(const value_type& item, const Duration& d) { std::unqiue_lock<std::mutex> lock(mutex_); if (not_full_.wait_for(lock, d, [&](){ return not full(); })) { container_.push(item); not_empty_.notify_one(); return true; } else { return false; } } template <typename Duration> bool take_for(const Duration& d, value_type& out) { std::unique_lock<std::mutex> lock(mutex_); if (not_empty_.wait_for(lock, d, [&](){ return not empty(); })) { out = container_.front(); container_.pop(); not_full_.notify_one(); return true; } else { return false; } } }; #endif // QUEUE_BLOCK_QUEUE_HPP_ <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkImageCast.h> #include <mitkTensorImage.h> #include <mitkOdfImage.h> #include <mitkIOUtil.h> #include <itkDiffusionTensor3D.h> #include <mitkTestingMacros.h> #include <itkDiffusionTensor3DReconstructionImageFilter.h> #include <itkDiffusionTensor3D.h> #include <itkDiffusionQballReconstructionImageFilter.h> #include <itkAnalyticalDiffusionQballReconstructionImageFilter.h> #include <mitkImage.h> #include <mitkDiffusionPropertyHelper.h> int mitkImageReconstructionTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkImageReconstructionTest"); MITK_TEST_CONDITION_REQUIRED(argc>1,"check for input data") try { mitk::Image::Pointer dwi = mitk::IOUtil::Load<mitk::Image>(argv[1]); itk::VectorImage<short,3>::Pointer itkVectorImagePointer = itk::VectorImage<short,3>::New(); mitk::CastToItkImage(dwi, itkVectorImagePointer); float b_value = mitk::DiffusionPropertyHelper::GetReferenceBValue( dwi ); mitk::DiffusionPropertyHelper::GradientDirectionsContainerType::Pointer gradients = mitk::DiffusionPropertyHelper::GetGradientContainer(dwi); { MITK_INFO << "Tensor reconstruction " << argv[2]; mitk::TensorImage::Pointer tensorImage = mitk::IOUtil::Load<mitk::TensorImage>(argv[2]); typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, float > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->Update(); mitk::TensorImage::Pointer testImage = mitk::TensorImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *tensorImage, 0.0001, true), "tensor reconstruction test."); } { MITK_INFO << "Numerical Q-ball reconstruction " << argv[3]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[3]); typedef itk::DiffusionQballReconstructionImageFilter<short, short, float, ODF_SAMPLING_SIZE> QballReconstructionImageFilterType; QballReconstructionImageFilterType::Pointer filter = QballReconstructionImageFilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "Numerical Q-ball reconstruction test."); } { MITK_INFO << "Standard Q-ball reconstruction " << argv[4]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[4]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "Standard Q-ball reconstruction test."); } { MITK_INFO << "CSA Q-ball reconstruction " << argv[5]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[5]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "CSA Q-ball reconstruction test."); } { MITK_INFO << "ADC profile reconstruction " << argv[6]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[6]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_ADC_ONLY); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "ADC profile reconstruction test."); } { MITK_INFO << "Raw signal modeling " << argv[7]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[7]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_RAW_SIGNAL); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.1, true), "Raw signal modeling test."); } } catch (const itk::ExceptionObject& e) { MITK_INFO << e; return EXIT_FAILURE; } catch (const std::exception& e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_TEST_END(); } <commit_msg>Fix exception output<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkImageCast.h> #include <mitkTensorImage.h> #include <mitkOdfImage.h> #include <mitkIOUtil.h> #include <itkDiffusionTensor3D.h> #include <mitkTestingMacros.h> #include <itkDiffusionTensor3DReconstructionImageFilter.h> #include <itkDiffusionTensor3D.h> #include <itkDiffusionQballReconstructionImageFilter.h> #include <itkAnalyticalDiffusionQballReconstructionImageFilter.h> #include <mitkImage.h> #include <mitkDiffusionPropertyHelper.h> int mitkImageReconstructionTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkImageReconstructionTest"); MITK_TEST_CONDITION_REQUIRED(argc>1,"check for input data") try { mitk::Image::Pointer dwi = mitk::IOUtil::Load<mitk::Image>(argv[1]); itk::VectorImage<short,3>::Pointer itkVectorImagePointer = itk::VectorImage<short,3>::New(); mitk::CastToItkImage(dwi, itkVectorImagePointer); float b_value = mitk::DiffusionPropertyHelper::GetReferenceBValue( dwi ); mitk::DiffusionPropertyHelper::GradientDirectionsContainerType::Pointer gradients = mitk::DiffusionPropertyHelper::GetGradientContainer(dwi); { MITK_INFO << "Tensor reconstruction " << argv[2]; mitk::TensorImage::Pointer tensorImage = mitk::IOUtil::Load<mitk::TensorImage>(argv[2]); typedef itk::DiffusionTensor3DReconstructionImageFilter< short, short, float > TensorReconstructionImageFilterType; TensorReconstructionImageFilterType::Pointer filter = TensorReconstructionImageFilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->Update(); mitk::TensorImage::Pointer testImage = mitk::TensorImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *tensorImage, 0.0001, true), "tensor reconstruction test."); } { MITK_INFO << "Numerical Q-ball reconstruction " << argv[3]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[3]); typedef itk::DiffusionQballReconstructionImageFilter<short, short, float, ODF_SAMPLING_SIZE> QballReconstructionImageFilterType; QballReconstructionImageFilterType::Pointer filter = QballReconstructionImageFilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetNormalizationMethod(QballReconstructionImageFilterType::QBR_STANDARD); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "Numerical Q-ball reconstruction test."); } { MITK_INFO << "Standard Q-ball reconstruction " << argv[4]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[4]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_STANDARD); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "Standard Q-ball reconstruction test."); } { MITK_INFO << "CSA Q-ball reconstruction " << argv[5]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[5]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_SOLID_ANGLE); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "CSA Q-ball reconstruction test."); } { MITK_INFO << "ADC profile reconstruction " << argv[6]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[6]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_ADC_ONLY); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.0001, true), "ADC profile reconstruction test."); } { MITK_INFO << "Raw signal modeling " << argv[7]; mitk::OdfImage::Pointer odfImage = mitk::IOUtil::Load<mitk::OdfImage>(argv[7]); typedef itk::AnalyticalDiffusionQballReconstructionImageFilter<short,short,float,4,ODF_SAMPLING_SIZE> FilterType; FilterType::Pointer filter = FilterType::New(); filter->SetBValue( b_value ); filter->SetGradientImage( gradients, itkVectorImagePointer ); filter->SetLambda(0.006); filter->SetNormalizationMethod(FilterType::QBAR_RAW_SIGNAL); filter->Update(); mitk::OdfImage::Pointer testImage = mitk::OdfImage::New(); testImage->InitializeByItk( filter->GetOutput() ); testImage->SetVolume( filter->GetOutput()->GetBufferPointer() ); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(*testImage, *odfImage, 0.1, true), "Raw signal modeling test."); } } catch (const itk::ExceptionObject& e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (const std::exception& e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_TEST_END(); } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2016 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 <string> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "joynr/serializer/Serializer.h" #include "joynr/InterfaceRegistrar.h" #include "joynr/Request.h" #include "joynr/vehicle/IGps.h" #include "joynr/vehicle/GpsRequestInterpreter.h" #include "joynr/tests/testRequestInterpreter.h" #include "joynr/IRequestInterpreter.h" #include "tests/utils/MockObjects.h" #include "utils/MockCallback.h" #include "joynr/exceptions/MethodInvocationException.h" using ::testing::A; using ::testing::_; MATCHER_P(providerRuntimeException, msg, "") { return arg.getTypeName() == joynr::exceptions::ProviderRuntimeException::TYPE_NAME() && arg.getMessage() == msg; } MATCHER_P2(methodInvocationExceptionWithProviderVersion, msg, expectedProviderVersion, "") { const joynr::exceptions::MethodInvocationException *methodInvocationExceptionPtr; return arg.getTypeName() == joynr::exceptions::MethodInvocationException::TYPE_NAME() && arg.getMessage() == msg && (methodInvocationExceptionPtr = dynamic_cast<const joynr::exceptions::MethodInvocationException*>(&arg)) != nullptr && methodInvocationExceptionPtr->getProviderVersion() == expectedProviderVersion; } using namespace joynr; class RequestInterpreterTest : public ::testing::Test { public: RequestInterpreterTest() : gpsInterfaceName(vehicle::IGpsBase::INTERFACE_NAME()) { } protected: std::string gpsInterfaceName; }; // we need to serialize, then deserialize the request to get it in a state which can be passed to a request interpreter template <typename... Ts> joynr::Request initRequest(std::string methodName, std::vector<std::string> paramDataTypes, Ts... paramValues) { Request outgoingRequest; outgoingRequest.setMethodName(methodName); outgoingRequest.setParamDatatypes(std::move(paramDataTypes)); outgoingRequest.setParams(std::move(paramValues)...); using OutputStream = muesli::StringOStream; OutputStream ostream; muesli::JsonOutputArchive<OutputStream> oarchive(ostream); oarchive(outgoingRequest); joynr::Request incomingRequest; using InputStream = muesli::StringIStream; InputStream istream(ostream.getString()); auto iarchive = std::make_shared<muesli::JsonInputArchive<InputStream>>(istream); (*iarchive)(incomingRequest); return incomingRequest; } TEST_F(RequestInterpreterTest, execute_callsMethodOnRequestCallerWithMapParameter) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, mapParameters(A<const types::TestTypes::TStringKeyMap&>(), A<std::function<void(const types::TestTypes::TStringKeyMap&)>>(), A<std::function<void(const exceptions::JoynrException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "mapParameters"; types::TestTypes::TStringKeyMap inputMap; std::vector<std::string> paramDatatypes = {"joynr.types.TestTypes.TStringKeyMap"}; auto callback = std::make_shared<MockCallback<Reply&&>>(); auto onSuccess = [inputMap, callback] (Reply&& reply) { //EXPECT_EQ(inputMap, response.at(0).get<types::TestTypes::TStringKeyMap>()); callback->onSuccess(std::move(reply)); }; auto onError = [] (const exceptions::JoynrException& exception) { ADD_FAILURE()<< "unexpected call of onError function"; }; // since Google Mock does not support r-value references, the call to onSuccess(Reply&&) is proxied to onSuccess(const Reply&) EXPECT_CALL(*callback, onSuccess(A<const Reply&>())).Times(1); Request request = initRequest(methodName, paramDatatypes, inputMap); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsMethodOnRequestCaller) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, getLocation(A<std::function<void(const types::Localisation::GpsLocation&)>>(), A<std::function<void(const exceptions::ProviderRuntimeException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "getLocation"; auto callback = std::make_shared<MockCallback<Reply&&>>(); auto onSuccess = [callback] (Reply&& response) { // EXPECT_EQ(types::Localisation::GpsLocation(), response.at(0).get<types::Localisation::GpsLocation>()); callback->onSuccess(std::move(response)); }; auto onError = [] (const exceptions::JoynrException&) { ADD_FAILURE()<< "unexpected call of onError function"; }; // since Google Mock does not support r-value references, the call to onSuccess(Reply&&) is proxied to onSuccess(const Reply&) EXPECT_CALL(*callback, onSuccess(A<const Reply&>())).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsMethodOnRequestCallerWithProviderRuntimeException) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, methodWithProviderRuntimeException(A<std::function<void()>>(), A<std::function<void(const exceptions::JoynrException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "methodWithProviderRuntimeException"; auto callback = std::make_shared<MockCallback<void>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(providerRuntimeException(mockCaller->providerRuntimeExceptionTestMsg))).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsGetterMethodOnRequestCallerWithProviderRuntimeException) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, getAttributeWithProviderRuntimeException(A<std::function<void(const std::int32_t&)>>(), A<std::function<void(const exceptions::ProviderRuntimeException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "getAttributeWithProviderRuntimeException"; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(providerRuntimeException(mockCaller->providerRuntimeExceptionTestMsg))).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsMethodWithInvalidArguments) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "sumInts"; std::vector<std::string> paramDatatypes; paramDatatypes.push_back("Integer[]"); auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion("Illegal argument for method sumInts: ints (Integer[])", expectedProviderVersion))).Times(1); Request request = initRequest(methodName, paramDatatypes, std::string("invalidParamCannotBeConvertedToInteger[]")); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsSetterMethodWithInvalidArguments) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "setTestAttribute"; std::vector<std::string> paramDatatypes = {"Doesn'tMatter"}; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion("Illegal argument for attribute setter setTestAttribute (Integer)", expectedProviderVersion))).Times(1); Request request = initRequest(methodName, paramDatatypes, std::string("invalidParamCannotBeConvertedTostd::Int32_t")); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsSetterMethodWithInvalidArguments2) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "setTestAttribute"; std::vector<std::string> paramDatatypes = {"Doesn'tMatter"}; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion("Illegal argument for attribute setter setTestAttribute (Integer)", expectedProviderVersion))).Times(1); Request request = initRequest(methodName, paramDatatypes, types::Localisation::GpsLocation()); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsNonExistingMethod) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "execute_callsNonExistingMethod"; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion("unknown method name for interface test: execute_callsNonExistingMethod", expectedProviderVersion))).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST(RequestInterpreterDeathTest, get_assertsUnknownInterface) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); ASSERT_DEATH(registrar.getRequestInterpreter("unknown interface"), "Assertion.*"); } TEST_F(RequestInterpreterTest, create_createsGpsInterpreter) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); registrar.reset(); registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_FALSE(gpsInterpreter.get() == 0); } TEST_F(RequestInterpreterTest, create_multipleCallsReturnSameInterpreter) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); registrar.reset(); registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter1 = registrar.getRequestInterpreter(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter2 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_EQ(gpsInterpreter1, gpsInterpreter2); } TEST_F(RequestInterpreterTest, registerUnregister) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); registrar.reset(); // Register the interface twice and check that the interpreter does not change registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter1 = registrar.getRequestInterpreter(gpsInterfaceName); registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter2 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_EQ(gpsInterpreter1, gpsInterpreter2); // Unregister once registrar.unregisterRequestInterpreter(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter3 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_EQ(gpsInterpreter1, gpsInterpreter3); // Unregister again registrar.unregisterRequestInterpreter(gpsInterfaceName); // Register the interface - this should create a new request interpreter registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter4 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_NE(gpsInterpreter1, gpsInterpreter4); } <commit_msg>[C++] Fix RequestInterpreterTest to use muesli.<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2016 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 <string> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "joynr/serializer/Serializer.h" #include "joynr/InterfaceRegistrar.h" #include "joynr/Request.h" #include "joynr/vehicle/IGps.h" #include "joynr/vehicle/GpsRequestInterpreter.h" #include "joynr/tests/testRequestInterpreter.h" #include "joynr/IRequestInterpreter.h" #include "tests/utils/MockObjects.h" #include "utils/MockCallback.h" #include "joynr/exceptions/MethodInvocationException.h" using ::testing::A; using ::testing::_; MATCHER_P(providerRuntimeException, msg, "") { return arg.getTypeName() == joynr::exceptions::ProviderRuntimeException::TYPE_NAME() && arg.getMessage() == msg; } MATCHER_P(methodInvocationExceptionWithProviderVersion, expectedProviderVersion, "") { const joynr::exceptions::MethodInvocationException *methodInvocationExceptionPtr; return arg.getTypeName() == joynr::exceptions::MethodInvocationException::TYPE_NAME() && (methodInvocationExceptionPtr = dynamic_cast<const joynr::exceptions::MethodInvocationException*>(&arg)) != nullptr && methodInvocationExceptionPtr->getProviderVersion() == expectedProviderVersion; } using namespace joynr; class RequestInterpreterTest : public ::testing::Test { public: RequestInterpreterTest() : gpsInterfaceName(vehicle::IGpsBase::INTERFACE_NAME()) { } protected: std::string gpsInterfaceName; }; // we need to serialize, then deserialize the request to get it in a state which can be passed to a request interpreter template <typename... Ts> joynr::Request initRequest(std::string methodName, std::vector<std::string> paramDataTypes, Ts... paramValues) { Request outgoingRequest; outgoingRequest.setMethodName(methodName); outgoingRequest.setParamDatatypes(std::move(paramDataTypes)); outgoingRequest.setParams(std::move(paramValues)...); using OutputStream = muesli::StringOStream; OutputStream ostream; muesli::JsonOutputArchive<OutputStream> oarchive(ostream); oarchive(outgoingRequest); joynr::Request incomingRequest; using InputStream = muesli::StringIStream; InputStream istream(ostream.getString()); auto iarchive = std::make_shared<muesli::JsonInputArchive<InputStream>>(istream); (*iarchive)(incomingRequest); return incomingRequest; } TEST_F(RequestInterpreterTest, execute_callsMethodOnRequestCallerWithMapParameter) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, mapParameters(A<const types::TestTypes::TStringKeyMap&>(), A<std::function<void(const types::TestTypes::TStringKeyMap&)>>(), A<std::function<void(const exceptions::JoynrException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "mapParameters"; types::TestTypes::TStringKeyMap inputMap; std::vector<std::string> paramDatatypes = {"joynr.types.TestTypes.TStringKeyMap"}; auto callback = std::make_shared<MockCallback<Reply&&>>(); auto onSuccess = [inputMap, callback] (Reply&& reply) { //EXPECT_EQ(inputMap, response.at(0).get<types::TestTypes::TStringKeyMap>()); callback->onSuccess(std::move(reply)); }; auto onError = [] (const exceptions::JoynrException& exception) { ADD_FAILURE()<< "unexpected call of onError function"; }; // since Google Mock does not support r-value references, the call to onSuccess(Reply&&) is proxied to onSuccess(const Reply&) EXPECT_CALL(*callback, onSuccess(A<const Reply&>())).Times(1); Request request = initRequest(methodName, paramDatatypes, inputMap); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsMethodOnRequestCaller) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, getLocation(A<std::function<void(const types::Localisation::GpsLocation&)>>(), A<std::function<void(const exceptions::ProviderRuntimeException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "getLocation"; auto callback = std::make_shared<MockCallback<Reply&&>>(); auto onSuccess = [callback] (Reply&& response) { // EXPECT_EQ(types::Localisation::GpsLocation(), response.at(0).get<types::Localisation::GpsLocation>()); callback->onSuccess(std::move(response)); }; auto onError = [] (const exceptions::JoynrException&) { ADD_FAILURE()<< "unexpected call of onError function"; }; // since Google Mock does not support r-value references, the call to onSuccess(Reply&&) is proxied to onSuccess(const Reply&) EXPECT_CALL(*callback, onSuccess(A<const Reply&>())).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsMethodOnRequestCallerWithProviderRuntimeException) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, methodWithProviderRuntimeException(A<std::function<void()>>(), A<std::function<void(const exceptions::JoynrException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "methodWithProviderRuntimeException"; auto callback = std::make_shared<MockCallback<void>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(providerRuntimeException(mockCaller->providerRuntimeExceptionTestMsg))).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsGetterMethodOnRequestCallerWithProviderRuntimeException) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); EXPECT_CALL( *mockCaller, getAttributeWithProviderRuntimeException(A<std::function<void(const std::int32_t&)>>(), A<std::function<void(const exceptions::ProviderRuntimeException&)>>()) ) .Times(1); tests::testRequestInterpreter interpreter; std::string methodName = "getAttributeWithProviderRuntimeException"; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(providerRuntimeException(mockCaller->providerRuntimeExceptionTestMsg))).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsMethodWithInvalidArguments) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "sumInts"; std::vector<std::string> paramDatatypes; paramDatatypes.push_back("Integer[]"); auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion(expectedProviderVersion))).Times(1); Request request = initRequest(methodName, paramDatatypes, std::string("invalidParamCannotBeConvertedToInteger[]")); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsSetterMethodWithInvalidArguments) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "setTestAttribute"; std::vector<std::string> paramDatatypes = {"Doesn'tMatter"}; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion(expectedProviderVersion))).Times(1); Request request = initRequest(methodName, paramDatatypes, std::string("invalidParamCannotBeConvertedTostd::Int32_t")); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsSetterMethodWithInvalidArguments2) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "setTestAttribute"; std::vector<std::string> paramDatatypes = {"Doesn'tMatter"}; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion(expectedProviderVersion))).Times(1); Request request = initRequest(methodName, paramDatatypes, types::Localisation::GpsLocation()); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST_F(RequestInterpreterTest, execute_callsNonExistingMethod) { auto mockCaller = std::make_shared<MockTestRequestCaller>(); auto expectedProviderVersion = mockCaller->getProviderVersion(); tests::testRequestInterpreter interpreter; std::string methodName = "execute_callsNonExistingMethod"; auto callback = std::make_shared<MockCallback<std::int32_t>>(); auto onSuccess = [] (joynr::Reply&&) {ADD_FAILURE()<< "unexpected call of onSuccess function";}; auto onError = [callback] (const exceptions::JoynrException& exception) { callback->onError(exception); }; EXPECT_CALL(*callback, onError(methodInvocationExceptionWithProviderVersion(expectedProviderVersion))).Times(1); Request request = initRequest(methodName, {}); interpreter.execute(mockCaller, request, onSuccess, onError); } TEST(RequestInterpreterDeathTest, get_assertsUnknownInterface) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); ASSERT_DEATH(registrar.getRequestInterpreter("unknown interface"), "Assertion.*"); } TEST_F(RequestInterpreterTest, create_createsGpsInterpreter) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); registrar.reset(); registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_FALSE(gpsInterpreter.get() == 0); } TEST_F(RequestInterpreterTest, create_multipleCallsReturnSameInterpreter) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); registrar.reset(); registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter1 = registrar.getRequestInterpreter(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter2 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_EQ(gpsInterpreter1, gpsInterpreter2); } TEST_F(RequestInterpreterTest, registerUnregister) { InterfaceRegistrar& registrar = InterfaceRegistrar::instance(); registrar.reset(); // Register the interface twice and check that the interpreter does not change registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter1 = registrar.getRequestInterpreter(gpsInterfaceName); registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter2 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_EQ(gpsInterpreter1, gpsInterpreter2); // Unregister once registrar.unregisterRequestInterpreter(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter3 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_EQ(gpsInterpreter1, gpsInterpreter3); // Unregister again registrar.unregisterRequestInterpreter(gpsInterfaceName); // Register the interface - this should create a new request interpreter registrar.registerRequestInterpreter<vehicle::GpsRequestInterpreter>(gpsInterfaceName); std::shared_ptr<IRequestInterpreter> gpsInterpreter4 = registrar.getRequestInterpreter(gpsInterfaceName); EXPECT_NE(gpsInterpreter1, gpsInterpreter4); } <|endoftext|>
<commit_before>/* Definition of libpqxx exception classes. * * pqxx::sql_error, pqxx::broken_connection, pqxx::in_doubt_error, ... * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/except instead. * * Copyright (c) 2000-2020, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this * mistake, or contact the author. */ #ifndef PQXX_H_EXCEPT #define PQXX_H_EXCEPT #include "pqxx/compiler-public.hxx" #include "pqxx/internal/compiler-internal-pre.hxx" #include <stdexcept> #include <string> namespace pqxx { /** * @addtogroup exception Exception classes * * These exception classes follow, roughly, the two-level hierarchy defined by * the PostgreSQL error codes (see Appendix A of the PostgreSQL documentation * corresponding to your server version). This is not a complete mapping * though. There are other differences as well, e.g. the error code * @c statement_completion_unknown has a separate status in libpqxx as * @c in_doubt_error, and @c too_many_connections is classified as a * @c broken_connection rather than a subtype of @c insufficient_resources. * * @see http://www.postgresql.org/docs/9.4/interactive/errcodes-appendix.html * * @{ */ /// Run-time failure encountered by libpqxx, similar to std::runtime_error. struct PQXX_LIBEXPORT failure : std::runtime_error { explicit failure(std::string const &); }; /// Exception class for lost or failed backend connection. /** * @warning When this happens on Unix-like systems, you may also get a SIGPIPE * signal. That signal aborts the program by default, so if you wish to be * able to continue after a connection breaks, be sure to disarm this signal. * * If you're working on a Unix-like system, see the manual page for * @c signal (2) on how to deal with SIGPIPE. The easiest way to make this * signal harmless is to make your program ignore it: * * @code * #include <signal.h> * * int main() * { * signal(SIGPIPE, SIG_IGN); * // ... * @endcode */ struct PQXX_LIBEXPORT broken_connection : failure { broken_connection(); explicit broken_connection(std::string const &); }; /// Exception class for failed queries. /** Carries, in addition to a regular error message, a copy of the failed query * and (if available) the SQLSTATE value accompanying the error. */ class PQXX_LIBEXPORT sql_error : public failure { /// Query string. Empty if unknown. std::string const m_query; /// SQLSTATE string describing the error type, if known; or empty string. std::string const m_sqlstate; public: explicit sql_error( std::string const &whatarg = "", std::string const &Q = "", char const sqlstate[] = nullptr); virtual ~sql_error() noexcept override; /// The query whose execution triggered the exception [[nodiscard]] PQXX_PURE std::string const &query() const noexcept; /// SQLSTATE error code if known, or empty string otherwise. [[nodiscard]] PQXX_PURE std::string const &sqlstate() const noexcept; }; /// "Help, I don't know whether transaction was committed successfully!" /** Exception that might be thrown in rare cases where the connection to the * database is lost while finishing a database transaction, and there's no way * of telling whether it was actually executed by the backend. In this case * the database is left in an indeterminate (but consistent) state, and only * manual inspection will tell which is the case. */ struct PQXX_LIBEXPORT in_doubt_error : failure { explicit in_doubt_error(std::string const &); }; /// The backend saw itself forced to roll back the ongoing transaction. struct PQXX_LIBEXPORT transaction_rollback : sql_error { explicit transaction_rollback( std::string const &whatarg, std::string const &q = "", char const sqlstate[] = nullptr); }; /// Transaction failed to serialize. Please retry it. /** Can only happen at transaction isolation levels REPEATABLE READ and * SERIALIZABLE. * * The current transaction cannot be committed without violating the guarantees * made by its isolation level. This is the effect of a conflict with another * ongoing transaction. The transaction may still succeed if you try to * perform it again. */ struct PQXX_LIBEXPORT serialization_failure : transaction_rollback { explicit serialization_failure( std::string const &whatarg, std::string const &q, char const sqlstate[] = nullptr); }; /// We can't tell whether our last statement succeeded. struct PQXX_LIBEXPORT statement_completion_unknown : transaction_rollback { explicit statement_completion_unknown( std::string const &whatarg, std::string const &q, char const sqlstate[] = nullptr); }; /// The ongoing transaction has deadlocked. Retrying it may help. struct PQXX_LIBEXPORT deadlock_detected : transaction_rollback { explicit deadlock_detected( std::string const &whatarg, std::string const &q, char const sqlstate[] = nullptr); }; /// Internal error in libpqxx library struct PQXX_LIBEXPORT internal_error : std::logic_error { explicit internal_error(std::string const &); }; /// Error in usage of libpqxx library, similar to std::logic_error struct PQXX_LIBEXPORT usage_error : std::logic_error { explicit usage_error(std::string const &); }; /// Invalid argument passed to libpqxx, similar to std::invalid_argument struct PQXX_LIBEXPORT argument_error : std::invalid_argument { explicit argument_error(std::string const &); }; /// Value conversion failed, e.g. when converting "Hello" to int. struct PQXX_LIBEXPORT conversion_error : std::domain_error { explicit conversion_error(std::string const &); }; /// Could not convert value to string: not enough buffer space. struct PQXX_LIBEXPORT conversion_overrun : conversion_error { explicit conversion_overrun(std::string const &); }; /// Something is out of range, similar to std::out_of_range struct PQXX_LIBEXPORT range_error : std::out_of_range { explicit range_error(std::string const &); }; /// Query returned an unexpected number of rows. struct PQXX_LIBEXPORT unexpected_rows : public range_error { explicit unexpected_rows(std::string const &msg) : range_error{msg} {} }; /// Database feature not supported in current setup. struct PQXX_LIBEXPORT feature_not_supported : sql_error { explicit feature_not_supported( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; /// Error in data provided to SQL statement. struct PQXX_LIBEXPORT data_exception : sql_error { explicit data_exception( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT integrity_constraint_violation : sql_error { explicit integrity_constraint_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT restrict_violation : integrity_constraint_violation { explicit restrict_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT not_null_violation : integrity_constraint_violation { explicit not_null_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT foreign_key_violation : integrity_constraint_violation { explicit foreign_key_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT unique_violation : integrity_constraint_violation { explicit unique_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT check_violation : integrity_constraint_violation { explicit check_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT invalid_cursor_state : sql_error { explicit invalid_cursor_state( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT invalid_sql_statement_name : sql_error { explicit invalid_sql_statement_name( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT invalid_cursor_name : sql_error { explicit invalid_cursor_name( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT syntax_error : sql_error { /// Approximate position in string where error occurred, or -1 if unknown. int const error_position; explicit syntax_error( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr, int pos = -1) : sql_error{err, Q, sqlstate}, error_position{pos} {} }; struct PQXX_LIBEXPORT undefined_column : syntax_error { explicit undefined_column( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : syntax_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT undefined_function : syntax_error { explicit undefined_function( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : syntax_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT undefined_table : syntax_error { explicit undefined_table( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : syntax_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT insufficient_privilege : sql_error { explicit insufficient_privilege( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; /// Resource shortage on the server struct PQXX_LIBEXPORT insufficient_resources : sql_error { explicit insufficient_resources( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT disk_full : insufficient_resources { explicit disk_full( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : insufficient_resources{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT out_of_memory : insufficient_resources { explicit out_of_memory( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : insufficient_resources{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT too_many_connections : broken_connection { explicit too_many_connections(std::string const &err) : broken_connection{err} {} }; /// PL/pgSQL error /** Exceptions derived from this class are errors from PL/pgSQL procedures. */ struct PQXX_LIBEXPORT plpgsql_error : sql_error { explicit plpgsql_error( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; /// Exception raised in PL/pgSQL procedure struct PQXX_LIBEXPORT plpgsql_raise : plpgsql_error { explicit plpgsql_raise( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : plpgsql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT plpgsql_no_data_found : plpgsql_error { explicit plpgsql_no_data_found( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : plpgsql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT plpgsql_too_many_rows : plpgsql_error { explicit plpgsql_too_many_rows( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : plpgsql_error{err, Q, sqlstate} {} }; /** * @} */ } // namespace pqxx #include "pqxx/internal/compiler-internal-post.hxx" #endif <commit_msg>Add note.<commit_after>/* Definition of libpqxx exception classes. * * pqxx::sql_error, pqxx::broken_connection, pqxx::in_doubt_error, ... * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/except instead. * * Copyright (c) 2000-2020, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this * mistake, or contact the author. */ #ifndef PQXX_H_EXCEPT #define PQXX_H_EXCEPT #include "pqxx/compiler-public.hxx" #include "pqxx/internal/compiler-internal-pre.hxx" #include <stdexcept> #include <string> // TODO: Move vtable to except.cxx, by implementing destructors there. namespace pqxx { /** * @addtogroup exception Exception classes * * These exception classes follow, roughly, the two-level hierarchy defined by * the PostgreSQL error codes (see Appendix A of the PostgreSQL documentation * corresponding to your server version). This is not a complete mapping * though. There are other differences as well, e.g. the error code * @c statement_completion_unknown has a separate status in libpqxx as * @c in_doubt_error, and @c too_many_connections is classified as a * @c broken_connection rather than a subtype of @c insufficient_resources. * * @see http://www.postgresql.org/docs/9.4/interactive/errcodes-appendix.html * * @{ */ /// Run-time failure encountered by libpqxx, similar to std::runtime_error. struct PQXX_LIBEXPORT failure : std::runtime_error { explicit failure(std::string const &); }; /// Exception class for lost or failed backend connection. /** * @warning When this happens on Unix-like systems, you may also get a SIGPIPE * signal. That signal aborts the program by default, so if you wish to be * able to continue after a connection breaks, be sure to disarm this signal. * * If you're working on a Unix-like system, see the manual page for * @c signal (2) on how to deal with SIGPIPE. The easiest way to make this * signal harmless is to make your program ignore it: * * @code * #include <signal.h> * * int main() * { * signal(SIGPIPE, SIG_IGN); * // ... * @endcode */ struct PQXX_LIBEXPORT broken_connection : failure { broken_connection(); explicit broken_connection(std::string const &); }; /// Exception class for failed queries. /** Carries, in addition to a regular error message, a copy of the failed query * and (if available) the SQLSTATE value accompanying the error. */ class PQXX_LIBEXPORT sql_error : public failure { /// Query string. Empty if unknown. std::string const m_query; /// SQLSTATE string describing the error type, if known; or empty string. std::string const m_sqlstate; public: explicit sql_error( std::string const &whatarg = "", std::string const &Q = "", char const sqlstate[] = nullptr); virtual ~sql_error() noexcept override; /// The query whose execution triggered the exception [[nodiscard]] PQXX_PURE std::string const &query() const noexcept; /// SQLSTATE error code if known, or empty string otherwise. [[nodiscard]] PQXX_PURE std::string const &sqlstate() const noexcept; }; /// "Help, I don't know whether transaction was committed successfully!" /** Exception that might be thrown in rare cases where the connection to the * database is lost while finishing a database transaction, and there's no way * of telling whether it was actually executed by the backend. In this case * the database is left in an indeterminate (but consistent) state, and only * manual inspection will tell which is the case. */ struct PQXX_LIBEXPORT in_doubt_error : failure { explicit in_doubt_error(std::string const &); }; /// The backend saw itself forced to roll back the ongoing transaction. struct PQXX_LIBEXPORT transaction_rollback : sql_error { explicit transaction_rollback( std::string const &whatarg, std::string const &q = "", char const sqlstate[] = nullptr); }; /// Transaction failed to serialize. Please retry it. /** Can only happen at transaction isolation levels REPEATABLE READ and * SERIALIZABLE. * * The current transaction cannot be committed without violating the guarantees * made by its isolation level. This is the effect of a conflict with another * ongoing transaction. The transaction may still succeed if you try to * perform it again. */ struct PQXX_LIBEXPORT serialization_failure : transaction_rollback { explicit serialization_failure( std::string const &whatarg, std::string const &q, char const sqlstate[] = nullptr); }; /// We can't tell whether our last statement succeeded. struct PQXX_LIBEXPORT statement_completion_unknown : transaction_rollback { explicit statement_completion_unknown( std::string const &whatarg, std::string const &q, char const sqlstate[] = nullptr); }; /// The ongoing transaction has deadlocked. Retrying it may help. struct PQXX_LIBEXPORT deadlock_detected : transaction_rollback { explicit deadlock_detected( std::string const &whatarg, std::string const &q, char const sqlstate[] = nullptr); }; /// Internal error in libpqxx library struct PQXX_LIBEXPORT internal_error : std::logic_error { explicit internal_error(std::string const &); }; /// Error in usage of libpqxx library, similar to std::logic_error struct PQXX_LIBEXPORT usage_error : std::logic_error { explicit usage_error(std::string const &); }; /// Invalid argument passed to libpqxx, similar to std::invalid_argument struct PQXX_LIBEXPORT argument_error : std::invalid_argument { explicit argument_error(std::string const &); }; /// Value conversion failed, e.g. when converting "Hello" to int. struct PQXX_LIBEXPORT conversion_error : std::domain_error { explicit conversion_error(std::string const &); }; /// Could not convert value to string: not enough buffer space. struct PQXX_LIBEXPORT conversion_overrun : conversion_error { explicit conversion_overrun(std::string const &); }; /// Something is out of range, similar to std::out_of_range struct PQXX_LIBEXPORT range_error : std::out_of_range { explicit range_error(std::string const &); }; /// Query returned an unexpected number of rows. struct PQXX_LIBEXPORT unexpected_rows : public range_error { explicit unexpected_rows(std::string const &msg) : range_error{msg} {} }; /// Database feature not supported in current setup. struct PQXX_LIBEXPORT feature_not_supported : sql_error { explicit feature_not_supported( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; /// Error in data provided to SQL statement. struct PQXX_LIBEXPORT data_exception : sql_error { explicit data_exception( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT integrity_constraint_violation : sql_error { explicit integrity_constraint_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT restrict_violation : integrity_constraint_violation { explicit restrict_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT not_null_violation : integrity_constraint_violation { explicit not_null_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT foreign_key_violation : integrity_constraint_violation { explicit foreign_key_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT unique_violation : integrity_constraint_violation { explicit unique_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT check_violation : integrity_constraint_violation { explicit check_violation( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : integrity_constraint_violation{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT invalid_cursor_state : sql_error { explicit invalid_cursor_state( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT invalid_sql_statement_name : sql_error { explicit invalid_sql_statement_name( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT invalid_cursor_name : sql_error { explicit invalid_cursor_name( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT syntax_error : sql_error { /// Approximate position in string where error occurred, or -1 if unknown. int const error_position; explicit syntax_error( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr, int pos = -1) : sql_error{err, Q, sqlstate}, error_position{pos} {} }; struct PQXX_LIBEXPORT undefined_column : syntax_error { explicit undefined_column( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : syntax_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT undefined_function : syntax_error { explicit undefined_function( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : syntax_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT undefined_table : syntax_error { explicit undefined_table( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : syntax_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT insufficient_privilege : sql_error { explicit insufficient_privilege( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; /// Resource shortage on the server struct PQXX_LIBEXPORT insufficient_resources : sql_error { explicit insufficient_resources( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT disk_full : insufficient_resources { explicit disk_full( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : insufficient_resources{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT out_of_memory : insufficient_resources { explicit out_of_memory( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : insufficient_resources{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT too_many_connections : broken_connection { explicit too_many_connections(std::string const &err) : broken_connection{err} {} }; /// PL/pgSQL error /** Exceptions derived from this class are errors from PL/pgSQL procedures. */ struct PQXX_LIBEXPORT plpgsql_error : sql_error { explicit plpgsql_error( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : sql_error{err, Q, sqlstate} {} }; /// Exception raised in PL/pgSQL procedure struct PQXX_LIBEXPORT plpgsql_raise : plpgsql_error { explicit plpgsql_raise( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : plpgsql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT plpgsql_no_data_found : plpgsql_error { explicit plpgsql_no_data_found( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : plpgsql_error{err, Q, sqlstate} {} }; struct PQXX_LIBEXPORT plpgsql_too_many_rows : plpgsql_error { explicit plpgsql_too_many_rows( std::string const &err, std::string const &Q = "", char const sqlstate[] = nullptr) : plpgsql_error{err, Q, sqlstate} {} }; /** * @} */ } // namespace pqxx #include "pqxx/internal/compiler-internal-post.hxx" #endif <|endoftext|>
<commit_before>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Ensure the result will fit. assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end)); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= std::distance(src_begin, src_end)); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(2 * half_length + 1); // Iterators in source and destination I1 src_pos = src_begin; I1 dest_pos = dest_begin; // Get the initial window in sequential order with reflection // Insert elements in order to the multiset for sorting. // Store all multiset iterators into the deque in sequential order. std::deque<T> window_init(half_length + 1); for (I_diff_t j = half_length + 1; j > 0;) { window_init[--j] = *(src_pos++); } for (I_diff_t j = 0; j < half_length; j++) { window_iters[j] = sorted_window.insert(window_init[j]); } for (I_diff_t j = half_length; j < 2 * half_length + 1; j++) { window_iters[j] = sorted_window.insert(window_init.back()); window_init.pop_back(); } // Window position corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); typename multiset::iterator rank_point = sorted_window.begin(); std::advance(rank_point, rank_pos); // Roll window forward one value at a time. typename multiset::iterator prev_iter; T prev_value; T next_value; I_diff_t window_reflect_pos = 2 * half_length; while ( window_reflect_pos >= 0 ) { *(dest_pos++) = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); // Determine next value to add to window. // Handle special cases like reflection at the end. if ( src_pos == src_end ) { if ( window_reflect_pos == 0 ) { window_reflect_pos -= 2; next_value = prev_value; } else { window_reflect_pos -= 2; next_value = *(window_iters[window_reflect_pos]); } } else { next_value = *(src_pos++); } // Remove old value and add new value to the window. // Handle special cases where `rank_pos` may have an adjusted position // due to where the old and new values are inserted. if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <commit_msg>Clean up initial window's deque when done<commit_after>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Ensure the result will fit. assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end)); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= std::distance(src_begin, src_end)); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(2 * half_length + 1); // Iterators in source and destination I1 src_pos = src_begin; I1 dest_pos = dest_begin; // Get the initial window in sequential order with reflection // Insert elements in order to the multiset for sorting. // Store all multiset iterators into the deque in sequential order. { std::deque<T> window_init(half_length + 1); for (I_diff_t j = half_length + 1; j > 0;) { window_init[--j] = *(src_pos++); } for (I_diff_t j = 0; j < half_length; j++) { window_iters[j] = sorted_window.insert(window_init[j]); } for (I_diff_t j = half_length; j < 2 * half_length + 1; j++) { window_iters[j] = sorted_window.insert(window_init.back()); window_init.pop_back(); } } // Window position corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); typename multiset::iterator rank_point = sorted_window.begin(); std::advance(rank_point, rank_pos); // Roll window forward one value at a time. typename multiset::iterator prev_iter; T prev_value; T next_value; I_diff_t window_reflect_pos = 2 * half_length; while ( window_reflect_pos >= 0 ) { *(dest_pos++) = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); // Determine next value to add to window. // Handle special cases like reflection at the end. if ( src_pos == src_end ) { if ( window_reflect_pos == 0 ) { window_reflect_pos -= 2; next_value = prev_value; } else { window_reflect_pos -= 2; next_value = *(window_iters[window_reflect_pos]); } } else { next_value = *(src_pos++); } // Remove old value and add new value to the window. // Handle special cases where `rank_pos` may have an adjusted position // due to where the old and new values are inserted. if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <|endoftext|>
<commit_before>#pragma once #include <cstring> #include <pmmintrin.h> namespace rack { /** Abstraction of byte-aligned values for SIMD CPU acceleration. */ namespace simd { /** Generic class for vector types. This class is designed to be used just like you use scalars, with extra features for handling bitwise logic, conditions, loading, and storing. Usage example: float a[4], b[4]; float_4 a = float_4::load(in); float_4 b = 2.f * a / (1 - a); b *= sin(2 * M_PI * a); b.store(out); */ template <typename T, int N> struct Vector; /** Wrapper for `__m128` representing an aligned vector of 4 single-precision float values. */ template <> struct Vector<float, 4> { union { __m128 v; /** Accessing this array of scalars is slow and defeats the purpose of vectorizing. */ float s[4]; }; /** Constructs an uninitialized vector. */ Vector() {} /** Constructs a vector from a native `__m128` type. */ Vector(__m128 v) : v(v) {} /** Constructs a vector with all elements set to `x`. */ Vector(float x) { v = _mm_set1_ps(x); } /** Constructs a vector from four values. */ Vector(float x1, float x2, float x3, float x4) { v = _mm_set_ps(x1, x2, x3, x4); } /** Returns a vector initialized to zero. */ static Vector zero() { return Vector(_mm_setzero_ps()); } /** Returns a vector with all 1 bits. */ static Vector mask() { return _mm_castsi128_ps(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } /** Reads an array of 4 values. */ static Vector load(const float *x) { /* My benchmarks show that _mm_loadu_ps() performs equally as fast as _mm_load_ps() when data is actually aligned. This post seems to agree. https://stackoverflow.com/a/20265193/272642 So use _mm_loadu_ps() for generality, so you can load unaligned arrays using the same function (although it will be slower). */ return Vector(_mm_loadu_ps(x)); } /** Writes an array of 4 values. */ void store(float *x) { _mm_storeu_ps(x, v); } }; template <> struct Vector<int32_t, 4> { union { __m128i v; int32_t s[4]; }; Vector() {} Vector(__m128i v) : v(v) {} Vector(int32_t x) { v = _mm_set1_epi32(x); } Vector(int32_t x1, int32_t x2, int32_t x3, int32_t x4) { v = _mm_set_epi32(x1, x2, x3, x4); } static Vector zero() { return Vector(_mm_setzero_si128()); } static Vector mask() { return Vector(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } static Vector load(const int32_t *x) { // HACK // Use _mm_loadu_si128() because GCC doesn't support _mm_loadu_si32() return Vector(_mm_loadu_si128((__m128i*) x)); } void store(int32_t *x) { // HACK // Use _mm_storeu_si128() because GCC doesn't support _mm_storeu_si32() _mm_storeu_si128((__m128i*) x, v); } }; // Instructions not available as operators /** `~a & b` */ inline Vector<float, 4> andnot(const Vector<float, 4> &a, const Vector<float, 4> &b) { return Vector<float, 4>(_mm_andnot_ps(a.v, b.v)); } // Operator overloads /** `a @ b` */ #define DECLARE_VECTOR_OPERATOR_INFIX(t, s, operator, func) \ inline Vector<t, s> operator(const Vector<t, s> &a, const Vector<t, s> &b) { \ return Vector<t, s>(func(a.v, b.v)); \ } /** `a @= b` */ #define DECLARE_VECTOR_OPERATOR_INCREMENT(t, s, operator, opfunc) \ inline Vector<t, s> &operator(Vector<t, s> &a, const Vector<t, s> &b) { \ a = opfunc(a, b); \ return a; \ } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator+, _mm_add_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator+, _mm_add_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator-, _mm_sub_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator-, _mm_sub_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator*, _mm_mul_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator*, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator/, _mm_div_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator/, NOT AVAILABLE IN SSE3) /* Use these to apply logic, bit masks, and conditions to elements. Boolean operators on vectors give 0x00000000 for false and 0xffffffff for true, for each vector element. Examples: Subtract 1 from value if greater than or equal to 1. x -= (x >= 1.f) & 1.f; */ DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator^, _mm_xor_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator^, _mm_xor_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator&, _mm_and_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator&, _mm_and_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator|, _mm_or_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator|, _mm_or_si128) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator*=, operator*) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator*=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator/=, operator/) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator/=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator==, _mm_cmpeq_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator==, _mm_cmpeq_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>=, _mm_cmpge_ps) inline Vector<int32_t, 4> operator>=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpgt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>, _mm_cmpgt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator>, _mm_cmpgt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<=, _mm_cmple_ps) inline Vector<int32_t, 4> operator<=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmplt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<, _mm_cmplt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator<, _mm_cmplt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator!=, _mm_cmpneq_ps) inline Vector<int32_t, 4> operator!=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpeq_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } /** `+a` */ inline Vector<float, 4> operator+(const Vector<float, 4> &a) { return a; } inline Vector<int32_t, 4> operator+(const Vector<int32_t, 4> &a) { return a; } /** `-a` */ inline Vector<float, 4> operator-(const Vector<float, 4> &a) { return 0.f - a; } inline Vector<int32_t, 4> operator-(const Vector<int32_t, 4> &a) { return 0 - a; } /** `++a` */ inline Vector<float, 4> &operator++(Vector<float, 4> &a) { a += 1.f; return a; } inline Vector<int32_t, 4> &operator++(Vector<int32_t, 4> &a) { a += 1; return a; } /** `--a` */ inline Vector<float, 4> &operator--(Vector<float, 4> &a) { a -= 1.f; return a; } inline Vector<int32_t, 4> &operator--(Vector<int32_t, 4> &a) { a -= 1; return a; } /** `a++` */ inline Vector<float, 4> operator++(Vector<float, 4> &a, int) { Vector<float, 4> b = a; ++a; return b; } inline Vector<int32_t, 4> operator++(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; ++a; return b; } /** `a--` */ inline Vector<float, 4> operator--(Vector<float, 4> &a, int) { Vector<float, 4> b = a; --a; return b; } inline Vector<int32_t, 4> operator--(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; --a; return b; } /** `~a` */ inline Vector<float, 4> operator~(const Vector<float, 4> &a) { return a ^ Vector<float, 4>::mask(); } inline Vector<int32_t, 4> operator~(const Vector<int32_t, 4> &a) { return a ^ Vector<int32_t, 4>::mask(); } // Typedefs typedef Vector<float, 4> float_4; typedef Vector<int32_t, 4> int32_4; } // namespace simd } // namespace rack <commit_msg>Add conversions and casts to simd::Vector types.<commit_after>#pragma once #include <cstring> #include <pmmintrin.h> namespace rack { /** Abstraction of byte-aligned values for SIMD CPU acceleration. */ namespace simd { /** Generic class for vector types. This class is designed to be used just like you use scalars, with extra features for handling bitwise logic, conditions, loading, and storing. Usage example: float a[4], b[4]; float_4 a = float_4::load(in); float_4 b = 2.f * a / (1 - a); b *= sin(2 * M_PI * a); b.store(out); */ template <typename T, int N> struct Vector; /** Wrapper for `__m128` representing an aligned vector of 4 single-precision float values. */ template <> struct Vector<float, 4> { union { __m128 v; /** Accessing this array of scalars is slow and defeats the purpose of vectorizing. */ float s[4]; }; /** Constructs an uninitialized vector. */ Vector() {} /** Constructs a vector from a native `__m128` type. */ Vector(__m128 v) : v(v) {} /** Constructs a vector with all elements set to `x`. */ Vector(float x) { v = _mm_set1_ps(x); } /** Constructs a vector from four values. */ Vector(float x1, float x2, float x3, float x4) { v = _mm_set_ps(x1, x2, x3, x4); } /** Returns a vector initialized to zero. */ static Vector zero() { return Vector(_mm_setzero_ps()); } /** Returns a vector with all 1 bits. */ static Vector mask() { return _mm_castsi128_ps(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } /** Reads an array of 4 values. */ static Vector load(const float *x) { /* My benchmarks show that _mm_loadu_ps() performs equally as fast as _mm_load_ps() when data is actually aligned. This post seems to agree. https://stackoverflow.com/a/20265193/272642 So use _mm_loadu_ps() for generality, so you can load unaligned arrays using the same function (although it will be slower). */ return Vector(_mm_loadu_ps(x)); } /** Writes an array of 4 values. */ void store(float *x) { _mm_storeu_ps(x, v); } // Conversions Vector(Vector<int32_t, 4> a); // Casts static Vector cast(Vector<int32_t, 4> a); }; template <> struct Vector<int32_t, 4> { union { __m128i v; int32_t s[4]; }; Vector() {} Vector(__m128i v) : v(v) {} Vector(int32_t x) { v = _mm_set1_epi32(x); } Vector(int32_t x1, int32_t x2, int32_t x3, int32_t x4) { v = _mm_set_epi32(x1, x2, x3, x4); } static Vector zero() { return Vector(_mm_setzero_si128()); } static Vector mask() { return Vector(_mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128())); } static Vector load(const int32_t *x) { // HACK // Use _mm_loadu_si128() because GCC doesn't support _mm_loadu_si32() return Vector(_mm_loadu_si128((__m128i*) x)); } void store(int32_t *x) { // HACK // Use _mm_storeu_si128() because GCC doesn't support _mm_storeu_si32() _mm_storeu_si128((__m128i*) x, v); } Vector(Vector<float, 4> a); static Vector cast(Vector<float, 4> a); }; // Conversions and casts inline Vector<float, 4>::Vector(Vector<int32_t, 4> a) { v = _mm_cvtepi32_ps(a.v); } inline Vector<int32_t, 4>::Vector(Vector<float, 4> a) { v = _mm_cvtps_epi32(a.v); } inline Vector<float, 4> Vector<float, 4>::cast(Vector<int32_t, 4> a) { return Vector(_mm_castsi128_ps(a.v)); } inline Vector<int32_t, 4> Vector<int32_t, 4>::cast(Vector<float, 4> a) { return Vector(_mm_castps_si128(a.v)); } // Instructions not available as operators /** `~a & b` */ inline Vector<float, 4> andnot(const Vector<float, 4> &a, const Vector<float, 4> &b) { return Vector<float, 4>(_mm_andnot_ps(a.v, b.v)); } // Operator overloads /** `a @ b` */ #define DECLARE_VECTOR_OPERATOR_INFIX(t, s, operator, func) \ inline Vector<t, s> operator(const Vector<t, s> &a, const Vector<t, s> &b) { \ return Vector<t, s>(func(a.v, b.v)); \ } /** `a @= b` */ #define DECLARE_VECTOR_OPERATOR_INCREMENT(t, s, operator, opfunc) \ inline Vector<t, s> &operator(Vector<t, s> &a, const Vector<t, s> &b) { \ a = opfunc(a, b); \ return a; \ } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator+, _mm_add_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator+, _mm_add_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator-, _mm_sub_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator-, _mm_sub_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator*, _mm_mul_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator*, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator/, _mm_div_ps) // DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator/, NOT AVAILABLE IN SSE3) /* Use these to apply logic, bit masks, and conditions to elements. Boolean operators on vectors give 0x00000000 for false and 0xffffffff for true, for each vector element. Examples: Subtract 1 from value if greater than or equal to 1. x -= (x >= 1.f) & 1.f; */ DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator^, _mm_xor_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator^, _mm_xor_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator&, _mm_and_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator&, _mm_and_si128) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator|, _mm_or_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator|, _mm_or_si128) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator+=, operator+) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator-=, operator-) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator*=, operator*) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator*=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator/=, operator/) // DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator/=, NOT AVAILABLE IN SSE3) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator^=, operator^) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator&=, operator&) DECLARE_VECTOR_OPERATOR_INCREMENT(float, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INCREMENT(int32_t, 4, operator|=, operator|) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator==, _mm_cmpeq_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator==, _mm_cmpeq_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>=, _mm_cmpge_ps) inline Vector<int32_t, 4> operator>=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpgt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator>, _mm_cmpgt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator>, _mm_cmpgt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<=, _mm_cmple_ps) inline Vector<int32_t, 4> operator<=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmplt_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator<, _mm_cmplt_ps) DECLARE_VECTOR_OPERATOR_INFIX(int32_t, 4, operator<, _mm_cmplt_epi32) DECLARE_VECTOR_OPERATOR_INFIX(float, 4, operator!=, _mm_cmpneq_ps) inline Vector<int32_t, 4> operator!=(const Vector<int32_t, 4> &a, const Vector<int32_t, 4> &b) { return Vector<int32_t, 4>(_mm_cmpeq_epi32(a.v, b.v)) ^ Vector<int32_t, 4>::mask(); } /** `+a` */ inline Vector<float, 4> operator+(const Vector<float, 4> &a) { return a; } inline Vector<int32_t, 4> operator+(const Vector<int32_t, 4> &a) { return a; } /** `-a` */ inline Vector<float, 4> operator-(const Vector<float, 4> &a) { return 0.f - a; } inline Vector<int32_t, 4> operator-(const Vector<int32_t, 4> &a) { return 0 - a; } /** `++a` */ inline Vector<float, 4> &operator++(Vector<float, 4> &a) { a += 1.f; return a; } inline Vector<int32_t, 4> &operator++(Vector<int32_t, 4> &a) { a += 1; return a; } /** `--a` */ inline Vector<float, 4> &operator--(Vector<float, 4> &a) { a -= 1.f; return a; } inline Vector<int32_t, 4> &operator--(Vector<int32_t, 4> &a) { a -= 1; return a; } /** `a++` */ inline Vector<float, 4> operator++(Vector<float, 4> &a, int) { Vector<float, 4> b = a; ++a; return b; } inline Vector<int32_t, 4> operator++(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; ++a; return b; } /** `a--` */ inline Vector<float, 4> operator--(Vector<float, 4> &a, int) { Vector<float, 4> b = a; --a; return b; } inline Vector<int32_t, 4> operator--(Vector<int32_t, 4> &a, int) { Vector<int32_t, 4> b = a; --a; return b; } /** `~a` */ inline Vector<float, 4> operator~(const Vector<float, 4> &a) { return a ^ Vector<float, 4>::mask(); } inline Vector<int32_t, 4> operator~(const Vector<int32_t, 4> &a) { return a ^ Vector<int32_t, 4>::mask(); } // Typedefs typedef Vector<float, 4> float_4; typedef Vector<int32_t, 4> int32_4; } // namespace simd } // namespace rack <|endoftext|>
<commit_before>#include "acceptandpayofferlistpage.h" #include "ui_acceptandpayofferlistpage.h" #include "init.h" #include "util.h" #include "offeracceptdialog.h" #include "offeracceptdialogbtc.h" #include "offer.h" #include "syscoingui.h" #include "guiutil.h" #include "platformstyle.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #include <QString> #include <QByteArray> #include <QPixmap> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QRegExp> #include <QStringList> #include <QDesktopServices> #include "rpcserver.h" #include "alias.h" #include "walletmodel.h" using namespace std; extern const CRPCTable tableRPC; AcceptandPayOfferListPage::AcceptandPayOfferListPage(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), platformStyle(platformStyle), ui(new Ui::AcceptandPayOfferListPage) { sAddress = ""; bOnlyAcceptBTC = false; ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!platformStyle->getImagesOnButtons()) { ui->lookupButton->setIcon(QIcon()); ui->acceptButton->setIcon(QIcon()); ui->imageButton->setIcon(QIcon()); } else { ui->lookupButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/search")); ui->acceptButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/cart")); } ui->imageButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/imageplaceholder")); this->offerPaid = false; this->URIHandled = false; ui->labelExplanation->setText(tr("Purchase an offer, Syscoin will be used from your balance to complete the transaction")); connect(ui->acceptButton, SIGNAL(clicked()), this, SLOT(acceptOffer())); connect(ui->lookupButton, SIGNAL(clicked()), this, SLOT(lookup())); connect(ui->offeridEdit, SIGNAL(textChanged(const QString &)), this, SLOT(resetState())); ui->notesEdit->setStyleSheet("color: rgb(0, 0, 0); background-color: rgb(255, 255, 255)"); ui->aliasDisclaimer->setText(tr("<font color='blue'>Select an Alias</font>")); m_netwManager = new QNetworkAccessManager(this); m_placeholderImage.load(":/images/" + theme + "/imageplaceholder"); ui->imageButton->setToolTip(tr("Click to open image in browser...")); ui->infoCert->setVisible(false); ui->certLabel->setVisible(false); RefreshImage(); } void AcceptandPayOfferListPage::loadAliases() { ui->aliasEdit->clear(); string strMethod = string("aliaslist"); UniValue params(UniValue::VARR); UniValue result ; string name_str; int expired = 0; try { result = tableRPC.execute(strMethod, params); if (result.type() == UniValue::VARR) { name_str = ""; expired = 0; const UniValue &arr = result.get_array(); for (unsigned int idx = 0; idx < arr.size(); idx++) { const UniValue& input = arr[idx]; if (input.type() != UniValue::VOBJ) continue; const UniValue& o = input.get_obj(); name_str = ""; expired = 0; const UniValue& name_value = find_value(o, "name"); if (name_value.type() == UniValue::VSTR) name_str = name_value.get_str(); const UniValue& expired_value = find_value(o, "expired"); if (expired_value.type() == UniValue::VNUM) expired = expired_value.get_int(); if(expired == 0) { QString name = QString::fromStdString(name_str); ui->aliasEdit->addItem(name); } } } } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()), QMessageBox::Ok, QMessageBox::Ok); } } void AcceptandPayOfferListPage::on_imageButton_clicked() { if(m_url.isValid()) QDesktopServices::openUrl(QUrl(m_url.toString(),QUrl::TolerantMode)); } void AcceptandPayOfferListPage::netwManagerFinished() { QNetworkReply* reply = (QNetworkReply*)sender(); if(!reply) return; if (reply->error() != QNetworkReply::NoError) { QMessageBox::critical(this, windowTitle(), reply->errorString(), QMessageBox::Ok, QMessageBox::Ok); return; } QByteArray imageData = reply->readAll(); QPixmap pixmap; pixmap.loadFromData(imageData); QIcon ButtonIcon(pixmap); ui->imageButton->setIcon(ButtonIcon); reply->deleteLater(); } AcceptandPayOfferListPage::~AcceptandPayOfferListPage() { delete ui; this->URIHandled = false; } void AcceptandPayOfferListPage::resetState() { this->offerPaid = false; this->URIHandled = false; updateCaption(); } void AcceptandPayOfferListPage::updateCaption() { if(this->offerPaid) { ui->labelExplanation->setText(tr("<font color='green'>You have successfully paid for this offer!</font>")); } else { ui->labelExplanation->setText(tr("Purchase this offer, Syscoin will be used from your balance to complete the transaction")); } } void AcceptandPayOfferListPage::OpenPayDialog() { OfferAcceptDialog dlg(platformStyle, ui->aliasPegEdit->currentText(), ui->aliasEdit->currentText(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this); if(dlg.exec()) { this->offerPaid = dlg.getPaymentStatus(); } updateCaption(); } void AcceptandPayOfferListPage::OpenBTCPayDialog() { OfferAcceptDialogBTC dlg(platformStyle, ui->aliasEdit->currentText(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this); if(dlg.exec()) { this->offerPaid = dlg.getPaymentStatus(); } updateCaption(); } // send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands. void AcceptandPayOfferListPage::acceptOffer() { if(ui->qtyEdit->text().toUInt() <= 0) { QMessageBox::information(this, windowTitle(), tr("Invalid quantity when trying to accept this offer!"), QMessageBox::Ok, QMessageBox::Ok); return; } if(ui->notesEdit->toPlainText().size() <= 0 && ui->infoCert->text().size() <= 0) { QMessageBox::information(this, windowTitle(), tr("Please enter pertinent information required to the offer in the <b>Notes</b> field (address, e-mail address, shipping notes, etc)."), QMessageBox::Ok, QMessageBox::Ok); return; } if(ui->aliasEdit->currentText().size() <= 0) { QMessageBox::information(this, windowTitle(), tr("Please choose an alias before purchasing this offer."), QMessageBox::Ok, QMessageBox::Ok); return; } this->offerPaid = false; ui->labelExplanation->setText(tr("Waiting for confirmation on the purchase of this offer")); if(bOnlyAcceptBTC) OpenBTCPayDialog(); else OpenPayDialog(); } bool AcceptandPayOfferListPage::lookup(const QString &lookupid) { QString id = lookupid; if(id == QString("")) { id = ui->offeridEdit->text(); } string strError; string strMethod = string("offerinfo"); UniValue params(UniValue::VARR); UniValue result; params.push_back(id.toStdString()); try { result = tableRPC.execute(strMethod, params); if (result.type() == UniValue::VOBJ) { const UniValue &offerObj = result.get_obj(); COffer offerOut; const string &strRand = find_value(offerObj, "offer").get_str(); const string &strAddress = find_value(offerObj, "address").get_str(); offerOut.vchCert = vchFromString(find_value(offerObj, "cert").get_str()); string alias = find_value(offerObj, "alias").get_str(); offerOut.sTitle = vchFromString(find_value(offerObj, "title").get_str()); offerOut.sCategory = vchFromString(find_value(offerObj, "category").get_str()); offerOut.sCurrencyCode = vchFromString(find_value(offerObj, "currency").get_str()); offerOut.vchAliasPeg = vchFromString(find_value(offerObj, "alias_peg").get_str()); if(find_value(offerObj, "quantity").get_str() == "unlimited") offerOut.nQty = -1; else offerOut.nQty = QString::fromStdString(find_value(offerObj, "quantity").get_str()).toUInt(); offerOut.bOnlyAcceptBTC = find_value(offerObj, "btconly").get_str() == "Yes"? true: false; string descString = find_value(offerObj, "description").get_str(); offerOut.sDescription = vchFromString(descString); UniValue outerDescValue(UniValue::VSTR); bool read = outerDescValue.read(descString); if (read) { if(outerDescValue.type() == UniValue::VOBJ) { const UniValue &outerDescObj = outerDescValue.get_obj(); const UniValue &descValue = find_value(outerDescObj, "description"); if (descValue.type() == UniValue::VSTR) { offerOut.sDescription = vchFromString(descValue.get_str()); } } } setValue(QString::fromStdString(alias), QString::fromStdString(strRand), offerOut, QString::fromStdString(find_value(offerObj, "price").get_str()), QString::fromStdString(strAddress)); return true; } } catch (UniValue& objError) { QMessageBox::critical(this, windowTitle(), tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + id, QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()), QMessageBox::Ok, QMessageBox::Ok); } return false; } bool AcceptandPayOfferListPage::handlePaymentRequest(const SendCoinsRecipient *rv) { if(this->URIHandled) { QMessageBox::critical(this, windowTitle(), tr("URI has been already handled"), QMessageBox::Ok, QMessageBox::Ok); return false; } ui->qtyEdit->setText(QString::number(rv->amount)); ui->notesEdit->setPlainText(rv->message); if(lookup(rv->address)) { this->URIHandled = true; acceptOffer(); this->URIHandled = false; } return true; } void AcceptandPayOfferListPage::setValue(const QString& strAlias, const QString& strRand, COffer &offer, QString price, QString address) { loadAliases(); ui->offeridEdit->setText(strRand); if(!offer.vchCert.empty()) { ui->infoCert->setVisible(true); ui->certLabel->setVisible(true); ui->infoCert->setText(QString::fromStdString(stringFromVch(offer.vchCert))); } else { ui->infoCert->setVisible(false); ui->infoCert->setText(""); ui->certLabel->setVisible(false); } ui->sellerEdit->setText(strAlias); ui->infoTitle->setText(QString::fromStdString(stringFromVch(offer.sTitle))); ui->infoCategory->setText(QString::fromStdString(stringFromVch(offer.sCategory))); ui->infoCurrency->setText(QString::fromStdString(stringFromVch(offer.sCurrencyCode))); ui->aliasPegEdit->setText(QString::fromStdString(stringFromVch(offer.vchAliasPeg))); ui->infoPrice->setText(price); if(offer.nQty == -1) ui->infoQty->setText(tr("unlimited")); else ui->infoQty->setText(QString::number(offer.nQty)); ui->infoDescription->setPlainText(QString::fromStdString(stringFromVch(offer.sDescription))); ui->qtyEdit->setText(QString("1")); ui->notesEdit->setPlainText(QString("")); bOnlyAcceptBTC = offer.bOnlyAcceptBTC; sAddress = address; QRegExp rx("(?:https?|ftp)://\\S+"); rx.indexIn(QString::fromStdString(stringFromVch(offer.sDescription))); m_imageList = rx.capturedTexts(); RefreshImage(); } void AcceptandPayOfferListPage::RefreshImage() { QIcon ButtonIcon(m_placeholderImage); ui->imageButton->setIcon(ButtonIcon); if(m_imageList.size() > 0 && m_imageList.at(0) != QString("")) { QString parsedURL = m_imageList.at(0).simplified(); m_url = QUrl(parsedURL); if(m_url.isValid()) { QNetworkRequest request(m_url); request.setRawHeader("Accept", "q=0.9,image/webp,*/*;q=0.8"); request.setRawHeader("Cache-Control", "no-cache"); request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36"); QNetworkReply *reply = m_netwManager->get(request); reply->ignoreSslErrors(); connect(reply, SIGNAL(finished()), this, SLOT(netwManagerFinished())); } } } <commit_msg>typo<commit_after>#include "acceptandpayofferlistpage.h" #include "ui_acceptandpayofferlistpage.h" #include "init.h" #include "util.h" #include "offeracceptdialog.h" #include "offeracceptdialogbtc.h" #include "offer.h" #include "syscoingui.h" #include "guiutil.h" #include "platformstyle.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #include <QString> #include <QByteArray> #include <QPixmap> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QRegExp> #include <QStringList> #include <QDesktopServices> #include "rpcserver.h" #include "alias.h" #include "walletmodel.h" using namespace std; extern const CRPCTable tableRPC; AcceptandPayOfferListPage::AcceptandPayOfferListPage(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), platformStyle(platformStyle), ui(new Ui::AcceptandPayOfferListPage) { sAddress = ""; bOnlyAcceptBTC = false; ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!platformStyle->getImagesOnButtons()) { ui->lookupButton->setIcon(QIcon()); ui->acceptButton->setIcon(QIcon()); ui->imageButton->setIcon(QIcon()); } else { ui->lookupButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/search")); ui->acceptButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/cart")); } ui->imageButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/imageplaceholder")); this->offerPaid = false; this->URIHandled = false; ui->labelExplanation->setText(tr("Purchase an offer, Syscoin will be used from your balance to complete the transaction")); connect(ui->acceptButton, SIGNAL(clicked()), this, SLOT(acceptOffer())); connect(ui->lookupButton, SIGNAL(clicked()), this, SLOT(lookup())); connect(ui->offeridEdit, SIGNAL(textChanged(const QString &)), this, SLOT(resetState())); ui->notesEdit->setStyleSheet("color: rgb(0, 0, 0); background-color: rgb(255, 255, 255)"); ui->aliasDisclaimer->setText(tr("<font color='blue'>Select an Alias</font>")); m_netwManager = new QNetworkAccessManager(this); m_placeholderImage.load(":/images/" + theme + "/imageplaceholder"); ui->imageButton->setToolTip(tr("Click to open image in browser...")); ui->infoCert->setVisible(false); ui->certLabel->setVisible(false); RefreshImage(); } void AcceptandPayOfferListPage::loadAliases() { ui->aliasEdit->clear(); string strMethod = string("aliaslist"); UniValue params(UniValue::VARR); UniValue result ; string name_str; int expired = 0; try { result = tableRPC.execute(strMethod, params); if (result.type() == UniValue::VARR) { name_str = ""; expired = 0; const UniValue &arr = result.get_array(); for (unsigned int idx = 0; idx < arr.size(); idx++) { const UniValue& input = arr[idx]; if (input.type() != UniValue::VOBJ) continue; const UniValue& o = input.get_obj(); name_str = ""; expired = 0; const UniValue& name_value = find_value(o, "name"); if (name_value.type() == UniValue::VSTR) name_str = name_value.get_str(); const UniValue& expired_value = find_value(o, "expired"); if (expired_value.type() == UniValue::VNUM) expired = expired_value.get_int(); if(expired == 0) { QString name = QString::fromStdString(name_str); ui->aliasEdit->addItem(name); } } } } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()), QMessageBox::Ok, QMessageBox::Ok); } } void AcceptandPayOfferListPage::on_imageButton_clicked() { if(m_url.isValid()) QDesktopServices::openUrl(QUrl(m_url.toString(),QUrl::TolerantMode)); } void AcceptandPayOfferListPage::netwManagerFinished() { QNetworkReply* reply = (QNetworkReply*)sender(); if(!reply) return; if (reply->error() != QNetworkReply::NoError) { QMessageBox::critical(this, windowTitle(), reply->errorString(), QMessageBox::Ok, QMessageBox::Ok); return; } QByteArray imageData = reply->readAll(); QPixmap pixmap; pixmap.loadFromData(imageData); QIcon ButtonIcon(pixmap); ui->imageButton->setIcon(ButtonIcon); reply->deleteLater(); } AcceptandPayOfferListPage::~AcceptandPayOfferListPage() { delete ui; this->URIHandled = false; } void AcceptandPayOfferListPage::resetState() { this->offerPaid = false; this->URIHandled = false; updateCaption(); } void AcceptandPayOfferListPage::updateCaption() { if(this->offerPaid) { ui->labelExplanation->setText(tr("<font color='green'>You have successfully paid for this offer!</font>")); } else { ui->labelExplanation->setText(tr("Purchase this offer, Syscoin will be used from your balance to complete the transaction")); } } void AcceptandPayOfferListPage::OpenPayDialog() { OfferAcceptDialog dlg(platformStyle, ui->aliasPegEdit->text(), ui->aliasEdit->currentText(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this); if(dlg.exec()) { this->offerPaid = dlg.getPaymentStatus(); } updateCaption(); } void AcceptandPayOfferListPage::OpenBTCPayDialog() { OfferAcceptDialogBTC dlg(platformStyle, ui->aliasEdit->text(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this); if(dlg.exec()) { this->offerPaid = dlg.getPaymentStatus(); } updateCaption(); } // send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands. void AcceptandPayOfferListPage::acceptOffer() { if(ui->qtyEdit->text().toUInt() <= 0) { QMessageBox::information(this, windowTitle(), tr("Invalid quantity when trying to accept this offer!"), QMessageBox::Ok, QMessageBox::Ok); return; } if(ui->notesEdit->toPlainText().size() <= 0 && ui->infoCert->text().size() <= 0) { QMessageBox::information(this, windowTitle(), tr("Please enter pertinent information required to the offer in the <b>Notes</b> field (address, e-mail address, shipping notes, etc)."), QMessageBox::Ok, QMessageBox::Ok); return; } if(ui->aliasEdit->currentText().size() <= 0) { QMessageBox::information(this, windowTitle(), tr("Please choose an alias before purchasing this offer."), QMessageBox::Ok, QMessageBox::Ok); return; } this->offerPaid = false; ui->labelExplanation->setText(tr("Waiting for confirmation on the purchase of this offer")); if(bOnlyAcceptBTC) OpenBTCPayDialog(); else OpenPayDialog(); } bool AcceptandPayOfferListPage::lookup(const QString &lookupid) { QString id = lookupid; if(id == QString("")) { id = ui->offeridEdit->text(); } string strError; string strMethod = string("offerinfo"); UniValue params(UniValue::VARR); UniValue result; params.push_back(id.toStdString()); try { result = tableRPC.execute(strMethod, params); if (result.type() == UniValue::VOBJ) { const UniValue &offerObj = result.get_obj(); COffer offerOut; const string &strRand = find_value(offerObj, "offer").get_str(); const string &strAddress = find_value(offerObj, "address").get_str(); offerOut.vchCert = vchFromString(find_value(offerObj, "cert").get_str()); string alias = find_value(offerObj, "alias").get_str(); offerOut.sTitle = vchFromString(find_value(offerObj, "title").get_str()); offerOut.sCategory = vchFromString(find_value(offerObj, "category").get_str()); offerOut.sCurrencyCode = vchFromString(find_value(offerObj, "currency").get_str()); offerOut.vchAliasPeg = vchFromString(find_value(offerObj, "alias_peg").get_str()); if(find_value(offerObj, "quantity").get_str() == "unlimited") offerOut.nQty = -1; else offerOut.nQty = QString::fromStdString(find_value(offerObj, "quantity").get_str()).toUInt(); offerOut.bOnlyAcceptBTC = find_value(offerObj, "btconly").get_str() == "Yes"? true: false; string descString = find_value(offerObj, "description").get_str(); offerOut.sDescription = vchFromString(descString); UniValue outerDescValue(UniValue::VSTR); bool read = outerDescValue.read(descString); if (read) { if(outerDescValue.type() == UniValue::VOBJ) { const UniValue &outerDescObj = outerDescValue.get_obj(); const UniValue &descValue = find_value(outerDescObj, "description"); if (descValue.type() == UniValue::VSTR) { offerOut.sDescription = vchFromString(descValue.get_str()); } } } setValue(QString::fromStdString(alias), QString::fromStdString(strRand), offerOut, QString::fromStdString(find_value(offerObj, "price").get_str()), QString::fromStdString(strAddress)); return true; } } catch (UniValue& objError) { QMessageBox::critical(this, windowTitle(), tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + id, QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()), QMessageBox::Ok, QMessageBox::Ok); } return false; } bool AcceptandPayOfferListPage::handlePaymentRequest(const SendCoinsRecipient *rv) { if(this->URIHandled) { QMessageBox::critical(this, windowTitle(), tr("URI has been already handled"), QMessageBox::Ok, QMessageBox::Ok); return false; } ui->qtyEdit->setText(QString::number(rv->amount)); ui->notesEdit->setPlainText(rv->message); if(lookup(rv->address)) { this->URIHandled = true; acceptOffer(); this->URIHandled = false; } return true; } void AcceptandPayOfferListPage::setValue(const QString& strAlias, const QString& strRand, COffer &offer, QString price, QString address) { loadAliases(); ui->offeridEdit->setText(strRand); if(!offer.vchCert.empty()) { ui->infoCert->setVisible(true); ui->certLabel->setVisible(true); ui->infoCert->setText(QString::fromStdString(stringFromVch(offer.vchCert))); } else { ui->infoCert->setVisible(false); ui->infoCert->setText(""); ui->certLabel->setVisible(false); } ui->sellerEdit->setText(strAlias); ui->infoTitle->setText(QString::fromStdString(stringFromVch(offer.sTitle))); ui->infoCategory->setText(QString::fromStdString(stringFromVch(offer.sCategory))); ui->infoCurrency->setText(QString::fromStdString(stringFromVch(offer.sCurrencyCode))); ui->aliasPegEdit->setText(QString::fromStdString(stringFromVch(offer.vchAliasPeg))); ui->infoPrice->setText(price); if(offer.nQty == -1) ui->infoQty->setText(tr("unlimited")); else ui->infoQty->setText(QString::number(offer.nQty)); ui->infoDescription->setPlainText(QString::fromStdString(stringFromVch(offer.sDescription))); ui->qtyEdit->setText(QString("1")); ui->notesEdit->setPlainText(QString("")); bOnlyAcceptBTC = offer.bOnlyAcceptBTC; sAddress = address; QRegExp rx("(?:https?|ftp)://\\S+"); rx.indexIn(QString::fromStdString(stringFromVch(offer.sDescription))); m_imageList = rx.capturedTexts(); RefreshImage(); } void AcceptandPayOfferListPage::RefreshImage() { QIcon ButtonIcon(m_placeholderImage); ui->imageButton->setIcon(ButtonIcon); if(m_imageList.size() > 0 && m_imageList.at(0) != QString("")) { QString parsedURL = m_imageList.at(0).simplified(); m_url = QUrl(parsedURL); if(m_url.isValid()) { QNetworkRequest request(m_url); request.setRawHeader("Accept", "q=0.9,image/webp,*/*;q=0.8"); request.setRawHeader("Cache-Control", "no-cache"); request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36"); QNetworkReply *reply = m_netwManager->get(request); reply->ignoreSslErrors(); connect(reply, SIGNAL(finished()), this, SLOT(netwManagerFinished())); } } } <|endoftext|>
<commit_before>// https://leetcode.com/problems/course-schedule-ii/ /* There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. For example: 2, [[1,0]] There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] 4, [[1,0],[2,0],[3,1],[3,2]] There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3]. */ #include <vector> #include <utility> #include <iostream> #include <algorithm> struct GraphNode { int m_value; bool visited; std::vector<GraphNode*> m_edges; explicit GraphNode(int value): m_value(value), visited(false), m_edges() {} }; class Solution { public: std::vector<int> findOrder(int numCourses, std::vector<std::pair<int, int>>& prerequisites) const { std::vector<int> ordering; std::vector<GraphNode*> graph(numCourses); // Construct a graph of the pairs // [[1,0],[2,0],[3,1],[3,2]] -> [<1, 2>, <3>, <3>, <0>] for (int i = 0; i < (int)prerequisites.size(); ++i) { const auto& edge = prerequisites[i]; if (graph[edge.first] == nullptr) { graph[edge.first] = new GraphNode(edge.first); } if (graph[edge.second] == nullptr) { graph[edge.second] = new GraphNode(edge.second); } graph[edge.second]->m_edges.push_back(graph[edge.first]); } // Topologically sort the graph for (int i = 0; i < numCourses; ++i) { auto node = graph[i]; if (node) { visit(node, ordering); } else { ordering.push_back(i); } } std::reverse(ordering.begin(), ordering.end()); // Clean up and return for (auto& x : graph) delete x; return ordering; } private: void visit(GraphNode* node, std::vector<int>& ordering) const { if (node->visited) return; node->visited = true; auto& edges = node->m_edges; for (int i = 0; i < (int)edges.size(); ++i) { visit(edges[i], ordering); } ordering.push_back(node->m_value); } }; <commit_msg>:art: fix course schedule using Kahn's<commit_after>// https://leetcode.com/problems/course-schedule-ii/ /* There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. For example: 2, [[1,0]] There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] 4, [[1,0],[2,0],[3,1],[3,2]] There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3]. */ #include <vector> #include <utility> #include <iostream> #include <algorithm> #include <unordered_set> struct GraphNode { unsigned m_indegree; std::unordered_set<int> m_edges; GraphNode(): m_indegree(0), m_edges() {} }; class Solution { public: std::vector<int> findOrder(int numCourses, std::vector<std::pair<int, int>>& prerequisites) const { std::vector<int> ordering; std::vector<int> topNodes; std::vector<GraphNode*> graph(numCourses, nullptr); // Build a graph from the edges for (size_t i = 0; i < prerequisites.size(); ++i) { auto const& edge = prerequisites[i]; if (graph[edge.first] == nullptr) { graph[edge.first] = new GraphNode(); } if (graph[edge.second] == nullptr) { graph[edge.second] = new GraphNode(); } auto& edges = graph[edge.second]->m_edges; if (edges.find(edge.first) == edges.end()) { edges.insert(edge.first); graph[edge.first]->m_indegree++; } } // Push edges with degree 0 into topNodes for (int i = 0; i < numCourses; ++i) { if (graph[i] == nullptr) ordering.push_back(i); else if (graph[i]->m_indegree == 0) topNodes.push_back(i); } // Kahn's algorithm while (topNodes.size() > 0) { int const node = topNodes.back(); auto const& edges = graph[node]->m_edges; topNodes.pop_back(); ordering.push_back(node); for (int const node : edges) { GraphNode* const g = graph[node]; g->m_indegree--; if (g->m_indegree == 0) { topNodes.push_back(node); } } } // If all nodes don't have a degree of 0 then there's a cycle for (int i = 0; i < numCourses; ++i) { if (graph[i] && graph[i]->m_indegree != 0) { ordering = {}; break; } } // Clean up memory and return for (int i = 0; i < numCourses; ++i) { if (graph[i] != nullptr) delete graph[i]; } return ordering; } }; int main() { Solution s; std::pair<int, int> pair1 = std::make_pair(1, 0); std::pair<int, int> pair2 = std::make_pair(2, 0); std::vector<std::pair<int,int>> vec = { pair1, pair2 }; auto ordering = s.findOrder(4, vec); std::cout << "RESULTS\n"; for (auto x : ordering) std::cout << x << std::endl; } <|endoftext|>
<commit_before>#ifndef PYTHONIC_TYPES_SET_HPP #define PYTHONIC_TYPES_SET_HPP #include "pythonic/include/types/set.hpp" #include "pythonic/types/assignable.hpp" #include "pythonic/types/empty_iterator.hpp" #include "pythonic/types/list.hpp" #include "pythonic/utils/iterator.hpp" #include "pythonic/utils/reserve.hpp" #include "pythonic/utils/shared_ref.hpp" #include "pythonic/builtins/in.hpp" #include <set> #include <memory> #include <utility> #include <limits> #include <algorithm> #include <iterator> PYTHONIC_NS_BEGIN namespace types { /// set implementation // constructors template <class T> set<T>::set() : data(utils::no_memory()) { } template <class T> template <class InputIterator> set<T>::set(InputIterator start, InputIterator stop) : data() { std::copy(start, stop, std::back_inserter(*this)); } template <class T> set<T>::set(empty_set const &) : data() { } template <class T> set<T>::set(T const &value, single_value) : data() { data->insert(value); } template <class T> set<T>::set(std::initializer_list<value_type> l) : data(std::move(l)) { } template <class T> set<T>::set(set<T> const &other) : data(other.data) { } template <class T> template <class F> set<T>::set(set<F> const &other) : data() { std::copy(other.begin(), other.end(), std::inserter(*data, data->begin())); } // iterators template <class T> typename set<T>::iterator set<T>::begin() { return data->begin(); } template <class T> typename set<T>::const_iterator set<T>::begin() const { return data->begin(); } template <class T> typename set<T>::iterator set<T>::end() { return data->end(); } template <class T> typename set<T>::const_iterator set<T>::end() const { return data->end(); } template <class T> typename set<T>::reverse_iterator set<T>::rbegin() { return data->rbegin(); } template <class T> typename set<T>::const_reverse_iterator set<T>::rbegin() const { return data->rbegin(); } template <class T> typename set<T>::reverse_iterator set<T>::rend() { return data->rend(); } template <class T> typename set<T>::const_reverse_iterator set<T>::rend() const { return data->rend(); } // modifiers template <class T> T set<T>::pop() { if (size() <= 0) throw std::out_of_range("Trying to pop() an empty set."); T tmp = *begin(); data->erase(begin()); return tmp; } template <class T> void set<T>::add(const T &x) { data->insert(x); } template <class T> void set<T>::push_back(const T &x) { data->insert(x); } template <class T> void set<T>::clear() { data->clear(); } template <class T> template <class U> void set<T>::discard(U const &elem) { // Remove element elem from the set if it is present. data->erase(elem); } template <class T> template <class U> void set<T>::remove(U const &elem) { // Remove element elem from the set. Raises KeyError if elem is ! // contained in the set. if (!data->erase(elem)) throw std::runtime_error( "set.delete() : couldn't delete element ! in the set."); } // set interface template <class T> set<T>::operator bool() const { return !data->empty(); } template <class T> long set<T>::size() const { return data->size(); } // Misc template <class T> set<T> set<T>::copy() const { return set<T>(begin(), end()); } template <class T> template <class U> bool set<T>::isdisjoint(U const &other) const { // Return true if the this has no elements in common with other. for (iterator it = begin(); it != end(); ++it) { if (in(other, *it)) return false; } return true; } template <class T> template <class U> bool set<T>::issubset(U const &other) const { // Test whether every element in the set is in other. for (iterator it = begin(); it != end(); ++it) { if (!in(other, *it)) return false; } return true; } template <class T> template <class U> bool set<T>::issuperset(U const &other) const { // Test whether every element in other is in the set. return other.issubset(*this); } template <class T> set<T> set<T>::union_() const { return set<T>(begin(), end()); } template <class T> template <typename U, typename... Types> typename __combined<set<T>, U, Types...>::type set<T>::union_(U &&other, Types &&... others) const { typename __combined<set<T>, U, Types...>::type tmp = union_(std::forward<Types...>(others)...); tmp.data->insert(other.begin(), other.end()); return tmp; } template <class T> template <typename... Types> none_type set<T>::update(Types &&... others) { *this = union_(std::forward<Types>(others)...); return {}; } template <class T> set<T> set<T>::intersection() const { return set<T>(begin(), end()); } template <class T> template <typename U, typename... Types> typename __combined<set<T>, U, Types...>::type set<T>::intersection(U const &other, Types const &... others) const { // Return a new set with elements common to the set && all others. typename __combined<set<T>, U, Types...>::type tmp = intersection(others...); for (auto it = tmp.begin(); it != tmp.end(); ++it) { if (!in(other, *it)) tmp.discard( *it); // faster than remove() but ! direct interaction with data } return tmp; } template <class T> template <typename... Types> void set<T>::intersection_update(Types const &... others) { *this = intersection(others...); } template <class T> set<T> set<T>::difference() const { return set<T>(begin(), end()); } template <class T> template <typename U, typename... Types> set<T> set<T>::difference(U const &other, Types const &... others) const { // Return a new set with elements in the set that are ! in the others. set<T> tmp = difference(others...); /* for(iterator it=tmp.begin(); it!=tmp.end();++it){ if(other.get_data().find(*it)!=other.end()) tmp.discard(*it); } */ // This algo will do several times the same find(), because // std::set::erase() calls find. Lame! for (typename U::const_iterator it = other.begin(); it != other.end(); ++it) { tmp.discard(*it); } return tmp; } template <class T> template <class V> bool set<T>::contains(V const &v) const { return data->find(v) != data->end(); } template <class T> template <typename... Types> void set<T>::difference_update(Types const &... others) { *this = difference(others...); } template <class T> template <typename U> set<typename __combined<T, U>::type> set<T>::symmetric_difference(set<U> const &other) const { // Return a new set with elements in either the set || other but ! both. // return ((*this-other) | (other-*this)); // We must use fcts && ! operators because fcts have to handle any // iterable objects && operators only sets (cf python ref) return (this->difference(other)).union_(other.difference(*this)); } template <class T> template <typename U> typename __combined<U, set<T>>::type set<T>::symmetric_difference(U const &other) const { // Return a new set with elements in either the set || other but ! both. set<typename std::iterator_traits<typename U::iterator>::value_type> tmp( other.begin(), other.end()); // We must use fcts && ! operators because fcts have to handle any // iterable objects && operators only sets (cf python ref) return (this->difference(other)).union_(tmp.difference(*this)); } template <class T> template <typename U> void set<T>::symmetric_difference_update(U const &other) { *this = symmetric_difference(other); } // Operators template <class T> template <class U> bool set<T>::operator==(set<U> const &other) const { return *data == *other.data; } template <class T> template <class U> bool set<T>::operator<=(set<U> const &other) const { // Every element in *this is in other return issubset(other); } template <class T> template <class U> bool set<T>::operator<(set<U> const &other) const { // Every element in this is in other && this != other return (*this <= other) && (this->size() != other.size()); } template <class T> template <class U> bool set<T>::operator>=(set<U> const &other) const { // Every element in other is in set return other <= *this; } template <class T> template <class U> bool set<T>::operator>(set<U> const &other) const { // Every element in other is in set && this != other return other < *this; } template <class T> template <class U> set<typename __combined<T, U>::type> set<T>:: operator|(set<U> const &other) const { return union_(other); } template <class T> template <class U> void set<T>::operator|=(set<U> const &other) { update(other); } template <class T> template <class U> set<typename __combined<U, T>::type> set<T>:: operator&(set<U> const &other) const { return intersection(other); } template <class T> template <class U> void set<T>::operator&=(set<U> const &other) { return intersection_update(other); } template <class T> template <class U> set<T> set<T>::operator-(set<U> const &other) const { return difference(other); } template <class T> template <class U> void set<T>::operator-=(set<U> const &other) { return difference_update(other); } template <class T> template <class U> set<typename __combined<U, T>::type> set<T>:: operator^(set<U> const &other) const { return symmetric_difference(other); } template <class T> template <class U> void set<T>::operator^=(set<U> const &other) { return symmetric_difference_update(other); } template <class T> intptr_t set<T>::id() const { return reinterpret_cast<intptr_t>(&(*data)); } template <class T> std::ostream &operator<<(std::ostream &os, set<T> const &v) { if (v.size() == 0) { return os << "set()"; } os << "{"; const char *commaSeparator = ""; for (const auto &e : v) { os << commaSeparator << e; commaSeparator = ", "; } return os << "}"; } /// empty_set implementation empty_set empty_set::operator|(empty_set const &) { return empty_set(); } template <class T> set<T> empty_set::operator|(set<T> const &s) { return s; } template <class U> U empty_set::operator&(U const &s) { return {}; } template <class U> U empty_set::operator-(U const &s) { return {}; } empty_set empty_set::operator^(empty_set const &) { return empty_set(); } template <class T> set<T> empty_set::operator^(set<T> const &s) { return s; } template <class... Types> none_type empty_set::update(Types &&...) { return {}; } empty_set::operator bool() { return false; } empty_set::iterator empty_set::begin() const { return empty_iterator(); } empty_set::iterator empty_set::end() const { return empty_iterator(); } template <class V> bool empty_set::contains(V const &) const { return false; } } PYTHONIC_NS_END #ifdef ENABLE_PYTHON_MODULE PYTHONIC_NS_BEGIN template <typename T> PyObject *to_python<types::set<T>>::convert(types::set<T> const &v) { PyObject *obj = PySet_New(nullptr); for (auto const &e : v) PySet_Add(obj, ::to_python(e)); return obj; } PyObject *to_python<types::empty_set>::convert(types::empty_set) { return PySet_New(nullptr); } template <class T> bool from_python<types::set<T>>::is_convertible(PyObject *obj) { if (PySet_Check(obj)) { PyObject *iterator = PyObject_GetIter(obj); if (PyObject *item = PyIter_Next(iterator)) { bool res = ::is_convertible<T>(item); Py_DECREF(item); Py_DECREF(iterator); return res; } else { Py_DECREF(iterator); return true; } } return false; } template <class T> types::set<T> from_python<types::set<T>>::convert(PyObject *obj) { types::set<T> v = types::empty_set(); // may be useful to reserve more space ? PyObject *iterator = PyObject_GetIter(obj); while (PyObject *item = PyIter_Next(iterator)) { v.add(::from_python<T>(item)); Py_DECREF(item); } Py_DECREF(iterator); return v; } PYTHONIC_NS_END #endif #endif <commit_msg>FIX: set intersection<commit_after>#ifndef PYTHONIC_TYPES_SET_HPP #define PYTHONIC_TYPES_SET_HPP #include "pythonic/include/types/set.hpp" #include "pythonic/types/assignable.hpp" #include "pythonic/types/empty_iterator.hpp" #include "pythonic/types/list.hpp" #include "pythonic/utils/iterator.hpp" #include "pythonic/utils/reserve.hpp" #include "pythonic/utils/shared_ref.hpp" #include "pythonic/builtins/in.hpp" #include <set> #include <memory> #include <utility> #include <limits> #include <algorithm> #include <iterator> PYTHONIC_NS_BEGIN namespace types { /// set implementation // constructors template <class T> set<T>::set() : data(utils::no_memory()) { } template <class T> template <class InputIterator> set<T>::set(InputIterator start, InputIterator stop) : data() { std::copy(start, stop, std::back_inserter(*this)); } template <class T> set<T>::set(empty_set const &) : data() { } template <class T> set<T>::set(T const &value, single_value) : data() { data->insert(value); } template <class T> set<T>::set(std::initializer_list<value_type> l) : data(std::move(l)) { } template <class T> set<T>::set(set<T> const &other) : data(other.data) { } template <class T> template <class F> set<T>::set(set<F> const &other) : data() { std::copy(other.begin(), other.end(), std::inserter(*data, data->begin())); } // iterators template <class T> typename set<T>::iterator set<T>::begin() { return data->begin(); } template <class T> typename set<T>::const_iterator set<T>::begin() const { return data->begin(); } template <class T> typename set<T>::iterator set<T>::end() { return data->end(); } template <class T> typename set<T>::const_iterator set<T>::end() const { return data->end(); } template <class T> typename set<T>::reverse_iterator set<T>::rbegin() { return data->rbegin(); } template <class T> typename set<T>::const_reverse_iterator set<T>::rbegin() const { return data->rbegin(); } template <class T> typename set<T>::reverse_iterator set<T>::rend() { return data->rend(); } template <class T> typename set<T>::const_reverse_iterator set<T>::rend() const { return data->rend(); } // modifiers template <class T> T set<T>::pop() { if (size() <= 0) throw std::out_of_range("Trying to pop() an empty set."); T tmp = *begin(); data->erase(begin()); return tmp; } template <class T> void set<T>::add(const T &x) { data->insert(x); } template <class T> void set<T>::push_back(const T &x) { data->insert(x); } template <class T> void set<T>::clear() { data->clear(); } template <class T> template <class U> void set<T>::discard(U const &elem) { // Remove element elem from the set if it is present. data->erase(elem); } template <class T> template <class U> void set<T>::remove(U const &elem) { // Remove element elem from the set. Raises KeyError if elem is ! // contained in the set. if (!data->erase(elem)) throw std::runtime_error( "set.delete() : couldn't delete element ! in the set."); } // set interface template <class T> set<T>::operator bool() const { return !data->empty(); } template <class T> long set<T>::size() const { return data->size(); } // Misc template <class T> set<T> set<T>::copy() const { return set<T>(begin(), end()); } template <class T> template <class U> bool set<T>::isdisjoint(U const &other) const { // Return true if the this has no elements in common with other. for (iterator it = begin(); it != end(); ++it) { if (in(other, *it)) return false; } return true; } template <class T> template <class U> bool set<T>::issubset(U const &other) const { // Test whether every element in the set is in other. for (iterator it = begin(); it != end(); ++it) { if (!in(other, *it)) return false; } return true; } template <class T> template <class U> bool set<T>::issuperset(U const &other) const { // Test whether every element in other is in the set. return other.issubset(*this); } template <class T> set<T> set<T>::union_() const { return set<T>(begin(), end()); } template <class T> template <typename U, typename... Types> typename __combined<set<T>, U, Types...>::type set<T>::union_(U &&other, Types &&... others) const { typename __combined<set<T>, U, Types...>::type tmp = union_(std::forward<Types...>(others)...); tmp.data->insert(other.begin(), other.end()); return tmp; } template <class T> template <typename... Types> none_type set<T>::update(Types &&... others) { *this = union_(std::forward<Types>(others)...); return {}; } template <class T> set<T> set<T>::intersection() const { return set<T>(begin(), end()); } template <class T> template <typename U, typename... Types> typename __combined<set<T>, U, Types...>::type set<T>::intersection(U const &other, Types const &... others) const { // Return a new set with elements common to the set && all others. typename __combined<set<T>, U, Types...>::type tmp = intersection(others...); for (auto it = begin(); it != end(); ++it) { if (!in(other, *it)) tmp.discard( *it); // faster than remove() but ! direct interaction with data } return tmp; } template <class T> template <typename... Types> void set<T>::intersection_update(Types const &... others) { *this = intersection(others...); } template <class T> set<T> set<T>::difference() const { return set<T>(begin(), end()); } template <class T> template <typename U, typename... Types> set<T> set<T>::difference(U const &other, Types const &... others) const { // Return a new set with elements in the set that are ! in the others. set<T> tmp = difference(others...); /* for(iterator it=tmp.begin(); it!=tmp.end();++it){ if(other.get_data().find(*it)!=other.end()) tmp.discard(*it); } */ // This algo will do several times the same find(), because // std::set::erase() calls find. Lame! for (typename U::const_iterator it = other.begin(); it != other.end(); ++it) { tmp.discard(*it); } return tmp; } template <class T> template <class V> bool set<T>::contains(V const &v) const { return data->find(v) != data->end(); } template <class T> template <typename... Types> void set<T>::difference_update(Types const &... others) { *this = difference(others...); } template <class T> template <typename U> set<typename __combined<T, U>::type> set<T>::symmetric_difference(set<U> const &other) const { // Return a new set with elements in either the set || other but ! both. // return ((*this-other) | (other-*this)); // We must use fcts && ! operators because fcts have to handle any // iterable objects && operators only sets (cf python ref) return (this->difference(other)).union_(other.difference(*this)); } template <class T> template <typename U> typename __combined<U, set<T>>::type set<T>::symmetric_difference(U const &other) const { // Return a new set with elements in either the set || other but ! both. set<typename std::iterator_traits<typename U::iterator>::value_type> tmp( other.begin(), other.end()); // We must use fcts && ! operators because fcts have to handle any // iterable objects && operators only sets (cf python ref) return (this->difference(other)).union_(tmp.difference(*this)); } template <class T> template <typename U> void set<T>::symmetric_difference_update(U const &other) { *this = symmetric_difference(other); } // Operators template <class T> template <class U> bool set<T>::operator==(set<U> const &other) const { return *data == *other.data; } template <class T> template <class U> bool set<T>::operator<=(set<U> const &other) const { // Every element in *this is in other return issubset(other); } template <class T> template <class U> bool set<T>::operator<(set<U> const &other) const { // Every element in this is in other && this != other return (*this <= other) && (this->size() != other.size()); } template <class T> template <class U> bool set<T>::operator>=(set<U> const &other) const { // Every element in other is in set return other <= *this; } template <class T> template <class U> bool set<T>::operator>(set<U> const &other) const { // Every element in other is in set && this != other return other < *this; } template <class T> template <class U> set<typename __combined<T, U>::type> set<T>:: operator|(set<U> const &other) const { return union_(other); } template <class T> template <class U> void set<T>::operator|=(set<U> const &other) { update(other); } template <class T> template <class U> set<typename __combined<U, T>::type> set<T>:: operator&(set<U> const &other) const { return intersection(other); } template <class T> template <class U> void set<T>::operator&=(set<U> const &other) { return intersection_update(other); } template <class T> template <class U> set<T> set<T>::operator-(set<U> const &other) const { return difference(other); } template <class T> template <class U> void set<T>::operator-=(set<U> const &other) { return difference_update(other); } template <class T> template <class U> set<typename __combined<U, T>::type> set<T>:: operator^(set<U> const &other) const { return symmetric_difference(other); } template <class T> template <class U> void set<T>::operator^=(set<U> const &other) { return symmetric_difference_update(other); } template <class T> intptr_t set<T>::id() const { return reinterpret_cast<intptr_t>(&(*data)); } template <class T> std::ostream &operator<<(std::ostream &os, set<T> const &v) { if (v.size() == 0) { return os << "set()"; } os << "{"; const char *commaSeparator = ""; for (const auto &e : v) { os << commaSeparator << e; commaSeparator = ", "; } return os << "}"; } /// empty_set implementation empty_set empty_set::operator|(empty_set const &) { return empty_set(); } template <class T> set<T> empty_set::operator|(set<T> const &s) { return s; } template <class U> U empty_set::operator&(U const &s) { return {}; } template <class U> U empty_set::operator-(U const &s) { return {}; } empty_set empty_set::operator^(empty_set const &) { return empty_set(); } template <class T> set<T> empty_set::operator^(set<T> const &s) { return s; } template <class... Types> none_type empty_set::update(Types &&...) { return {}; } empty_set::operator bool() { return false; } empty_set::iterator empty_set::begin() const { return empty_iterator(); } empty_set::iterator empty_set::end() const { return empty_iterator(); } template <class V> bool empty_set::contains(V const &) const { return false; } } PYTHONIC_NS_END #ifdef ENABLE_PYTHON_MODULE PYTHONIC_NS_BEGIN template <typename T> PyObject *to_python<types::set<T>>::convert(types::set<T> const &v) { PyObject *obj = PySet_New(nullptr); for (auto const &e : v) PySet_Add(obj, ::to_python(e)); return obj; } PyObject *to_python<types::empty_set>::convert(types::empty_set) { return PySet_New(nullptr); } template <class T> bool from_python<types::set<T>>::is_convertible(PyObject *obj) { if (PySet_Check(obj)) { PyObject *iterator = PyObject_GetIter(obj); if (PyObject *item = PyIter_Next(iterator)) { bool res = ::is_convertible<T>(item); Py_DECREF(item); Py_DECREF(iterator); return res; } else { Py_DECREF(iterator); return true; } } return false; } template <class T> types::set<T> from_python<types::set<T>>::convert(PyObject *obj) { types::set<T> v = types::empty_set(); // may be useful to reserve more space ? PyObject *iterator = PyObject_GetIter(obj); while (PyObject *item = PyIter_Next(iterator)) { v.add(::from_python<T>(item)); Py_DECREF(item); } Py_DECREF(iterator); return v; } PYTHONIC_NS_END #endif #endif <|endoftext|>
<commit_before>#pragma once namespace openMVG { namespace robust { enum EROBUST_ESTIMATOR { ROBUST_ESTIMATOR_START = 0, ROBUST_ESTIMATOR_ACRANSAC = 1, //< A-Contrario Ransac. ROBUST_ESTIMATOR_RANSAC = 2, //< Classic Ransac. ROBUST_ESTIMATOR_LSMEDS = 3, //< Variant of RANSAC using Least Median of Squares. ROBUST_ESTIMATOR_LORANSAC = 4, //< LO-Ransac. ROBUST_ESTIMATOR_MAXCONSENSUS = 5, //< Naive implementation of RANSAC without noise and iteration reduction options. ROBUST_ESTIMATOR_END }; inline std::string EROBUST_ESTIMATOR_enumToString(EROBUST_ESTIMATOR estimator) { switch(estimator) { case ROBUST_ESTIMATOR_ACRANSAC: return "acransac"; case ROBUST_ESTIMATOR_RANSAC: return "ransac"; case ROBUST_ESTIMATOR_LSMEDS: return "lsmeds"; case ROBUST_ESTIMATOR_LORANSAC: return "loransac"; case ROBUST_ESTIMATOR_MAXCONSENSUS: return "maxconsensus"; case ROBUST_ESTIMATOR_START: case ROBUST_ESTIMATOR_END: break; } throw std::out_of_range("Invalid Ransac type Enum"); } inline EROBUST_ESTIMATOR EROBUST_ESTIMATOR_stringToEnum(const std::string& estimator) { if(estimator == "acransac") return ROBUST_ESTIMATOR_ACRANSAC; if(estimator == "ransac") return ROBUST_ESTIMATOR_RANSAC; if(estimator == "lsmeds") return ROBUST_ESTIMATOR_LSMEDS; if(estimator == "loransac") return ROBUST_ESTIMATOR_LORANSAC; if(estimator == "maxconsensus") return ROBUST_ESTIMATOR_MAXCONSENSUS; throw std::out_of_range("Invalid Ransac type string " + estimator); } inline std::ostream& operator<<(std::ostream& os, EROBUST_ESTIMATOR e) { return os << EROBUST_ESTIMATOR_enumToString(e); } } //namespace robust } //namespace openMVG <commit_msg>[robust] added operator>> for EROBUST_ESTIMATOR and missing includes<commit_after>#pragma once #include <string> #include <iostream> namespace openMVG { namespace robust { enum EROBUST_ESTIMATOR { ROBUST_ESTIMATOR_START = 0, ROBUST_ESTIMATOR_ACRANSAC = 1, //< A-Contrario Ransac. ROBUST_ESTIMATOR_RANSAC = 2, //< Classic Ransac. ROBUST_ESTIMATOR_LSMEDS = 3, //< Variant of RANSAC using Least Median of Squares. ROBUST_ESTIMATOR_LORANSAC = 4, //< LO-Ransac. ROBUST_ESTIMATOR_MAXCONSENSUS = 5, //< Naive implementation of RANSAC without noise and iteration reduction options. ROBUST_ESTIMATOR_END }; inline std::string EROBUST_ESTIMATOR_enumToString(EROBUST_ESTIMATOR estimator) { switch(estimator) { case ROBUST_ESTIMATOR_ACRANSAC: return "acransac"; case ROBUST_ESTIMATOR_RANSAC: return "ransac"; case ROBUST_ESTIMATOR_LSMEDS: return "lsmeds"; case ROBUST_ESTIMATOR_LORANSAC: return "loransac"; case ROBUST_ESTIMATOR_MAXCONSENSUS: return "maxconsensus"; case ROBUST_ESTIMATOR_START: case ROBUST_ESTIMATOR_END: break; } throw std::out_of_range("Invalid Ransac type Enum"); } inline EROBUST_ESTIMATOR EROBUST_ESTIMATOR_stringToEnum(const std::string& estimator) { if(estimator == "acransac") return ROBUST_ESTIMATOR_ACRANSAC; if(estimator == "ransac") return ROBUST_ESTIMATOR_RANSAC; if(estimator == "lsmeds") return ROBUST_ESTIMATOR_LSMEDS; if(estimator == "loransac") return ROBUST_ESTIMATOR_LORANSAC; if(estimator == "maxconsensus") return ROBUST_ESTIMATOR_MAXCONSENSUS; throw std::out_of_range("Invalid Ransac type string " + estimator); } inline std::ostream& operator<<(std::ostream& os, EROBUST_ESTIMATOR e) { return os << EROBUST_ESTIMATOR_enumToString(e); } inline std::istream& operator>>(std::istream& in, robust::EROBUST_ESTIMATOR& estimatorType) { std::string token; in >> token; estimatorType = robust::EROBUST_ESTIMATOR_stringToEnum(token); return in; } } //namespace robust } //namespace openMVG <|endoftext|>
<commit_before>/* * SlideParser.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 "SlideParser.hpp" #include <iostream> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/algorithm/string.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/StringUtils.hpp> #include <core/text/DcfParser.hpp> #include <session/SessionModuleContext.hpp> using namespace core; namespace session { namespace modules { namespace presentation { namespace { struct CompareName { CompareName(const std::string& name) : name_(name) {} bool operator()(const Slide::Field& field) const { return boost::iequals(name_, field.first); } private: std::string name_; }; bool isCommandField(const std::string& name) { return boost::iequals(name, "help-doc") || boost::iequals(name, "help-topic") || boost::iequals(name, "source") || boost::iequals(name, "console") || boost::iequals(name, "console-input") || boost::iequals(name, "execute") || boost::iequals(name, "pause"); } bool isAtCommandField(const std::string& name) { return isCommandField(name) || boost::iequals(name, "pause"); } bool isValidField(const std::string& name) { return isCommandField(name) || boost::iequals(name, "title") || boost::iequals(name, "author") || boost::iequals(name, "date") || boost::iequals(name, "transition") || boost::iequals(name, "font-family") || boost::iequals(name, "font-import") || boost::iequals(name, "navigation") || boost::iequals(name, "incremental") || boost::iequals(name, "id") || boost::iequals(name, "audio") || boost::iequals(name, "video") || boost::iequals(name, "type") || boost::iequals(name, "at"); } std::string normalizeFieldValue(const std::string& value) { std::string normalized = text::dcfMultilineAsFolded(value); return boost::algorithm::trim_copy(normalized); } } // anonymous namespace json::Object Command::asJson() const { json::Object commandJson; commandJson["name"] = name(); commandJson["params"] = params(); return commandJson; } json::Object AtCommand::asJson() const { json::Object atCommandJson; atCommandJson["at"] = seconds(); atCommandJson["command"] = command().asJson(); return atCommandJson; } // default title to true if there is a title provided and we // aren't in a video slide bool Slide::showTitle() const { std::string defaultTitle = (!title().empty() && video().empty()) ? "true" : "false"; return boost::iequals(fieldValue("title", defaultTitle), "true"); } std::vector<Command> Slide::commands() const { std::vector<Command> commands; BOOST_FOREACH(const Slide::Field& field, fields_) { if (isCommandField(field.first)) commands.push_back(Command(field.first, field.second)); } return commands; } std::vector<AtCommand> Slide::atCommands() const { std::vector<AtCommand> atCommands; boost::regex re("^([0-9]+)\\:([0-9]{2})\\s+([^\\:]+)(?:\\:\\s+(.*))?$"); std::vector<std::string> atFields = fieldValues("at"); BOOST_FOREACH(const std::string& atField, atFields) { boost::smatch match; if (boost::regex_match(atField, match, re)) { std::string cmd = match[3]; if (isAtCommandField(cmd)) { int mins = safe_convert::stringTo<int>(match[1], 0); int secs = (mins*60) + safe_convert::stringTo<int>(match[2], 0); Command command(cmd, match[4]); atCommands.push_back(AtCommand(secs, command)); } else { module_context::consoleWriteError("Unrecognized command '" + cmd + "'\n"); } } else { module_context::consoleWriteError( "Skipping at command with invalid syntax:\n at: " + atField + "\n"); } } return atCommands; } std::vector<std::string> Slide::fields() const { std::vector<std::string> fields; BOOST_FOREACH(const Field& field, fields_) { fields.push_back(field.first); } return fields; } std::string Slide::fieldValue(const std::string& name, const std::string& defaultValue) const { std::vector<Field>::const_iterator it = std::find_if(fields_.begin(), fields_.end(), CompareName(name)); if (it != fields_.end()) return normalizeFieldValue(it->second); else return defaultValue; } std::vector<std::string> Slide::fieldValues(const std::string& name) const { std::vector<std::string> values; BOOST_FOREACH(const Field& field, fields_) { if (boost::iequals(name, field.first)) values.push_back(normalizeFieldValue(field.second)); } return values; } namespace { void insertField(std::vector<Slide::Field>* pFields, const Slide::Field& field) { pFields->push_back(field); } } // anonymous namespace std::string Slide::transition() const { std::string value = fieldValue("transition", "linear"); if (value == "rotate") value = "default"; return value; } std::string SlideDeck::title() const { if (!slides_.empty()) return slides_[0].title(); else return std::string(); } std::string SlideDeck::fontFamily() const { if (!slides_.empty()) return slides_[0].fontFamily(); else return std::string(); } std::string SlideDeck::transition() const { if (!slides_.empty()) return slides_[0].transition(); else return "linear"; } std::string SlideDeck::navigation() const { if (!slides_.empty()) return slides_[0].navigation(); else return "slides"; } std::string SlideDeck::incremental() const { std::string val = !slides_.empty() ? slides_[0].incremental() : ""; if (!val.empty()) return val; else return "false"; } Error SlideDeck::readSlides(const FilePath& filePath) { // clear existing slides_.clear(); // capture base dir baseDir_ = filePath.parent(); // read the file std::string slides; Error error = readStringFromFile(filePath, &slides, string_utils::LineEndingPosix); if (error) return error; // split into lines std::vector<std::string> lines; boost::algorithm::split(lines, slides, boost::algorithm::is_any_of("\n")); // find indexes of lines with 3 or more consecutive equals boost::regex re("^\\={3,}\\s*$"); std::vector<std::size_t> headerLines; for (std::size_t i = 0; i<lines.size(); i++) { boost::smatch m; if (boost::regex_match(lines[i], m, re)) headerLines.push_back(i); } // capture the preamble (if any) preamble_.clear(); if (!headerLines.empty()) { for (std::size_t i = 0; i<(headerLines[0]-1); i++) preamble_.append(lines[i]); } // loop through the header lines to capture the slides for (std::size_t i = 0; i<headerLines.size(); i++) { // line index std::size_t lineIndex = headerLines[i]; // title is the line before (if there is one) std::string title = lineIndex > 0 ? lines[lineIndex-1] : ""; // find the begin index (line after) std::size_t beginIndex = lineIndex + 1; // find the end index (next section or end of file) std::size_t endIndex; if (i < (headerLines.size()-1)) endIndex = headerLines[i+1] - 1; else endIndex = lines.size(); // now iterate through from begin to end and break into fields and content bool inFields = true; std::string fields, content; for (std::size_t l = beginIndex; l<endIndex; l++) { if (inFields) { std::string line = boost::algorithm::trim_copy(lines[l]); if (!line.empty()) fields += line + "\n"; else inFields = false; } else { content += lines[l] + "\n"; } } // now parse the fields std::string errMsg; std::vector<Slide::Field> slideFields; Error error = text::parseDcfFile(fields, false, boost::bind(insertField, &slideFields, _1), &errMsg); if (error) { std::string badLine = error.getProperty("line-contents"); if (!badLine.empty()) module_context::consoleWriteError("Invalid DCF field:\n " + badLine + "\n"); return error; } // validate all of the fields BOOST_FOREACH(const Slide::Field& field, slideFields) { if (!isValidField(field.first)) { module_context::consoleWriteError("Unrecognized field '" + field.first + "'\n"); } } // create the slide slides_.push_back(Slide(title, slideFields, content)); } // if the deck is empty then insert a placeholder first slide if (slides_.empty()) { slides_.push_back(Slide(filePath.parent().filename(), std::vector<Slide::Field>(), std::string())); } return Success(); } } // namespace presentation } // namespace modules } // namesapce session <commit_msg>check for no preamble before appending<commit_after>/* * SlideParser.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 "SlideParser.hpp" #include <iostream> #include <boost/foreach.hpp> #include <boost/regex.hpp> #include <boost/algorithm/string.hpp> #include <core/Error.hpp> #include <core/FilePath.hpp> #include <core/FileSerializer.hpp> #include <core/SafeConvert.hpp> #include <core/StringUtils.hpp> #include <core/text/DcfParser.hpp> #include <session/SessionModuleContext.hpp> using namespace core; namespace session { namespace modules { namespace presentation { namespace { struct CompareName { CompareName(const std::string& name) : name_(name) {} bool operator()(const Slide::Field& field) const { return boost::iequals(name_, field.first); } private: std::string name_; }; bool isCommandField(const std::string& name) { return boost::iequals(name, "help-doc") || boost::iequals(name, "help-topic") || boost::iequals(name, "source") || boost::iequals(name, "console") || boost::iequals(name, "console-input") || boost::iequals(name, "execute") || boost::iequals(name, "pause"); } bool isAtCommandField(const std::string& name) { return isCommandField(name) || boost::iequals(name, "pause"); } bool isValidField(const std::string& name) { return isCommandField(name) || boost::iequals(name, "title") || boost::iequals(name, "author") || boost::iequals(name, "date") || boost::iequals(name, "transition") || boost::iequals(name, "font-family") || boost::iequals(name, "font-import") || boost::iequals(name, "navigation") || boost::iequals(name, "incremental") || boost::iequals(name, "id") || boost::iequals(name, "audio") || boost::iequals(name, "video") || boost::iequals(name, "type") || boost::iequals(name, "at"); } std::string normalizeFieldValue(const std::string& value) { std::string normalized = text::dcfMultilineAsFolded(value); return boost::algorithm::trim_copy(normalized); } } // anonymous namespace json::Object Command::asJson() const { json::Object commandJson; commandJson["name"] = name(); commandJson["params"] = params(); return commandJson; } json::Object AtCommand::asJson() const { json::Object atCommandJson; atCommandJson["at"] = seconds(); atCommandJson["command"] = command().asJson(); return atCommandJson; } // default title to true if there is a title provided and we // aren't in a video slide bool Slide::showTitle() const { std::string defaultTitle = (!title().empty() && video().empty()) ? "true" : "false"; return boost::iequals(fieldValue("title", defaultTitle), "true"); } std::vector<Command> Slide::commands() const { std::vector<Command> commands; BOOST_FOREACH(const Slide::Field& field, fields_) { if (isCommandField(field.first)) commands.push_back(Command(field.first, field.second)); } return commands; } std::vector<AtCommand> Slide::atCommands() const { std::vector<AtCommand> atCommands; boost::regex re("^([0-9]+)\\:([0-9]{2})\\s+([^\\:]+)(?:\\:\\s+(.*))?$"); std::vector<std::string> atFields = fieldValues("at"); BOOST_FOREACH(const std::string& atField, atFields) { boost::smatch match; if (boost::regex_match(atField, match, re)) { std::string cmd = match[3]; if (isAtCommandField(cmd)) { int mins = safe_convert::stringTo<int>(match[1], 0); int secs = (mins*60) + safe_convert::stringTo<int>(match[2], 0); Command command(cmd, match[4]); atCommands.push_back(AtCommand(secs, command)); } else { module_context::consoleWriteError("Unrecognized command '" + cmd + "'\n"); } } else { module_context::consoleWriteError( "Skipping at command with invalid syntax:\n at: " + atField + "\n"); } } return atCommands; } std::vector<std::string> Slide::fields() const { std::vector<std::string> fields; BOOST_FOREACH(const Field& field, fields_) { fields.push_back(field.first); } return fields; } std::string Slide::fieldValue(const std::string& name, const std::string& defaultValue) const { std::vector<Field>::const_iterator it = std::find_if(fields_.begin(), fields_.end(), CompareName(name)); if (it != fields_.end()) return normalizeFieldValue(it->second); else return defaultValue; } std::vector<std::string> Slide::fieldValues(const std::string& name) const { std::vector<std::string> values; BOOST_FOREACH(const Field& field, fields_) { if (boost::iequals(name, field.first)) values.push_back(normalizeFieldValue(field.second)); } return values; } namespace { void insertField(std::vector<Slide::Field>* pFields, const Slide::Field& field) { pFields->push_back(field); } } // anonymous namespace std::string Slide::transition() const { std::string value = fieldValue("transition", "linear"); if (value == "rotate") value = "default"; return value; } std::string SlideDeck::title() const { if (!slides_.empty()) return slides_[0].title(); else return std::string(); } std::string SlideDeck::fontFamily() const { if (!slides_.empty()) return slides_[0].fontFamily(); else return std::string(); } std::string SlideDeck::transition() const { if (!slides_.empty()) return slides_[0].transition(); else return "linear"; } std::string SlideDeck::navigation() const { if (!slides_.empty()) return slides_[0].navigation(); else return "slides"; } std::string SlideDeck::incremental() const { std::string val = !slides_.empty() ? slides_[0].incremental() : ""; if (!val.empty()) return val; else return "false"; } Error SlideDeck::readSlides(const FilePath& filePath) { // clear existing slides_.clear(); // capture base dir baseDir_ = filePath.parent(); // read the file std::string slides; Error error = readStringFromFile(filePath, &slides, string_utils::LineEndingPosix); if (error) return error; // split into lines std::vector<std::string> lines; boost::algorithm::split(lines, slides, boost::algorithm::is_any_of("\n")); // find indexes of lines with 3 or more consecutive equals boost::regex re("^\\={3,}\\s*$"); std::vector<std::size_t> headerLines; for (std::size_t i = 0; i<lines.size(); i++) { boost::smatch m; if (boost::regex_match(lines[i], m, re)) headerLines.push_back(i); } // capture the preamble (if any) preamble_.clear(); if (!headerLines.empty()) { if (headerLines[0] > 1) { for (std::size_t i = 0; i<(headerLines[0] - 1); i++) preamble_.append(lines[i]); } } // loop through the header lines to capture the slides for (std::size_t i = 0; i<headerLines.size(); i++) { // line index std::size_t lineIndex = headerLines[i]; // title is the line before (if there is one) std::string title = lineIndex > 0 ? lines[lineIndex-1] : ""; // find the begin index (line after) std::size_t beginIndex = lineIndex + 1; // find the end index (next section or end of file) std::size_t endIndex; if (i < (headerLines.size()-1)) endIndex = headerLines[i+1] - 1; else endIndex = lines.size(); // now iterate through from begin to end and break into fields and content bool inFields = true; std::string fields, content; for (std::size_t l = beginIndex; l<endIndex; l++) { if (inFields) { std::string line = boost::algorithm::trim_copy(lines[l]); if (!line.empty()) fields += line + "\n"; else inFields = false; } else { content += lines[l] + "\n"; } } // now parse the fields std::string errMsg; std::vector<Slide::Field> slideFields; Error error = text::parseDcfFile(fields, false, boost::bind(insertField, &slideFields, _1), &errMsg); if (error) { std::string badLine = error.getProperty("line-contents"); if (!badLine.empty()) module_context::consoleWriteError("Invalid DCF field:\n " + badLine + "\n"); return error; } // validate all of the fields BOOST_FOREACH(const Slide::Field& field, slideFields) { if (!isValidField(field.first)) { module_context::consoleWriteError("Unrecognized field '" + field.first + "'\n"); } } // create the slide slides_.push_back(Slide(title, slideFields, content)); } // if the deck is empty then insert a placeholder first slide if (slides_.empty()) { slides_.push_back(Slide(filePath.parent().filename(), std::vector<Slide::Field>(), std::string())); } return Success(); } } // namespace presentation } // namespace modules } // namesapce session <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <stack> using namespace std; class Node { public: int data; bool visited; vector<Node> adj; Node(int d) { visited = false; data = d; } }; class Graph { public: vector<Node> G; int N; Graph(int n_nodes) { N = n_nodes; } void add_nodes(){ int data; for(int i=0;i<N;i++) {cout<<"Enter node data"<<i<<endl; cin>>data; G.push_back(Node(data));} } void add_edge(int src,int dst) { G[src].adj.push_back(G[dst]); cout<<"Added successfully node: "<<G[src].adj[0].data; } }; void dfs_traverse(Graph G, Node startNode) { stack<Node> holder; holder.push(startNode); startNode.visited = true; while(!holder.empty()) { Node current = holder.top(); holder.pop(); for(int i=0;i<current.adj.size();i++) { if(!current.adj[i].visited) { holder.push(current.adj[i]); current.adj[i].visited = true; } } } } int main() { Graph my_graph(5); my_graph.add_nodes(); my_graph.add_edge(0,3); my_graph.add_edge(2,4); my_graph.add_edge(1,4); my_graph.add_edge(2,3); return 0; } <commit_msg>some refactors to code<commit_after>#include <iostream> #include <vector> #include <stack> using namespace std; class Node { public: int data; bool visited; vector<Node> adj; Node(int d) { visited = false; data = d; } }; class Graph { public: vector<Node> G; int N; Graph(int n_nodes) { N = n_nodes; } void add_nodes(){ int data; for(int i=0;i<N;i++) G.push_back(Node(i)); } void add_edge(int src,int dst) { G[src].adj.push_back(G[dst]); cout<<"Added node: "<<G[src].adj[0].data<<" to "<<G[src].data<<endl; } }; void dfs_traverse(Graph G, Node startNode) { stack<Node> holder; holder.push(startNode); startNode.visited = true; while(!holder.empty()) { Node current = holder.top(); holder.pop(); for(int i=0;i<current.adj.size();i++) { if(!current.adj[i].visited) { holder.push(current.adj[i]); current.adj[i].visited = true; } } } } int main() { int V,E; int src,dst; cout<<"Vertex Count"; cin>>V; cout<<"Edge Count"; cin>>E; Graph my_graph(V); cout<<"Graph Initialized with: "<<V<<" vertices"<<endl; my_graph.add_nodes(); for(int i=0;i<E;i++){ cout<<"Input : Source -> Destination"<<endl; cin>>src>>dst; my_graph.add_edge(src,dst); } return 0; } <|endoftext|>
<commit_before>/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "usUtils_p.h" #include "usServiceListeners_p.h" #include "usServiceReferenceBasePrivate.h" #include "usCoreModuleContext_p.h" #include "usModule.h" #include "usModuleContext.h" US_BEGIN_NAMESPACE const int ServiceListeners::OBJECTCLASS_IX = 0; const int ServiceListeners::SERVICE_ID_IX = 1; ServiceListeners::ServiceListeners(CoreModuleContext* coreCtx) : coreCtx(coreCtx) { hashedServiceKeys.push_back(ServiceConstants::OBJECTCLASS()); hashedServiceKeys.push_back(ServiceConstants::SERVICE_ID()); } void ServiceListeners::AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data, const std::string& filter) { US_UNUSED(Lock(this)); ServiceListenerEntry sle(mc, listener, data, filter); RemoveServiceListener_unlocked(sle); serviceSet.insert(sle); coreCtx->serviceHooks.HandleServiceListenerReg(sle); CheckSimple(sle); } void ServiceListeners::RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data) { ServiceListenerEntry entryToRemove(mc, listener, data); US_UNUSED(Lock(this)); RemoveServiceListener_unlocked(entryToRemove); } void ServiceListeners::RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove) { ServiceListenerEntries::const_iterator it = serviceSet.find(entryToRemove); if (it != serviceSet.end()) { it->SetRemoved(true); coreCtx->serviceHooks.HandleServiceListenerUnreg(*it); RemoveFromCache(*it); serviceSet.erase(it); } } void ServiceListeners::AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) { MutexLock lock(moduleListenerMapMutex); ModuleListenerMap::value_type::second_type& listeners = moduleListenerMap[mc]; if (std::find_if(listeners.begin(), listeners.end(), std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))) == listeners.end()) { listeners.push_back(std::make_pair(listener, data)); } } void ServiceListeners::RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) { MutexLock lock(moduleListenerMapMutex); moduleListenerMap[mc].remove_if(std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))); } void ServiceListeners::ModuleChanged(const ModuleEvent& evt) { ModuleListenerMap filteredModuleListeners; coreCtx->moduleHooks.FilterModuleEventReceivers(evt, filteredModuleListeners); for(ModuleListenerMap::iterator iter = filteredModuleListeners.begin(), end = filteredModuleListeners.end(); iter != end; ++iter) { for (ModuleListenerMap::mapped_type::iterator iter2 = iter->second.begin(), end2 = iter->second.end(); iter2 != end2; ++iter2) { (iter2->first)(evt); } } } void ServiceListeners::RemoveAllListeners(ModuleContext* mc) { { US_UNUSED(Lock(this)); for (ServiceListenerEntries::iterator it = serviceSet.begin(); it != serviceSet.end(); ) { if (it->GetModuleContext() == mc) { RemoveFromCache(*it); serviceSet.erase(it++); } else { ++it; } } } { MutexLock lock(moduleListenerMapMutex); moduleListenerMap.erase(mc); } } void ServiceListeners::HooksModuleStopped(ModuleContext* mc) { US_UNUSED(Lock(this)); std::vector<ServiceListenerEntry> entries; for (ServiceListenerEntries::iterator it = serviceSet.begin(); it != serviceSet.end(); ) { if (it->GetModuleContext() == mc) { entries.push_back(*it); } } coreCtx->serviceHooks.HandleServiceListenerUnreg(entries); } void ServiceListeners::ServiceChanged(ServiceListenerEntries& receivers, const ServiceEvent& evt) { ServiceListenerEntries matchBefore; ServiceChanged(receivers, evt, matchBefore); } void ServiceListeners::ServiceChanged(ServiceListenerEntries& receivers, const ServiceEvent& evt, ServiceListenerEntries& matchBefore) { int n = 0; if (!matchBefore.empty()) { for (ServiceListenerEntries::const_iterator l = receivers.begin(); l != receivers.end(); ++l) { matchBefore.erase(*l); } } for (ServiceListenerEntries::const_iterator l = receivers.begin(); l != receivers.end(); ++l) { if (!l->IsRemoved()) { try { ++n; l->CallDelegate(evt); } catch (...) { US_WARN << "Service listener" #ifdef US_MODULE_SUPPORT_ENABLED << " in " << l->GetModule()->GetName() #endif << " threw an exception!"; } } } //US_DEBUG << "Notified " << n << " listeners"; } void ServiceListeners::GetMatchingServiceListeners(const ServiceEvent& evt, ServiceListenerEntries& set, bool lockProps) { US_UNUSED(Lock(this)); // Filter the original set of listeners ServiceListenerEntries receivers = serviceSet; coreCtx->serviceHooks.FilterServiceEventReceivers(evt, receivers); // Check complicated or empty listener filters for (std::list<ServiceListenerEntry>::const_iterator sse = complicatedListeners.begin(); sse != complicatedListeners.end(); ++sse) { if (receivers.count(*sse) == 0) continue; const LDAPExpr& ldapExpr = sse->GetLDAPExpr(); if (ldapExpr.IsNull() || ldapExpr.Evaluate(evt.GetServiceReference().d->GetProperties(), false)) { set.insert(*sse); } } //US_DEBUG << "Added " << set.size() << " out of " << n // << " listeners with complicated filters"; // Check the cache const std::vector<std::string> c(any_cast<std::vector<std::string> > (evt.GetServiceReference().d->GetProperty(ServiceConstants::OBJECTCLASS(), lockProps))); for (std::vector<std::string>::const_iterator objClass = c.begin(); objClass != c.end(); ++objClass) { AddToSet(set, receivers, OBJECTCLASS_IX, *objClass); } long service_id = any_cast<long>(evt.GetServiceReference().d->GetProperty(ServiceConstants::SERVICE_ID(), lockProps)); std::stringstream ss; ss << service_id; AddToSet(set, receivers, SERVICE_ID_IX, ss.str()); } std::vector<ServiceListenerHook::ListenerInfo> ServiceListeners::GetListenerInfoCollection() const { US_UNUSED(Lock(this)); std::vector<ServiceListenerHook::ListenerInfo> result; result.reserve(serviceSet.size()); for (ServiceListenerEntries::const_iterator iter = serviceSet.begin(), iterEnd = serviceSet.end(); iter != iterEnd; ++iter) { result.push_back(*iter); } return result; } void ServiceListeners::RemoveFromCache(const ServiceListenerEntry& sle) { if (!sle.GetLocalCache().empty()) { for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { CacheType& keymap = cache[i]; std::vector<std::string>& l = sle.GetLocalCache()[i]; for (std::vector<std::string>::const_iterator it = l.begin(); it != l.end(); ++it) { std::list<ServiceListenerEntry>& sles = keymap[*it]; sles.remove(sle); if (sles.empty()) { keymap.erase(*it); } } } } else { complicatedListeners.remove(sle); } } void ServiceListeners::CheckSimple(const ServiceListenerEntry& sle) { if (sle.GetLDAPExpr().IsNull()) { complicatedListeners.push_back(sle); } else { LDAPExpr::LocalCache local_cache; if (sle.GetLDAPExpr().IsSimple(hashedServiceKeys, local_cache, false)) { sle.GetLocalCache() = local_cache; for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { for (std::vector<std::string>::const_iterator it = local_cache[i].begin(); it != local_cache[i].end(); ++it) { std::list<ServiceListenerEntry>& sles = cache[i][*it]; sles.push_back(sle); } } } else { //US_DEBUG << "Too complicated filter: " << sle.GetFilter(); complicatedListeners.push_back(sle); } } } void ServiceListeners::AddToSet(ServiceListenerEntries& set, const ServiceListenerEntries& receivers, int cache_ix, const std::string& val) { std::list<ServiceListenerEntry>& l = cache[cache_ix][val]; if (!l.empty()) { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches " << l.size(); for (std::list<ServiceListenerEntry>::const_iterator entry = l.begin(); entry != l.end(); ++entry) { if (receivers.count(*entry)) { set.insert(*entry); } } } else { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches none"; } } US_END_NAMESPACE <commit_msg>Removed unused US_MODULE_SUPPORT_ENABLED macro.<commit_after>/*============================================================================= Library: CppMicroServices Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics 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 "usUtils_p.h" #include "usServiceListeners_p.h" #include "usServiceReferenceBasePrivate.h" #include "usCoreModuleContext_p.h" #include "usModule.h" #include "usModuleContext.h" US_BEGIN_NAMESPACE const int ServiceListeners::OBJECTCLASS_IX = 0; const int ServiceListeners::SERVICE_ID_IX = 1; ServiceListeners::ServiceListeners(CoreModuleContext* coreCtx) : coreCtx(coreCtx) { hashedServiceKeys.push_back(ServiceConstants::OBJECTCLASS()); hashedServiceKeys.push_back(ServiceConstants::SERVICE_ID()); } void ServiceListeners::AddServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data, const std::string& filter) { US_UNUSED(Lock(this)); ServiceListenerEntry sle(mc, listener, data, filter); RemoveServiceListener_unlocked(sle); serviceSet.insert(sle); coreCtx->serviceHooks.HandleServiceListenerReg(sle); CheckSimple(sle); } void ServiceListeners::RemoveServiceListener(ModuleContext* mc, const ServiceListenerEntry::ServiceListener& listener, void* data) { ServiceListenerEntry entryToRemove(mc, listener, data); US_UNUSED(Lock(this)); RemoveServiceListener_unlocked(entryToRemove); } void ServiceListeners::RemoveServiceListener_unlocked(const ServiceListenerEntry& entryToRemove) { ServiceListenerEntries::const_iterator it = serviceSet.find(entryToRemove); if (it != serviceSet.end()) { it->SetRemoved(true); coreCtx->serviceHooks.HandleServiceListenerUnreg(*it); RemoveFromCache(*it); serviceSet.erase(it); } } void ServiceListeners::AddModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) { MutexLock lock(moduleListenerMapMutex); ModuleListenerMap::value_type::second_type& listeners = moduleListenerMap[mc]; if (std::find_if(listeners.begin(), listeners.end(), std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))) == listeners.end()) { listeners.push_back(std::make_pair(listener, data)); } } void ServiceListeners::RemoveModuleListener(ModuleContext* mc, const ModuleListener& listener, void* data) { MutexLock lock(moduleListenerMapMutex); moduleListenerMap[mc].remove_if(std::bind1st(ModuleListenerCompare(), std::make_pair(listener, data))); } void ServiceListeners::ModuleChanged(const ModuleEvent& evt) { ModuleListenerMap filteredModuleListeners; coreCtx->moduleHooks.FilterModuleEventReceivers(evt, filteredModuleListeners); for(ModuleListenerMap::iterator iter = filteredModuleListeners.begin(), end = filteredModuleListeners.end(); iter != end; ++iter) { for (ModuleListenerMap::mapped_type::iterator iter2 = iter->second.begin(), end2 = iter->second.end(); iter2 != end2; ++iter2) { (iter2->first)(evt); } } } void ServiceListeners::RemoveAllListeners(ModuleContext* mc) { { US_UNUSED(Lock(this)); for (ServiceListenerEntries::iterator it = serviceSet.begin(); it != serviceSet.end(); ) { if (it->GetModuleContext() == mc) { RemoveFromCache(*it); serviceSet.erase(it++); } else { ++it; } } } { MutexLock lock(moduleListenerMapMutex); moduleListenerMap.erase(mc); } } void ServiceListeners::HooksModuleStopped(ModuleContext* mc) { US_UNUSED(Lock(this)); std::vector<ServiceListenerEntry> entries; for (ServiceListenerEntries::iterator it = serviceSet.begin(); it != serviceSet.end(); ) { if (it->GetModuleContext() == mc) { entries.push_back(*it); } } coreCtx->serviceHooks.HandleServiceListenerUnreg(entries); } void ServiceListeners::ServiceChanged(ServiceListenerEntries& receivers, const ServiceEvent& evt) { ServiceListenerEntries matchBefore; ServiceChanged(receivers, evt, matchBefore); } void ServiceListeners::ServiceChanged(ServiceListenerEntries& receivers, const ServiceEvent& evt, ServiceListenerEntries& matchBefore) { int n = 0; if (!matchBefore.empty()) { for (ServiceListenerEntries::const_iterator l = receivers.begin(); l != receivers.end(); ++l) { matchBefore.erase(*l); } } for (ServiceListenerEntries::const_iterator l = receivers.begin(); l != receivers.end(); ++l) { if (!l->IsRemoved()) { try { ++n; l->CallDelegate(evt); } catch (...) { US_WARN << "Service listener" << " in " << l->GetModuleContext()->GetModule()->GetName() << " threw an exception!"; } } } //US_DEBUG << "Notified " << n << " listeners"; } void ServiceListeners::GetMatchingServiceListeners(const ServiceEvent& evt, ServiceListenerEntries& set, bool lockProps) { US_UNUSED(Lock(this)); // Filter the original set of listeners ServiceListenerEntries receivers = serviceSet; coreCtx->serviceHooks.FilterServiceEventReceivers(evt, receivers); // Check complicated or empty listener filters for (std::list<ServiceListenerEntry>::const_iterator sse = complicatedListeners.begin(); sse != complicatedListeners.end(); ++sse) { if (receivers.count(*sse) == 0) continue; const LDAPExpr& ldapExpr = sse->GetLDAPExpr(); if (ldapExpr.IsNull() || ldapExpr.Evaluate(evt.GetServiceReference().d->GetProperties(), false)) { set.insert(*sse); } } //US_DEBUG << "Added " << set.size() << " out of " << n // << " listeners with complicated filters"; // Check the cache const std::vector<std::string> c(any_cast<std::vector<std::string> > (evt.GetServiceReference().d->GetProperty(ServiceConstants::OBJECTCLASS(), lockProps))); for (std::vector<std::string>::const_iterator objClass = c.begin(); objClass != c.end(); ++objClass) { AddToSet(set, receivers, OBJECTCLASS_IX, *objClass); } long service_id = any_cast<long>(evt.GetServiceReference().d->GetProperty(ServiceConstants::SERVICE_ID(), lockProps)); std::stringstream ss; ss << service_id; AddToSet(set, receivers, SERVICE_ID_IX, ss.str()); } std::vector<ServiceListenerHook::ListenerInfo> ServiceListeners::GetListenerInfoCollection() const { US_UNUSED(Lock(this)); std::vector<ServiceListenerHook::ListenerInfo> result; result.reserve(serviceSet.size()); for (ServiceListenerEntries::const_iterator iter = serviceSet.begin(), iterEnd = serviceSet.end(); iter != iterEnd; ++iter) { result.push_back(*iter); } return result; } void ServiceListeners::RemoveFromCache(const ServiceListenerEntry& sle) { if (!sle.GetLocalCache().empty()) { for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { CacheType& keymap = cache[i]; std::vector<std::string>& l = sle.GetLocalCache()[i]; for (std::vector<std::string>::const_iterator it = l.begin(); it != l.end(); ++it) { std::list<ServiceListenerEntry>& sles = keymap[*it]; sles.remove(sle); if (sles.empty()) { keymap.erase(*it); } } } } else { complicatedListeners.remove(sle); } } void ServiceListeners::CheckSimple(const ServiceListenerEntry& sle) { if (sle.GetLDAPExpr().IsNull()) { complicatedListeners.push_back(sle); } else { LDAPExpr::LocalCache local_cache; if (sle.GetLDAPExpr().IsSimple(hashedServiceKeys, local_cache, false)) { sle.GetLocalCache() = local_cache; for (std::size_t i = 0; i < hashedServiceKeys.size(); ++i) { for (std::vector<std::string>::const_iterator it = local_cache[i].begin(); it != local_cache[i].end(); ++it) { std::list<ServiceListenerEntry>& sles = cache[i][*it]; sles.push_back(sle); } } } else { //US_DEBUG << "Too complicated filter: " << sle.GetFilter(); complicatedListeners.push_back(sle); } } } void ServiceListeners::AddToSet(ServiceListenerEntries& set, const ServiceListenerEntries& receivers, int cache_ix, const std::string& val) { std::list<ServiceListenerEntry>& l = cache[cache_ix][val]; if (!l.empty()) { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches " << l.size(); for (std::list<ServiceListenerEntry>::const_iterator entry = l.begin(); entry != l.end(); ++entry) { if (receivers.count(*entry)) { set.insert(*entry); } } } else { //US_DEBUG << hashedServiceKeys[cache_ix] << " matches none"; } } US_END_NAMESPACE <|endoftext|>
<commit_before>/* Copyright 2013 Miro Knejp See the accompanied LICENSE file for licensing details. */ /** \file Adds shortcut type traits proposed for C++14. \author Miro Knejp */ #ifndef XTD_xtd_type_traits_bc035fe3_9c1b_4ff7_9b1b_2657f0dab836 #define XTD_xtd_type_traits_bc035fe3_9c1b_4ff7_9b1b_2657f0dab836 #include <type_traits> namespace xtd { /// \name 20.11.7.1, const-volatile modifications //@{ template<class T> using remove_const_t = typename std::remove_const<T>::type; template<class T> using remove_volatile_t = typename std::remove_volatile<T>::type; template<class T> using remove_cv_t = typename std::remove_cv<T>::type; template<class T> using add_const_t = typename std::add_const<T>::type; template<class T> using add_volatile_t = typename std::add_volatile<T>::type; template<class T> using add_cv_t = typename std::add_cv<T>::type; //@} /// \name 20.11.7.2, reference modifications //@{ template<class T> using remove_reference_t = typename std::remove_reference<T>::type; template<class T> using add_lvalue_reference_t = typename std::add_lvalue_reference<T>::type; template<class T> using add_rvalue_reference_t = typename std::add_rvalue_reference<T>::type; //@} /// \name 20.11.7.3, sign modifications //@{ template<class T> using make_signed_t = typename std::make_signed<T>::type; template<class T> using make_unsigned_t = typename std::make_unsigned<T>::type; //@} /// \name 20.11.7.4, array modifications //@{ template<class T> using remove_extent_t = typename std::remove_extent<T>::type; template<class T> using remove_all_extents_t = typename std::remove_all_extents<T>::type; //@} /// \name 20.11.7.5, pointer modifications //@{ template<class T> using remove_pointer_t = typename std::remove_pointer<T>::type; template<class T> using add_pointer_t = typename std::add_pointer<T>::type; //@} /// \name 20.11.7.6, other transformations //@{ // template<std::size_t Len, std::size_t Align = default-alignment> // using aligned_storage_t = typename std::aligned_storage<Len,Align>::type; // template<std::size_t Len, class... Types> // using aligned_union_t = typename std::aligned_union<Len,Types...>::type; template<class T> using decay_t = typename std::decay<T>::type; template<bool b, class T = void> using enable_if_t = typename std::enable_if<b,T>::type; template<bool b, class T, class F> using conditional_t = typename std::conditional<b,T,F>::type; template<class... T> using common_type_t = typename std::common_type<T...>::type; template<class T> using underlying_type_t = typename std::underlying_type<T>::type; template<class T> using result_of_t = typename std::result_of<T>::type; //@} } // namespace xtf #endif // XTD_xtd_type_traits_bc035fe3_9c1b_4ff7_9b1b_2657f0dab836 <commit_msg>Removed type_traits as they are obsolete with C++14<commit_after><|endoftext|>
<commit_before>//(c) 2016-2017 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include "contig_extender.h" #include "output_generator.h" void ContigExtender::generateUnbranchingPaths() { GraphProcessor proc(_graph, _asmSeqs, _readSeqs); _unbranchingPaths = proc.getUnbranchingPaths(); _edgeToPath.clear(); for (auto& path : _unbranchingPaths) { if (path.id.strand()) { Logger::get().debug() << "UPath " << path.id.signedId() << ": " << path.edgesStr(); } for (auto& edge : path.path) { _edgeToPath[edge] = &path; } } Logger::get().debug() << "Final graph contiain " << _unbranchingPaths.size() / 2 << " egdes"; } void ContigExtender::generateContigs(bool graphContinue) { OutputGenerator outGen(_graph, _aligner, _asmSeqs, _readSeqs); auto coreSeqs = outGen.generatePathSequences(_unbranchingPaths); std::unordered_map<UnbranchingPath*, FastaRecord*> upathsSeqs; for (size_t i = 0; i < _unbranchingPaths.size(); ++i) { upathsSeqs[&_unbranchingPaths[i]] = &coreSeqs[i]; } std::vector<const GraphAlignment*> interestingAlignments; for (auto& aln : _aligner.getAlignments()) { if (aln.size() > 1) interestingAlignments.push_back(&aln); } std::unordered_set<GraphEdge*> coveredRepeats; std::unordered_map<const GraphEdge*, bool> repeatDirections; auto canTraverse = [&repeatDirections] (const GraphEdge* edge) { if (edge->isLooped() && edge->selfComplement) return false; return !repeatDirections.count(edge) || repeatDirections.at(edge); }; typedef std::pair<GraphPath, std::string> PathAndSeq; auto extendPathRight = [this, &coveredRepeats, &repeatDirections, &upathsSeqs, &canTraverse, &interestingAlignments, graphContinue] (UnbranchingPath& upath) { bool extendFwd = !upath.path.back()->nodeRight->outEdges.empty(); if (!extendFwd) return PathAndSeq(); //first, choose the longest aligned read from this edge int32_t maxExtension = 0; GraphAlignment bestAlignment; for (auto pathPtr : interestingAlignments) { const GraphAlignment& path = *pathPtr; for (size_t i = 0; i < path.size(); ++i) { if (path[i].edge == upath.path.back() && i < path.size() - 1) { size_t j = i + 1; while (j < path.size() && path[j].edge->repetitive && canTraverse(path[j].edge)) ++j; if (j == i + 1) break; int32_t alnLen = path[j - 1].overlap.curEnd - path[i + 1].overlap.curBegin; if (alnLen > maxExtension) { maxExtension = alnLen; bestAlignment.clear(); std::copy(path.begin() + i + 1, path.begin() + j, std::back_inserter(bestAlignment)); } break; } } } if (maxExtension == 0) return PathAndSeq(); auto upathAln = this->asUpathAlignment(bestAlignment); auto lastUpath = upathAln.back().upath; int32_t overhang = upathsSeqs[lastUpath]->sequence.length() - upathAln.back().aln.back().overlap.curEnd + upathAln.back().aln.front().overlap.curBegin; bool lastIncomplete = overhang > (int)Config::get("max_separation") && !lastUpath->isLoop(); Logger::get().debug() << "Ctg " << upath.id.signedId() << " overhang " << overhang << " upath " << lastUpath->id.signedId(); for (size_t i = 0; i < upathAln.size(); ++i) { //in case we don't extend using graph structure, //dont mark the last upath as covered if it is //incomplete if (i == upathAln.size() - 1 && lastIncomplete && !graphContinue) break; for (auto& aln : upathAln[i].aln) { repeatDirections[aln.edge] = true; repeatDirections[_graph.complementEdge(aln.edge)] = false; coveredRepeats.insert(aln.edge); coveredRepeats.insert(_graph.complementEdge(aln.edge)); } } //generate extension sequence std::string extendedSeq; if (lastIncomplete && graphContinue) { upathAln.pop_back(); } if (!upathAln.empty()) { FastaRecord::Id readId = bestAlignment.front().overlap.curId; int32_t readStart = upathAln.front().aln.front().overlap.curBegin; int32_t readEnd = upathAln.back().aln.back().overlap.curEnd; extendedSeq = _readSeqs.getSeq(readId) .substr(readStart, readEnd - readStart).str(); } if (lastIncomplete && graphContinue) { extendedSeq += upathsSeqs[lastUpath]->sequence.str(); } GraphPath extendedPath; for (auto& ualn : upathAln) { for (auto& edgeAln : ualn.aln) extendedPath.push_back(edgeAln.edge); } if (lastIncomplete && graphContinue) { for (auto& edge : lastUpath->path) extendedPath.push_back(edge); } return PathAndSeq(extendedPath, extendedSeq); }; std::unordered_map<FastaRecord::Id, UnbranchingPath*> idToPath; for (auto& ctg : _unbranchingPaths) { idToPath[ctg.id] = &ctg; } for (auto& upath : _unbranchingPaths) { if (upath.repetitive || !upath.id.strand()) continue; if (!idToPath.count(upath.id.rc())) continue; //self-complement auto rightExt = extendPathRight(upath); auto leftExt = extendPathRight(*idToPath[upath.id.rc()]); leftExt.first = _graph.complementPath(leftExt.first); leftExt.second = DnaSequence(leftExt.second).complement().str(); Contig contig(upath); auto leftPaths = this->asUpaths(leftExt.first); auto rightPaths = this->asUpaths(rightExt.first); GraphPath leftEdges; for (auto& path : leftPaths) { leftEdges.insert(leftEdges.end(), path->path.begin(), path->path.end()); } contig.graphEdges.path.insert(contig.graphEdges.path.begin(), leftEdges.begin(), leftEdges.end()); contig.graphPaths.insert(contig.graphPaths.begin(), leftPaths.begin(), leftPaths.end()); GraphPath rightEdges; for (auto& path : rightPaths) { rightEdges.insert(rightEdges.end(), path->path.begin(), path->path.end()); } contig.graphEdges.path.insert(contig.graphEdges.path.end(), rightEdges.begin(), rightEdges.end()); contig.graphPaths.insert(contig.graphPaths.end(), rightPaths.begin(), rightPaths.end()); auto coreSeq = upathsSeqs[&upath]->sequence.str(); contig.sequence = DnaSequence(leftExt.second + coreSeq + rightExt.second); _contigs.push_back(std::move(contig)); } //add repetitive contigs that were not covered by the extended paths int numCovered = 0; for (auto& upath : _unbranchingPaths) { if (!upath.repetitive || !upath.id.strand()) continue; bool covered = false; for (auto& edge : upath.path) { if (coveredRepeats.count(edge)) covered = true; } if (!covered) { _contigs.emplace_back(upath); _contigs.back().sequence = upathsSeqs[&upath]->sequence; } else { ++numCovered; //Logger::get().debug() << "Covered: " << upath.id.signedId(); } } Logger::get().debug() << "Covered " << numCovered << " repetitive contigs"; Logger::get().info() << "Generated " << _contigs.size() << " contigs"; } std::vector<UnbranchingPath*> ContigExtender::asUpaths(const GraphPath& path) { std::vector<UnbranchingPath*> upathRepr; for (size_t i = 0; i < path.size(); ++i) { UnbranchingPath* upath = _edgeToPath.at(path[i]); if (upathRepr.empty() || upathRepr.back() != upath || path[i - 1] == path[i]) { upathRepr.push_back(upath); } } return upathRepr; } std::vector<ContigExtender::UpathAlignment> ContigExtender::asUpathAlignment(const GraphAlignment& graphAln) { std::vector<ContigExtender::UpathAlignment> upathAln; for (size_t i = 0; i < graphAln.size(); ++i) { UnbranchingPath* upath = _edgeToPath.at(graphAln[i].edge); if (upathAln.empty() || upathAln.back().upath != upath || graphAln[i - 1].edge == graphAln[i].edge) { upathAln.emplace_back(); upathAln.back().upath = upath; } upathAln.back().aln.push_back(graphAln[i]); } return upathAln; } void ContigExtender::outputStatsTable(const std::string& filename) { std::ofstream fout(filename); if (!fout) throw std::runtime_error("Can't write " + filename); fout << "seq_name\tlength\tcoverage\tcircular\trepeat" << "\tmult\ttelomere\tgraph_path\n"; char YES_NO[] = {'-', '+'}; for (auto& ctg : _contigs) { std::string pathStr; for (auto& upath : ctg.graphPaths) { pathStr += std::to_string(upath->id.signedId()) + ","; } pathStr.pop_back(); int estMult = std::max(1.0f, roundf((float)ctg.graphEdges.meanCoverage / _meanCoverage)); std::string telomereStr; bool telLeft = (ctg.graphEdges.path.front()->nodeLeft->isTelomere()); bool telRight = (ctg.graphEdges.path.back()->nodeRight->isTelomere()); if (telLeft && !telRight) telomereStr = "left"; if (!telLeft && telRight) telomereStr = "right"; if (telLeft && telRight) telomereStr = "both"; if (!telLeft && !telRight) telomereStr = "none"; fout << ctg.graphEdges.name() << "\t" << ctg.sequence.length() << "\t" << ctg.graphEdges.meanCoverage << "\t" << YES_NO[ctg.graphEdges.circular] << "\t" << YES_NO[ctg.graphEdges.repetitive] << "\t" << estMult << "\t" << telomereStr << "\t" << pathStr << "\n"; Logger::get().debug() << "Contig: " << ctg.graphEdges.id.signedId() << ": " << pathStr; } } void ContigExtender::outputContigs(const std::string& filename) { std::vector<FastaRecord> contigsFasta; for (auto& ctg : _contigs) { contigsFasta.emplace_back(ctg.sequence, ctg.graphEdges.name(), FastaRecord::ID_NONE); } SequenceContainer::writeFasta(contigsFasta, filename); } void ContigExtender::outputScaffoldConnections(const std::string& filename) { std::ofstream fout(filename); if (!fout) throw std::runtime_error("Can't open " + filename); auto reachableEdges = [this](GraphEdge* edge) { std::vector<GraphEdge*> dfsStack; std::unordered_set<GraphEdge*> visited; std::unordered_set<GraphEdge*> reachableUnique; std::unordered_set<GraphEdge*> traversedRepeats; dfsStack.push_back(edge); while(!dfsStack.empty()) { auto curEdge = dfsStack.back(); dfsStack.pop_back(); if (visited.count(curEdge)) continue; visited.insert(curEdge); visited.insert(_graph.complementEdge(curEdge)); for (auto& adjEdge: curEdge->nodeRight->outEdges) { if (adjEdge->isRepetitive() && !visited.count(adjEdge)) { dfsStack.push_back(adjEdge); traversedRepeats.insert(adjEdge); } else if (!adjEdge->isRepetitive() && adjEdge != edge) { reachableUnique.insert(adjEdge); } } } return reachableUnique; }; for (auto& edge : _graph.iterEdges()) { if (edge->repetitive) continue; auto reachableUnique = reachableEdges(edge); if (reachableUnique.size() != 1) continue; GraphEdge* outEdge = *reachableUnique.begin(); if (reachableEdges(_graph.complementEdge(outEdge)).size() != 1) continue; if ((edge->nodeRight->isBifurcation() || outEdge->nodeLeft->isBifurcation()) && edge->edgeId != outEdge->edgeId.rc() && abs(edge->edgeId.signedId()) < abs(outEdge->edgeId.signedId())) { UnbranchingPath* leftCtg = this->asUpaths({edge}).front(); UnbranchingPath* rightCtg = this->asUpaths({outEdge}).front(); if (leftCtg != rightCtg) { fout << leftCtg->nameUnsigned() << "\t" << (leftCtg->id.strand() ? '+' : '-') << "\t" << rightCtg->nameUnsigned() << "\t" << (rightCtg->id.strand() ? '+' : '-') << "\n"; } } } } <commit_msg>a slight fix for contig extension in subassemblies mode<commit_after>//(c) 2016-2017 by Authors //This file is a part of ABruijn program. //Released under the BSD license (see LICENSE file) #include "contig_extender.h" #include "output_generator.h" void ContigExtender::generateUnbranchingPaths() { GraphProcessor proc(_graph, _asmSeqs, _readSeqs); _unbranchingPaths = proc.getUnbranchingPaths(); _edgeToPath.clear(); for (auto& path : _unbranchingPaths) { if (path.id.strand()) { Logger::get().debug() << "UPath " << path.id.signedId() << ": " << path.edgesStr(); } for (auto& edge : path.path) { _edgeToPath[edge] = &path; } } Logger::get().debug() << "Final graph contiain " << _unbranchingPaths.size() / 2 << " egdes"; } void ContigExtender::generateContigs(bool graphContinue) { OutputGenerator outGen(_graph, _aligner, _asmSeqs, _readSeqs); auto coreSeqs = outGen.generatePathSequences(_unbranchingPaths); std::unordered_map<UnbranchingPath*, FastaRecord*> upathsSeqs; for (size_t i = 0; i < _unbranchingPaths.size(); ++i) { upathsSeqs[&_unbranchingPaths[i]] = &coreSeqs[i]; } std::vector<const GraphAlignment*> interestingAlignments; for (auto& aln : _aligner.getAlignments()) { if (aln.size() > 1) interestingAlignments.push_back(&aln); } std::unordered_set<GraphEdge*> coveredRepeats; std::unordered_map<const GraphEdge*, bool> repeatDirections; auto canTraverse = [&repeatDirections] (const GraphEdge* edge) { if (edge->isLooped() && edge->selfComplement) return false; return !repeatDirections.count(edge) || repeatDirections.at(edge); }; typedef std::pair<GraphPath, std::string> PathAndSeq; auto extendPathRight = [this, &coveredRepeats, &repeatDirections, &upathsSeqs, &canTraverse, &interestingAlignments, graphContinue] (UnbranchingPath& upath) { bool extendFwd = !upath.path.back()->nodeRight->outEdges.empty(); if (!extendFwd) return PathAndSeq(); //first, choose the longest aligned read from this edge int32_t maxExtension = 0; GraphAlignment bestAlignment; for (auto pathPtr : interestingAlignments) { const GraphAlignment& path = *pathPtr; for (size_t i = 0; i < path.size(); ++i) { if (path[i].edge == upath.path.back() && i < path.size() - 1) { size_t j = i + 1; while (j < path.size() && path[j].edge->repetitive && canTraverse(path[j].edge)) ++j; if (j == i + 1) break; int32_t alnLen = path[j - 1].overlap.curEnd - path[i + 1].overlap.curBegin; if (alnLen > maxExtension) { maxExtension = alnLen; bestAlignment.clear(); std::copy(path.begin() + i + 1, path.begin() + j, std::back_inserter(bestAlignment)); } break; } } } if (maxExtension == 0) return PathAndSeq(); auto upathAln = this->asUpathAlignment(bestAlignment); auto lastUpath = upathAln.back().upath; int32_t overhang = upathsSeqs[lastUpath]->sequence.length() - upathAln.back().aln.back().overlap.curEnd + upathAln.back().aln.front().overlap.curBegin; bool lastIncomplete = overhang > (int)Config::get("max_separation"); Logger::get().debug() << "Ctg " << upath.id.signedId() << " overhang " << overhang << " upath " << lastUpath->id.signedId(); for (size_t i = 0; i < upathAln.size(); ++i) { //in case we don't extend using graph structure, //dont mark the last upath as covered if it is //incomplete if (i == upathAln.size() - 1 && lastIncomplete && !graphContinue) break; for (auto& aln : upathAln[i].aln) { repeatDirections[aln.edge] = true; repeatDirections[_graph.complementEdge(aln.edge)] = false; coveredRepeats.insert(aln.edge); coveredRepeats.insert(_graph.complementEdge(aln.edge)); } } //generate extension sequence std::string extendedSeq; if (lastIncomplete && graphContinue && !lastUpath->isLoop()) { upathAln.pop_back(); } if (!upathAln.empty()) { FastaRecord::Id readId = bestAlignment.front().overlap.curId; int32_t readStart = upathAln.front().aln.front().overlap.curBegin; int32_t readEnd = upathAln.back().aln.back().overlap.curEnd; extendedSeq = _readSeqs.getSeq(readId) .substr(readStart, readEnd - readStart).str(); } if (lastIncomplete && graphContinue && !lastUpath->isLoop()) { extendedSeq += upathsSeqs[lastUpath]->sequence.str(); } GraphPath extendedPath; for (auto& ualn : upathAln) { for (auto& edgeAln : ualn.aln) extendedPath.push_back(edgeAln.edge); } if (lastIncomplete && graphContinue && !lastUpath->isLoop()) { for (auto& edge : lastUpath->path) extendedPath.push_back(edge); } return PathAndSeq(extendedPath, extendedSeq); }; std::unordered_map<FastaRecord::Id, UnbranchingPath*> idToPath; for (auto& ctg : _unbranchingPaths) { idToPath[ctg.id] = &ctg; } for (auto& upath : _unbranchingPaths) { if (upath.repetitive || !upath.id.strand()) continue; if (!idToPath.count(upath.id.rc())) continue; //self-complement auto rightExt = extendPathRight(upath); auto leftExt = extendPathRight(*idToPath[upath.id.rc()]); leftExt.first = _graph.complementPath(leftExt.first); leftExt.second = DnaSequence(leftExt.second).complement().str(); Contig contig(upath); auto leftPaths = this->asUpaths(leftExt.first); auto rightPaths = this->asUpaths(rightExt.first); GraphPath leftEdges; for (auto& path : leftPaths) { leftEdges.insert(leftEdges.end(), path->path.begin(), path->path.end()); } contig.graphEdges.path.insert(contig.graphEdges.path.begin(), leftEdges.begin(), leftEdges.end()); contig.graphPaths.insert(contig.graphPaths.begin(), leftPaths.begin(), leftPaths.end()); GraphPath rightEdges; for (auto& path : rightPaths) { rightEdges.insert(rightEdges.end(), path->path.begin(), path->path.end()); } contig.graphEdges.path.insert(contig.graphEdges.path.end(), rightEdges.begin(), rightEdges.end()); contig.graphPaths.insert(contig.graphPaths.end(), rightPaths.begin(), rightPaths.end()); auto coreSeq = upathsSeqs[&upath]->sequence.str(); contig.sequence = DnaSequence(leftExt.second + coreSeq + rightExt.second); _contigs.push_back(std::move(contig)); } //add repetitive contigs that were not covered by the extended paths int numCovered = 0; for (auto& upath : _unbranchingPaths) { if (!upath.repetitive || !upath.id.strand()) continue; bool covered = false; for (auto& edge : upath.path) { if (coveredRepeats.count(edge)) covered = true; } if (!covered) { _contigs.emplace_back(upath); _contigs.back().sequence = upathsSeqs[&upath]->sequence; } else { ++numCovered; //Logger::get().debug() << "Covered: " << upath.id.signedId(); } } Logger::get().debug() << "Covered " << numCovered << " repetitive contigs"; Logger::get().info() << "Generated " << _contigs.size() << " contigs"; } std::vector<UnbranchingPath*> ContigExtender::asUpaths(const GraphPath& path) { std::vector<UnbranchingPath*> upathRepr; for (size_t i = 0; i < path.size(); ++i) { UnbranchingPath* upath = _edgeToPath.at(path[i]); if (upathRepr.empty() || upathRepr.back() != upath || path[i - 1] == path[i]) { upathRepr.push_back(upath); } } return upathRepr; } std::vector<ContigExtender::UpathAlignment> ContigExtender::asUpathAlignment(const GraphAlignment& graphAln) { std::vector<ContigExtender::UpathAlignment> upathAln; for (size_t i = 0; i < graphAln.size(); ++i) { UnbranchingPath* upath = _edgeToPath.at(graphAln[i].edge); if (upathAln.empty() || upathAln.back().upath != upath || graphAln[i - 1].edge == graphAln[i].edge) { upathAln.emplace_back(); upathAln.back().upath = upath; } upathAln.back().aln.push_back(graphAln[i]); } return upathAln; } void ContigExtender::outputStatsTable(const std::string& filename) { std::ofstream fout(filename); if (!fout) throw std::runtime_error("Can't write " + filename); fout << "seq_name\tlength\tcoverage\tcircular\trepeat" << "\tmult\ttelomere\tgraph_path\n"; char YES_NO[] = {'-', '+'}; for (auto& ctg : _contigs) { std::string pathStr; for (auto& upath : ctg.graphPaths) { pathStr += std::to_string(upath->id.signedId()) + ","; } pathStr.pop_back(); int estMult = std::max(1.0f, roundf((float)ctg.graphEdges.meanCoverage / _meanCoverage)); std::string telomereStr; bool telLeft = (ctg.graphEdges.path.front()->nodeLeft->isTelomere()); bool telRight = (ctg.graphEdges.path.back()->nodeRight->isTelomere()); if (telLeft && !telRight) telomereStr = "left"; if (!telLeft && telRight) telomereStr = "right"; if (telLeft && telRight) telomereStr = "both"; if (!telLeft && !telRight) telomereStr = "none"; fout << ctg.graphEdges.name() << "\t" << ctg.sequence.length() << "\t" << ctg.graphEdges.meanCoverage << "\t" << YES_NO[ctg.graphEdges.circular] << "\t" << YES_NO[ctg.graphEdges.repetitive] << "\t" << estMult << "\t" << telomereStr << "\t" << pathStr << "\n"; Logger::get().debug() << "Contig: " << ctg.graphEdges.id.signedId() << ": " << pathStr; } } void ContigExtender::outputContigs(const std::string& filename) { std::vector<FastaRecord> contigsFasta; for (auto& ctg : _contigs) { contigsFasta.emplace_back(ctg.sequence, ctg.graphEdges.name(), FastaRecord::ID_NONE); } SequenceContainer::writeFasta(contigsFasta, filename); } void ContigExtender::outputScaffoldConnections(const std::string& filename) { std::ofstream fout(filename); if (!fout) throw std::runtime_error("Can't open " + filename); auto reachableEdges = [this](GraphEdge* edge) { std::vector<GraphEdge*> dfsStack; std::unordered_set<GraphEdge*> visited; std::unordered_set<GraphEdge*> reachableUnique; std::unordered_set<GraphEdge*> traversedRepeats; dfsStack.push_back(edge); while(!dfsStack.empty()) { auto curEdge = dfsStack.back(); dfsStack.pop_back(); if (visited.count(curEdge)) continue; visited.insert(curEdge); visited.insert(_graph.complementEdge(curEdge)); for (auto& adjEdge: curEdge->nodeRight->outEdges) { if (adjEdge->isRepetitive() && !visited.count(adjEdge)) { dfsStack.push_back(adjEdge); traversedRepeats.insert(adjEdge); } else if (!adjEdge->isRepetitive() && adjEdge != edge) { reachableUnique.insert(adjEdge); } } } return reachableUnique; }; for (auto& edge : _graph.iterEdges()) { if (edge->repetitive) continue; auto reachableUnique = reachableEdges(edge); if (reachableUnique.size() != 1) continue; GraphEdge* outEdge = *reachableUnique.begin(); if (reachableEdges(_graph.complementEdge(outEdge)).size() != 1) continue; if ((edge->nodeRight->isBifurcation() || outEdge->nodeLeft->isBifurcation()) && edge->edgeId != outEdge->edgeId.rc() && abs(edge->edgeId.signedId()) < abs(outEdge->edgeId.signedId())) { UnbranchingPath* leftCtg = this->asUpaths({edge}).front(); UnbranchingPath* rightCtg = this->asUpaths({outEdge}).front(); if (leftCtg != rightCtg) { fout << leftCtg->nameUnsigned() << "\t" << (leftCtg->id.strand() ? '+' : '-') << "\t" << rightCtg->nameUnsigned() << "\t" << (rightCtg->id.strand() ? '+' : '-') << "\n"; } } } } <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "orc/OrcFile.hh" #include <fstream> namespace orc { class FileInputStream : public InputStream { private: std::string filename ; std::ifstream file; long totalLength; public: FileInputStream(std::string _filename) { filename = _filename ; file.open(filename.c_str(), std::ios::in | std::ios::binary); file.seekg(0,file.end); totalLength = file.tellg(); } ~FileInputStream(); long getLength() const { return totalLength; } void read(void* buffer, unsigned long offset, unsigned long length) override { file.seekg(static_cast<std::streamoff>(offset)); file.read(static_cast<char*>(buffer), static_cast<std::streamsize>(length)); } const std::string& getName() const override { return filename; } }; FileInputStream::~FileInputStream() { file.close(); } std::unique_ptr<InputStream> readLocalFile(const std::string& path) { return std::unique_ptr<InputStream>(new FileInputStream(path)); } } <commit_msg>Fixes #44. Replace the file primitives in FileInputStream with the lower level equivalents. (omalley)<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "orc/OrcFile.hh" #include "Exceptions.hh" #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> namespace orc { class FileInputStream : public InputStream { private: std::string filename ; int file; off_t totalLength; public: FileInputStream(std::string _filename) { filename = _filename ; file = open(filename.c_str(), O_RDONLY); if (file == -1) { throw ParseError("Can't open " + filename); } struct stat fileStat; if (fstat(file, &fileStat) == -1) { throw ParseError("Can't stat " + filename); } totalLength = fileStat.st_size; } ~FileInputStream(); long getLength() const { return totalLength; } void read(void* buffer, unsigned long offset, unsigned long length) override { ssize_t bytesRead = pread(file, buffer, length, static_cast<off_t>(offset)); if (bytesRead == -1) { throw ParseError("Bad read of " + filename); } if (static_cast<unsigned long>(bytesRead) != length) { throw ParseError("Short read of " + filename); } } const std::string& getName() const override { return filename; } }; FileInputStream::~FileInputStream() { close(file); } std::unique_ptr<InputStream> readLocalFile(const std::string& path) { return std::unique_ptr<InputStream>(new FileInputStream(path)); } } <|endoftext|>
<commit_before>#pragma once #include "manipulator/details/base.hpp" #include "manipulator/details/types.hpp" #include "types.hpp" #include "virtual_hid_device_client.hpp" #include <mach/mach_time.h> namespace krbn { namespace manipulator { namespace details { class post_event_to_virtual_devices final : public base { public: class queue final { public: class event final { public: enum class type { keyboard_event, pointing_input, }; event(const pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event& keyboard_event, uint64_t time_stamp) : type_(type::keyboard_event), keyboard_event_(keyboard_event), time_stamp_(time_stamp) { } event(const pqrs::karabiner_virtual_hid_device::hid_report::pointing_input& pointing_input, uint64_t time_stamp) : type_(type::pointing_input), pointing_input_(pointing_input), time_stamp_(time_stamp) { } const pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event* get_keyboard_event(void) const { if (type_ == type::keyboard_event) { return &keyboard_event_; } return nullptr; } const pqrs::karabiner_virtual_hid_device::hid_report::pointing_input* get_pointing_input(void) const { if (type_ == type::pointing_input) { return &pointing_input_; } return nullptr; } uint64_t get_time_stamp(void) const { return time_stamp_; } private: type type_; union { pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event keyboard_event_; pqrs::karabiner_virtual_hid_device::hid_report::pointing_input pointing_input_; }; uint64_t time_stamp_; }; queue(void) { } void emplace_back_event(const pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event& keyboard_event, uint64_t time_stamp) { events_.emplace_back(keyboard_event, time_stamp); } void emplace_back_event(const pqrs::karabiner_virtual_hid_device::hid_report::pointing_input& pointing_input, uint64_t time_stamp) { events_.emplace_back(pointing_input, time_stamp); } bool empty(void) const { return events_.empty(); } void post_events(virtual_hid_device_client& virtual_hid_device_client) { if (timer_ && timer_->fired()) { timer_ = nullptr; } if (timer_) { return; } uint64_t now = mach_absolute_time(); while (!events_.empty()) { auto& e = events_.front(); if (e.get_time_stamp() > now) { timer_ = std::make_unique<gcd_utility::main_queue_after_timer>(e.get_time_stamp(), ^{ post_events(virtual_hid_device_client); }); return; } if (auto keyboard_event = e.get_keyboard_event()) { virtual_hid_device_client.dispatch_keyboard_event(*keyboard_event); } if (auto pointing_input = e.get_pointing_input()) { virtual_hid_device_client.post_pointing_input_report(*pointing_input); } events_.erase(std::begin(events_)); } } private: std::vector<event> events_; std::unique_ptr<gcd_utility::main_queue_after_timer> timer_; }; post_event_to_virtual_devices(void) : base(), queue_() { } virtual ~post_event_to_virtual_devices(void) { } virtual void manipulate(event_queue::queued_event& front_input_event, const event_queue& input_event_queue, event_queue& output_event_queue, uint64_t time_stamp) { output_event_queue.push_back_event(front_input_event); front_input_event.set_valid(false); switch (front_input_event.get_event().get_type()) { case event_queue::queued_event::event::type::key_code: if (auto key_code = front_input_event.get_event().get_key_code()) { if (auto usage_page = types::get_usage_page(*key_code)) { if (auto usage = types::get_usage(*key_code)) { pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event keyboard_event; keyboard_event.usage_page = *usage_page; keyboard_event.usage = *usage; keyboard_event.value = front_input_event.get_event_type() == event_type::key_down; queue_.emplace_back_event(keyboard_event, front_input_event.get_time_stamp()); } } return; } break; case event_queue::queued_event::event::type::pointing_button: case event_queue::queued_event::event::type::pointing_x: case event_queue::queued_event::event::type::pointing_y: case event_queue::queued_event::event::type::pointing_vertical_wheel: case event_queue::queued_event::event::type::pointing_horizontal_wheel: { pqrs::karabiner_virtual_hid_device::hid_report::pointing_input report; auto bits = output_event_queue.get_pointing_button_manager().get_hid_report_bits(); report.buttons[0] = (bits >> 0) & 0xff; report.buttons[1] = (bits >> 8) & 0xff; report.buttons[2] = (bits >> 16) & 0xff; report.buttons[3] = (bits >> 24) & 0xff; if (auto integer_value = front_input_event.get_event().get_integer_value()) { switch (front_input_event.get_event().get_type()) { case event_queue::queued_event::event::type::pointing_x: report.x = *integer_value; break; case event_queue::queued_event::event::type::pointing_y: report.y = *integer_value; break; case event_queue::queued_event::event::type::pointing_vertical_wheel: report.vertical_wheel = *integer_value; break; case event_queue::queued_event::event::type::pointing_horizontal_wheel: report.horizontal_wheel = *integer_value; break; case event_queue::queued_event::event::type::key_code: case event_queue::queued_event::event::type::pointing_button: // Do nothing break; } } queue_.emplace_back_event(report, front_input_event.get_time_stamp()); break; } } } virtual bool active(void) const { return !queue_.empty(); } virtual void device_ungrabbed_callback(device_id device_id, event_queue& output_event_queue, uint64_t time_stamp) { // Do nothing } private: queue queue_; }; } // namespace details } // namespace manipulator } // namespace krbn <commit_msg>add operator==<commit_after>#pragma once #include "boost_defs.hpp" #include "manipulator/details/base.hpp" #include "manipulator/details/types.hpp" #include "types.hpp" #include "virtual_hid_device_client.hpp" #include <boost/optional.hpp> #include <mach/mach_time.h> namespace krbn { namespace manipulator { namespace details { class post_event_to_virtual_devices final : public base { public: class queue final { public: class event final { public: enum class type { keyboard_event, pointing_input, }; event(const pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event& keyboard_event, uint64_t time_stamp) : type_(type::keyboard_event), keyboard_event_(keyboard_event), time_stamp_(time_stamp) { } event(const pqrs::karabiner_virtual_hid_device::hid_report::pointing_input& pointing_input, uint64_t time_stamp) : type_(type::pointing_input), pointing_input_(pointing_input), time_stamp_(time_stamp) { } type get_type(void) const { return type_; } boost::optional<pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event> get_keyboard_event(void) const { if (type_ == type::keyboard_event) { return keyboard_event_; } return boost::none; } boost::optional<pqrs::karabiner_virtual_hid_device::hid_report::pointing_input> get_pointing_input(void) const { if (type_ == type::pointing_input) { return pointing_input_; } return boost::none; } uint64_t get_time_stamp(void) const { return time_stamp_; } bool operator==(const event& other) const { return get_type() == other.get_type() && get_keyboard_event() == other.get_keyboard_event() && get_pointing_input() == other.get_pointing_input() && get_time_stamp() == other.get_time_stamp(); } private: type type_; union { pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event keyboard_event_; pqrs::karabiner_virtual_hid_device::hid_report::pointing_input pointing_input_; }; uint64_t time_stamp_; }; queue(void) { } void emplace_back_event(const pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event& keyboard_event, uint64_t time_stamp) { events_.emplace_back(keyboard_event, time_stamp); } void emplace_back_event(const pqrs::karabiner_virtual_hid_device::hid_report::pointing_input& pointing_input, uint64_t time_stamp) { events_.emplace_back(pointing_input, time_stamp); } bool empty(void) const { return events_.empty(); } void post_events(virtual_hid_device_client& virtual_hid_device_client) { if (timer_ && timer_->fired()) { timer_ = nullptr; } if (timer_) { return; } uint64_t now = mach_absolute_time(); while (!events_.empty()) { auto& e = events_.front(); if (e.get_time_stamp() > now) { timer_ = std::make_unique<gcd_utility::main_queue_after_timer>(e.get_time_stamp(), ^{ post_events(virtual_hid_device_client); }); return; } if (auto keyboard_event = e.get_keyboard_event()) { virtual_hid_device_client.dispatch_keyboard_event(*keyboard_event); } if (auto pointing_input = e.get_pointing_input()) { virtual_hid_device_client.post_pointing_input_report(*pointing_input); } events_.erase(std::begin(events_)); } } private: std::vector<event> events_; std::unique_ptr<gcd_utility::main_queue_after_timer> timer_; }; post_event_to_virtual_devices(void) : base(), queue_() { } virtual ~post_event_to_virtual_devices(void) { } virtual void manipulate(event_queue::queued_event& front_input_event, const event_queue& input_event_queue, event_queue& output_event_queue, uint64_t time_stamp) { output_event_queue.push_back_event(front_input_event); front_input_event.set_valid(false); switch (front_input_event.get_event().get_type()) { case event_queue::queued_event::event::type::key_code: if (auto key_code = front_input_event.get_event().get_key_code()) { if (auto usage_page = types::get_usage_page(*key_code)) { if (auto usage = types::get_usage(*key_code)) { pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event keyboard_event; keyboard_event.usage_page = *usage_page; keyboard_event.usage = *usage; keyboard_event.value = front_input_event.get_event_type() == event_type::key_down; queue_.emplace_back_event(keyboard_event, front_input_event.get_time_stamp()); } } return; } break; case event_queue::queued_event::event::type::pointing_button: case event_queue::queued_event::event::type::pointing_x: case event_queue::queued_event::event::type::pointing_y: case event_queue::queued_event::event::type::pointing_vertical_wheel: case event_queue::queued_event::event::type::pointing_horizontal_wheel: { pqrs::karabiner_virtual_hid_device::hid_report::pointing_input report; auto bits = output_event_queue.get_pointing_button_manager().get_hid_report_bits(); report.buttons[0] = (bits >> 0) & 0xff; report.buttons[1] = (bits >> 8) & 0xff; report.buttons[2] = (bits >> 16) & 0xff; report.buttons[3] = (bits >> 24) & 0xff; if (auto integer_value = front_input_event.get_event().get_integer_value()) { switch (front_input_event.get_event().get_type()) { case event_queue::queued_event::event::type::pointing_x: report.x = *integer_value; break; case event_queue::queued_event::event::type::pointing_y: report.y = *integer_value; break; case event_queue::queued_event::event::type::pointing_vertical_wheel: report.vertical_wheel = *integer_value; break; case event_queue::queued_event::event::type::pointing_horizontal_wheel: report.horizontal_wheel = *integer_value; break; case event_queue::queued_event::event::type::key_code: case event_queue::queued_event::event::type::pointing_button: // Do nothing break; } } queue_.emplace_back_event(report, front_input_event.get_time_stamp()); break; } } } virtual bool active(void) const { return !queue_.empty(); } virtual void device_ungrabbed_callback(device_id device_id, event_queue& output_event_queue, uint64_t time_stamp) { // Do nothing } private: queue queue_; }; } // namespace details } // namespace manipulator } // namespace krbn <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "compileoutputwindow.h" #include "buildmanager.h" #include "showoutputtaskhandler.h" #include "task.h" #include "projectexplorer.h" #include "projectexplorersettings.h" #include "taskhub.h" #include <coreplugin/outputwindow.h> #include <coreplugin/find/basetextfind.h> #include <extensionsystem/pluginmanager.h> #include <texteditor/texteditorsettings.h> #include <texteditor/fontsettings.h> #include <utils/ansiescapecodehandler.h> #include <QIcon> #include <QTextCharFormat> #include <QTextBlock> #include <QTextCursor> #include <QPlainTextEdit> #include <QToolButton> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; namespace { const int MAX_LINECOUNT = 100000; } namespace ProjectExplorer { namespace Internal { class CompileOutputTextEdit : public Core::OutputWindow { Q_OBJECT public: CompileOutputTextEdit(const Core::Context &context) : Core::OutputWindow(context) { fontSettingsChanged(); connect(TextEditor::TextEditorSettings::instance(), SIGNAL(fontSettingsChanged(TextEditor::FontSettings)), this, SLOT(fontSettingsChanged())); } void addTask(const Task &task, int blocknumber) { m_taskids.insert(blocknumber, task.taskId); } void clearTasks() { m_taskids.clear(); } private slots: void fontSettingsChanged() { setFont(TextEditor::TextEditorSettings::fontSettings().font()); } protected: void mouseDoubleClickEvent(QMouseEvent *ev) { int line = cursorForPosition(ev->pos()).block().blockNumber(); if (unsigned taskid = m_taskids.value(line, 0)) TaskHub::showTaskInEditor(taskid); else QPlainTextEdit::mouseDoubleClickEvent(ev); } private: QHash<int, unsigned int> m_taskids; //Map blocknumber to taskId }; } // namespace Internal } // namespace ProjectExplorer CompileOutputWindow::CompileOutputWindow(QAction *cancelBuildAction) : m_cancelBuildButton(new QToolButton), m_escapeCodeHandler(new Utils::AnsiEscapeCodeHandler) { Core::Context context(Constants::C_COMPILE_OUTPUT); m_outputWindow = new CompileOutputTextEdit(context); m_outputWindow->setWindowTitle(tr("Compile Output")); m_outputWindow->setWindowIcon(QIcon(QLatin1String(Constants::ICON_WINDOW))); m_outputWindow->setReadOnly(true); m_outputWindow->setUndoRedoEnabled(false); m_outputWindow->setMaxLineCount(MAX_LINECOUNT); // Let selected text be colored as if the text edit was editable, // otherwise the highlight for searching is too light QPalette p = m_outputWindow->palette(); QColor activeHighlight = p.color(QPalette::Active, QPalette::Highlight); p.setColor(QPalette::Highlight, activeHighlight); QColor activeHighlightedText = p.color(QPalette::Active, QPalette::HighlightedText); p.setColor(QPalette::HighlightedText, activeHighlightedText); m_outputWindow->setPalette(p); m_cancelBuildButton->setDefaultAction(cancelBuildAction); Aggregation::Aggregate *agg = new Aggregation::Aggregate; agg->add(m_outputWindow); agg->add(new Core::BaseTextFind(m_outputWindow)); qRegisterMetaType<QTextCharFormat>("QTextCharFormat"); m_handler = new ShowOutputTaskHandler(this); ExtensionSystem::PluginManager::addObject(m_handler); connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()), this, SLOT(updateWordWrapMode())); updateWordWrapMode(); } CompileOutputWindow::~CompileOutputWindow() { ExtensionSystem::PluginManager::removeObject(m_handler); delete m_handler; delete m_cancelBuildButton; delete m_escapeCodeHandler; } void CompileOutputWindow::updateWordWrapMode() { m_outputWindow->setWordWrapEnabled(ProjectExplorerPlugin::projectExplorerSettings().wrapAppOutput); } bool CompileOutputWindow::hasFocus() const { return m_outputWindow->window()->focusWidget() == m_outputWindow; } bool CompileOutputWindow::canFocus() const { return true; } void CompileOutputWindow::setFocus() { m_outputWindow->setFocus(); } QWidget *CompileOutputWindow::outputWidget(QWidget *) { return m_outputWindow; } QList<QWidget *> CompileOutputWindow::toolBarWidgets() const { return QList<QWidget *>() << m_cancelBuildButton; } static QColor mix_colors(const QColor &a, const QColor &b) { return QColor((a.red() + 2 * b.red()) / 3, (a.green() + 2 * b.green()) / 3, (a.blue() + 2* b.blue()) / 3, (a.alpha() + 2 * b.alpha()) / 3); } void CompileOutputWindow::appendText(const QString &text, BuildStep::OutputFormat format) { QPalette p = m_outputWindow->palette(); QTextCharFormat textFormat; switch (format) { case BuildStep::NormalOutput: textFormat.setForeground(p.color(QPalette::Text)); textFormat.setFontWeight(QFont::Normal); break; case BuildStep::ErrorOutput: textFormat.setForeground(mix_colors(p.color(QPalette::Text), QColor(Qt::red))); textFormat.setFontWeight(QFont::Normal); break; case BuildStep::MessageOutput: textFormat.setForeground(mix_colors(p.color(QPalette::Text), QColor(Qt::blue))); break; case BuildStep::ErrorMessageOutput: textFormat.setForeground(mix_colors(p.color(QPalette::Text), QColor(Qt::red))); textFormat.setFontWeight(QFont::Bold); break; } foreach (const Utils::FormattedText &output, m_escapeCodeHandler->parseText(Utils::FormattedText(text, textFormat))) m_outputWindow->appendText(output.text, output.format); } void CompileOutputWindow::clearContents() { m_outputWindow->clear(); m_outputWindow->clearTasks(); m_taskPositions.clear(); } void CompileOutputWindow::visibilityChanged(bool) { } int CompileOutputWindow::priorityInStatusBar() const { return 50; } bool CompileOutputWindow::canNext() const { return false; } bool CompileOutputWindow::canPrevious() const { return false; } void CompileOutputWindow::goToNext() { } void CompileOutputWindow::goToPrev() { } bool CompileOutputWindow::canNavigate() const { return false; } void CompileOutputWindow::registerPositionOf(const Task &task) { int blocknumber = m_outputWindow->blockCount(); if (blocknumber > MAX_LINECOUNT) return; m_taskPositions.insert(task.taskId, blocknumber); m_outputWindow->addTask(task, blocknumber); } bool CompileOutputWindow::knowsPositionOf(const Task &task) { return (m_taskPositions.contains(task.taskId)); } void CompileOutputWindow::showPositionOf(const Task &task) { int position = m_taskPositions.value(task.taskId); QTextCursor newCursor(m_outputWindow->document()->findBlockByNumber(position)); newCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); m_outputWindow->setTextCursor(newCursor); } void CompileOutputWindow::flush() { if (m_escapeCodeHandler) m_escapeCodeHandler->endFormatScope(); } #include "compileoutputwindow.moc" <commit_msg>Compile output: Do not do scroll wheel zooming<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "compileoutputwindow.h" #include "buildmanager.h" #include "showoutputtaskhandler.h" #include "task.h" #include "projectexplorer.h" #include "projectexplorersettings.h" #include "taskhub.h" #include <coreplugin/outputwindow.h> #include <coreplugin/find/basetextfind.h> #include <extensionsystem/pluginmanager.h> #include <texteditor/texteditorsettings.h> #include <texteditor/fontsettings.h> #include <utils/ansiescapecodehandler.h> #include <QIcon> #include <QTextCharFormat> #include <QTextBlock> #include <QTextCursor> #include <QPlainTextEdit> #include <QToolButton> using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; namespace { const int MAX_LINECOUNT = 100000; } namespace ProjectExplorer { namespace Internal { class CompileOutputTextEdit : public Core::OutputWindow { Q_OBJECT public: CompileOutputTextEdit(const Core::Context &context) : Core::OutputWindow(context) { fontSettingsChanged(); connect(TextEditor::TextEditorSettings::instance(), SIGNAL(fontSettingsChanged(TextEditor::FontSettings)), this, SLOT(fontSettingsChanged())); } void addTask(const Task &task, int blocknumber) { m_taskids.insert(blocknumber, task.taskId); } void clearTasks() { m_taskids.clear(); } private slots: void fontSettingsChanged() { setFont(TextEditor::TextEditorSettings::fontSettings().font()); } protected: void wheelEvent(QWheelEvent *ev) { // from QPlainTextEdit, but without scroll wheel zooming QAbstractScrollArea::wheelEvent(ev); updateMicroFocus(); } void mouseDoubleClickEvent(QMouseEvent *ev) { int line = cursorForPosition(ev->pos()).block().blockNumber(); if (unsigned taskid = m_taskids.value(line, 0)) TaskHub::showTaskInEditor(taskid); else QPlainTextEdit::mouseDoubleClickEvent(ev); } private: QHash<int, unsigned int> m_taskids; //Map blocknumber to taskId }; } // namespace Internal } // namespace ProjectExplorer CompileOutputWindow::CompileOutputWindow(QAction *cancelBuildAction) : m_cancelBuildButton(new QToolButton), m_escapeCodeHandler(new Utils::AnsiEscapeCodeHandler) { Core::Context context(Constants::C_COMPILE_OUTPUT); m_outputWindow = new CompileOutputTextEdit(context); m_outputWindow->setWindowTitle(tr("Compile Output")); m_outputWindow->setWindowIcon(QIcon(QLatin1String(Constants::ICON_WINDOW))); m_outputWindow->setReadOnly(true); m_outputWindow->setUndoRedoEnabled(false); m_outputWindow->setMaxLineCount(MAX_LINECOUNT); // Let selected text be colored as if the text edit was editable, // otherwise the highlight for searching is too light QPalette p = m_outputWindow->palette(); QColor activeHighlight = p.color(QPalette::Active, QPalette::Highlight); p.setColor(QPalette::Highlight, activeHighlight); QColor activeHighlightedText = p.color(QPalette::Active, QPalette::HighlightedText); p.setColor(QPalette::HighlightedText, activeHighlightedText); m_outputWindow->setPalette(p); m_cancelBuildButton->setDefaultAction(cancelBuildAction); Aggregation::Aggregate *agg = new Aggregation::Aggregate; agg->add(m_outputWindow); agg->add(new Core::BaseTextFind(m_outputWindow)); qRegisterMetaType<QTextCharFormat>("QTextCharFormat"); m_handler = new ShowOutputTaskHandler(this); ExtensionSystem::PluginManager::addObject(m_handler); connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()), this, SLOT(updateWordWrapMode())); updateWordWrapMode(); } CompileOutputWindow::~CompileOutputWindow() { ExtensionSystem::PluginManager::removeObject(m_handler); delete m_handler; delete m_cancelBuildButton; delete m_escapeCodeHandler; } void CompileOutputWindow::updateWordWrapMode() { m_outputWindow->setWordWrapEnabled(ProjectExplorerPlugin::projectExplorerSettings().wrapAppOutput); } bool CompileOutputWindow::hasFocus() const { return m_outputWindow->window()->focusWidget() == m_outputWindow; } bool CompileOutputWindow::canFocus() const { return true; } void CompileOutputWindow::setFocus() { m_outputWindow->setFocus(); } QWidget *CompileOutputWindow::outputWidget(QWidget *) { return m_outputWindow; } QList<QWidget *> CompileOutputWindow::toolBarWidgets() const { return QList<QWidget *>() << m_cancelBuildButton; } static QColor mix_colors(const QColor &a, const QColor &b) { return QColor((a.red() + 2 * b.red()) / 3, (a.green() + 2 * b.green()) / 3, (a.blue() + 2* b.blue()) / 3, (a.alpha() + 2 * b.alpha()) / 3); } void CompileOutputWindow::appendText(const QString &text, BuildStep::OutputFormat format) { QPalette p = m_outputWindow->palette(); QTextCharFormat textFormat; switch (format) { case BuildStep::NormalOutput: textFormat.setForeground(p.color(QPalette::Text)); textFormat.setFontWeight(QFont::Normal); break; case BuildStep::ErrorOutput: textFormat.setForeground(mix_colors(p.color(QPalette::Text), QColor(Qt::red))); textFormat.setFontWeight(QFont::Normal); break; case BuildStep::MessageOutput: textFormat.setForeground(mix_colors(p.color(QPalette::Text), QColor(Qt::blue))); break; case BuildStep::ErrorMessageOutput: textFormat.setForeground(mix_colors(p.color(QPalette::Text), QColor(Qt::red))); textFormat.setFontWeight(QFont::Bold); break; } foreach (const Utils::FormattedText &output, m_escapeCodeHandler->parseText(Utils::FormattedText(text, textFormat))) m_outputWindow->appendText(output.text, output.format); } void CompileOutputWindow::clearContents() { m_outputWindow->clear(); m_outputWindow->clearTasks(); m_taskPositions.clear(); } void CompileOutputWindow::visibilityChanged(bool) { } int CompileOutputWindow::priorityInStatusBar() const { return 50; } bool CompileOutputWindow::canNext() const { return false; } bool CompileOutputWindow::canPrevious() const { return false; } void CompileOutputWindow::goToNext() { } void CompileOutputWindow::goToPrev() { } bool CompileOutputWindow::canNavigate() const { return false; } void CompileOutputWindow::registerPositionOf(const Task &task) { int blocknumber = m_outputWindow->blockCount(); if (blocknumber > MAX_LINECOUNT) return; m_taskPositions.insert(task.taskId, blocknumber); m_outputWindow->addTask(task, blocknumber); } bool CompileOutputWindow::knowsPositionOf(const Task &task) { return (m_taskPositions.contains(task.taskId)); } void CompileOutputWindow::showPositionOf(const Task &task) { int position = m_taskPositions.value(task.taskId); QTextCursor newCursor(m_outputWindow->document()->findBlockByNumber(position)); newCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); m_outputWindow->setTextCursor(newCursor); } void CompileOutputWindow::flush() { if (m_escapeCodeHandler) m_escapeCodeHandler->endFormatScope(); } #include "compileoutputwindow.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qbsprojectmanager.h" #include "qbslogsink.h" #include "qbsproject.h" #include "qbsprojectmanagerconstants.h" #include "qbsprojectmanagerplugin.h" #include <projectexplorer/kitinformation.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> #include <qmljstools/qmljstoolsconstants.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtkitinformation.h> #include <utils/qtcassert.h> #include <QVariantMap> #include <qbs.h> // qbs settings structure: const char PROFILE_LIST[] = "preferences.qtcreator.kit."; const char PROFILES_PREFIX[] = "profiles."; // Qt related settings: const char QTCORE_BINPATH[] = ".qt.core.binPath"; const char QTCORE_INCPATH[] = ".qt.core.incPath"; const char QTCORE_LIBPATH[] = ".qt.core.libPath"; const char QTCORE_VERSION[] = ".qt.core.version"; const char QTCORE_NAMESPACE[] = ".qt.core.namespace"; const char QTCORE_LIBINFIX[] = ".qt.core.libInfix"; const char QTCORE_MKSPEC[] = ".qt.core.mkspecPath"; // Toolchain related settings: const char QBS_TARGETOS[] = ".qbs.targetOS"; const char QBS_SYSROOT[] = ".qbs.sysroot"; const char QBS_ARCHITECTURE[] = ".qbs.architecture"; const char QBS_TOOLCHAIN[] = ".qbs.toolchain"; const char CPP_TOOLCHAINPATH[] = ".cpp.toolchainInstallPath"; const char CPP_COMPILERNAME[] = ".cpp.compilerName"; const QChar sep = QChar(QLatin1Char('.')); namespace QbsProjectManager { qbs::Settings *QbsManager::m_settings = new qbs::Settings(QLatin1String("QtProject"), QLatin1String("qbs")); QbsManager::QbsManager(Internal::QbsProjectManagerPlugin *plugin) : m_plugin(plugin) { setObjectName(QLatin1String("QbsProjectManager")); connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsChanged()), this, SLOT(pushKitsToQbs())); qbs::Logger::instance().setLogSink(new Internal::QbsLogSink); qbs::Logger::instance().setLevel(qbs::LoggerWarning); } QbsManager::~QbsManager() { delete m_settings; } QString QbsManager::mimeType() const { return QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE); } ProjectExplorer::Project *QbsManager::openProject(const QString &fileName, QString *errorString) { Q_UNUSED(errorString); // FIXME: This is way too simplistic! return new Internal::QbsProject(this, fileName); } QString QbsManager::profileForKit(const ProjectExplorer::Kit *k) const { if (!k) return QString(); return m_settings->value(QString::fromLatin1(PROFILE_LIST) + k->id().toString()).toString(); } void QbsManager::setProfileForKit(const QString &name, const ProjectExplorer::Kit *k) { m_settings->setValue(QString::fromLatin1(PROFILE_LIST) + k->id().toString(), name); } QStringList QbsManager::profileNames() const { QStringList keyList = m_settings->allKeys(); QStringList result; foreach (const QString &key, keyList) { if (!key.startsWith(QString::fromLatin1(PROFILES_PREFIX))) continue; QString profile = key; profile.remove(0, QString::fromLatin1(PROFILES_PREFIX).count()); profile = profile.left(profile.indexOf(sep)); if (!result.contains(profile)) result << profile; } return result; } qbs::Settings *QbsManager::settings() { return m_settings; } void QbsManager::addProfile(const QString &name, const QVariantMap &data) { const QString base = QLatin1String(PROFILES_PREFIX) + name; foreach (const QString &key, data.keys()) m_settings->setValue(base + key, data.value(key)); } void QbsManager::removeCreatorProfiles() { QStringList keyList = m_settings->allKeys(); QStringList profilesToDelete; // Find profiles to remove: foreach (const QString &key, keyList) { if (!key.startsWith(QLatin1String(PROFILE_LIST))) continue; profilesToDelete.append(m_settings->value(key).toString()); m_settings->remove(key); } // Remove profiles: foreach (const QString &key, keyList) { if (!key.startsWith(QLatin1String(PROFILES_PREFIX))) continue; const QString kitname = key.mid(QString::fromLatin1(PROFILES_PREFIX).size()); foreach (const QString &i, profilesToDelete) { if (kitname.startsWith(i + sep)) m_settings->remove(key); } } } void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k) { QStringList usedProfileNames = profileNames(); const QString name = ProjectExplorer::Project::makeUnique(k->fileSystemFriendlyName(), usedProfileNames); setProfileForKit(name, k); QVariantMap data; QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(k); if (qt) { data.insert(QLatin1String(QTCORE_BINPATH), qt->binPath().toUserOutput()); data.insert(QLatin1String(QTCORE_INCPATH), qt->headerPath().toUserOutput()); data.insert(QLatin1String(QTCORE_LIBPATH), qt->libraryPath().toUserOutput()); data.insert(QLatin1String(QTCORE_MKSPEC), qt->mkspecsPath().toUserOutput()); data.insert(QLatin1String(QTCORE_NAMESPACE), qt->qtNamespace()); data.insert(QLatin1String(QTCORE_LIBINFIX), qt->qtLibInfix()); data.insert(QLatin1String(QTCORE_VERSION), qt->qtVersionString()); } if (ProjectExplorer::SysRootKitInformation::hasSysRoot(k)) data.insert(QLatin1String(QBS_SYSROOT), ProjectExplorer::SysRootKitInformation::sysRoot(k).toUserOutput()); ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k); if (tc) { // FIXME/CLARIFY: How to pass the sysroot? ProjectExplorer::Abi targetAbi = tc->targetAbi(); QString architecture = ProjectExplorer::Abi::toString(targetAbi.architecture()); if (targetAbi.wordWidth() == 64) architecture.append(QLatin1String("_64")); data.insert(QLatin1String(QBS_ARCHITECTURE), architecture); if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) { data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("windows")); data.insert(QLatin1String(QBS_TOOLCHAIN), targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor ? QLatin1String("mingw") : QLatin1String("msvc")); } else if (targetAbi.os() == ProjectExplorer::Abi::MacOS) { data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("mac")); data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc")); } else if (targetAbi.os() == ProjectExplorer::Abi::LinuxOS) { data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("linux")); data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc")); } Utils::FileName cxx = tc->compilerCommand(); data.insert(QLatin1String(CPP_TOOLCHAINPATH), cxx.toFileInfo().absolutePath()); data.insert(QLatin1String(CPP_COMPILERNAME), cxx.toFileInfo().fileName()); } addProfile(name, data); } void QbsManager::pushKitsToQbs() { // Get all keys removeCreatorProfiles(); // add definitions from our kits foreach (const ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits()) addProfileFromKit(k); } } // namespace QbsProjectManager <commit_msg>Qbs: Allow for tweaking of Qbs log level via environment<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qbsprojectmanager.h" #include "qbslogsink.h" #include "qbsproject.h" #include "qbsprojectmanagerconstants.h" #include "qbsprojectmanagerplugin.h" #include <projectexplorer/kitinformation.h> #include <projectexplorer/kitmanager.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> #include <qmljstools/qmljstoolsconstants.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtkitinformation.h> #include <utils/qtcassert.h> #include <QVariantMap> #include <qbs.h> // qbs settings structure: const char PROFILE_LIST[] = "preferences.qtcreator.kit."; const char PROFILES_PREFIX[] = "profiles."; // Qt related settings: const char QTCORE_BINPATH[] = ".qt.core.binPath"; const char QTCORE_INCPATH[] = ".qt.core.incPath"; const char QTCORE_LIBPATH[] = ".qt.core.libPath"; const char QTCORE_VERSION[] = ".qt.core.version"; const char QTCORE_NAMESPACE[] = ".qt.core.namespace"; const char QTCORE_LIBINFIX[] = ".qt.core.libInfix"; const char QTCORE_MKSPEC[] = ".qt.core.mkspecPath"; // Toolchain related settings: const char QBS_TARGETOS[] = ".qbs.targetOS"; const char QBS_SYSROOT[] = ".qbs.sysroot"; const char QBS_ARCHITECTURE[] = ".qbs.architecture"; const char QBS_TOOLCHAIN[] = ".qbs.toolchain"; const char CPP_TOOLCHAINPATH[] = ".cpp.toolchainInstallPath"; const char CPP_COMPILERNAME[] = ".cpp.compilerName"; const QChar sep = QChar(QLatin1Char('.')); namespace QbsProjectManager { qbs::Settings *QbsManager::m_settings = new qbs::Settings(QLatin1String("QtProject"), QLatin1String("qbs")); QbsManager::QbsManager(Internal::QbsProjectManagerPlugin *plugin) : m_plugin(plugin) { setObjectName(QLatin1String("QbsProjectManager")); connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsChanged()), this, SLOT(pushKitsToQbs())); qbs::Logger::instance().setLogSink(new Internal::QbsLogSink); int level = qbs::LoggerWarning; const QString levelEnv = QString::fromLocal8Bit(qgetenv("QBS_LOG_LEVEL")); if (!levelEnv.isEmpty()) { int tmp = levelEnv.toInt(); if (tmp < static_cast<int>(qbs::LoggerMinLevel)) tmp = static_cast<int>(qbs::LoggerMinLevel); if (tmp > static_cast<int>(qbs::LoggerMaxLevel)) tmp = static_cast<int>(qbs::LoggerMaxLevel); level = tmp; } qbs::Logger::instance().setLevel(level); } QbsManager::~QbsManager() { delete m_settings; } QString QbsManager::mimeType() const { return QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE); } ProjectExplorer::Project *QbsManager::openProject(const QString &fileName, QString *errorString) { Q_UNUSED(errorString); // FIXME: This is way too simplistic! return new Internal::QbsProject(this, fileName); } QString QbsManager::profileForKit(const ProjectExplorer::Kit *k) const { if (!k) return QString(); return m_settings->value(QString::fromLatin1(PROFILE_LIST) + k->id().toString()).toString(); } void QbsManager::setProfileForKit(const QString &name, const ProjectExplorer::Kit *k) { m_settings->setValue(QString::fromLatin1(PROFILE_LIST) + k->id().toString(), name); } QStringList QbsManager::profileNames() const { QStringList keyList = m_settings->allKeys(); QStringList result; foreach (const QString &key, keyList) { if (!key.startsWith(QString::fromLatin1(PROFILES_PREFIX))) continue; QString profile = key; profile.remove(0, QString::fromLatin1(PROFILES_PREFIX).count()); profile = profile.left(profile.indexOf(sep)); if (!result.contains(profile)) result << profile; } return result; } qbs::Settings *QbsManager::settings() { return m_settings; } void QbsManager::addProfile(const QString &name, const QVariantMap &data) { const QString base = QLatin1String(PROFILES_PREFIX) + name; foreach (const QString &key, data.keys()) m_settings->setValue(base + key, data.value(key)); } void QbsManager::removeCreatorProfiles() { QStringList keyList = m_settings->allKeys(); QStringList profilesToDelete; // Find profiles to remove: foreach (const QString &key, keyList) { if (!key.startsWith(QLatin1String(PROFILE_LIST))) continue; profilesToDelete.append(m_settings->value(key).toString()); m_settings->remove(key); } // Remove profiles: foreach (const QString &key, keyList) { if (!key.startsWith(QLatin1String(PROFILES_PREFIX))) continue; const QString kitname = key.mid(QString::fromLatin1(PROFILES_PREFIX).size()); foreach (const QString &i, profilesToDelete) { if (kitname.startsWith(i + sep)) m_settings->remove(key); } } } void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k) { QStringList usedProfileNames = profileNames(); const QString name = ProjectExplorer::Project::makeUnique(k->fileSystemFriendlyName(), usedProfileNames); setProfileForKit(name, k); QVariantMap data; QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(k); if (qt) { data.insert(QLatin1String(QTCORE_BINPATH), qt->binPath().toUserOutput()); data.insert(QLatin1String(QTCORE_INCPATH), qt->headerPath().toUserOutput()); data.insert(QLatin1String(QTCORE_LIBPATH), qt->libraryPath().toUserOutput()); data.insert(QLatin1String(QTCORE_MKSPEC), qt->mkspecsPath().toUserOutput()); data.insert(QLatin1String(QTCORE_NAMESPACE), qt->qtNamespace()); data.insert(QLatin1String(QTCORE_LIBINFIX), qt->qtLibInfix()); data.insert(QLatin1String(QTCORE_VERSION), qt->qtVersionString()); } if (ProjectExplorer::SysRootKitInformation::hasSysRoot(k)) data.insert(QLatin1String(QBS_SYSROOT), ProjectExplorer::SysRootKitInformation::sysRoot(k).toUserOutput()); ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k); if (tc) { // FIXME/CLARIFY: How to pass the sysroot? ProjectExplorer::Abi targetAbi = tc->targetAbi(); QString architecture = ProjectExplorer::Abi::toString(targetAbi.architecture()); if (targetAbi.wordWidth() == 64) architecture.append(QLatin1String("_64")); data.insert(QLatin1String(QBS_ARCHITECTURE), architecture); if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) { data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("windows")); data.insert(QLatin1String(QBS_TOOLCHAIN), targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor ? QLatin1String("mingw") : QLatin1String("msvc")); } else if (targetAbi.os() == ProjectExplorer::Abi::MacOS) { data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("mac")); data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc")); } else if (targetAbi.os() == ProjectExplorer::Abi::LinuxOS) { data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("linux")); data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc")); } Utils::FileName cxx = tc->compilerCommand(); data.insert(QLatin1String(CPP_TOOLCHAINPATH), cxx.toFileInfo().absolutePath()); data.insert(QLatin1String(CPP_COMPILERNAME), cxx.toFileInfo().fileName()); } addProfile(name, data); } void QbsManager::pushKitsToQbs() { // Get all keys removeCreatorProfiles(); // add definitions from our kits foreach (const ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits()) addProfileFromKit(k); } } // namespace QbsProjectManager <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mss_attribute_accessors_manual.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mss_attribute_accessors_manual.H /// @brief Manually created attribute accessors. /// Some attributes aren't in files we want to incorporate in to our automated /// accessor generator. EC workarounds is one example - everytime someone creates /// a work-around they'd be burdened with updating this file. /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Steven Glancy <sglancy@usi.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: Memory #ifndef MSS_ATTR_ACCESS_MANUAL_H_ #define MSS_ATTR_ACCESS_MANUAL_H_ #include <fapi2.H> #include <lib/utils/find.H> namespace mss { /// /// @brief 2N mode helper /// When figuring out 2N mode we need to access two attributes. This helper /// gives us a place to put that common code /// @tparam T the fapi2::TargetType of the input target /// @param[in] the target from which to get the 2N mode autoset attribute /// @return true iff 2N mode is 'on' /// template< fapi2::TargetType T > inline bool two_n_mode_helper(const fapi2::Target<T>& i_target) { uint8_t l_2n_autoset = 0; uint8_t l_2n_mrw_mode = 0; // There are no VPD enums defined for 2N autoset <shrug>. constexpr uint8_t ATTR_MSS_VPD_MR_MC_2N_MODE_AUTOSET_2N_MODE = 0x02; const auto l_mcs = mss::find_target<fapi2::TARGET_TYPE_MCS>(i_target); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_MSS_VPD_MR_MC_2N_MODE_AUTOSET, l_mcs, l_2n_autoset) ); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_MSS_MRW_DRAM_2N_MODE, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_2n_mrw_mode) ); // If the MRW states 'auto' we use what's in VPD, otherwise we use what's in the MRW. return (l_2n_mrw_mode == fapi2::ENUM_ATTR_MSS_MRW_DRAM_2N_MODE_AUTO) ? l_2n_autoset == ATTR_MSS_VPD_MR_MC_2N_MODE_AUTOSET_2N_MODE : l_2n_mrw_mode == fapi2::ENUM_ATTR_MSS_MRW_DRAM_2N_MODE_FORCE_TO_2N_MODE; fapi_try_exit: FAPI_ERR("failed accessing vpd_mr_mc_2n_mode_autoset or mrw_dram_2n_mode: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_UT_EC_NIMBUS_LESS_THAN_TWO_OH getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff we're on a Nimbus < EC 2.0 /// template< fapi2::TargetType T > inline bool chip_ec_nimbus_lt_2_0(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_UT_EC_NIMBUS_LESS_THAN_TWO_OH, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_UT_EC_NIMBUS_LESS_THAN_TWO_OH: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MCBIST_END_OF_RANK getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mcbist_end_of_rank(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MCBIST_END_OF_RANK, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MCBIST_END_OF_RANK: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_WR_VREF getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_wr_vref(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_WR_VREF, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_WR_VREF: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_DQS_POLARITY getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_dqs_polarity(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_DQS_POLARITY, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_DQS_POLARITY: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_VCCD_OVERRIDE getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_vccd_override(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_VCCD_OVERRIDE, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_VCCD_OVERRIDE: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_VREF_DAC getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_vref_dac(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_VREF_DAC, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_VREF_DAC: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_VREG_COARSE getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_vreg_coarse(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_VREG_COARSE, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_VREG_COARSE: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_WAT_DEBUG_ATTN getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_wat_debug_attn(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_WAT_DEBUG_ATTN, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_WAT_DEBUG_ATTN: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_TRAINING_BAD_BITS getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_training_bad_bits(const fapi2::Target<T>& i_target) { // TODO RTC:165862 - need to get the minor EC number and check that in here. const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_TRAINING_BAD_BITS, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_TRAINING_BAD_BITS: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } } // close mss namespace #endif <commit_msg>Add minor minor version feature support to getecid<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mss_attribute_accessors_manual.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file mss_attribute_accessors_manual.H /// @brief Manually created attribute accessors. /// Some attributes aren't in files we want to incorporate in to our automated /// accessor generator. EC workarounds is one example - everytime someone creates /// a work-around they'd be burdened with updating this file. /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Steven Glancy <sglancy@usi.ibm.com> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: Memory #ifndef MSS_ATTR_ACCESS_MANUAL_H_ #define MSS_ATTR_ACCESS_MANUAL_H_ #include <fapi2.H> #include <lib/utils/find.H> namespace mss { /// /// @brief 2N mode helper /// When figuring out 2N mode we need to access two attributes. This helper /// gives us a place to put that common code /// @tparam T the fapi2::TargetType of the input target /// @param[in] the target from which to get the 2N mode autoset attribute /// @return true iff 2N mode is 'on' /// template< fapi2::TargetType T > inline bool two_n_mode_helper(const fapi2::Target<T>& i_target) { uint8_t l_2n_autoset = 0; uint8_t l_2n_mrw_mode = 0; // There are no VPD enums defined for 2N autoset <shrug>. constexpr uint8_t ATTR_MSS_VPD_MR_MC_2N_MODE_AUTOSET_2N_MODE = 0x02; const auto l_mcs = mss::find_target<fapi2::TARGET_TYPE_MCS>(i_target); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_MSS_VPD_MR_MC_2N_MODE_AUTOSET, l_mcs, l_2n_autoset) ); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_MSS_MRW_DRAM_2N_MODE, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_2n_mrw_mode) ); // If the MRW states 'auto' we use what's in VPD, otherwise we use what's in the MRW. return (l_2n_mrw_mode == fapi2::ENUM_ATTR_MSS_MRW_DRAM_2N_MODE_AUTO) ? l_2n_autoset == ATTR_MSS_VPD_MR_MC_2N_MODE_AUTOSET_2N_MODE : l_2n_mrw_mode == fapi2::ENUM_ATTR_MSS_MRW_DRAM_2N_MODE_FORCE_TO_2N_MODE; fapi_try_exit: FAPI_ERR("failed accessing vpd_mr_mc_2n_mode_autoset or mrw_dram_2n_mode: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_UT_EC_NIMBUS_LESS_THAN_TWO_OH getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff we're on a Nimbus < EC 2.0 /// template< fapi2::TargetType T > inline bool chip_ec_nimbus_lt_2_0(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_UT_EC_NIMBUS_LESS_THAN_TWO_OH, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_UT_EC_NIMBUS_LESS_THAN_TWO_OH: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MCBIST_END_OF_RANK getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mcbist_end_of_rank(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MCBIST_END_OF_RANK, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MCBIST_END_OF_RANK: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_WR_VREF getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_wr_vref(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; uint8_t l_do_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_WR_VREF, l_chip, l_value) ); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_DO_MSS_WR_VREF, l_chip, l_do_value) ); return (l_value != 0) && (l_do_value == fapi2::ENUM_ATTR_DO_MSS_WR_VREF_YES); fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_WR_VREF or ATTR_DO_MSS_WR_VREF: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_DQS_POLARITY getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_dqs_polarity(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_DQS_POLARITY, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_DQS_POLARITY: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_VCCD_OVERRIDE getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_vccd_override(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; uint8_t l_do_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_VCCD_OVERRIDE, l_chip, l_value) ); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_DO_MSS_VCCD_OVERRIDE, l_chip, l_do_value) ); return (l_value != 0) && (l_do_value == fapi2::ENUM_ATTR_DO_MSS_VCCD_OVERRIDE_YES); fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_VCCD_OVERRIDE or ATTR_DO_MSS_VCCD_OVERRIDE: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_VREF_DAC getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_vref_dac(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; uint8_t l_do_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_VREF_DAC, l_chip, l_value) ); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_DO_MSS_VREF_DAC, l_chip, l_do_value) ); return (l_value != 0) && (l_do_value == fapi2::ENUM_ATTR_DO_MSS_VREF_DAC_YES); fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_VREF_DAC or ATTR_DO_MSS_VREF_DAC: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_VREG_COARSE getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_vreg_coarse(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; uint8_t l_do_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_VREG_COARSE, l_chip, l_value) ); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_DO_MSS_VREG_COARSE, l_chip, l_do_value) ); return (l_value != 0) && (l_do_value == fapi2::ENUM_ATTR_DO_MSS_VREG_COARSE_YES); fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_VREG_COARSE or ATTR_DO_MSS_VREG_COARSE: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_WAT_DEBUG_ATTN getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_wat_debug_attn(const fapi2::Target<T>& i_target) { const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_WAT_DEBUG_ATTN, l_chip, l_value) ); return l_value != 0; fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_WAT_DEBUG_ATTN: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } /// /// @brief ATTR_CHIP_EC_FEATURE_MSS_TRAINING_BAD_BITS getter /// @tparam T the fapi2 target type of the target /// @param[in] const ref to the target /// @return bool true iff feature is enabled /// template< fapi2::TargetType T > inline bool chip_ec_feature_mss_training_bad_bits(const fapi2::Target<T>& i_target) { // TODO RTC:165862 - need to get the minor EC number and check that in here. const auto l_chip = mss::find_target<fapi2::TARGET_TYPE_PROC_CHIP>(i_target); uint8_t l_value = 0; uint8_t l_do_value = 0; FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_MSS_TRAINING_BAD_BITS, l_chip, l_value) ); FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_DO_MSS_TRAINING_BAD_BITS, l_chip, l_do_value) ); return (l_value != 0) && (l_do_value == fapi2::ENUM_ATTR_DO_MSS_TRAINING_BAD_BITS_YES); fapi_try_exit: FAPI_ERR("failed accessing ATTR_CHIP_EC_FEATURE_MSS_TRAINING_BAD_BITS" " or ATTR_DO_MSS_TRAINING_BAD_BITS: 0x%lx (target: %s)", uint64_t(fapi2::current_err), mss::c_str(i_target)); fapi2::Assert(false); return false; } } // close mss namespace #endif <|endoftext|>
<commit_before>/** * @file Nanoshield_Termopar.cpp * This is the library to access the Termopar Nanoshield version 2 * * Copyright (c) 2015 Circuitar * This software is released under the MIT license. See the attached LICENSE file for details. */ #include "Nanoshield_Termopar.h" // MAX31856 registers #define MAX31856_REG_CR0 0x00 #define MAX31856_REG_CR1 0x01 #define MAX31856_REG_MASK 0x02 #define MAX31856_REG_CJHF 0x03 #define MAX31856_REG_CJLF 0x04 #define MAX31856_REG_LTHFTH 0x05 #define MAX31856_REG_LTHFTL 0x06 #define MAX31856_REG_LTLFTH 0x07 #define MAX31856_REG_LTLFTL 0x08 #define MAX31856_REG_CJTO 0x09 #define MAX31856_REG_CJTH 0x0A #define MAX31856_REG_CJTL 0x0B #define MAX31856_REG_LTCBH 0x0C #define MAX31856_REG_LTCBM 0x0D #define MAX31856_REG_LTCBL 0x0E #define MAX31856_REG_SR 0x0F // MAX31856 register read/write masks #define MAX31856_REG_READ 0x00 #define MAX31856_REG_WRITE 0x80 SPISettings Nanoshield_Termopar::spiSettings = SPISettings(1000000, MSBFIRST, SPI_MODE1); Nanoshield_Termopar::Nanoshield_Termopar(uint8_t cs, TcType type, TcAveraging avg) { this->cs = cs; this->type = type; this->avg = avg; this->internal = 0; this->external = 0; this->fault = 0; } void Nanoshield_Termopar::begin() { pinMode(cs, OUTPUT); digitalWrite(cs, HIGH); SPI.begin(); // Initialize MAX31856 SPI.beginTransaction(spiSettings); digitalWrite(cs, LOW); SPI.transfer(MAX31856_REG_CR0 | MAX31856_REG_WRITE); SPI.transfer(0x90); // Setup CR0 register: // Automatic conversion mode // Enable fault detection mode 1 (OCFAULT) // Cold juntion sensor enabled // Fault detection in comparator mode // Noise rejection = 60Hz SPI.transfer(((uint8_t)avg << 4) | ((uint8_t)type & 0x0F)); // Setup CR1 register: // Setup selected averaging mode // Setup selected thermocouple type SPI.transfer(0x03); // Setup MASK register: // Enable overvoltage/undervoltage detection // Enable open circuit detection digitalWrite(cs, HIGH); SPI.endTransaction(); } void Nanoshield_Termopar::read() { uint16_t cj = 0; uint32_t ltc = 0; SPI.beginTransaction(spiSettings); digitalWrite(cs, LOW); SPI.transfer(MAX31856_REG_CJTH | MAX31856_REG_READ); cj |= (uint16_t)SPI.transfer(0) << 8; cj |= SPI.transfer(0); ltc |= (uint32_t)SPI.transfer(0) << 16; ltc |= (uint32_t)SPI.transfer(0) << 8; ltc |= (uint32_t)SPI.transfer(0); fault = SPI.transfer(0); digitalWrite(cs, HIGH); SPI.endTransaction(); internal = (cj / 4) * 0.015625; external = ((int32_t)(ltc >= (1 << 23) ? ltc - (1 << 24) : ltc) / 32) * 0.0078125; } double Nanoshield_Termopar::getInternal() { return internal; } double Nanoshield_Termopar::getExternal() { return external; } bool Nanoshield_Termopar::isExternalOutOfRange() { return (fault & 0x40) != 0; } bool Nanoshield_Termopar::isInternalOutOfRange() { return (fault & 0x80) != 0; } bool Nanoshield_Termopar::isOverUnderVoltage() { return (fault & 0x02) != 0; } bool Nanoshield_Termopar::isOpen() { return (fault & 0x01) != 0; } bool Nanoshield_Termopar::hasError() { return (fault & 0xC3) != 0; } <commit_msg>Fix conversion for negative temperatures.<commit_after>/** * @file Nanoshield_Termopar.cpp * This is the library to access the Termopar Nanoshield version 2 * * Copyright (c) 2015 Circuitar * This software is released under the MIT license. See the attached LICENSE file for details. */ #include "Nanoshield_Termopar.h" // MAX31856 registers #define MAX31856_REG_CR0 0x00 #define MAX31856_REG_CR1 0x01 #define MAX31856_REG_MASK 0x02 #define MAX31856_REG_CJHF 0x03 #define MAX31856_REG_CJLF 0x04 #define MAX31856_REG_LTHFTH 0x05 #define MAX31856_REG_LTHFTL 0x06 #define MAX31856_REG_LTLFTH 0x07 #define MAX31856_REG_LTLFTL 0x08 #define MAX31856_REG_CJTO 0x09 #define MAX31856_REG_CJTH 0x0A #define MAX31856_REG_CJTL 0x0B #define MAX31856_REG_LTCBH 0x0C #define MAX31856_REG_LTCBM 0x0D #define MAX31856_REG_LTCBL 0x0E #define MAX31856_REG_SR 0x0F // MAX31856 register read/write masks #define MAX31856_REG_READ 0x00 #define MAX31856_REG_WRITE 0x80 SPISettings Nanoshield_Termopar::spiSettings = SPISettings(1000000, MSBFIRST, SPI_MODE1); Nanoshield_Termopar::Nanoshield_Termopar(uint8_t cs, TcType type, TcAveraging avg) { this->cs = cs; this->type = type; this->avg = avg; this->internal = 0; this->external = 0; this->fault = 0; } void Nanoshield_Termopar::begin() { pinMode(cs, OUTPUT); digitalWrite(cs, HIGH); SPI.begin(); // Initialize MAX31856 SPI.beginTransaction(spiSettings); digitalWrite(cs, LOW); SPI.transfer(MAX31856_REG_CR0 | MAX31856_REG_WRITE); SPI.transfer(0x90); // Setup CR0 register: // Automatic conversion mode // Enable fault detection mode 1 (OCFAULT) // Cold juntion sensor enabled // Fault detection in comparator mode // Noise rejection = 60Hz SPI.transfer(((uint8_t)avg << 4) | ((uint8_t)type & 0x0F)); // Setup CR1 register: // Setup selected averaging mode // Setup selected thermocouple type SPI.transfer(0x03); // Setup MASK register: // Enable overvoltage/undervoltage detection // Enable open circuit detection digitalWrite(cs, HIGH); SPI.endTransaction(); } void Nanoshield_Termopar::read() { uint16_t cj = 0; uint32_t ltc = 0; SPI.beginTransaction(spiSettings); digitalWrite(cs, LOW); SPI.transfer(MAX31856_REG_CJTH | MAX31856_REG_READ); cj |= (uint16_t)SPI.transfer(0) << 8; cj |= SPI.transfer(0); ltc |= (uint32_t)SPI.transfer(0) << 16; ltc |= (uint32_t)SPI.transfer(0) << 8; ltc |= (uint32_t)SPI.transfer(0); fault = SPI.transfer(0); digitalWrite(cs, HIGH); SPI.endTransaction(); internal = (cj / 4) * 0.015625; external = ((int32_t)(ltc >= (1UL << 23) ? ltc - (1UL << 24) : ltc) / 32) * 0.0078125; } double Nanoshield_Termopar::getInternal() { return internal; } double Nanoshield_Termopar::getExternal() { return external; } bool Nanoshield_Termopar::isExternalOutOfRange() { return (fault & 0x40) != 0; } bool Nanoshield_Termopar::isInternalOutOfRange() { return (fault & 0x80) != 0; } bool Nanoshield_Termopar::isOverUnderVoltage() { return (fault & 0x02) != 0; } bool Nanoshield_Termopar::isOpen() { return (fault & 0x01) != 0; } bool Nanoshield_Termopar::hasError() { return (fault & 0xC3) != 0; } <|endoftext|>
<commit_before>#include "Player.hpp" #include <iostream> #include "Tile.hpp" bool Player::intersects(const GameObject& cmp) { const sf::FloatRect &tmpRect = mySprite->getGlobalBounds(); sf::Vector2f tmpPos(tmpRect.left, tmpRect.top); return intersects(tmpPos, cmp); } bool Player::intersects(const sf::Vector2f &testPos, const GameObject& cmp) { if (dynamic_cast<const Tile*>(&cmp) && dynamic_cast<const Tile*>(&cmp)->walkable) return false; // TODO: aus intersect in allgemeineren Teil verschieben sf::FloatRect tmpRect(testPos.x + 3 * mySprite->getScale().x, testPos.y + (32 - 10) * mySprite->getScale().y, 10* mySprite->getScale().x, 10* mySprite->getScale().y); /* tmpRect.top += 32 - 10; tmpRect.left += 3; tmpRect.width = 10; tmpRect.height = 10;*/ if (cmp.mySprite == 0) return false; return cmp.mySprite->getGlobalBounds().intersects(tmpRect); } void Player::update (sf::Time deltaTime) { float dT = float(deltaTime.asMilliseconds()); float currTime = globalClock.getElapsedTime().asSeconds()*40; // get input from globals and process: sf::Vector2f tmpPos = getPosition(); int width = getWidth(); int height = getHeight(); int dir = -1; if (input[0]) { tmpPos.x -= 0.08 * dT* (.75+.25*(sin(currTime)+1)); dir = 3; } if (input[1]) { tmpPos.x += 0.08 * dT*(.75+.25*(sin(currTime)+1)); dir = 2; } if (input[2]) { tmpPos.y -= 0.08 * dT*(.75+.25*(sin(currTime)+1)); dir = 1; } if (input[3]) { tmpPos.y += 0.08 * dT*(.75+.25*(sin(currTime)+1)); dir = 0; } if (tmpPos.x > screenWidth) tmpPos.x -= screenWidth; if (tmpPos.x + width < 0) tmpPos.x += screenWidth; if (tmpPos.y > screenHeight) tmpPos.y -= screenHeight; if (tmpPos.y + height < 0) tmpPos.y += screenHeight; if (dir > -1) { animationStep += 0.08*dT / slowFactor; doggieStep += 0.08*dT / slowFactor; direction = dir; } else { animationStep = 0.; doggieStep = 0.; } if (animationStep >= 4.) animationStep -= 3; if (doggieStep >= 6.) doggieStep -= 5; bool collides = false; //check for collisions: for (std::vector<GameObject*>::const_iterator tileIt = sceneManager.getCurrentScene().gameBoard.begin(); tileIt != sceneManager.getCurrentScene().gameBoard.end(); tileIt++) { sf::Vector2f distVec = ((*tileIt)->getPosition() - getPosition()); // ... //std::cout<<(*tileIt)->mySprite->getGlobalBounds().left<<" , "<<(*tileIt)->mySprite->getGlobalBounds().top<<" , "<<mySprite->getGlobalBounds().left<<" , "<<mySprite->getGlobalBounds().left<<" , "<<std::endl; if (distVec.x * distVec.x + distVec.y * distVec.y < 60 * 60 && intersects(tmpPos, **tileIt)) // first condition does quick distance check, 60 is arbitrary safe distance { collides = true; } } if (!collides) { // doggie follows the hero if (dir > -1) { positionQueue.push(tmpPos); directionQueue.push(direction); } setPosition(tmpPos.x, tmpPos.y); if (!positionQueue.empty()){ doggieSprite->setPosition(positionQueue.front().x, positionQueue.front().y + 18*mySprite->getScale().y); } } if (mySprite != 0 && doggieSprite != 0) { if (!directionQueue.empty()){ doggieSprite->setTextureRect(sf::IntRect((directionQueue.front() + 4) * 16, DoggieAnimState[int(doggieStep)] * 16, 16, 16)); } else { doggieSprite->setTextureRect(sf::IntRect(4*16,0, 16, 16)); } window.draw(*doggieSprite); if (!positionQueue.empty() && !directionQueue.empty() && positionQueue.size() > 16) // delay of doggie movement { directionQueue.pop(); positionQueue.pop(); } mySprite->setTextureRect(sf::IntRect(direction * 16, PlayerAnimState[int(animationStep)] * 32, 16, 32)); window.draw(*mySprite); } } <commit_msg>Doggie-Relativgeschwindigkeit gefixt<commit_after>#include "Player.hpp" #include <iostream> #include "Tile.hpp" bool Player::intersects(const GameObject& cmp) { const sf::FloatRect &tmpRect = mySprite->getGlobalBounds(); sf::Vector2f tmpPos(tmpRect.left, tmpRect.top); return intersects(tmpPos, cmp); } bool Player::intersects(const sf::Vector2f &testPos, const GameObject& cmp) { if (dynamic_cast<const Tile*>(&cmp) && dynamic_cast<const Tile*>(&cmp)->walkable) return false; // TODO: aus intersect in allgemeineren Teil verschieben sf::FloatRect tmpRect(testPos.x + 3 * mySprite->getScale().x, testPos.y + (32 - 10) * mySprite->getScale().y, 10* mySprite->getScale().x, 10* mySprite->getScale().y); /* tmpRect.top += 32 - 10; tmpRect.left += 3; tmpRect.width = 10; tmpRect.height = 10;*/ if (cmp.mySprite == 0) return false; return cmp.mySprite->getGlobalBounds().intersects(tmpRect); } void Player::update (sf::Time deltaTime) { float dT = float(deltaTime.asMilliseconds()); float currTime = globalClock.getElapsedTime().asSeconds(); // get input from globals and process: sf::Vector2f tmpPos = getPosition(); int width = getWidth(); int height = getHeight(); int dir = -1; if (input[0]) { tmpPos.x -= 0.12 * dT* (.75+.25*(sin(currTime*40)+1)); dir = 3; } if (input[1]) { tmpPos.x += 0.12 * dT*(.75+.25*(sin(currTime*40)+1)); dir = 2; } if (input[2]) { tmpPos.y -= 0.12 * dT*(.75+.25*(sin(currTime*40)+1)); dir = 1; } if (input[3]) { tmpPos.y += 0.12 * dT*(.75+.25*(sin(currTime*40)+1)); dir = 0; } if (tmpPos.x > screenWidth) tmpPos.x -= screenWidth; if (tmpPos.x + width < 0) tmpPos.x += screenWidth; if (tmpPos.y > screenHeight) tmpPos.y -= screenHeight; if (tmpPos.y + height < 0) tmpPos.y += screenHeight; if (dir > -1) { animationStep += 0.08*dT / slowFactor; doggieStep += 0.08*dT / slowFactor; direction = dir; } else { animationStep = 0.; doggieStep = 0.; } if (animationStep >= 4.) animationStep -= 3; if (doggieStep >= 6.) doggieStep -= 5; bool collides = false; //check for collisions: for (std::vector<GameObject*>::const_iterator tileIt = sceneManager.getCurrentScene().gameBoard.begin(); tileIt != sceneManager.getCurrentScene().gameBoard.end(); tileIt++) { sf::Vector2f distVec = ((*tileIt)->getPosition() - getPosition()); // ... //std::cout<<(*tileIt)->mySprite->getGlobalBounds().left<<" , "<<(*tileIt)->mySprite->getGlobalBounds().top<<" , "<<mySprite->getGlobalBounds().left<<" , "<<mySprite->getGlobalBounds().left<<" , "<<std::endl; if (distVec.x * distVec.x + distVec.y * distVec.y < 60 * 60 && intersects(tmpPos, **tileIt)) // first condition does quick distance check, 60 is arbitrary safe distance { collides = true; } } if (!collides) { // doggie follows the hero if (dir > -1) { positionQueue.push(tmpPos); directionQueue.push(direction); } setPosition(tmpPos.x, tmpPos.y); if (!positionQueue.empty()){ doggieSprite->setPosition(positionQueue.front().x, positionQueue.front().y + 18*mySprite->getScale().y); } } //std::cout<<"1/dT "<<.256/dT<<std::endl; if (mySprite != 0 && doggieSprite != 0) { if (!directionQueue.empty()){ doggieSprite->setTextureRect(sf::IntRect((directionQueue.front() + 4) * 16, DoggieAnimState[int(doggieStep)] * 16, 16, 16)); } else { doggieSprite->setTextureRect(sf::IntRect(4*16,0, 16, 16)); } window.draw(*doggieSprite); if (!positionQueue.empty() && !directionQueue.empty() && positionQueue.size() > 256./dT) // delay of doggie movement { directionQueue.pop(); positionQueue.pop(); } mySprite->setTextureRect(sf::IntRect(direction * 16, PlayerAnimState[int(animationStep)] * 32, 16, 32)); window.draw(*mySprite); } } <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 "GraphTrack.h" #include <GteVector.h> #include <absl/strings/str_format.h> #include <algorithm> #include <cstdint> #include "Geometry.h" #include "GlCanvas.h" #include "TextRenderer.h" #include "TimeGraph.h" #include "TimeGraphLayout.h" GraphTrack::GraphTrack(CaptureViewElement* parent, TimeGraph* time_graph, TimeGraphLayout* layout, std::string name, const CaptureData* capture_data) : Track(parent, time_graph, layout, capture_data) { SetName(name); SetLabel(name); } void GraphTrack::UpdatePrimitives(Batcher* batcher, uint64_t min_tick, uint64_t max_tick, PickingMode picking_mode, float z_offset) { GlCanvas* canvas = time_graph_->GetCanvas(); const orbit_gl::Viewport& viewport = canvas->GetViewport(); float track_width = viewport.GetVisibleWorldWidth(); SetSize(track_width, GetHeight()); pos_[0] = viewport.GetWorldTopLeft()[0]; Color color = GetBackgroundColor(); const Color kLineColor(0, 128, 255, 128); const Color kDotColor(0, 128, 255, 255); float track_z = GlCanvas::kZValueTrack + z_offset; float graph_z = GlCanvas::kZValueEventBar + z_offset; float dot_z = GlCanvas::kZValueBox + z_offset; Box box(pos_, Vec2(size_[0], -size_[1]), track_z); batcher->AddBox(box, color, shared_from_this()); const bool picking = picking_mode != PickingMode::kNone; if (!picking) { double time_range = static_cast<double>(max_tick - min_tick); if (values_.size() < 2 || time_range == 0) return; auto it = values_.upper_bound(min_tick); if (it == values_.end()) return; if (it != values_.begin()) --it; uint64_t previous_time = it->first; double last_normalized_value = (it->second - min_) * inv_value_range_; constexpr float kDotRadius = 2.f; float base_y = pos_[1] - size_[1]; float y1 = 0; DrawSquareDot(batcher, Vec2(time_graph_->GetWorldFromTick(previous_time), base_y + static_cast<float>(last_normalized_value) * size_[1]), kDotRadius, dot_z, kDotColor); for (++it; it != values_.end(); ++it) { if (previous_time > max_tick) break; uint64_t time = it->first; double normalized_value = (it->second - min_) * inv_value_range_; float x0 = time_graph_->GetWorldFromTick(previous_time); float x1 = time_graph_->GetWorldFromTick(time); float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1]; y1 = base_y + static_cast<float>(normalized_value) * size_[1]; batcher->AddLine(Vec2(x0, y0), Vec2(x1, y0), graph_z, kLineColor); batcher->AddLine(Vec2(x1, y0), Vec2(x1, y1), graph_z, kLineColor); DrawSquareDot(batcher, Vec2(x1, y1), kDotRadius, dot_z, kDotColor); previous_time = time; last_normalized_value = normalized_value; } if (!values_.empty()) { float x0 = time_graph_->GetWorldFromTick(previous_time); float x1 = time_graph_->GetWorldFromTick(max_tick); batcher->AddLine(Vec2(x0, y1), Vec2(x1, y1), graph_z, kLineColor); } } } void GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode, float z_offset) { Track::Draw(canvas, picking_mode, z_offset); if (values_.empty() || picking_mode != PickingMode::kNone) { return; } const Color kBlack(0, 0, 0, 255); const Color kWhite(255, 255, 255, 255); float text_z = GlCanvas::kZValueTrackText + z_offset; float label_z = GlCanvas::kZValueTrackLabel + z_offset; // Add warning threshold text box and line. Batcher* ui_batcher = canvas->GetBatcher(); uint32_t font_size = layout_->CalculateZoomedFontSize(); if (warning_threshold_.has_value()) { const Color kThresholdColor(244, 67, 54, 255); double normalized_value = (warning_threshold_.value().second - min_) * inv_value_range_; float x = pos_[0]; float y = pos_[1] - size_[1] + static_cast<float>(normalized_value) * size_[1]; Vec2 from(x, y); Vec2 to(x + size_[0], y); std::string text = warning_threshold_.value().first; float string_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(string_width, layout_->GetTextBoxHeight()); Vec2 text_box_position(pos_[0] + layout_->GetRightMargin(), y - layout_->GetTextBoxHeight() / 2.f); canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), text_z, kThresholdColor, font_size, text_box_size[0]); ui_batcher->AddLine(from, from + Vec2(layout_->GetRightMargin() / 2.f, 0), text_z, kThresholdColor); ui_batcher->AddLine(Vec2(text_box_position[0] + text_box_size[0], y), to, text_z, kThresholdColor); } // Add value upper bound text box (e.g., the "Memory Total" text box for the memory tracks). if (value_upper_bound_.has_value()) { std::string text = value_upper_bound_.value().first; float string_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(string_width, layout_->GetTextBoxHeight()); Vec2 text_box_position(pos_[0] + size_[0] - text_box_size[0] - layout_->GetRightMargin() - layout_->GetSliderWidth(), pos_[1] - layout_->GetTextBoxHeight() / 2.f); canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), text_z, kWhite, font_size, text_box_size[0]); } // Add value lower bound text box. if (value_lower_bound_.has_value()) { std::string text = value_lower_bound_.value().first; float string_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(string_width, layout_->GetTextBoxHeight()); Vec2 text_box_position(pos_[0] + size_[0] - text_box_size[0] - layout_->GetRightMargin() - layout_->GetSliderWidth(), pos_[1] - size_[1]); canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), text_z, kWhite, font_size, text_box_size[0]); } // Draw label uint64_t current_mouse_time_ns = time_graph_->GetCurrentMouseTimeNs(); auto previous_point = GetPreviousValueAndTime(current_mouse_time_ns); double value = previous_point.has_value() ? previous_point.value().second : values_.begin()->second; uint64_t first_time = values_.begin()->first; uint64_t label_time = std::max(current_mouse_time_ns, first_time); float point_x = time_graph_->GetWorldFromTick(label_time); double normalized_value = (value - min_) * inv_value_range_; float point_y = pos_[1] - size_[1] * (1.f - static_cast<float>(normalized_value)); std::string text = value_decimal_digits_.has_value() ? absl::StrFormat("%.*f", value_decimal_digits_.value(), value) : std::to_string(value); absl::StrAppend(&text, label_unit_); DrawLabel(canvas, Vec2(point_x, point_y), text, kBlack, kWhite, label_z); } void GraphTrack::DrawSquareDot(Batcher* batcher, Vec2 center, float radius, float z, const Color& color) { Vec2 position(center[0] - radius, center[1] - radius); Vec2 size(2 * radius, 2 * radius); batcher->AddBox(Box(position, size, z), color); } void GraphTrack::DrawLabel(GlCanvas* canvas, Vec2 target_pos, const std::string& text, const Color& text_color, const Color& font_color, float z) { uint32_t font_size = layout_->CalculateZoomedFontSize(); float text_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(text_width, layout_->GetTextBoxHeight()); float arrow_width = text_box_size[1] / 2.f; bool arrow_is_left_directed = target_pos[0] < canvas->GetViewport().GetWorldTopLeft()[0] + text_box_size[0] + arrow_width; Vec2 text_box_position( target_pos[0] + (arrow_is_left_directed ? arrow_width : -arrow_width - text_box_size[0]), target_pos[1] - text_box_size[1] / 2.f); Box arrow_text_box(text_box_position, text_box_size, z); Vec3 arrow_extra_point(target_pos[0], target_pos[1], z); Batcher* ui_batcher = canvas->GetBatcher(); ui_batcher->AddBox(arrow_text_box, font_color); if (arrow_is_left_directed) { ui_batcher->AddTriangle( Triangle(arrow_text_box.vertices[0], arrow_text_box.vertices[1], arrow_extra_point), font_color); } else { ui_batcher->AddTriangle( Triangle(arrow_text_box.vertices[2], arrow_text_box.vertices[3], arrow_extra_point), font_color); } canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), z, text_color, font_size, text_box_size[0]); } void GraphTrack::AddValue(double value, uint64_t time) { values_[time] = value; max_ = std::max(max_, value); min_ = std::min(min_, value); value_range_ = max_ - min_; if (value_range_ > 0) inv_value_range_ = 1.0 / value_range_; } std::optional<std::pair<uint64_t, double> > GraphTrack::GetPreviousValueAndTime( uint64_t time) const { auto iterator_lower = values_.upper_bound(time); if (iterator_lower == values_.begin()) { return {}; } --iterator_lower; return *iterator_lower; } float GraphTrack::GetHeight() const { float height = layout_->GetTextBoxHeight() + layout_->GetSpaceBetweenTracksAndThread() + layout_->GetEventTrackHeight() + layout_->GetTrackBottomMargin(); return height; } void GraphTrack::SetWarningThresholdWhenEmpty(const std::string& pretty_label, double raw_value) { if (warning_threshold_.has_value()) return; warning_threshold_ = std::make_pair(pretty_label, raw_value); UpdateMinAndMax(raw_value); } void GraphTrack::SetValueUpperBoundWhenEmpty(const std::string& pretty_label, double raw_value) { if (value_upper_bound_.has_value()) return; value_upper_bound_ = std::make_pair(pretty_label, raw_value); UpdateMinAndMax(raw_value); } void GraphTrack::SetValueLowerBoundWhenEmpty(const std::string& pretty_label, double raw_value) { if (value_lower_bound_.has_value()) return; value_lower_bound_ = std::make_pair(pretty_label, raw_value); UpdateMinAndMax(raw_value); } void GraphTrack::SetLabelUnitWhenEmpty(const std::string& label_unit) { if (!label_unit_.empty()) return; label_unit_ = label_unit; } void GraphTrack::SetValueDecimalDigitsWhenEmpty(uint8_t value_decimal_digits) { if (value_decimal_digits_.has_value()) return; value_decimal_digits_ = value_decimal_digits; } void GraphTrack::UpdateMinAndMax(double value) { max_ = std::max(max_, value); min_ = std::min(min_, value); } void GraphTrack::OnTimer(const orbit_client_protos::TimerInfo& timer_info) { constexpr uint32_t kDepth = 0; std::shared_ptr<TimerChain> timer_chain = timers_[kDepth]; if (timer_chain == nullptr) { timer_chain = std::make_shared<TimerChain>(); timers_[kDepth] = timer_chain; } TextBox text_box(Vec2(0, 0), Vec2(0, 0), ""); text_box.SetTimerInfo(timer_info); timer_chain->push_back(text_box); } std::vector<std::shared_ptr<TimerChain>> GraphTrack::GetAllChains() const { std::vector<std::shared_ptr<TimerChain>> chains; for (const auto& pair : timers_) { chains.push_back(pair.second); } return chains; }<commit_msg>Clang-format<commit_after>// Copyright (c) 2020 The Orbit 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 "GraphTrack.h" #include <GteVector.h> #include <absl/strings/str_format.h> #include <algorithm> #include <cstdint> #include "Geometry.h" #include "GlCanvas.h" #include "TextRenderer.h" #include "TimeGraph.h" #include "TimeGraphLayout.h" GraphTrack::GraphTrack(CaptureViewElement* parent, TimeGraph* time_graph, TimeGraphLayout* layout, std::string name, const CaptureData* capture_data) : Track(parent, time_graph, layout, capture_data) { SetName(name); SetLabel(name); } void GraphTrack::UpdatePrimitives(Batcher* batcher, uint64_t min_tick, uint64_t max_tick, PickingMode picking_mode, float z_offset) { GlCanvas* canvas = time_graph_->GetCanvas(); const orbit_gl::Viewport& viewport = canvas->GetViewport(); float track_width = viewport.GetVisibleWorldWidth(); SetSize(track_width, GetHeight()); pos_[0] = viewport.GetWorldTopLeft()[0]; Color color = GetBackgroundColor(); const Color kLineColor(0, 128, 255, 128); const Color kDotColor(0, 128, 255, 255); float track_z = GlCanvas::kZValueTrack + z_offset; float graph_z = GlCanvas::kZValueEventBar + z_offset; float dot_z = GlCanvas::kZValueBox + z_offset; Box box(pos_, Vec2(size_[0], -size_[1]), track_z); batcher->AddBox(box, color, shared_from_this()); const bool picking = picking_mode != PickingMode::kNone; if (!picking) { double time_range = static_cast<double>(max_tick - min_tick); if (values_.size() < 2 || time_range == 0) return; auto it = values_.upper_bound(min_tick); if (it == values_.end()) return; if (it != values_.begin()) --it; uint64_t previous_time = it->first; double last_normalized_value = (it->second - min_) * inv_value_range_; constexpr float kDotRadius = 2.f; float base_y = pos_[1] - size_[1]; float y1 = 0; DrawSquareDot(batcher, Vec2(time_graph_->GetWorldFromTick(previous_time), base_y + static_cast<float>(last_normalized_value) * size_[1]), kDotRadius, dot_z, kDotColor); for (++it; it != values_.end(); ++it) { if (previous_time > max_tick) break; uint64_t time = it->first; double normalized_value = (it->second - min_) * inv_value_range_; float x0 = time_graph_->GetWorldFromTick(previous_time); float x1 = time_graph_->GetWorldFromTick(time); float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1]; y1 = base_y + static_cast<float>(normalized_value) * size_[1]; batcher->AddLine(Vec2(x0, y0), Vec2(x1, y0), graph_z, kLineColor); batcher->AddLine(Vec2(x1, y0), Vec2(x1, y1), graph_z, kLineColor); DrawSquareDot(batcher, Vec2(x1, y1), kDotRadius, dot_z, kDotColor); previous_time = time; last_normalized_value = normalized_value; } if (!values_.empty()) { float x0 = time_graph_->GetWorldFromTick(previous_time); float x1 = time_graph_->GetWorldFromTick(max_tick); batcher->AddLine(Vec2(x0, y1), Vec2(x1, y1), graph_z, kLineColor); } } } void GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode, float z_offset) { Track::Draw(canvas, picking_mode, z_offset); if (values_.empty() || picking_mode != PickingMode::kNone) { return; } const Color kBlack(0, 0, 0, 255); const Color kWhite(255, 255, 255, 255); float text_z = GlCanvas::kZValueTrackText + z_offset; float label_z = GlCanvas::kZValueTrackLabel + z_offset; // Add warning threshold text box and line. Batcher* ui_batcher = canvas->GetBatcher(); uint32_t font_size = layout_->CalculateZoomedFontSize(); if (warning_threshold_.has_value()) { const Color kThresholdColor(244, 67, 54, 255); double normalized_value = (warning_threshold_.value().second - min_) * inv_value_range_; float x = pos_[0]; float y = pos_[1] - size_[1] + static_cast<float>(normalized_value) * size_[1]; Vec2 from(x, y); Vec2 to(x + size_[0], y); std::string text = warning_threshold_.value().first; float string_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(string_width, layout_->GetTextBoxHeight()); Vec2 text_box_position(pos_[0] + layout_->GetRightMargin(), y - layout_->GetTextBoxHeight() / 2.f); canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), text_z, kThresholdColor, font_size, text_box_size[0]); ui_batcher->AddLine(from, from + Vec2(layout_->GetRightMargin() / 2.f, 0), text_z, kThresholdColor); ui_batcher->AddLine(Vec2(text_box_position[0] + text_box_size[0], y), to, text_z, kThresholdColor); } // Add value upper bound text box (e.g., the "Memory Total" text box for the memory tracks). if (value_upper_bound_.has_value()) { std::string text = value_upper_bound_.value().first; float string_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(string_width, layout_->GetTextBoxHeight()); Vec2 text_box_position(pos_[0] + size_[0] - text_box_size[0] - layout_->GetRightMargin() - layout_->GetSliderWidth(), pos_[1] - layout_->GetTextBoxHeight() / 2.f); canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), text_z, kWhite, font_size, text_box_size[0]); } // Add value lower bound text box. if (value_lower_bound_.has_value()) { std::string text = value_lower_bound_.value().first; float string_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(string_width, layout_->GetTextBoxHeight()); Vec2 text_box_position(pos_[0] + size_[0] - text_box_size[0] - layout_->GetRightMargin() - layout_->GetSliderWidth(), pos_[1] - size_[1]); canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), text_z, kWhite, font_size, text_box_size[0]); } // Draw label uint64_t current_mouse_time_ns = time_graph_->GetCurrentMouseTimeNs(); auto previous_point = GetPreviousValueAndTime(current_mouse_time_ns); double value = previous_point.has_value() ? previous_point.value().second : values_.begin()->second; uint64_t first_time = values_.begin()->first; uint64_t label_time = std::max(current_mouse_time_ns, first_time); float point_x = time_graph_->GetWorldFromTick(label_time); double normalized_value = (value - min_) * inv_value_range_; float point_y = pos_[1] - size_[1] * (1.f - static_cast<float>(normalized_value)); std::string text = value_decimal_digits_.has_value() ? absl::StrFormat("%.*f", value_decimal_digits_.value(), value) : std::to_string(value); absl::StrAppend(&text, label_unit_); DrawLabel(canvas, Vec2(point_x, point_y), text, kBlack, kWhite, label_z); } void GraphTrack::DrawSquareDot(Batcher* batcher, Vec2 center, float radius, float z, const Color& color) { Vec2 position(center[0] - radius, center[1] - radius); Vec2 size(2 * radius, 2 * radius); batcher->AddBox(Box(position, size, z), color); } void GraphTrack::DrawLabel(GlCanvas* canvas, Vec2 target_pos, const std::string& text, const Color& text_color, const Color& font_color, float z) { uint32_t font_size = layout_->CalculateZoomedFontSize(); float text_width = canvas->GetTextRenderer().GetStringWidth(text.c_str(), font_size); Vec2 text_box_size(text_width, layout_->GetTextBoxHeight()); float arrow_width = text_box_size[1] / 2.f; bool arrow_is_left_directed = target_pos[0] < canvas->GetViewport().GetWorldTopLeft()[0] + text_box_size[0] + arrow_width; Vec2 text_box_position( target_pos[0] + (arrow_is_left_directed ? arrow_width : -arrow_width - text_box_size[0]), target_pos[1] - text_box_size[1] / 2.f); Box arrow_text_box(text_box_position, text_box_size, z); Vec3 arrow_extra_point(target_pos[0], target_pos[1], z); Batcher* ui_batcher = canvas->GetBatcher(); ui_batcher->AddBox(arrow_text_box, font_color); if (arrow_is_left_directed) { ui_batcher->AddTriangle( Triangle(arrow_text_box.vertices[0], arrow_text_box.vertices[1], arrow_extra_point), font_color); } else { ui_batcher->AddTriangle( Triangle(arrow_text_box.vertices[2], arrow_text_box.vertices[3], arrow_extra_point), font_color); } canvas->GetTextRenderer().AddText(text.c_str(), text_box_position[0], text_box_position[1] + layout_->GetTextOffset(), z, text_color, font_size, text_box_size[0]); } void GraphTrack::AddValue(double value, uint64_t time) { values_[time] = value; max_ = std::max(max_, value); min_ = std::min(min_, value); value_range_ = max_ - min_; if (value_range_ > 0) inv_value_range_ = 1.0 / value_range_; } std::optional<std::pair<uint64_t, double>> GraphTrack::GetPreviousValueAndTime( uint64_t time) const { auto iterator_lower = values_.upper_bound(time); if (iterator_lower == values_.begin()) { return {}; } --iterator_lower; return *iterator_lower; } float GraphTrack::GetHeight() const { float height = layout_->GetTextBoxHeight() + layout_->GetSpaceBetweenTracksAndThread() + layout_->GetEventTrackHeight() + layout_->GetTrackBottomMargin(); return height; } void GraphTrack::SetWarningThresholdWhenEmpty(const std::string& pretty_label, double raw_value) { if (warning_threshold_.has_value()) return; warning_threshold_ = std::make_pair(pretty_label, raw_value); UpdateMinAndMax(raw_value); } void GraphTrack::SetValueUpperBoundWhenEmpty(const std::string& pretty_label, double raw_value) { if (value_upper_bound_.has_value()) return; value_upper_bound_ = std::make_pair(pretty_label, raw_value); UpdateMinAndMax(raw_value); } void GraphTrack::SetValueLowerBoundWhenEmpty(const std::string& pretty_label, double raw_value) { if (value_lower_bound_.has_value()) return; value_lower_bound_ = std::make_pair(pretty_label, raw_value); UpdateMinAndMax(raw_value); } void GraphTrack::SetLabelUnitWhenEmpty(const std::string& label_unit) { if (!label_unit_.empty()) return; label_unit_ = label_unit; } void GraphTrack::SetValueDecimalDigitsWhenEmpty(uint8_t value_decimal_digits) { if (value_decimal_digits_.has_value()) return; value_decimal_digits_ = value_decimal_digits; } void GraphTrack::UpdateMinAndMax(double value) { max_ = std::max(max_, value); min_ = std::min(min_, value); } void GraphTrack::OnTimer(const orbit_client_protos::TimerInfo& timer_info) { constexpr uint32_t kDepth = 0; std::shared_ptr<TimerChain> timer_chain = timers_[kDepth]; if (timer_chain == nullptr) { timer_chain = std::make_shared<TimerChain>(); timers_[kDepth] = timer_chain; } TextBox text_box(Vec2(0, 0), Vec2(0, 0), ""); text_box.SetTimerInfo(timer_info); timer_chain->push_back(text_box); } std::vector<std::shared_ptr<TimerChain>> GraphTrack::GetAllChains() const { std::vector<std::shared_ptr<TimerChain>> chains; for (const auto& pair : timers_) { chains.push_back(pair.second); } return chains; }<|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <chrono> #include <iostream> #include "cuda.h" #include "cuda_runtime.h" #include "cuda_runtime_api.h" #include "egblas.hpp" #define cuda_check(call) \ { \ auto status = call; \ if (status != cudaSuccess) { \ std::cerr << "CUDA error: " << cudaGetErrorString(status) << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ exit(1); \ } \ } namespace { using timer = std::chrono::high_resolution_clock; using microseconds = std::chrono::microseconds; float* prepare_cpu(size_t N, float s){ float* x_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { x_cpu[i] = s * (i + 1); } return x_cpu; } float* prepare_gpu(size_t N, float* x_cpu){ float* x_gpu; cuda_check(cudaMalloc((void**)&x_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(x_gpu, x_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); return x_gpu; } void release(float* x_cpu, float* x_gpu){ delete[] x_cpu; cuda_check(cudaFree(x_gpu)); } void bench_saxpy(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.0f); auto* y_cpu = prepare_cpu(N, 3.0f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); std::cout << "saxpy(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_saxpy(){ bench_saxpy(100); bench_saxpy(1000); bench_saxpy(10000); bench_saxpy(100000); bench_saxpy(1000000); bench_saxpy(10000000); bench_saxpy(100000000); std::cout << std::endl; } void bench_saxpby(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* y_cpu = prepare_cpu(N, 3.1f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); std::cout << "saxpby(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_saxpby(){ bench_saxpby(100); bench_saxpby(1000); bench_saxpby(10000); bench_saxpby(100000); bench_saxpby(1000000); bench_saxpby(10000000); bench_saxpby(100000000); std::cout << std::endl; } } // End of anonymous namespace int main(){ bench_saxpy(); bench_saxpby(); } <commit_msg>New benchmark for shuffle<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <chrono> #include <iostream> #include "cuda.h" #include "cuda_runtime.h" #include "cuda_runtime_api.h" #include "egblas.hpp" #define cuda_check(call) \ { \ auto status = call; \ if (status != cudaSuccess) { \ std::cerr << "CUDA error: " << cudaGetErrorString(status) << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ exit(1); \ } \ } namespace { using timer = std::chrono::high_resolution_clock; using microseconds = std::chrono::microseconds; float* prepare_cpu(size_t N, float s){ float* x_cpu = new float[N]; for (size_t i = 0; i < N; ++i) { x_cpu[i] = s * (i + 1); } return x_cpu; } float* prepare_gpu(size_t N, float* x_cpu){ float* x_gpu; cuda_check(cudaMalloc((void**)&x_gpu, N * sizeof(float))); cuda_check(cudaMemcpy(x_gpu, x_cpu, N * sizeof(float), cudaMemcpyHostToDevice)); return x_gpu; } void release(float* x_cpu, float* x_gpu){ delete[] x_cpu; cuda_check(cudaFree(x_gpu)); } void bench_saxpy(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.0f); auto* y_cpu = prepare_cpu(N, 3.0f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpy(N, 2.1f, x_gpu, 1, y_gpu, 1); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); std::cout << "saxpy(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_saxpy(){ bench_saxpy(100); bench_saxpy(1000); bench_saxpy(10000); bench_saxpy(100000); bench_saxpy(1000000); bench_saxpy(10000000); bench_saxpy(100000000); std::cout << std::endl; } void bench_saxpby(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* y_cpu = prepare_cpu(N, 3.1f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_saxpby(N, 2.54f, x_gpu, 1, 3.49f, y_gpu, 1); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); std::cout << "saxpby(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_saxpby(){ bench_saxpby(100); bench_saxpby(1000); bench_saxpby(10000); bench_saxpby(100000); bench_saxpby(1000000); bench_saxpby(10000000); bench_saxpby(100000000); std::cout << std::endl; } void bench_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* x_gpu = prepare_gpu(N, x_cpu); egblas_shuffle_seed(N, x_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_shuffle_seed(N, x_gpu, 4, 42); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); std::cout << "shuffle(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_shuffle(){ bench_shuffle(100); bench_shuffle(1000); bench_shuffle(10000); bench_shuffle(100000); std::cout << std::endl; } void bench_par_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N, 2.2f); auto* y_cpu = prepare_cpu(N, 3.1f); auto* x_gpu = prepare_gpu(N, x_cpu); auto* y_gpu = prepare_gpu(N, y_cpu); egblas_par_shuffle_seed(N, x_gpu, 4, y_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_par_shuffle_seed(N, x_gpu, 4, y_gpu, 4, 42); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); std::cout << "par_shuffle(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_par_shuffle(){ bench_par_shuffle(100); bench_par_shuffle(1000); bench_par_shuffle(10000); bench_par_shuffle(100000); std::cout << std::endl; } void bench_big_shuffle(size_t N, size_t repeat = 100) { auto* x_cpu = prepare_cpu(N * 1024, 2.2f); auto* x_gpu = prepare_gpu(N * 1024, x_cpu); egblas_shuffle_seed(N, x_gpu, 4 * 1024, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_shuffle_seed(N, x_gpu, 4 * 1024, 42); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); std::cout << "big_shuffle(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_big_shuffle(){ bench_big_shuffle(100); bench_big_shuffle(1000); bench_big_shuffle(10000); std::cout << std::endl; } void bench_par_big_shuffle(size_t N,size_t repeat = 100){ auto* x_cpu = prepare_cpu(N * 1024, 2.2f); auto* y_cpu = prepare_cpu(N * 1024, 3.1f); auto* x_gpu = prepare_gpu(N * 1024, x_cpu); auto* y_gpu = prepare_gpu(N * 1024, y_cpu); egblas_par_shuffle_seed(N, x_gpu, 4 * 1024, y_gpu, 4, 42); auto t0 = timer::now(); for(size_t i = 0; i < repeat; ++i){ egblas_par_shuffle_seed(N, x_gpu, 4 * 1024, y_gpu, 4, 42); } auto t1 = timer::now(); auto us = std::chrono::duration_cast<microseconds>(t1 - t0).count(); auto us_avg = us / double(repeat); cuda_check(cudaMemcpy(x_cpu, x_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); cuda_check(cudaMemcpy(y_cpu, y_gpu, N * 1024 * sizeof(float), cudaMemcpyDeviceToHost)); release(x_cpu, x_gpu); release(y_cpu, y_gpu); std::cout << "par_big_shuffle(" << N << "): Tot: " << us << "us Avg: " << us_avg << "us Throughput: " << (1e6 / double(us_avg)) * N << "E/s" << std::endl; } void bench_par_big_shuffle(){ bench_par_big_shuffle(100); bench_par_big_shuffle(1000); bench_par_big_shuffle(10000); std::cout << std::endl; } } // End of anonymous namespace int main(){ bench_shuffle(); bench_par_shuffle(); bench_big_shuffle(); bench_par_big_shuffle(); bench_saxpy(); bench_saxpby(); } <|endoftext|>
<commit_before>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE source in the root of the Project. #include <boost/python.hpp> #include <boost/optional.hpp> #include <nix.hpp> #include <nix/util/util.hpp> #include <accessors.hpp> #include <transmorgify.hpp> #include <PyUtil.hpp> using namespace nix; using namespace boost::python; namespace nixpy { struct UnitWrap {}; bool isScalableSingleUnit(const std::string &unitA, const std::string &unitB) { return util::isScalable(unitA, unitB); } bool isScalableMultiUnits(const std::vector<std::string> &unitsA, const std::vector<std::string> &unitsB) { return util::isScalable(unitsA, unitsB); } struct NameWrap {}; void PyUtil::do_export() { class_<UnitWrap> ("unit_helper") .def("unit_sanitizer", util::unitSanitizer).staticmethod("unit_sanitizer") .def("is_si_unit", util::isSIUnit).staticmethod("is_si_unit") .def("is_atomic_unit", util::isAtomicSIUnit).staticmethod("is_atomic_unit") .def("is_compound_unit", util::isCompoundSIUnit).staticmethod("is_compound_unit") .def("is_scalable", &isScalableMultiUnits).staticmethod("is_scalable") .def("scaling", util::getSIScaling).staticmethod("scaling") ; class_<NameWrap> ("name_helper") .def("name_sanitizer", util::nameSanitizer).staticmethod("name_sanitizer") .def("name_check", util::nameCheck).staticmethod("name_check") .def("create_id", util::createId).staticmethod("create_id") ; } } <commit_msg>[util] simplified names<commit_after>// Copyright (c) 2014, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE source in the root of the Project. #include <boost/python.hpp> #include <boost/optional.hpp> #include <nix.hpp> #include <nix/util/util.hpp> #include <accessors.hpp> #include <transmorgify.hpp> #include <PyUtil.hpp> using namespace nix; using namespace boost::python; namespace nixpy { struct UnitWrap {}; bool isScalableSingleUnit(const std::string &unitA, const std::string &unitB) { return util::isScalable(unitA, unitB); } bool isScalableMultiUnits(const std::vector<std::string> &unitsA, const std::vector<std::string> &unitsB) { return util::isScalable(unitsA, unitsB); } struct NameWrap {}; void PyUtil::do_export() { class_<UnitWrap> ("units") .def("sanitizer", util::unitSanitizer).staticmethod("sanitizer") .def("is_si", util::isSIUnit).staticmethod("is_si") .def("is_atomic", util::isAtomicSIUnit).staticmethod("is_atomic") .def("is_compound", util::isCompoundSIUnit).staticmethod("is_compound") .def("scalable", &isScalableMultiUnits).staticmethod("scalable") .def("scaling", util::getSIScaling).staticmethod("scaling") ; class_<NameWrap> ("names") .def("sanitizer", util::nameSanitizer).staticmethod("sanitizer") .def("check", util::nameCheck).staticmethod("check") .def("create_id", util::createId).staticmethod("create_id") ; } } <|endoftext|>
<commit_before>// Copyright (c) 2013-2014 Anton Kozhevnikov, Thomas Schulthess // 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 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. /** \file potential.cpp * * \brief Contains implementation oof constructor and destructor of sirius::Potential class. */ #include "potential.h" namespace sirius { Potential::Potential(Simulation_context& ctx__) : ctx_(ctx__), unit_cell_(ctx__.unit_cell()), comm_(ctx__.comm()), pseudo_density_order(9), mixer_(nullptr) { runtime::Timer t("sirius::Potential::Potential"); if (ctx_.full_potential() || ctx_.esm_type() == electronic_structure_method_t::paw_pseudopotential) { lmax_ = std::max(ctx_.lmax_rho(), ctx_.lmax_pot()); sht_ = std::unique_ptr<SHT>(new SHT(lmax_)); } if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) { l_by_lm_ = Utils::l_by_lm(lmax_); /* precompute i^l */ zil_.resize(lmax_ + 1); for (int l = 0; l <= lmax_; l++) { zil_[l] = std::pow(double_complex(0, 1), l); } zilm_.resize(Utils::lmmax(lmax_)); for (int l = 0, lm = 0; l <= lmax_; l++) { for (int m = -l; m <= l; m++, lm++) { zilm_[lm] = zil_[l]; } } } effective_potential_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 1); //int need_gvec = (ctx_.full_potential()) ? 0 : 1; int need_gvec{1}; for (int j = 0; j < ctx_.num_mag_dims(); j++) { effective_magnetic_field_[j] = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), need_gvec); } hartree_potential_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 1); hartree_potential_->allocate_mt(false); xc_potential_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 0); xc_potential_->allocate_mt(false); xc_energy_density_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 0); xc_energy_density_->allocate_mt(false); if (!ctx_.full_potential()) { local_potential_ = new Periodic_function<double>(ctx_, 0, 0); local_potential_->zero(); generate_local_potential(); } vh_el_ = mdarray<double, 1>(unit_cell_.num_atoms()); if (ctx_.full_potential()) { gvec_ylm_ = mdarray<double_complex, 2>(ctx_.lmmax_pot(), ctx_.gvec().gvec_count(comm_.rank())); for (int igloc = 0; igloc < ctx_.gvec().gvec_count(comm_.rank()); igloc++) { int ig = ctx_.gvec().gvec_offset(comm_.rank()) + igloc; auto rtp = SHT::spherical_coordinates(ctx_.gvec().gvec_cart(ig)); SHT::spherical_harmonics(ctx_.lmax_pot(), rtp[1], rtp[2], &gvec_ylm_(0, igloc)); } } init(); /* create list of XC functionals */ for (auto& xc_label: ctx_.xc_functionals()) { xc_func_.push_back(new XC_functional(xc_label, ctx_.num_spins())); } /* in case of PAW */ if (ctx_.esm_type() == electronic_structure_method_t::paw_pseudopotential) { init_PAW(); } } Potential::~Potential() { delete effective_potential_; for (int j = 0; j < ctx_.num_mag_dims(); j++) delete effective_magnetic_field_[j]; delete hartree_potential_; delete xc_potential_; delete xc_energy_density_; if (!ctx_.full_potential()) delete local_potential_; if (mixer_ != nullptr) delete mixer_; for (auto& ixc: xc_func_) delete ixc; } } <commit_msg>get rid of pseudopotential flavours<commit_after>// Copyright (c) 2013-2014 Anton Kozhevnikov, Thomas Schulthess // 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 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. /** \file potential.cpp * * \brief Contains implementation oof constructor and destructor of sirius::Potential class. */ #include "potential.h" namespace sirius { Potential::Potential(Simulation_context& ctx__) : ctx_(ctx__), unit_cell_(ctx__.unit_cell()), comm_(ctx__.comm()), pseudo_density_order(9), mixer_(nullptr) { runtime::Timer t("sirius::Potential::Potential"); lmax_ = std::max(ctx_.lmax_rho(), ctx_.lmax_pot()); sht_ = std::unique_ptr<SHT>(new SHT(lmax_)); if (ctx_.esm_type() == electronic_structure_method_t::full_potential_lapwlo) { l_by_lm_ = Utils::l_by_lm(lmax_); /* precompute i^l */ zil_.resize(lmax_ + 1); for (int l = 0; l <= lmax_; l++) { zil_[l] = std::pow(double_complex(0, 1), l); } zilm_.resize(Utils::lmmax(lmax_)); for (int l = 0, lm = 0; l <= lmax_; l++) { for (int m = -l; m <= l; m++, lm++) { zilm_[lm] = zil_[l]; } } } effective_potential_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 1); //int need_gvec = (ctx_.full_potential()) ? 0 : 1; int need_gvec{1}; for (int j = 0; j < ctx_.num_mag_dims(); j++) { effective_magnetic_field_[j] = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), need_gvec); } hartree_potential_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 1); hartree_potential_->allocate_mt(false); xc_potential_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 0); xc_potential_->allocate_mt(false); xc_energy_density_ = new Periodic_function<double>(ctx_, ctx_.lmmax_pot(), 0); xc_energy_density_->allocate_mt(false); if (!ctx_.full_potential()) { local_potential_ = new Periodic_function<double>(ctx_, 0, 0); local_potential_->zero(); generate_local_potential(); } vh_el_ = mdarray<double, 1>(unit_cell_.num_atoms()); if (ctx_.full_potential()) { gvec_ylm_ = mdarray<double_complex, 2>(ctx_.lmmax_pot(), ctx_.gvec().gvec_count(comm_.rank())); for (int igloc = 0; igloc < ctx_.gvec().gvec_count(comm_.rank()); igloc++) { int ig = ctx_.gvec().gvec_offset(comm_.rank()) + igloc; auto rtp = SHT::spherical_coordinates(ctx_.gvec().gvec_cart(ig)); SHT::spherical_harmonics(ctx_.lmax_pot(), rtp[1], rtp[2], &gvec_ylm_(0, igloc)); } } init(); /* create list of XC functionals */ for (auto& xc_label: ctx_.xc_functionals()) { xc_func_.push_back(new XC_functional(xc_label, ctx_.num_spins())); } /* in case of PAW */ init_PAW(); } Potential::~Potential() { delete effective_potential_; for (int j = 0; j < ctx_.num_mag_dims(); j++) delete effective_magnetic_field_[j]; delete hartree_potential_; delete xc_potential_; delete xc_energy_density_; if (!ctx_.full_potential()) delete local_potential_; if (mixer_ != nullptr) delete mixer_; for (auto& ixc: xc_func_) delete ixc; } } <|endoftext|>
<commit_before>/* This file is part of the clazy static checker. Copyright (C) 2017 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "PreProcessorVisitor.h" #include <clang/Frontend/CompilerInstance.h> #include <clang/Lex/Preprocessor.h> #include <clang/Lex/MacroInfo.h> using namespace clang; using namespace std; PreProcessorVisitor::PreProcessorVisitor(const clang::CompilerInstance &ci) : clang::PPCallbacks() , m_ci(ci) { Preprocessor &pi = m_ci.getPreprocessor(); pi.addPPCallbacks(std::unique_ptr<PPCallbacks>(this)); } std::string PreProcessorVisitor::getTokenSpelling(const MacroDefinition &def) const { if (!def) return {}; MacroInfo *info = def.getMacroInfo(); if (!info) return {}; const Preprocessor &pp = m_ci.getPreprocessor(); string result; for (const auto &tok : info->tokens()) result += pp.getSpelling(tok); return result; } void PreProcessorVisitor::updateQtVersion() { if (m_qtMajorVersion == -1 || m_qtPatchVersion == -1 || m_qtMinorVersion == -1) { m_qtVersion = -1; } else { m_qtVersion = m_qtPatchVersion + m_qtMinorVersion * 100 + m_qtMajorVersion * 10000; } } static int stringToNumber(const string &str) { if (str.empty()) return -1; return atoi(str.c_str()); } void PreProcessorVisitor::MacroExpands(const Token &MacroNameTok, const MacroDefinition &def, SourceRange, const MacroArgs *) { IdentifierInfo *ii = MacroNameTok.getIdentifierInfo(); if (!ii) return; auto name = ii->getName(); if (name == "QT_VERSION_MAJOR") { m_qtMajorVersion = stringToNumber(getTokenSpelling(def)); updateQtVersion(); } if (name == "QT_VERSION_MINOR") { m_qtMinorVersion = stringToNumber(getTokenSpelling(def)); updateQtVersion(); } if (name == "QT_VERSION_PATCH") { m_qtPatchVersion = stringToNumber(getTokenSpelling(def)); updateQtVersion(); } } <commit_msg>Exit early from the PreProcessorVisitor once we get the Qt version<commit_after>/* This file is part of the clazy static checker. Copyright (C) 2017 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "PreProcessorVisitor.h" #include <clang/Frontend/CompilerInstance.h> #include <clang/Lex/Preprocessor.h> #include <clang/Lex/MacroInfo.h> using namespace clang; using namespace std; PreProcessorVisitor::PreProcessorVisitor(const clang::CompilerInstance &ci) : clang::PPCallbacks() , m_ci(ci) { Preprocessor &pi = m_ci.getPreprocessor(); pi.addPPCallbacks(std::unique_ptr<PPCallbacks>(this)); } std::string PreProcessorVisitor::getTokenSpelling(const MacroDefinition &def) const { if (!def) return {}; MacroInfo *info = def.getMacroInfo(); if (!info) return {}; const Preprocessor &pp = m_ci.getPreprocessor(); string result; for (const auto &tok : info->tokens()) result += pp.getSpelling(tok); return result; } void PreProcessorVisitor::updateQtVersion() { if (m_qtMajorVersion == -1 || m_qtPatchVersion == -1 || m_qtMinorVersion == -1) { m_qtVersion = -1; } else { m_qtVersion = m_qtPatchVersion + m_qtMinorVersion * 100 + m_qtMajorVersion * 10000; } } static int stringToNumber(const string &str) { if (str.empty()) return -1; return atoi(str.c_str()); } void PreProcessorVisitor::MacroExpands(const Token &MacroNameTok, const MacroDefinition &def, SourceRange, const MacroArgs *) { if (m_qtVersion != -1) return; IdentifierInfo *ii = MacroNameTok.getIdentifierInfo(); if (!ii) return; auto name = ii->getName(); if (name == "QT_VERSION_MAJOR") { m_qtMajorVersion = stringToNumber(getTokenSpelling(def)); updateQtVersion(); } if (name == "QT_VERSION_MINOR") { m_qtMinorVersion = stringToNumber(getTokenSpelling(def)); updateQtVersion(); } if (name == "QT_VERSION_PATCH") { m_qtPatchVersion = stringToNumber(getTokenSpelling(def)); updateQtVersion(); } } <|endoftext|>
<commit_before>#include "iteration/updater/source_updater_gauss_seidel.h" #include <sstream> #include "system/system.h" namespace bart { namespace iteration { namespace updater { template <> void SourceUpdaterGaussSeidel<formulation::CFEMStamperI>::UpdateScatteringSource( system::System& system, system::GroupNumber group, system::AngleIndex angle) { auto scattering_source_vector_ptr_ = this->GetSourceVectorPtr(VariableTerms::kScatteringSource, system, group, angle); *scattering_source_vector_ptr_ = 0; const system::moments::MomentVector &in_group_moment = system.current_moments->GetMoment({group, 0, 0}); const system::moments::MomentsMap& out_group_moments = system.current_moments->moments(); stamper_ptr_->StampScatteringSource(*scattering_source_vector_ptr_, group, in_group_moment, out_group_moments); } template <> void SourceUpdaterGaussSeidel<formulation::CFEMStamperI>::UpdateFissionSource( system::System& system, system::GroupNumber group, system::AngleIndex angle) { double k_effective; if (system.k_effective.has_value()) { k_effective = system.k_effective.value(); } else { AssertThrow(false, dealii::ExcMessage("System has no k_effective value")); } AssertThrow(k_effective > 0, dealii::ExcMessage("Bad k_effective value")); auto scattering_source_vector_ptr_ = this->GetSourceVectorPtr(VariableTerms::kFissionSource, system, group, angle); *scattering_source_vector_ptr_ = 0; const system::moments::MomentVector &in_group_moment = system.current_moments->GetMoment({group, 0, 0}); const system::moments::MomentsMap& out_group_moments = system.current_moments->moments(); stamper_ptr_->StampFissionSource(*scattering_source_vector_ptr_, group, system.k_effective.value(), in_group_moment, out_group_moments); } template class SourceUpdaterGaussSeidel<formulation::CFEMStamperI>; } // namespace updater } // namespace iteration } // namespace bart<commit_msg>cleaned up implementation of iteration::updater::SourceUpdaterGaussSeidel<commit_after>#include "iteration/updater/source_updater_gauss_seidel.h" #include <sstream> #include "system/system.h" namespace bart { namespace iteration { namespace updater { template <> void SourceUpdaterGaussSeidel<formulation::CFEMStamperI>::UpdateScatteringSource( system::System& system, system::GroupNumber group, system::AngleIndex angle) { auto scattering_source_vector_ptr_ = this->GetSourceVectorPtr(VariableTerms::kScatteringSource, system, group, angle); *scattering_source_vector_ptr_ = 0; const system::moments::MomentVector &in_group_moment = system.current_moments->GetMoment({group, 0, 0}); const system::moments::MomentsMap& out_group_moments = system.current_moments->moments(); stamper_ptr_->StampScatteringSource(*scattering_source_vector_ptr_, group, in_group_moment, out_group_moments); } template <> void SourceUpdaterGaussSeidel<formulation::CFEMStamperI>::UpdateFissionSource( system::System& system, system::GroupNumber group, system::AngleIndex angle) { AssertThrow(system.k_effective.has_value(), dealii::ExcMessage("System has no k_effective value")); const double k_effective = system.k_effective.value(); AssertThrow(k_effective > 0, dealii::ExcMessage("Bad k_effective value")); auto fission_source_vector_ptr_ = this->GetSourceVectorPtr(VariableTerms::kFissionSource, system, group, angle); *fission_source_vector_ptr_ = 0; const system::moments::MomentVector &in_group_moment = system.current_moments->GetMoment({group, 0, 0}); const system::moments::MomentsMap& out_group_moments = system.current_moments->moments(); stamper_ptr_->StampFissionSource(*fission_source_vector_ptr_, group, k_effective, in_group_moment, out_group_moments); } template class SourceUpdaterGaussSeidel<formulation::CFEMStamperI>; } // namespace updater } // namespace iteration } // namespace bart<|endoftext|>
<commit_before>/*========================================================================= Program: ParaView Module: vtkXMLDataElement.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000-2001 Kitware Inc. 469 Clifton Corporate Parkway, Clifton Park, NY, 12065, USA. 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 Kitware nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkXMLDataElement.h" #include "vtkObjectFactory.h" #include "vtkXMLDataParser.h" #include <ctype.h> vtkCxxRevisionMacro(vtkXMLDataElement, "1.1"); vtkStandardNewMacro(vtkXMLDataElement); //---------------------------------------------------------------------------- vtkXMLDataElement::vtkXMLDataElement() { this->Name = 0; this->Id = 0; this->Parent = 0; this->NumberOfAttributes = 0; this->AttributesSize = 5; this->AttributeNames = new char*[this->AttributesSize]; this->AttributeValues = new char*[this->AttributesSize]; this->NumberOfNestedElements = 0; this->NestedElementsSize = 10; this->NestedElements = new vtkXMLDataElement*[this->NestedElementsSize]; this->InlineDataPosition = 0; } //---------------------------------------------------------------------------- vtkXMLDataElement::~vtkXMLDataElement() { this->SetName(0); this->SetId(0); int i; for(i=0;i < this->NumberOfAttributes;++i) { delete [] this->AttributeNames[i]; delete [] this->AttributeValues[i]; } delete [] this->AttributeNames; delete [] this->AttributeValues; for(i=0;i < this->NumberOfNestedElements;++i) { this->NestedElements[i]->UnRegister(this); } delete [] this->NestedElements; } //---------------------------------------------------------------------------- void vtkXMLDataElement::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "XMLByteIndex: " << this->XMLByteIndex << "\n"; os << indent << "Name: " << (this->Name? this->Name : "(none)") << "\n"; os << indent << "Id: " << (this->Id? this->Id : "(none)") << "\n"; } //---------------------------------------------------------------------------- void vtkXMLDataElement::ReadXMLAttributes(const char** atts) { if(this->NumberOfAttributes > 0) { int i; for(i=0;i < this->NumberOfAttributes;++i) { delete [] this->AttributeNames[i]; delete [] this->AttributeValues[i]; } this->NumberOfAttributes = 0; } if(atts) { const char** attsIter = atts; int count=0; while(*attsIter++) { ++count; } this->NumberOfAttributes = count/2; this->AttributesSize = this->NumberOfAttributes; delete [] this->AttributeNames; delete [] this->AttributeValues; this->AttributeNames = new char* [this->AttributesSize]; this->AttributeValues = new char* [this->AttributesSize]; int i; for(i=0;i < this->NumberOfAttributes; ++i) { this->AttributeNames[i] = new char[strlen(atts[i*2])+1]; strcpy(this->AttributeNames[i], atts[i*2]); this->AttributeValues[i] = new char[strlen(atts[i*2+1])+1]; strcpy(this->AttributeValues[i], atts[i*2+1]); } } } //---------------------------------------------------------------------------- void vtkXMLDataElement::AddNestedElement(vtkXMLDataElement* element) { if(this->NumberOfNestedElements == this->NestedElementsSize) { int i; int newSize = this->NestedElementsSize*2; vtkXMLDataElement** newNestedElements = new vtkXMLDataElement*[newSize]; for(i=0;i < this->NumberOfNestedElements;++i) { newNestedElements[i] = this->NestedElements[i]; } delete [] this->NestedElements; this->NestedElements = newNestedElements; this->NestedElementsSize = newSize; } int index = this->NumberOfNestedElements++; this->NestedElements[index] = element; element->Register(this); element->SetParent(this); } //---------------------------------------------------------------------------- const char* vtkXMLDataElement::GetAttribute(const char* name) { int i; for(i=0; i < this->NumberOfAttributes;++i) { if(strcmp(this->AttributeNames[i], name) == 0) { return this->AttributeValues[i]; } } return 0; } //---------------------------------------------------------------------------- void vtkXMLDataElement::PrintXML(ostream& os, vtkIndent indent) { os << indent << "<" << this->Name; int i; for(i=0;i < this->NumberOfAttributes;++i) { os << " " << this->AttributeNames[i] << "=\"" << this->AttributeValues[i] << "\""; } if(this->NumberOfNestedElements > 0) { os << ">\n"; for(i=0;i < this->NumberOfNestedElements;++i) { vtkIndent nextIndent = indent.GetNextIndent(); this->NestedElements[i]->PrintXML(os, nextIndent); } os << indent << "</" << this->Name << ">\n"; } else { os << "/>\n"; } } //---------------------------------------------------------------------------- void vtkXMLDataElement::SetParent(vtkXMLDataElement* parent) { this->Parent = parent; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::GetParent() { return this->Parent; } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetNumberOfNestedElements() { return this->NumberOfNestedElements; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::GetNestedElement(int index) { if(index < this->NumberOfNestedElements) { return this->NestedElements[index]; } return 0; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::LookupElement(const char* id) { return this->LookupElementUpScope(id); } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::FindNestedElement(const char* id) { int i; for(i=0;i < this->NumberOfNestedElements;++i) { const char* nid = this->NestedElements[i]->GetId(); if(nid && (strcmp(nid, id) == 0)) { return this->NestedElements[i]; } } return 0; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::LookupElementInScope(const char* id) { // Pull off the first qualifier. const char* end = id; while(*end && (*end != '.')) ++end; int len = end - id; char* name = new char[len+1]; strncpy(name, id, len); name[len] = '\0'; // Find the qualifier in this scope. vtkXMLDataElement* next = this->FindNestedElement(name); if(next && (*end == '.')) { // Lookup rest of qualifiers in nested scope. next = next->LookupElementInScope(end+1); } delete [] name; return next; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::LookupElementUpScope(const char* id) { // Pull off the first qualifier. const char* end = id; while(*end && (*end != '.')) ++end; int len = end - id; char* name = new char[len+1]; strncpy(name, id, len); name[len] = '\0'; // Find most closely nested occurrence of first qualifier. vtkXMLDataElement* curScope = this; vtkXMLDataElement* start = 0; while(curScope && !start) { start = curScope->FindNestedElement(name); curScope = curScope->GetParent(); } if(start && (*end == '.')) { start = start->LookupElementInScope(end+1); } delete [] name; return start; } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetScalarAttribute(const char* name, int& value) { return this->GetVectorAttribute(name, 1, &value); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetScalarAttribute(const char* name, float& value) { return this->GetVectorAttribute(name, 1, &value); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetScalarAttribute(const char* name, unsigned long& value) { return this->GetVectorAttribute(name, 1, &value); } //---------------------------------------------------------------------------- #ifdef VTK_ID_TYPE_IS_NOT_BASIC_TYPE int vtkXMLDataElement::GetScalarAttribute(const char* name, vtkIdType& value) { return this->GetVectorAttribute(name, 1, &value); } #endif //---------------------------------------------------------------------------- template <class T> static int vtkXMLVectorAttributeParse(const char* str, int length, T* data) { if(!str || !length) { return 0; } strstream vstr; vstr << str << ends; int i; for(i=0;i < length;++i) { vstr >> data[i]; if(!vstr) { return i; } } return length; } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, int* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, float* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, unsigned long* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- #ifdef VTK_ID_TYPE_IS_NOT_BASIC_TYPE int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, vtkIdType* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } #endif //---------------------------------------------------------------------------- int vtkXMLDataElement::GetWordTypeAttribute(const char* name, int& value) { // These string values must match vtkXMLWriter::GetWordTypeName(). const char* v = this->GetAttribute(name); if(!v) { return 0; } else if(strcmp(v, "vtkIdType") == 0) { value = VTK_ID_TYPE; return 1; } else if(strcmp(v, "float") == 0) { value = VTK_FLOAT; return 1; } else if(strcmp(v, "double") == 0) { value = VTK_DOUBLE; return 1; } else if(strcmp(v, "int") == 0) { value = VTK_INT; return 1; } else if(strcmp(v, "unsigned int") == 0) { value = VTK_UNSIGNED_INT; return 1; } else if(strcmp(v, "long") == 0) { value = VTK_LONG; return 1; } else if(strcmp(v, "unsigned long") == 0) { value = VTK_UNSIGNED_LONG; return 1; } else if(strcmp(v, "short") == 0) { value = VTK_SHORT; return 1; } else if(strcmp(v, "unsigned short") == 0) { value = VTK_UNSIGNED_SHORT; return 1; } else if(strcmp(v, "unsigned char") == 0) { value = VTK_UNSIGNED_CHAR; return 1; } else if(strcmp(v, "char") == 0) { value = VTK_CHAR; return 1; } return 0; } //---------------------------------------------------------------------------- void vtkXMLDataElement::SeekInlineDataPosition(vtkXMLDataParser* parser) { istream* stream = parser->GetStream(); if(!this->InlineDataPosition) { // Scan for the start of the actual inline data. char c; stream->seekg(this->GetXMLByteIndex()); stream->clear(stream->rdstate() & ~ios::eofbit); stream->clear(stream->rdstate() & ~ios::failbit); while(stream->get(c) && (c != '>')); while(stream->get(c) && this->IsSpace(c)); unsigned long pos = stream->tellg(); this->InlineDataPosition = pos-1; } // Seek to the data position. stream->seekg(this->InlineDataPosition); } //---------------------------------------------------------------------------- int vtkXMLDataElement::IsSpace(char c) { return isspace(c); } <commit_msg>BUG: Added missing initializer for XMLByteIndex.<commit_after>/*========================================================================= Program: ParaView Module: vtkXMLDataElement.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000-2001 Kitware Inc. 469 Clifton Corporate Parkway, Clifton Park, NY, 12065, USA. 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 Kitware nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 AUTHORS 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 "vtkXMLDataElement.h" #include "vtkObjectFactory.h" #include "vtkXMLDataParser.h" #include <ctype.h> vtkCxxRevisionMacro(vtkXMLDataElement, "1.2"); vtkStandardNewMacro(vtkXMLDataElement); //---------------------------------------------------------------------------- vtkXMLDataElement::vtkXMLDataElement() { this->Name = 0; this->Id = 0; this->Parent = 0; this->NumberOfAttributes = 0; this->AttributesSize = 5; this->AttributeNames = new char*[this->AttributesSize]; this->AttributeValues = new char*[this->AttributesSize]; this->NumberOfNestedElements = 0; this->NestedElementsSize = 10; this->NestedElements = new vtkXMLDataElement*[this->NestedElementsSize]; this->InlineDataPosition = 0; this->XMLByteIndex = 0; } //---------------------------------------------------------------------------- vtkXMLDataElement::~vtkXMLDataElement() { this->SetName(0); this->SetId(0); int i; for(i=0;i < this->NumberOfAttributes;++i) { delete [] this->AttributeNames[i]; delete [] this->AttributeValues[i]; } delete [] this->AttributeNames; delete [] this->AttributeValues; for(i=0;i < this->NumberOfNestedElements;++i) { this->NestedElements[i]->UnRegister(this); } delete [] this->NestedElements; } //---------------------------------------------------------------------------- void vtkXMLDataElement::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "XMLByteIndex: " << this->XMLByteIndex << "\n"; os << indent << "Name: " << (this->Name? this->Name : "(none)") << "\n"; os << indent << "Id: " << (this->Id? this->Id : "(none)") << "\n"; } //---------------------------------------------------------------------------- void vtkXMLDataElement::ReadXMLAttributes(const char** atts) { if(this->NumberOfAttributes > 0) { int i; for(i=0;i < this->NumberOfAttributes;++i) { delete [] this->AttributeNames[i]; delete [] this->AttributeValues[i]; } this->NumberOfAttributes = 0; } if(atts) { const char** attsIter = atts; int count=0; while(*attsIter++) { ++count; } this->NumberOfAttributes = count/2; this->AttributesSize = this->NumberOfAttributes; delete [] this->AttributeNames; delete [] this->AttributeValues; this->AttributeNames = new char* [this->AttributesSize]; this->AttributeValues = new char* [this->AttributesSize]; int i; for(i=0;i < this->NumberOfAttributes; ++i) { this->AttributeNames[i] = new char[strlen(atts[i*2])+1]; strcpy(this->AttributeNames[i], atts[i*2]); this->AttributeValues[i] = new char[strlen(atts[i*2+1])+1]; strcpy(this->AttributeValues[i], atts[i*2+1]); } } } //---------------------------------------------------------------------------- void vtkXMLDataElement::AddNestedElement(vtkXMLDataElement* element) { if(this->NumberOfNestedElements == this->NestedElementsSize) { int i; int newSize = this->NestedElementsSize*2; vtkXMLDataElement** newNestedElements = new vtkXMLDataElement*[newSize]; for(i=0;i < this->NumberOfNestedElements;++i) { newNestedElements[i] = this->NestedElements[i]; } delete [] this->NestedElements; this->NestedElements = newNestedElements; this->NestedElementsSize = newSize; } int index = this->NumberOfNestedElements++; this->NestedElements[index] = element; element->Register(this); element->SetParent(this); } //---------------------------------------------------------------------------- const char* vtkXMLDataElement::GetAttribute(const char* name) { int i; for(i=0; i < this->NumberOfAttributes;++i) { if(strcmp(this->AttributeNames[i], name) == 0) { return this->AttributeValues[i]; } } return 0; } //---------------------------------------------------------------------------- void vtkXMLDataElement::PrintXML(ostream& os, vtkIndent indent) { os << indent << "<" << this->Name; int i; for(i=0;i < this->NumberOfAttributes;++i) { os << " " << this->AttributeNames[i] << "=\"" << this->AttributeValues[i] << "\""; } if(this->NumberOfNestedElements > 0) { os << ">\n"; for(i=0;i < this->NumberOfNestedElements;++i) { vtkIndent nextIndent = indent.GetNextIndent(); this->NestedElements[i]->PrintXML(os, nextIndent); } os << indent << "</" << this->Name << ">\n"; } else { os << "/>\n"; } } //---------------------------------------------------------------------------- void vtkXMLDataElement::SetParent(vtkXMLDataElement* parent) { this->Parent = parent; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::GetParent() { return this->Parent; } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetNumberOfNestedElements() { return this->NumberOfNestedElements; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::GetNestedElement(int index) { if(index < this->NumberOfNestedElements) { return this->NestedElements[index]; } return 0; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::LookupElement(const char* id) { return this->LookupElementUpScope(id); } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::FindNestedElement(const char* id) { int i; for(i=0;i < this->NumberOfNestedElements;++i) { const char* nid = this->NestedElements[i]->GetId(); if(nid && (strcmp(nid, id) == 0)) { return this->NestedElements[i]; } } return 0; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::LookupElementInScope(const char* id) { // Pull off the first qualifier. const char* end = id; while(*end && (*end != '.')) ++end; int len = end - id; char* name = new char[len+1]; strncpy(name, id, len); name[len] = '\0'; // Find the qualifier in this scope. vtkXMLDataElement* next = this->FindNestedElement(name); if(next && (*end == '.')) { // Lookup rest of qualifiers in nested scope. next = next->LookupElementInScope(end+1); } delete [] name; return next; } //---------------------------------------------------------------------------- vtkXMLDataElement* vtkXMLDataElement::LookupElementUpScope(const char* id) { // Pull off the first qualifier. const char* end = id; while(*end && (*end != '.')) ++end; int len = end - id; char* name = new char[len+1]; strncpy(name, id, len); name[len] = '\0'; // Find most closely nested occurrence of first qualifier. vtkXMLDataElement* curScope = this; vtkXMLDataElement* start = 0; while(curScope && !start) { start = curScope->FindNestedElement(name); curScope = curScope->GetParent(); } if(start && (*end == '.')) { start = start->LookupElementInScope(end+1); } delete [] name; return start; } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetScalarAttribute(const char* name, int& value) { return this->GetVectorAttribute(name, 1, &value); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetScalarAttribute(const char* name, float& value) { return this->GetVectorAttribute(name, 1, &value); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetScalarAttribute(const char* name, unsigned long& value) { return this->GetVectorAttribute(name, 1, &value); } //---------------------------------------------------------------------------- #ifdef VTK_ID_TYPE_IS_NOT_BASIC_TYPE int vtkXMLDataElement::GetScalarAttribute(const char* name, vtkIdType& value) { return this->GetVectorAttribute(name, 1, &value); } #endif //---------------------------------------------------------------------------- template <class T> static int vtkXMLVectorAttributeParse(const char* str, int length, T* data) { if(!str || !length) { return 0; } strstream vstr; vstr << str << ends; int i; for(i=0;i < length;++i) { vstr >> data[i]; if(!vstr) { return i; } } return length; } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, int* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, float* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, unsigned long* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } //---------------------------------------------------------------------------- #ifdef VTK_ID_TYPE_IS_NOT_BASIC_TYPE int vtkXMLDataElement::GetVectorAttribute(const char* name, int length, vtkIdType* data) { return vtkXMLVectorAttributeParse(this->GetAttribute(name), length, data); } #endif //---------------------------------------------------------------------------- int vtkXMLDataElement::GetWordTypeAttribute(const char* name, int& value) { // These string values must match vtkXMLWriter::GetWordTypeName(). const char* v = this->GetAttribute(name); if(!v) { return 0; } else if(strcmp(v, "vtkIdType") == 0) { value = VTK_ID_TYPE; return 1; } else if(strcmp(v, "float") == 0) { value = VTK_FLOAT; return 1; } else if(strcmp(v, "double") == 0) { value = VTK_DOUBLE; return 1; } else if(strcmp(v, "int") == 0) { value = VTK_INT; return 1; } else if(strcmp(v, "unsigned int") == 0) { value = VTK_UNSIGNED_INT; return 1; } else if(strcmp(v, "long") == 0) { value = VTK_LONG; return 1; } else if(strcmp(v, "unsigned long") == 0) { value = VTK_UNSIGNED_LONG; return 1; } else if(strcmp(v, "short") == 0) { value = VTK_SHORT; return 1; } else if(strcmp(v, "unsigned short") == 0) { value = VTK_UNSIGNED_SHORT; return 1; } else if(strcmp(v, "unsigned char") == 0) { value = VTK_UNSIGNED_CHAR; return 1; } else if(strcmp(v, "char") == 0) { value = VTK_CHAR; return 1; } return 0; } //---------------------------------------------------------------------------- void vtkXMLDataElement::SeekInlineDataPosition(vtkXMLDataParser* parser) { istream* stream = parser->GetStream(); if(!this->InlineDataPosition) { // Scan for the start of the actual inline data. char c; stream->seekg(this->GetXMLByteIndex()); stream->clear(stream->rdstate() & ~ios::eofbit); stream->clear(stream->rdstate() & ~ios::failbit); while(stream->get(c) && (c != '>')); while(stream->get(c) && this->IsSpace(c)); unsigned long pos = stream->tellg(); this->InlineDataPosition = pos-1; } // Seek to the data position. stream->seekg(this->InlineDataPosition); } //---------------------------------------------------------------------------- int vtkXMLDataElement::IsSpace(char c) { return isspace(c); } <|endoftext|>
<commit_before>/* -*- mode: c++; indent-tabs-mode: nil -*- */ /* QoreOracleStatement.cpp Qore Programming Language Copyright (C) 2003 - 2012 David Nichols This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "oracle.h" static inline bool wasInTransaction(Datasource *ds) { #ifdef _QORE_HAS_DATASOURCE_ACTIVETRANSACTION return ds->activeTransaction(); #else return ds->isInTransaction(); #endif } int QoreOracleStatement::execute(const char *who, ExceptionSink *xsink) { QoreOracleConnection *conn = (QoreOracleConnection *)ds->getPrivateData(); assert(conn->svchp); int status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT); //printd(0, "QoreOracleStatement::execute() stmthp=%p status=%d (OCI_ERROR=%d)\n", stmthp, status, OCI_ERROR); if (status == OCI_ERROR) { // see if server is connected ub4 server_status = 0; // get server handle OCIServer *svrh; if (conn->checkerr(OCIAttrGet(conn->svchp, OCI_HTYPE_SVCCTX, &svrh, 0, OCI_ATTR_SERVER, conn->errhp), who, xsink)) return -1; //printd(0, "QoreOracleStatement::execute() got server handle: %p\n", svrh); if (conn->checkerr(OCIAttrGet(svrh, OCI_HTYPE_SERVER, (dvoid *)&server_status, 0, OCI_ATTR_SERVER_STATUS, conn->errhp), who, xsink)) return -1; //printd(0, "QoreOracleStatement::execute() server_status=%d (OCI_SERVER_NOT_CONNECTED=%d)\n", server_status, OCI_SERVER_NOT_CONNECTED); if (server_status == OCI_SERVER_NOT_CONNECTED) { // check if a transaction was in progress if (wasInTransaction(ds)) xsink->raiseException("DBI:ORACLE:TRANSACTION-ERROR", "connection to Oracle database server lost while in a transaction; transaction has been lost"); // try to reconnect conn->logoff(); //printd(0, "QoreOracleStatement::execute() about to execute OCILogon() for reconnect\n"); if (conn->logon(xsink)) { //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn); // close datasource and remove private data ds->connectionAborted(); return -1; } if (conn->checkWarnings(xsink)) { //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn); // close datasource and remove private data ds->connectionAborted(); return -1; } // don't execute again if the connection was aborted while in a transaction if (wasInTransaction(ds)) return -1; //printd(0, "QoreOracleStatement::execute() returned from OCILogon() status=%d\n", status); status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT); if (status && conn->checkerr(status, who, xsink)) return -1; } else { //printd(0, "QoreOracleStatement::execute() error, but it's connected; status=%d who=%s\n", status, who); conn->checkerr(status, who, xsink); return -1; } } else if (status && conn->checkerr(status, who, xsink)) return -1; return 0; } QoreHashNode *QoreOracleStatement::fetchRow(OraResultSet &resultset, ExceptionSink *xsink) { // set up hash for row ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink); // copy data or perform per-value processing if needed for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) { OraColumnBuffer *w = *i; // assign value to hash h->setKeyValue(w->name, w->getValue(true, xsink), xsink); if (*xsink) return 0; } return h.release(); } QoreListNode *QoreOracleStatement::fetchRows(ExceptionSink *xsink) { OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRows():params", xsink); if (*xsink) return 0; return fetchRows(**resultset, -1, xsink); } QoreListNode *QoreOracleStatement::fetchRows(OraResultSet &resultset, int rows, ExceptionSink *xsink) { ReferenceHolder<QoreListNode> l(new QoreListNode, xsink); // setup temporary row to accept values if (resultset.define("QoreOracleStatement::fetchRows():define", xsink)) return 0; int num_rows = 0; // now finally fetch the data while (next(xsink)) { QoreHashNode *h = fetchRow(resultset, xsink); if (!h) return 0; // add row to list l->push(h); ++num_rows; if (rows > 0 && num_rows == rows) break; } //printd(2, "QoreOracleStatement::fetchRows(): %d column(s), %d row(s) retrieved as output\n", resultset.size(), l->size()); return *xsink ? 0 : l.release(); } #ifdef _QORE_HAS_DBI_SELECT_ROW QoreHashNode *QoreOracleStatement::fetchSingleRow(ExceptionSink *xsink) { OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRow():params", xsink); if (*xsink) return 0; ReferenceHolder<QoreHashNode> rv(xsink); // setup temporary row to accept values if (resultset->define("QoreOracleStatement::fetchRows():define", xsink)) return 0; //printd(2, "QoreOracleStatement::fetchRow(): %d column(s) retrieved as output\n", resultset->size()); // now finally fetch the data if (!next(xsink)) return 0; rv = fetchRow(**resultset, xsink); if (!rv) return 0; if (next(xsink)) { xsink->raiseExceptionArg("ORACLE-SELECT-ROW-ERROR", rv.release(), "SQL passed to selectRow() returned more than 1 row"); return 0; } return rv.release(); } #endif // retrieve results from statement and return hash QoreHashNode *QoreOracleStatement::fetchColumns(ExceptionSink *xsink) { OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchColumns():params", xsink); if (*xsink) return 0; return fetchColumns(**resultset, -1, xsink); } // retrieve results from statement and return hash QoreHashNode *QoreOracleStatement::fetchColumns(OraResultSet &resultset, int rows, ExceptionSink *xsink) { // allocate result hash for result value ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink); // create hash elements for each column, assign empty list for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) { //printd(5, "QoreOracleStatement::fetchColumns() allocating list for '%s' column\n", w->name); h->setKeyValue((*i)->name, new QoreListNode, xsink); } // setup temporary row to accept values if (resultset.define("QoreOracleStatement::fetchColumns():define", xsink)) return 0; int num_rows = 0; // now finally fetch the data while (next(xsink)) { // copy data or perform per-value processing if needed for (unsigned i = 0; i < resultset.clist.size(); ++i) { OraColumnBuffer *w = resultset.clist[i]; // get pointer to value of target node QoreListNode *l = reinterpret_cast<QoreListNode *>(h->getKeyValue(w->name, xsink)); if (!l) break; l->push(w->getValue(false, xsink)); if (*xsink) break; } ++num_rows; if (rows > 0 && num_rows == rows) break; } //printd(2, "QoreOracleStatement::fetchColumns(rows: %d): %d column(s), %d row(s) retrieved as output\n", rows, resultset.size(), num_rows); return *xsink ? 0 : h.release(); } <commit_msg>check exception status from getValue() before using value<commit_after>/* -*- mode: c++; indent-tabs-mode: nil -*- */ /* QoreOracleStatement.cpp Qore Programming Language Copyright (C) 2003 - 2012 David Nichols This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "oracle.h" static inline bool wasInTransaction(Datasource *ds) { #ifdef _QORE_HAS_DATASOURCE_ACTIVETRANSACTION return ds->activeTransaction(); #else return ds->isInTransaction(); #endif } int QoreOracleStatement::execute(const char *who, ExceptionSink *xsink) { QoreOracleConnection *conn = (QoreOracleConnection *)ds->getPrivateData(); assert(conn->svchp); int status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT); //printd(0, "QoreOracleStatement::execute() stmthp=%p status=%d (OCI_ERROR=%d)\n", stmthp, status, OCI_ERROR); if (status == OCI_ERROR) { // see if server is connected ub4 server_status = 0; // get server handle OCIServer *svrh; if (conn->checkerr(OCIAttrGet(conn->svchp, OCI_HTYPE_SVCCTX, &svrh, 0, OCI_ATTR_SERVER, conn->errhp), who, xsink)) return -1; //printd(0, "QoreOracleStatement::execute() got server handle: %p\n", svrh); if (conn->checkerr(OCIAttrGet(svrh, OCI_HTYPE_SERVER, (dvoid *)&server_status, 0, OCI_ATTR_SERVER_STATUS, conn->errhp), who, xsink)) return -1; //printd(0, "QoreOracleStatement::execute() server_status=%d (OCI_SERVER_NOT_CONNECTED=%d)\n", server_status, OCI_SERVER_NOT_CONNECTED); if (server_status == OCI_SERVER_NOT_CONNECTED) { // check if a transaction was in progress if (wasInTransaction(ds)) xsink->raiseException("DBI:ORACLE:TRANSACTION-ERROR", "connection to Oracle database server lost while in a transaction; transaction has been lost"); // try to reconnect conn->logoff(); //printd(0, "QoreOracleStatement::execute() about to execute OCILogon() for reconnect\n"); if (conn->logon(xsink)) { //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn); // close datasource and remove private data ds->connectionAborted(); return -1; } if (conn->checkWarnings(xsink)) { //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn); // close datasource and remove private data ds->connectionAborted(); return -1; } // don't execute again if the connection was aborted while in a transaction if (wasInTransaction(ds)) return -1; //printd(0, "QoreOracleStatement::execute() returned from OCILogon() status=%d\n", status); status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT); if (status && conn->checkerr(status, who, xsink)) return -1; } else { //printd(0, "QoreOracleStatement::execute() error, but it's connected; status=%d who=%s\n", status, who); conn->checkerr(status, who, xsink); return -1; } } else if (status && conn->checkerr(status, who, xsink)) return -1; return 0; } QoreHashNode *QoreOracleStatement::fetchRow(OraResultSet &resultset, ExceptionSink *xsink) { // set up hash for row ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink); // copy data or perform per-value processing if needed for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) { OraColumnBuffer *w = *i; // assign value to hash AbstractQoreNode* n = w->getValue(true, xsink); if (*xsink) { assert(!n); return 0; } h->setKeyValue(w->name, n, xsink); if (*xsink) return 0; } return h.release(); } QoreListNode *QoreOracleStatement::fetchRows(ExceptionSink *xsink) { OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRows():params", xsink); if (*xsink) return 0; return fetchRows(**resultset, -1, xsink); } QoreListNode *QoreOracleStatement::fetchRows(OraResultSet &resultset, int rows, ExceptionSink *xsink) { ReferenceHolder<QoreListNode> l(new QoreListNode, xsink); // setup temporary row to accept values if (resultset.define("QoreOracleStatement::fetchRows():define", xsink)) return 0; int num_rows = 0; // now finally fetch the data while (next(xsink)) { QoreHashNode *h = fetchRow(resultset, xsink); if (!h) return 0; // add row to list l->push(h); ++num_rows; if (rows > 0 && num_rows == rows) break; } //printd(2, "QoreOracleStatement::fetchRows(): %d column(s), %d row(s) retrieved as output\n", resultset.size(), l->size()); return *xsink ? 0 : l.release(); } #ifdef _QORE_HAS_DBI_SELECT_ROW QoreHashNode *QoreOracleStatement::fetchSingleRow(ExceptionSink *xsink) { OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRow():params", xsink); if (*xsink) return 0; ReferenceHolder<QoreHashNode> rv(xsink); // setup temporary row to accept values if (resultset->define("QoreOracleStatement::fetchRows():define", xsink)) return 0; //printd(2, "QoreOracleStatement::fetchRow(): %d column(s) retrieved as output\n", resultset->size()); // now finally fetch the data if (!next(xsink)) return 0; rv = fetchRow(**resultset, xsink); if (!rv) return 0; if (next(xsink)) { xsink->raiseExceptionArg("ORACLE-SELECT-ROW-ERROR", rv.release(), "SQL passed to selectRow() returned more than 1 row"); return 0; } return rv.release(); } #endif // retrieve results from statement and return hash QoreHashNode *QoreOracleStatement::fetchColumns(ExceptionSink *xsink) { OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchColumns():params", xsink); if (*xsink) return 0; return fetchColumns(**resultset, -1, xsink); } // retrieve results from statement and return hash QoreHashNode *QoreOracleStatement::fetchColumns(OraResultSet &resultset, int rows, ExceptionSink *xsink) { // allocate result hash for result value ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink); // create hash elements for each column, assign empty list for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) { //printd(5, "QoreOracleStatement::fetchColumns() allocating list for '%s' column\n", w->name); h->setKeyValue((*i)->name, new QoreListNode, xsink); } // setup temporary row to accept values if (resultset.define("QoreOracleStatement::fetchColumns():define", xsink)) return 0; int num_rows = 0; // now finally fetch the data while (next(xsink)) { // copy data or perform per-value processing if needed for (unsigned i = 0; i < resultset.clist.size(); ++i) { OraColumnBuffer *w = resultset.clist[i]; // get pointer to value of target node QoreListNode *l = reinterpret_cast<QoreListNode *>(h->getKeyValue(w->name, xsink)); if (!l) break; AbstractQoreNode* n = w->getValue(false, xsink); if (*xsink) { assert(!n); break; } l->push(n); if (*xsink) break; } ++num_rows; if (rows > 0 && num_rows == rows) break; } //printd(2, "QoreOracleStatement::fetchColumns(rows: %d): %d column(s), %d row(s) retrieved as output\n", rows, resultset.size(), num_rows); return *xsink ? 0 : h.release(); } <|endoftext|>
<commit_before>#include <QSettings> #include <QTranslator> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/project.h> #include <projectexplorer/target.h> #include <projectexplorer/task.h> #include <projectexplorer/buildconfiguration.h> #include <projectexplorer/buildsteplist.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/buildmanager.h> #include <coreplugin/icore.h> #include <QtPlugin> #include "QtcPaneEncodePlugin.h" #include "OptionsPage.h" #include "Utils.h" #include "Constants.h" using namespace QtcPaneEncode::Internal; using namespace QtcPaneEncode::Constants; using namespace Core; using namespace ProjectExplorer; using namespace ExtensionSystem; namespace { const QString appOutputPaneClassName = QLatin1String ("ProjectExplorer::Internal::AppOutputPane"); } QtcPaneEncodePlugin::QtcPaneEncodePlugin () : IPlugin () { // Create your members } QtcPaneEncodePlugin::~QtcPaneEncodePlugin () { // Unregister objects from the plugin manager's object pool // Delete members } bool QtcPaneEncodePlugin::initialize (const QStringList &arguments, QString *errorString) { // Register objects in the plugin manager's object pool // Load settings // Add actions to menus // Connect to other plugins' signals // In the initialize function, a plugin can be sure that the plugins it // depends on have initialized their members. Q_UNUSED (arguments) Q_UNUSED (errorString) initLanguage (); updateSettings (); OptionsPage *optionsPage = new OptionsPage; connect (optionsPage, SIGNAL (settingsChanged ()), SLOT (updateSettings ())); addAutoReleasedObject (optionsPage); return true; } void QtcPaneEncodePlugin::initLanguage () { const QString &language = Core::ICore::userInterfaceLanguage (); if (!language.isEmpty ()) { QStringList paths; paths << ICore::resourcePath () << ICore::userResourcePath (); const QString &trFile = QLatin1String ("QtcPaneEncode_") + language; QTranslator *translator = new QTranslator (this); foreach (const QString &path, paths) { if (translator->load (trFile, path + QLatin1String ("/translations"))) { qApp->installTranslator (translator); break; } } } } void QtcPaneEncodePlugin::updateSettings () { Q_ASSERT (Core::ICore::settings () != NULL); QSettings &settings = *(Core::ICore::settings ()); settings.beginGroup (SETTINGS_GROUP); if (settings.value (SETTINGS_BUILD_ENABLED, false).toBool ()) { buildEncoding_ = settings.value (SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray (); } else { buildEncoding_.clear (); } if (settings.value (SETTINGS_APP_ENABLED, false).toBool ()) { appEncoding_ = settings.value (SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray (); } else { appEncoding_.clear (); } settings.endGroup (); } void QtcPaneEncodePlugin::extensionsInitialized () { // Retrieve objects from the plugin manager's object pool // In the extensionsInitialized function, a plugin can be sure that all // plugins that depend on it are completely initialized. // Compiler output connect (BuildManager::instance (), SIGNAL (buildStateChanged (ProjectExplorer::Project *)), this, SLOT (handleBuild (ProjectExplorer::Project *))); connect (this, &QtcPaneEncodePlugin::newOutput, BuildManager::instance (), &BuildManager::addToOutputWindow); connect (this, &QtcPaneEncodePlugin::newTask, BuildManager::instance (), &BuildManager::addToTaskWindow); // Run control output QObject *appOutputPane = PluginManager::getObjectByClassName (appOutputPaneClassName); if (appOutputPane != NULL) { connect (ProjectExplorerPlugin::instance (), SIGNAL (runControlStarted (ProjectExplorer::RunControl *)), this, SLOT (handleRunStart (ProjectExplorer::RunControl *))); connect (this, SIGNAL (newMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), appOutputPane, SLOT (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat))); } else { qCritical () << "Failed to find appOutputPane"; } } ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown () { // Save settings // Disconnect from signals that are not needed during shutdown // Hide UI(if you add UI that is not in the main window directly) this->disconnect (); return SynchronousShutdown; } void QtcPaneEncodePlugin::handleBuild (ProjectExplorer::Project *project) { if (!BuildManager::isBuilding ()) { return; } const Target *buildingTarget = NULL; foreach (Target * target, project->targets ()) { if (BuildManager::isBuilding (target)) { buildingTarget = target; break; } } if (buildingTarget == NULL) { return; } BuildConfiguration *buildingConfiguration = NULL; foreach (BuildConfiguration * config, buildingTarget->buildConfigurations ()) { if (BuildManager::isBuilding (config)) { buildingConfiguration = config; break; } } if (buildingConfiguration == NULL) { return; } QList<Core::Id> stepsIds = buildingConfiguration->knownStepLists (); foreach (const Core::Id & id, stepsIds) { BuildStepList *steps = buildingConfiguration->stepList (id); if (steps == NULL) { continue; } for (int i = 0, end = steps->count (); i < end; ++i) { BuildStep *step = steps->at (i); disconnect (step, &BuildStep::addOutput, 0, 0); connect (step, SIGNAL (addOutput (QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), this, SLOT (addOutput (QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), Qt::UniqueConnection); disconnect (step, &BuildStep::addTask, 0, 0); connect (step, SIGNAL (addTask (ProjectExplorer::Task,int,int)), this, SLOT (addTask (ProjectExplorer::Task,int,int)), Qt::UniqueConnection); } } } void QtcPaneEncodePlugin::addTask (const Task &task, int linkedOutputLines, int skipLines) { if (buildEncoding_.isEmpty ()) { emit newTask (task, linkedOutputLines, skipLines); return; } Task convertedTask = task; // Unknown charset will be handled like auto-detection request convertedTask.description = reencode (task.description, QTextCodec::codecForName (buildEncoding_)); emit newTask (convertedTask, linkedOutputLines, skipLines); } void QtcPaneEncodePlugin::addOutput (const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) { if (buildEncoding_.isEmpty ()) { emit newOutput (string, format, newlineSetting); return; } QString convertedString = reencode (string, QTextCodec::codecForName (buildEncoding_)); emit newOutput (convertedString, format, newlineSetting); } void QtcPaneEncodePlugin::handleRunStart (RunControl *runControl) { QObject *appOutputPane = PluginManager::getObjectByClassName (appOutputPaneClassName); if (appOutputPane != NULL) { connect (runControl, SIGNAL (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), this, SLOT (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), Qt::UniqueConnection); disconnect (runControl, SIGNAL (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), appOutputPane, SLOT (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat))); } } void QtcPaneEncodePlugin::appendMessage (RunControl *rc, const QString &out, Utils::OutputFormat format) { if (appEncoding_.isEmpty ()) { emit newMessage (rc, out, format); return; } QString convertedOut = reencode (out, QTextCodec::codecForName (appEncoding_)); emit newMessage (rc, convertedOut, format); } <commit_msg>Qtc 4.7.0 update<commit_after>#include <QSettings> #include <QTranslator> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/project.h> #include <projectexplorer/target.h> #include <projectexplorer/task.h> #include <projectexplorer/buildconfiguration.h> #include <projectexplorer/buildsteplist.h> #include <extensionsystem/pluginmanager.h> #include <projectexplorer/buildmanager.h> #include <coreplugin/icore.h> #include <QtPlugin> #include "QtcPaneEncodePlugin.h" #include "OptionsPage.h" #include "Utils.h" #include "Constants.h" using namespace QtcPaneEncode::Internal; using namespace QtcPaneEncode::Constants; using namespace Core; using namespace ProjectExplorer; using namespace ExtensionSystem; namespace { const QString appOutputPaneName = QLatin1String ("AppOutputPane"); } QtcPaneEncodePlugin::QtcPaneEncodePlugin () : IPlugin () { // Create your members } QtcPaneEncodePlugin::~QtcPaneEncodePlugin () { // Unregister objects from the plugin manager's object pool // Delete members } bool QtcPaneEncodePlugin::initialize (const QStringList &arguments, QString *errorString) { // Register objects in the plugin manager's object pool // Load settings // Add actions to menus // Connect to other plugins' signals // In the initialize function, a plugin can be sure that the plugins it // depends on have initialized their members. Q_UNUSED (arguments) Q_UNUSED (errorString) initLanguage (); updateSettings (); OptionsPage *optionsPage = new OptionsPage(this); connect (optionsPage, SIGNAL (settingsChanged ()), SLOT (updateSettings ())); return true; } void QtcPaneEncodePlugin::initLanguage () { const QString &language = Core::ICore::userInterfaceLanguage (); if (!language.isEmpty ()) { QStringList paths; paths << ICore::resourcePath () << ICore::userResourcePath (); const QString &trFile = QLatin1String ("QtcPaneEncode_") + language; QTranslator *translator = new QTranslator (this); foreach (const QString &path, paths) { if (translator->load (trFile, path + QLatin1String ("/translations"))) { qApp->installTranslator (translator); break; } } } } void QtcPaneEncodePlugin::updateSettings () { Q_ASSERT (Core::ICore::settings () != NULL); QSettings &settings = *(Core::ICore::settings ()); settings.beginGroup (SETTINGS_GROUP); if (settings.value (SETTINGS_BUILD_ENABLED, false).toBool ()) { buildEncoding_ = settings.value (SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray (); } else { buildEncoding_.clear (); } if (settings.value (SETTINGS_APP_ENABLED, false).toBool ()) { appEncoding_ = settings.value (SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray (); } else { appEncoding_.clear (); } settings.endGroup (); } void QtcPaneEncodePlugin::extensionsInitialized () { // Retrieve objects from the plugin manager's object pool // In the extensionsInitialized function, a plugin can be sure that all // plugins that depend on it are completely initialized. // Compiler output connect (BuildManager::instance (), SIGNAL (buildStateChanged (ProjectExplorer::Project *)), this, SLOT (handleBuild (ProjectExplorer::Project *))); connect (this, &QtcPaneEncodePlugin::newOutput, BuildManager::instance (), &BuildManager::addToOutputWindow); connect (this, &QtcPaneEncodePlugin::newTask, BuildManager::instance (), &BuildManager::addToTaskWindow); // Run control output QObject *appOutputPane = PluginManager::getObjectByName (appOutputPaneName); if (appOutputPane != NULL) { connect (ProjectExplorerPlugin::instance (), SIGNAL (runControlStarted (ProjectExplorer::RunControl *)), this, SLOT (handleRunStart (ProjectExplorer::RunControl *))); connect (this, SIGNAL (newMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), appOutputPane, SLOT (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat))); } else { qCritical () << "Failed to find appOutputPane"; } } ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown () { // Save settings // Disconnect from signals that are not needed during shutdown // Hide UI(if you add UI that is not in the main window directly) this->disconnect (); return SynchronousShutdown; } void QtcPaneEncodePlugin::handleBuild (ProjectExplorer::Project *project) { if (!BuildManager::isBuilding ()) { return; } const Target *buildingTarget = NULL; foreach (Target * target, project->targets ()) { if (BuildManager::isBuilding (target)) { buildingTarget = target; break; } } if (buildingTarget == NULL) { return; } BuildConfiguration *buildingConfiguration = NULL; foreach (BuildConfiguration * config, buildingTarget->buildConfigurations ()) { if (BuildManager::isBuilding (config)) { buildingConfiguration = config; break; } } if (buildingConfiguration == NULL) { return; } QList<Core::Id> stepsIds = buildingConfiguration->knownStepLists (); foreach (const Core::Id & id, stepsIds) { BuildStepList *steps = buildingConfiguration->stepList (id); if (steps == NULL) { continue; } for (int i = 0, end = steps->count (); i < end; ++i) { BuildStep *step = steps->at (i); disconnect (step, &BuildStep::addOutput, 0, 0); connect (step, SIGNAL (addOutput (QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), this, SLOT (addOutput (QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)), Qt::UniqueConnection); disconnect (step, &BuildStep::addTask, 0, 0); connect (step, SIGNAL (addTask (ProjectExplorer::Task,int,int)), this, SLOT (addTask (ProjectExplorer::Task,int,int)), Qt::UniqueConnection); } } } void QtcPaneEncodePlugin::addTask (const Task &task, int linkedOutputLines, int skipLines) { if (buildEncoding_.isEmpty ()) { emit newTask (task, linkedOutputLines, skipLines); return; } Task convertedTask = task; // Unknown charset will be handled like auto-detection request convertedTask.description = reencode (task.description, QTextCodec::codecForName (buildEncoding_)); emit newTask (convertedTask, linkedOutputLines, skipLines); } void QtcPaneEncodePlugin::addOutput (const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) { if (buildEncoding_.isEmpty ()) { emit newOutput (string, format, newlineSetting); return; } QString convertedString = reencode (string, QTextCodec::codecForName (buildEncoding_)); emit newOutput (convertedString, format, newlineSetting); } void QtcPaneEncodePlugin::handleRunStart (RunControl *runControl) { QObject *appOutputPane = PluginManager::getObjectByName(appOutputPaneName); if (appOutputPane != NULL) { connect (runControl, SIGNAL (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), this, SLOT (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), Qt::UniqueConnection); disconnect (runControl, SIGNAL (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat)), appOutputPane, SLOT (appendMessage (ProjectExplorer::RunControl *,QString,Utils::OutputFormat))); } } void QtcPaneEncodePlugin::appendMessage (RunControl *rc, const QString &out, Utils::OutputFormat format) { if (appEncoding_.isEmpty ()) { emit newMessage (rc, out, format); return; } QString convertedOut = reencode (out, QTextCodec::codecForName (appEncoding_)); emit newMessage (rc, convertedOut, format); } <|endoftext|>
<commit_before>#include "learn_dx11/tess/terrain_tessellation_example.h" #include <cassert> #include <iostream> #include <iterator> #include <vector> using namespace cg; namespace { size_t bottom_left_index(size_t row, size_t column, size_t row_count, size_t column_count) { assert(row_count > 0); assert(column_count > 0); size_t r = cg::clamp(row + 1, size_t(0), row_count); size_t c = cg::clamp(column, size_t(0), column_count); return r * (row_count + 1) + c; } size_t bottom_right_index(size_t row, size_t column, size_t row_count, size_t column_count) { assert(row_count > 0); assert(column_count > 0); size_t r = cg::clamp(row + 1, size_t(0), row_count); size_t c = cg::clamp(column + 1, size_t(0), column_count); return r * (row_count + 1) + c; } size_t top_left_index(size_t row, size_t column, size_t row_count, size_t column_count) { assert(row_count > 0); assert(column_count > 0); size_t r = cg::clamp(row, size_t(0), row_count); size_t c = cg::clamp(column, size_t(0), column_count); return r * (row_count + 1) + c; } size_t top_right_index(size_t row, size_t column, size_t row_count, size_t column_count) { assert(row_count > 0); assert(column_count > 0); size_t r = cg::clamp(row, size_t(0), row_count); size_t c = cg::clamp(column + 1, size_t(0), column_count); return r * (row_count + 1) + c; } class Terrain_model final { public: Terrain_model(const uint2& cell_count); Terrain_model(const Terrain_model&) = delete; Terrain_model(Terrain_model&&) = delete; Terrain_model& operator=(const Terrain_model) = delete; Terrain_model& operator=(Terrain_model&&) = delete; const std::vector<float>& vertex_attribs() const noexcept { return _vertex_attribs; } const std::vector<uint32_t>& indices() const noexcept { return _indices; } private: // each vertex has position(float3) and tex_coord(float2) -> 5 components per vertex. static constexpr size_t vertex_component_count = 5; void init_vertex_attribs(const uint2& cell_count); void init_indices(const uint2& cell_count); std::vector<float> _vertex_attribs; std::vector<uint32_t> _indices; size_t _vertex_count = 0; }; Terrain_model::Terrain_model(const uint2& cell_count) : _vertex_count((cell_count.x + 1) * (cell_count.y + 1)) { assert(greater_than(cell_count, 0)); _vertex_attribs.reserve(_vertex_count * Terrain_model::vertex_component_count); _indices.resize(6 * cell_count.square()); init_vertex_attribs(cell_count); } void Terrain_model::init_vertex_attribs(const uint2& cell_count) { // positions are in range [(-0.5f, 0.0f, -0.5f), (0.5f, 0.0f, 0.5f)] // tex_coords are in range [(0.0, 0.0), (1.0, 1.0)] const size_t horz_coord_count = cell_count.width + 1; const size_t depth_coord_count = cell_count.height + 1; for (size_t z = 0; z < depth_coord_count; ++z) { const float z_coord = float(z) / cell_count.height; for (size_t x = 0; x < horz_coord_count; ++x) { const float x_coord = float(x) / cell_count.width; const float vert[Terrain_model::vertex_component_count] = { x_coord - 0.5f, 0.0f, z_coord - 0.5f, // position x_coord, z_coord // tex_coord }; _vertex_attribs.insert(_vertex_attribs.cend(), vert, vert + Terrain_model::vertex_component_count); } } for (size_t r = 0; r < cell_count.height; ++r) { for (size_t c = 0; c < cell_count.width; ++c) { std::cout << "[" << r << ", " << c << "] "; std::cout << bottom_left_index(r, c, cell_count.width, cell_count.height) << " " << bottom_right_index(r, c, horz_coord_count, depth_coord_count) << " " << top_right_index(r, c, horz_coord_count, depth_coord_count) << " " << top_left_index(r, c, horz_coord_count, depth_coord_count) << " "; } std::cout << std::endl; } } } // namespace namespace learn_dx11 { namespace tess { // ----- Terrain_tessellation_example ----- Terrain_tessellation_example::Terrain_tessellation_example(Render_context& rnd_ctx) : Example(rnd_ctx) { Terrain_model terrain_model(uint2(3, 2)); } void Terrain_tessellation_example::on_viewport_resize(const uint2& viewport_size) { } void Terrain_tessellation_example::render() { } } // namespace tess } // namespace learn_dx11 <commit_msg>tesselatin example Terrain_model building<commit_after>#include "learn_dx11/tess/terrain_tessellation_example.h" #include <cassert> #include <iostream> #include <iterator> #include <vector> using namespace cg; namespace { class Vertex_index_helper final { public: Vertex_index_helper(size_t row_count, size_t column_count) noexcept : _row_count(int64_t(row_count)), _column_count(int64_t(column_count)) { assert(row_count > 0); assert(column_count > 0); } uint32_t bottom_left_index(int64_t row, int64_t column) noexcept { int64_t r = cg::clamp(row, int64_t(0), _row_count); int64_t c = cg::clamp(column, int64_t(0), _column_count); return uint32_t(r * _row_count + c); } uint32_t bottom_right_index(int64_t row, int64_t column) noexcept { int64_t r = cg::clamp(row, int64_t(0), _row_count); int64_t c = cg::clamp(column + 1, int64_t(0), _column_count); return uint32_t(r * _row_count + c); } uint32_t top_left_index(int64_t row, int64_t column) noexcept { int64_t r = cg::clamp(row + 1, int64_t(0), _row_count); int64_t c = cg::clamp(column, int64_t(0), _column_count); return uint32_t(r * _row_count + c); } uint32_t top_right_index(int64_t row, int64_t column) noexcept { int64_t r = cg::clamp(row + 1, int64_t(0), _row_count); int64_t c = cg::clamp(column + 1, int64_t(0), _column_count); return uint32_t(r * _row_count + c); } private: int64_t _row_count = 0; int64_t _column_count = 0; }; struct Terrain_model final { // each vertex has position(float3) and tex_coord(float2) std::vector<float> vertex_attribs; // 12 indices for each patch. // 4 stands for the cell itselft (bottom left, bottom right, top left, top right) // 2 - left cell (bottom left, top left) // 2 - bottom cell (bottom left, bottom right) // 2 - right cell (bottom right, top right) // 2 - top cell (top left, top right) std::vector<uint32_t> indices; size_t patch_count = 0; }; Terrain_model make_terrain_model(size_t z_cell_count, size_t x_cell_count) { assert(z_cell_count > 0); assert(x_cell_count > 0); // each vertex has position(float3) and tex_coord(float2) -> 5 components per vertex. constexpr size_t vertex_component_count = 5; constexpr size_t patch_index_count = 12; const size_t expected_vertex_attrib_count = (z_cell_count + 1) * (x_cell_count + 1) * vertex_component_count; const size_t expected_index_count = z_cell_count * x_cell_count * patch_index_count; Terrain_model model; model.vertex_attribs.reserve(expected_vertex_attrib_count); model.indices.reserve(expected_index_count); model.patch_count = z_cell_count * x_cell_count; // ----- vertices ----- // positions are in range [(-0.5f, 0.0f, -0.5f), (0.5f, 0.0f, 0.5f)] // tex_coords are in range [(0.0, 0.0), (1.0, 1.0)] // bottom-left position of the grid is (-0.5f, 0.0f, 0.5f) tex_coords [0.0f, 0.0f] // top-right position of the grid is (0.5f, 0.0f, -0.5f) tex_coords [1.0f, 1.0f] const size_t z_coord_count = z_cell_count + 1; const size_t x_coord_count = x_cell_count + 1; for (size_t z = z_coord_count; z > 0; --z) { const float z_coord = float(z - 1) / z_cell_count; for (size_t x = 0; x < x_coord_count; ++x) { const float x_coord = float(x) / x_cell_count; const float vert[vertex_component_count] = { x_coord - 0.5f, 0.0f, z_coord - 0.5f, // position x_coord, 1.0f - z_coord // tex_coord }; model.vertex_attribs.insert(model.vertex_attribs.cend(), vert, vert + vertex_component_count); } } // ----- patch indices ----- Vertex_index_helper index_helper(z_cell_count, x_cell_count); for (int64_t r = 0; r < z_cell_count; ++r) { for (int64_t c = 0; c < x_cell_count; ++c) { //std::cout << std::endl << "<" << r << ", " << c << ">" << std::endl << std::endl; uint32_t patch_indices[patch_index_count]; patch_indices[0] = index_helper.bottom_left_index(r, c); patch_indices[1] = index_helper.bottom_right_index(r, c); patch_indices[2] = index_helper.top_left_index(r, c); patch_indices[3] = index_helper.top_right_index(r, c); // left cell: patch_indices[4] = index_helper.bottom_left_index(r, c - 1); patch_indices[5] = index_helper.top_left_index(r, c - 1); // bottom cell: patch_indices[6] = index_helper.bottom_left_index(r - 1, c); patch_indices[7] = index_helper.bottom_right_index(r - 1, c); // right cell: patch_indices[8] = index_helper.bottom_right_index(r, c + 1); patch_indices[9] = index_helper.top_right_index(r, c + 1); // top cell: patch_indices[10] = index_helper.top_left_index(r + 1, c); patch_indices[11] = index_helper.top_right_index(r + 1, c); model.indices.insert(model.indices.cend(), patch_indices, patch_indices + patch_index_count); //std::cout << patch_indices[0] << " " << patch_indices[1] << " " // << patch_indices[2] << " " << patch_indices[3] << " " << std::endl; //std::cout << "left:\t" << patch_indices[4] << " " << patch_indices[5] << std::endl; //std::cout << "bottom:\t" << patch_indices[6] << " " << patch_indices[7] << std::endl; //std::cout << "right:\t" << patch_indices[8] << " " << patch_indices[9] << std::endl; //std::cout << "top: \t" << patch_indices[10] << " " << patch_indices[11] << std::endl; } std::cout << std::endl; } assert(model.vertex_attribs.size() == expected_vertex_attrib_count); assert(model.indices.size() == expected_index_count); return model; } } // namespace namespace learn_dx11 { namespace tess { // ----- Terrain_tessellation_example ----- Terrain_tessellation_example::Terrain_tessellation_example(Render_context& rnd_ctx) : Example(rnd_ctx) { Terrain_model terrain_model = make_terrain_model(3, 2); } void Terrain_tessellation_example::on_viewport_resize(const uint2& viewport_size) { } void Terrain_tessellation_example::render() { } } // namespace tess } // namespace learn_dx11 <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2009 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/machine/LinearMachine.h> #include <shogun/labels/RegressionLabels.h> #include <shogun/features/DotFeatures.h> #include <shogun/labels/Labels.h> #include <shogun/mathematics/eigen3.h> using namespace shogun; using namespace Eigen; CLinearMachine::CLinearMachine(): CMachine() { init(); } CLinearMachine::CLinearMachine(bool compute_bias): CMachine() { init(); m_compute_bias = compute_bias; } CLinearMachine::CLinearMachine(CLinearMachine* machine) : CMachine() { init(); set_w(machine->get_w().clone()); set_bias(machine->get_bias()); } void CLinearMachine::init() { bias = 0; features = NULL; m_compute_bias = true; SG_ADD(&w, "w", "Parameter vector w.", MS_NOT_AVAILABLE); SG_ADD(&bias, "bias", "Bias b.", MS_NOT_AVAILABLE); SG_ADD((CSGObject**) &features, "features", "Feature object.", MS_NOT_AVAILABLE); } CLinearMachine::~CLinearMachine() { SG_UNREF(features); } float64_t CLinearMachine::apply_one(int32_t vec_idx) { return features->dense_dot(vec_idx, w.vector, w.vlen) + bias; } CRegressionLabels* CLinearMachine::apply_regression(CFeatures* data) { SGVector<float64_t> outputs = apply_get_outputs(data); return new CRegressionLabels(outputs); } CBinaryLabels* CLinearMachine::apply_binary(CFeatures* data) { SGVector<float64_t> outputs = apply_get_outputs(data); return new CBinaryLabels(outputs); } SGVector<float64_t> CLinearMachine::apply_get_outputs(CFeatures* data) { if (data) { if (!data->has_property(FP_DOT)) SG_ERROR("Specified features are not of type CDotFeatures\n") set_features((CDotFeatures*) data); } if (!features) return SGVector<float64_t>(); int32_t num=features->get_num_vectors(); ASSERT(num>0) ASSERT(w.vlen==features->get_dim_feature_space()) float64_t* out=SG_MALLOC(float64_t, num); features->dense_dot_range(out, 0, num, NULL, w.vector, w.vlen, bias); return SGVector<float64_t>(out,num); } SGVector<float64_t> CLinearMachine::get_w() const { return w; } void CLinearMachine::set_w(const SGVector<float64_t> src_w) { w=src_w; } void CLinearMachine::set_bias(float64_t b) { bias=b; } float64_t CLinearMachine::get_bias() { return bias; } void CLinearMachine::set_compute_bias(bool compute_bias) { m_compute_bias = compute_bias; } bool CLinearMachine::get_compute_bias() { return m_compute_bias; } void CLinearMachine::set_features(CDotFeatures* feat) { SG_REF(feat); SG_UNREF(features); features=feat; } CDotFeatures* CLinearMachine::get_features() { SG_REF(features); return features; } void CLinearMachine::store_model_features() { } void CLinearMachine::compute_bias(CFeatures* data) { REQUIRE(m_labels,"No labels set\n"); if (!data) data=features; REQUIRE(data,"No features provided and no featured previously set\n"); REQUIRE(m_labels->get_num_labels() == data->get_num_vectors(), "Number of training vectors (%d) does not match number of labels (%d)\n", m_labels->get_num_labels(), data->get_num_vectors()); SGVector<float64_t> outputs = apply_get_outputs(data); int32_t num_vec=data->get_num_vectors(); Map<VectorXd> eigen_outputs(outputs,num_vec); Map<VectorXd> eigen_labels(((CRegressionLabels*)m_labels)->get_labels(),num_vec); set_bias((eigen_labels - eigen_outputs).mean()) ; } bool CLinearMachine::train(CFeatures* data) { /* not allowed to train on locked data */ if (m_data_locked) { SG_ERROR("train data_lock() was called, only train_locked() is" " possible. Call data_unlock if you want to call train()\n", get_name()); } if (train_require_labels()) { REQUIRE(m_labels,"No labels given",this->get_name()); m_labels->ensure_valid(get_name()); } bool result = train_machine(data); if(m_compute_bias) compute_bias(data); return result; }<commit_msg>rename params to avoid warnings<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 1999-2009 Soeren Sonnenburg * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/machine/LinearMachine.h> #include <shogun/labels/RegressionLabels.h> #include <shogun/features/DotFeatures.h> #include <shogun/labels/Labels.h> #include <shogun/mathematics/eigen3.h> using namespace shogun; using namespace Eigen; CLinearMachine::CLinearMachine(): CMachine() { init(); } CLinearMachine::CLinearMachine(bool comput_bias): CMachine() { init(); set_compute_bias(comput_bias); } CLinearMachine::CLinearMachine(CLinearMachine* machine) : CMachine() { init(); set_w(machine->get_w().clone()); set_bias(machine->get_bias()); set_compute_bias(machine->get_compute_bias()); } void CLinearMachine::init() { bias = 0; features = NULL; m_compute_bias = true; SG_ADD(&w, "w", "Parameter vector w.", MS_NOT_AVAILABLE); SG_ADD(&bias, "bias", "Bias b.", MS_NOT_AVAILABLE); SG_ADD((CSGObject**) &features, "features", "Feature object.", MS_NOT_AVAILABLE); } CLinearMachine::~CLinearMachine() { SG_UNREF(features); } float64_t CLinearMachine::apply_one(int32_t vec_idx) { return features->dense_dot(vec_idx, w.vector, w.vlen) + bias; } CRegressionLabels* CLinearMachine::apply_regression(CFeatures* data) { SGVector<float64_t> outputs = apply_get_outputs(data); return new CRegressionLabels(outputs); } CBinaryLabels* CLinearMachine::apply_binary(CFeatures* data) { SGVector<float64_t> outputs = apply_get_outputs(data); return new CBinaryLabels(outputs); } SGVector<float64_t> CLinearMachine::apply_get_outputs(CFeatures* data) { if (data) { if (!data->has_property(FP_DOT)) SG_ERROR("Specified features are not of type CDotFeatures\n") set_features((CDotFeatures*) data); } if (!features) return SGVector<float64_t>(); int32_t num=features->get_num_vectors(); ASSERT(num>0) ASSERT(w.vlen==features->get_dim_feature_space()) float64_t* out=SG_MALLOC(float64_t, num); features->dense_dot_range(out, 0, num, NULL, w.vector, w.vlen, bias); return SGVector<float64_t>(out,num); } SGVector<float64_t> CLinearMachine::get_w() const { return w; } void CLinearMachine::set_w(const SGVector<float64_t> src_w) { w=src_w; } void CLinearMachine::set_bias(float64_t b) { bias=b; } float64_t CLinearMachine::get_bias() { return bias; } void CLinearMachine::set_compute_bias(bool comput_bias) { m_compute_bias = comput_bias; } bool CLinearMachine::get_compute_bias() { return m_compute_bias; } void CLinearMachine::set_features(CDotFeatures* feat) { SG_REF(feat); SG_UNREF(features); features=feat; } CDotFeatures* CLinearMachine::get_features() { SG_REF(features); return features; } void CLinearMachine::store_model_features() { } void CLinearMachine::compute_bias(CFeatures* data) { REQUIRE(m_labels,"No labels set\n"); if (!data) data=features; REQUIRE(data,"No features provided and no featured previously set\n"); REQUIRE(m_labels->get_num_labels() == data->get_num_vectors(), "Number of training vectors (%d) does not match number of labels (%d)\n", m_labels->get_num_labels(), data->get_num_vectors()); SGVector<float64_t> outputs = apply_get_outputs(data); int32_t num_vec=data->get_num_vectors(); Map<VectorXd> eigen_outputs(outputs,num_vec); Map<VectorXd> eigen_labels(((CRegressionLabels*)m_labels)->get_labels(),num_vec); set_bias((eigen_labels - eigen_outputs).mean()) ; } bool CLinearMachine::train(CFeatures* data) { /* not allowed to train on locked data */ if (m_data_locked) { SG_ERROR("train data_lock() was called, only train_locked() is" " possible. Call data_unlock if you want to call train()\n", get_name()); } if (train_require_labels()) { REQUIRE(m_labels,"No labels given",this->get_name()); m_labels->ensure_valid(get_name()); } bool result = train_machine(data); if(m_compute_bias) compute_bias(data); return result; }<|endoftext|>
<commit_before>// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef WIN32 #include "../backends/arb/ShArb.hpp" #endif /* WIN32 */ namespace SH { void ShInit(void) { static SH::ShRefCount<ShArb::ArbBackend> instance = new ShArb::ArbBackend(); } } <commit_msg>ifdef's for WIN32 only code...<commit_after>// Sh: A GPU metaprogramming language. // // Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory // Project administrator: Michael D. McCool // Authors: Zheng Qin, Stefanus Du Toit, Kevin Moule, Tiberiu S. Popa, // Michael D. McCool // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must // not claim that you wrote the original software. If you use this // software in a product, an acknowledgment in the product documentation // would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must // not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. ////////////////////////////////////////////////////////////////////////////// #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef WIN32 #include "../backends/arb/ShArb.hpp" #endif /* WIN32 */ namespace SH { void ShInit(void) { #ifdef WIN32 static SH::ShRefCount<ShArb::ArbBackend> instance = new ShArb::ArbBackend(); #endif /* WIN32 */ } } <|endoftext|>
<commit_before>// Include GLGizmoBase.hpp before I18N.hpp as it includes some libigl code, which overrides our localization "L" macro. #include "GLGizmoCut.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include <GL/glew.h> #include <wx/button.h> #include <wx/checkbox.h> #include <wx/stattext.h> #include <wx/sizer.h> #include <algorithm> #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/GUI_ObjectManipulation.hpp" #include "libslic3r/AppConfig.hpp" namespace Slic3r { namespace GUI { const double GLGizmoCut::Offset = 10.0; const double GLGizmoCut::Margin = 20.0; const std::array<float, 4> GLGizmoCut::GrabberColor = { 1.0, 0.5, 0.0, 1.0 }; GLGizmoCut::GLGizmoCut(GLCanvas3D& parent, const std::string& icon_filename, unsigned int sprite_id) : GLGizmoBase(parent, icon_filename, sprite_id) , m_cut_z(0.0) , m_max_z(0.0) , m_keep_upper(true) , m_keep_lower(true) , m_rotate_lower(false) {} std::string GLGizmoCut::get_tooltip() const { double cut_z = m_cut_z; if (wxGetApp().app_config->get("use_inches") == "1") cut_z *= ObjectManipulation::mm_to_in; return (m_hover_id == 0 || m_grabbers[0].dragging) ? "Z: " + format(cut_z, 2) : ""; } bool GLGizmoCut::on_init() { m_grabbers.emplace_back(); m_shortcut_key = WXK_CONTROL_C; return true; } std::string GLGizmoCut::on_get_name() const { return (_(L("Cut")) + " [C]").ToUTF8().data(); } void GLGizmoCut::on_set_state() { // Reset m_cut_z on gizmo activation if (get_state() == On) { m_cut_z = m_parent.get_selection().get_bounding_box().size()(2) / 2.0; } } bool GLGizmoCut::on_is_activable() const { const Selection& selection = m_parent.get_selection(); return selection.is_single_full_instance() && !selection.is_wipe_tower(); } void GLGizmoCut::on_start_dragging() { if (m_hover_id == -1) return; const Selection& selection = m_parent.get_selection(); const BoundingBoxf3& box = selection.get_bounding_box(); m_start_z = m_cut_z; update_max_z(selection); m_drag_pos = m_grabbers[m_hover_id].center; m_drag_center = box.center(); m_drag_center(2) = m_cut_z; } void GLGizmoCut::on_update(const UpdateData& data) { if (m_hover_id != -1) { set_cut_z(m_start_z + calc_projection(data.mouse_ray)); } } void GLGizmoCut::on_render() const { const Selection& selection = m_parent.get_selection(); update_max_z(selection); const BoundingBoxf3& box = selection.get_bounding_box(); Vec3d plane_center = box.center(); plane_center(2) = m_cut_z; const float min_x = box.min(0) - Margin; const float max_x = box.max(0) + Margin; const float min_y = box.min(1) - Margin; const float max_y = box.max(1) + Margin; glsafe(::glEnable(GL_DEPTH_TEST)); glsafe(::glDisable(GL_CULL_FACE)); glsafe(::glEnable(GL_BLEND)); glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); // Draw the cutting plane ::glBegin(GL_QUADS); ::glColor4f(0.8f, 0.8f, 0.8f, 0.5f); ::glVertex3f(min_x, min_y, plane_center(2)); ::glVertex3f(max_x, min_y, plane_center(2)); ::glVertex3f(max_x, max_y, plane_center(2)); ::glVertex3f(min_x, max_y, plane_center(2)); glsafe(::glEnd()); glsafe(::glEnable(GL_CULL_FACE)); glsafe(::glDisable(GL_BLEND)); // TODO: draw cut part contour? // Draw the grabber and the connecting line m_grabbers[0].center = plane_center; m_grabbers[0].center(2) = plane_center(2) + Offset; glsafe(::glDisable(GL_DEPTH_TEST)); glsafe(::glLineWidth(m_hover_id != -1 ? 2.0f : 1.5f)); glsafe(::glColor3f(1.0, 1.0, 0.0)); ::glBegin(GL_LINES); ::glVertex3dv(plane_center.data()); ::glVertex3dv(m_grabbers[0].center.data()); glsafe(::glEnd()); std::copy(std::begin(GrabberColor), std::end(GrabberColor), m_grabbers[0].color); m_grabbers[0].render(m_hover_id == 0, (float)((box.size()(0) + box.size()(1) + box.size()(2)) / 3.0)); } void GLGizmoCut::on_render_for_picking() const { glsafe(::glDisable(GL_DEPTH_TEST)); render_grabbers_for_picking(m_parent.get_selection().get_bounding_box()); } void GLGizmoCut::on_render_input_window(float x, float y, float bottom_limit) { static float last_y = 0.0f; static float last_h = 0.0f; m_imgui->begin(_(L("Cut")), ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); bool imperial_units = wxGetApp().app_config->get("use_inches") == "1"; // adjust window position to avoid overlap the view toolbar float win_h = ImGui::GetWindowHeight(); y = std::min(y, bottom_limit - win_h); ImGui::SetWindowPos(ImVec2(x, y), ImGuiCond_Always); if ((last_h != win_h) || (last_y != y)) { // ask canvas for another frame to render the window in the correct position m_parent.request_extra_frame(); if (last_h != win_h) last_h = win_h; if (last_y != y) last_y = y; } ImGui::AlignTextToFramePadding(); m_imgui->text("Z"); ImGui::SameLine(); ImGui::PushItemWidth(m_imgui->get_style_scaling() * 150.0f); double cut_z = m_cut_z; if (imperial_units) cut_z *= ObjectManipulation::mm_to_in; ImGui::InputDouble("", &cut_z, 0.0f, 0.0f, "%.2f"); ImGui::SameLine(); m_imgui->text(imperial_units ? _L("in") : _L("mm")); m_cut_z = cut_z * (imperial_units ? ObjectManipulation::in_to_mm : 1.0); ImGui::Separator(); m_imgui->checkbox(_(L("Keep upper part")), m_keep_upper); m_imgui->checkbox(_(L("Keep lower part")), m_keep_lower); m_imgui->checkbox(_(L("Rotate lower part upwards")), m_rotate_lower); ImGui::Separator(); m_imgui->disabled_begin(!m_keep_upper && !m_keep_lower); const bool cut_clicked = m_imgui->button(_(L("Perform cut"))); m_imgui->disabled_end(); m_imgui->end(); if (cut_clicked && (m_keep_upper || m_keep_lower)) { perform_cut(m_parent.get_selection()); } } void GLGizmoCut::update_max_z(const Selection& selection) const { m_max_z = selection.get_bounding_box().size()(2); set_cut_z(m_cut_z); } void GLGizmoCut::set_cut_z(double cut_z) const { // Clamp the plane to the object's bounding box m_cut_z = std::clamp(cut_z, 0.0, m_max_z); } void GLGizmoCut::perform_cut(const Selection& selection) { const int instance_idx = selection.get_instance_idx(); const int object_idx = selection.get_object_idx(); wxCHECK_RET(instance_idx >= 0 && object_idx >= 0, "GLGizmoCut: Invalid object selection"); // m_cut_z is the distance from the bed. Subtract possible SLA elevation. const GLVolume* first_glvolume = selection.get_volume(*selection.get_volume_idxs().begin()); coordf_t object_cut_z = m_cut_z - first_glvolume->get_sla_shift_z(); if (object_cut_z > 0.) wxGetApp().plater()->cut(object_idx, instance_idx, object_cut_z, m_keep_upper, m_keep_lower, m_rotate_lower); else { // the object is SLA-elevated and the plane is under it. } } double GLGizmoCut::calc_projection(const Linef3& mouse_ray) const { double projection = 0.0; const Vec3d starting_vec = m_drag_pos - m_drag_center; const double len_starting_vec = starting_vec.norm(); if (len_starting_vec != 0.0) { Vec3d mouse_dir = mouse_ray.unit_vector(); // finds the intersection of the mouse ray with the plane parallel to the camera viewport and passing throught the starting position // use ray-plane intersection see i.e. https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection algebric form // in our case plane normal and ray direction are the same (orthogonal view) // when moving to perspective camera the negative z unit axis of the camera needs to be transformed in world space and used as plane normal Vec3d inters = mouse_ray.a + (m_drag_pos - mouse_ray.a).dot(mouse_dir) / mouse_dir.squaredNorm() * mouse_dir; // vector from the starting position to the found intersection Vec3d inters_vec = inters - m_drag_pos; // finds projection of the vector along the staring direction projection = inters_vec.dot(starting_vec.normalized()); } return projection; } } // namespace GUI } // namespace Slic3r <commit_msg>Disable [Perform cut] button in Cut Gizmo dialog when the value of Z is not valid<commit_after>// Include GLGizmoBase.hpp before I18N.hpp as it includes some libigl code, which overrides our localization "L" macro. #include "GLGizmoCut.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include <GL/glew.h> #include <wx/button.h> #include <wx/checkbox.h> #include <wx/stattext.h> #include <wx/sizer.h> #include <algorithm> #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/GUI_ObjectManipulation.hpp" #include "libslic3r/AppConfig.hpp" namespace Slic3r { namespace GUI { const double GLGizmoCut::Offset = 10.0; const double GLGizmoCut::Margin = 20.0; const std::array<float, 4> GLGizmoCut::GrabberColor = { 1.0, 0.5, 0.0, 1.0 }; GLGizmoCut::GLGizmoCut(GLCanvas3D& parent, const std::string& icon_filename, unsigned int sprite_id) : GLGizmoBase(parent, icon_filename, sprite_id) , m_cut_z(0.0) , m_max_z(0.0) , m_keep_upper(true) , m_keep_lower(true) , m_rotate_lower(false) {} std::string GLGizmoCut::get_tooltip() const { double cut_z = m_cut_z; if (wxGetApp().app_config->get("use_inches") == "1") cut_z *= ObjectManipulation::mm_to_in; return (m_hover_id == 0 || m_grabbers[0].dragging) ? "Z: " + format(cut_z, 2) : ""; } bool GLGizmoCut::on_init() { m_grabbers.emplace_back(); m_shortcut_key = WXK_CONTROL_C; return true; } std::string GLGizmoCut::on_get_name() const { return (_(L("Cut")) + " [C]").ToUTF8().data(); } void GLGizmoCut::on_set_state() { // Reset m_cut_z on gizmo activation if (get_state() == On) { m_cut_z = m_parent.get_selection().get_bounding_box().size()(2) / 2.0; } } bool GLGizmoCut::on_is_activable() const { const Selection& selection = m_parent.get_selection(); return selection.is_single_full_instance() && !selection.is_wipe_tower(); } void GLGizmoCut::on_start_dragging() { if (m_hover_id == -1) return; const Selection& selection = m_parent.get_selection(); const BoundingBoxf3& box = selection.get_bounding_box(); m_start_z = m_cut_z; update_max_z(selection); m_drag_pos = m_grabbers[m_hover_id].center; m_drag_center = box.center(); m_drag_center(2) = m_cut_z; } void GLGizmoCut::on_update(const UpdateData& data) { if (m_hover_id != -1) set_cut_z(m_start_z + calc_projection(data.mouse_ray)); } void GLGizmoCut::on_render() const { const Selection& selection = m_parent.get_selection(); update_max_z(selection); const BoundingBoxf3& box = selection.get_bounding_box(); Vec3d plane_center = box.center(); plane_center(2) = m_cut_z; const float min_x = box.min(0) - Margin; const float max_x = box.max(0) + Margin; const float min_y = box.min(1) - Margin; const float max_y = box.max(1) + Margin; glsafe(::glEnable(GL_DEPTH_TEST)); glsafe(::glDisable(GL_CULL_FACE)); glsafe(::glEnable(GL_BLEND)); glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); // Draw the cutting plane ::glBegin(GL_QUADS); ::glColor4f(0.8f, 0.8f, 0.8f, 0.5f); ::glVertex3f(min_x, min_y, plane_center(2)); ::glVertex3f(max_x, min_y, plane_center(2)); ::glVertex3f(max_x, max_y, plane_center(2)); ::glVertex3f(min_x, max_y, plane_center(2)); glsafe(::glEnd()); glsafe(::glEnable(GL_CULL_FACE)); glsafe(::glDisable(GL_BLEND)); // TODO: draw cut part contour? // Draw the grabber and the connecting line m_grabbers[0].center = plane_center; m_grabbers[0].center(2) = plane_center(2) + Offset; glsafe(::glDisable(GL_DEPTH_TEST)); glsafe(::glLineWidth(m_hover_id != -1 ? 2.0f : 1.5f)); glsafe(::glColor3f(1.0, 1.0, 0.0)); ::glBegin(GL_LINES); ::glVertex3dv(plane_center.data()); ::glVertex3dv(m_grabbers[0].center.data()); glsafe(::glEnd()); std::copy(std::begin(GrabberColor), std::end(GrabberColor), m_grabbers[0].color); m_grabbers[0].render(m_hover_id == 0, (float)((box.size()(0) + box.size()(1) + box.size()(2)) / 3.0)); } void GLGizmoCut::on_render_for_picking() const { glsafe(::glDisable(GL_DEPTH_TEST)); render_grabbers_for_picking(m_parent.get_selection().get_bounding_box()); } void GLGizmoCut::on_render_input_window(float x, float y, float bottom_limit) { static float last_y = 0.0f; static float last_h = 0.0f; m_imgui->begin(_L("Cut"), ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse); bool imperial_units = wxGetApp().app_config->get("use_inches") == "1"; // adjust window position to avoid overlap the view toolbar float win_h = ImGui::GetWindowHeight(); y = std::min(y, bottom_limit - win_h); ImGui::SetWindowPos(ImVec2(x, y), ImGuiCond_Always); if (last_h != win_h || last_y != y) { // ask canvas for another frame to render the window in the correct position m_parent.request_extra_frame(); if (last_h != win_h) last_h = win_h; if (last_y != y) last_y = y; } ImGui::AlignTextToFramePadding(); m_imgui->text("Z"); ImGui::SameLine(); ImGui::PushItemWidth(m_imgui->get_style_scaling() * 150.0f); double cut_z = m_cut_z; if (imperial_units) cut_z *= ObjectManipulation::mm_to_in; ImGui::InputDouble("", &cut_z, 0.0f, 0.0f, "%.2f"); ImGui::SameLine(); m_imgui->text(imperial_units ? _L("in") : _L("mm")); m_cut_z = cut_z * (imperial_units ? ObjectManipulation::in_to_mm : 1.0); ImGui::Separator(); m_imgui->checkbox(_L("Keep upper part"), m_keep_upper); m_imgui->checkbox(_L("Keep lower part"), m_keep_lower); m_imgui->checkbox(_L("Rotate lower part upwards"), m_rotate_lower); ImGui::Separator(); m_imgui->disabled_begin((!m_keep_upper && !m_keep_lower) || m_cut_z <= 0.0 || m_max_z < m_cut_z); const bool cut_clicked = m_imgui->button(_L("Perform cut")); m_imgui->disabled_end(); m_imgui->end(); if (cut_clicked && (m_keep_upper || m_keep_lower)) perform_cut(m_parent.get_selection()); } void GLGizmoCut::update_max_z(const Selection& selection) const { m_max_z = selection.get_bounding_box().size()(2); set_cut_z(m_cut_z); } void GLGizmoCut::set_cut_z(double cut_z) const { // Clamp the plane to the object's bounding box m_cut_z = std::clamp(cut_z, 0.0, m_max_z); } void GLGizmoCut::perform_cut(const Selection& selection) { const int instance_idx = selection.get_instance_idx(); const int object_idx = selection.get_object_idx(); wxCHECK_RET(instance_idx >= 0 && object_idx >= 0, "GLGizmoCut: Invalid object selection"); // m_cut_z is the distance from the bed. Subtract possible SLA elevation. const GLVolume* first_glvolume = selection.get_volume(*selection.get_volume_idxs().begin()); coordf_t object_cut_z = m_cut_z - first_glvolume->get_sla_shift_z(); if (object_cut_z > 0.) wxGetApp().plater()->cut(object_idx, instance_idx, object_cut_z, m_keep_upper, m_keep_lower, m_rotate_lower); else { // the object is SLA-elevated and the plane is under it. } } double GLGizmoCut::calc_projection(const Linef3& mouse_ray) const { double projection = 0.0; const Vec3d starting_vec = m_drag_pos - m_drag_center; const double len_starting_vec = starting_vec.norm(); if (len_starting_vec != 0.0) { Vec3d mouse_dir = mouse_ray.unit_vector(); // finds the intersection of the mouse ray with the plane parallel to the camera viewport and passing throught the starting position // use ray-plane intersection see i.e. https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection algebric form // in our case plane normal and ray direction are the same (orthogonal view) // when moving to perspective camera the negative z unit axis of the camera needs to be transformed in world space and used as plane normal Vec3d inters = mouse_ray.a + (m_drag_pos - mouse_ray.a).dot(mouse_dir) / mouse_dir.squaredNorm() * mouse_dir; // vector from the starting position to the found intersection Vec3d inters_vec = inters - m_drag_pos; // finds projection of the vector along the staring direction projection = inters_vec.dot(starting_vec.normalized()); } return projection; } } // namespace GUI } // namespace Slic3r <|endoftext|>
<commit_before>/* ########## Copyright (C) 2015 Vincenzo Pacella ## ## Distributed under MIT license, see file LICENSE ## ## or <http://opensource.org/licenses/MIT> ## ## ########## ############################################################# shaduzlabs.com #####*/ #include <boost/python.hpp> using namespace boost::python; #include "cabl.h" namespace sl { namespace cabl { using namespace boost::python; //-------------------------------------------------------------------------------------------------- template <class T> boost::python::list toPythonList(std::vector<T> vector) { typename std::vector<T>::iterator iter; boost::python::list list; for (iter = vector.begin(); iter != vector.end(); ++iter) { list.append(*iter); } return list; } //-------------------------------------------------------------------------------------------------- struct NullDeleter { void operator()(const void*){} }; //-------------------------------------------------------------------------------------------------- std::shared_ptr<DeviceFactory> deviceFactory() { return std::shared_ptr<DeviceFactory>( &DeviceFactory::instance(), NullDeleter() ); } list enumerateDevices() { return toPythonList(ClientSingle::enumerateDevices()); } //-------------------------------------------------------------------------------------------------- void onPadChanged(PyObject* callable, Device::Pad pad_, uint16_t val_, bool shiftKey_) { // Invoke callable, passing a Python object which holds a reference to x boost::python::call<void>(callable, pad_, val_, shiftKey_); } BOOST_PYTHON_MODULE(pycabl) { enum_<DeviceDescriptor::Type>("DeviceDescriptorType") .value("USB", DeviceDescriptor::Type::USB) .value("MIDI", DeviceDescriptor::Type::MIDI) .value("HID", DeviceDescriptor::Type::HID) .value("Unknown", DeviceDescriptor::Type::Unknown) ; #define M_PAD_CASE(nPad) value("Pad1##nPad", Device::Pad::Pad##nPad) enum_<Device::Pad>("Pad") .M_PAD_CASE( 1).M_PAD_CASE( 2).M_PAD_CASE( 3).M_PAD_CASE( 4) .M_PAD_CASE( 5).M_PAD_CASE( 6).M_PAD_CASE( 7).M_PAD_CASE( 8) .M_PAD_CASE( 9).M_PAD_CASE(10).M_PAD_CASE(11).M_PAD_CASE(12) .M_PAD_CASE(13).M_PAD_CASE(14).M_PAD_CASE(15).M_PAD_CASE(16) .M_PAD_CASE(17).M_PAD_CASE(18).M_PAD_CASE(19).M_PAD_CASE(20) .M_PAD_CASE(21).M_PAD_CASE(22).M_PAD_CASE(23).M_PAD_CASE(24) .M_PAD_CASE(25).M_PAD_CASE(26).M_PAD_CASE(27).M_PAD_CASE(28) .M_PAD_CASE(29).M_PAD_CASE(30).M_PAD_CASE(31).M_PAD_CASE(32) .M_PAD_CASE(33).M_PAD_CASE(34).M_PAD_CASE(35).M_PAD_CASE(36) .M_PAD_CASE(37).M_PAD_CASE(38).M_PAD_CASE(39).M_PAD_CASE(40) .M_PAD_CASE(41).M_PAD_CASE(42).M_PAD_CASE(43).M_PAD_CASE(44) .M_PAD_CASE(45).M_PAD_CASE(46).M_PAD_CASE(47).M_PAD_CASE(48) .M_PAD_CASE(49).M_PAD_CASE(50).M_PAD_CASE(51).M_PAD_CASE(52) .M_PAD_CASE(53).M_PAD_CASE(54).M_PAD_CASE(55).M_PAD_CASE(56) .M_PAD_CASE(57).M_PAD_CASE(58).M_PAD_CASE(59).M_PAD_CASE(60) .M_PAD_CASE(61).M_PAD_CASE(62).M_PAD_CASE(63).M_PAD_CASE(64) ; #undef M_PAD_CASE class_<DeviceFactory, std::shared_ptr<DeviceFactory>, boost::noncopyable >("DeviceFactory",no_init) .def("instance",&deviceFactory ) .staticmethod("instance"); class_<ClientSingle, boost::noncopyable>("ClientSingle") .def("enumerateDevices",&enumerateDevices).staticmethod("enumerateDevices") .def("run",&ClientSingle::run); class_<DeviceDescriptor>("DeviceDescriptor", init<std::string, DeviceDescriptor::Type, DeviceDescriptor::tVendorId, DeviceDescriptor::tProductId>()) .def("getName",&DeviceDescriptor::getName, return_internal_reference<>()) ; } /* /this is the variable that will hold a reference to the python function PyObject *py_callback; //the following function will invoked from python to populate the call back reference PyObject *set_py_callback(PyObject *callable) { py_callback = callable; // Remember new callback return Py_None; } //Initialize and acquire the global interpreter lock PyEval_InitThreads(); //Ensure that the current thread is ready to call the Python C API PyGILState_STATE state = PyGILState_Ensure(); //invoke the python function boost::python::call<void>(py_callback); //release the global interpreter lock so other threads can resume execution PyGILState_Release(state); */ //-------------------------------------------------------------------------------------------------- } // cabl } // sl <commit_msg>updated python wrapper<commit_after>/* ########## Copyright (C) 2015 Vincenzo Pacella ## ## Distributed under MIT license, see file LICENSE ## ## or <http://opensource.org/licenses/MIT> ## ## ########## ############################################################# shaduzlabs.com #####*/ #include <boost/python.hpp> using namespace boost::python; #include "cabl.h" namespace sl { namespace cabl { using namespace boost::python; //-------------------------------------------------------------------------------------------------- void registerClientCallbacks( ClientSingle* pClass, object onConnected_, object onTick_, object onDisconnected_ ) { return pClass->setCallbacks( [onConnected_](){ PyGILState_STATE gstate = PyGILState_Ensure(); onConnected_(); PyGILState_Release(gstate); }, [onTick_](){ PyGILState_STATE gstate = PyGILState_Ensure(); onTick_(); PyGILState_Release(gstate); }, [onDisconnected_](){ PyGILState_STATE gstate = PyGILState_Ensure(); onDisconnected_(); PyGILState_Release(gstate); } ); } //-------------------------------------------------------------------------------------------------- template <class T> boost::python::list toPythonList(std::vector<T> vector) { typename std::vector<T>::iterator iter; boost::python::list list; for (iter = vector.begin(); iter != vector.end(); ++iter) { list.append(*iter); } return list; } //-------------------------------------------------------------------------------------------------- struct NullDeleter { void operator()(const void*){} }; //-------------------------------------------------------------------------------------------------- std::shared_ptr<DeviceFactory> deviceFactory() { return std::shared_ptr<DeviceFactory>( &DeviceFactory::instance(), NullDeleter() ); } list enumerateDevices() { return toPythonList(ClientSingle::enumerateDevices()); } //-------------------------------------------------------------------------------------------------- void onButtonChanged(PyObject* callable, Device::Button button_, bool val_, bool shiftKey_) { boost::python::call<void>(callable, button_, val_, shiftKey_); } //-------------------------------------------------------------------------------------------------- void onEncoderChanged(PyObject* callable, Device::Encoder encoder_, uint16_t val_, bool shiftKey_) { boost::python::call<void>(callable, encoder_, val_, shiftKey_); } //-------------------------------------------------------------------------------------------------- void onPadChanged(PyObject* callable, Device::Pad pad_, uint16_t val_, bool shiftKey_) { boost::python::call<void>(callable, pad_, val_, shiftKey_); } //-------------------------------------------------------------------------------------------------- void onKeyChanged(PyObject* callable, Device::Key key_, uint16_t val_, bool shiftKey_) { boost::python::call<void>(callable, key_, val_, shiftKey_); } //-------------------------------------------------------------------------------------------------- void onPotentiometerChanged( PyObject* callable, Device::Potentiometer pot_, uint16_t val_, bool shiftKey_ ) { boost::python::call<void>(callable, pot_, val_, shiftKey_); } //-------------------------------------------------------------------------------------------------- void onDeviceConnected(PyObject* callable) { boost::python::call<void>(callable); } //-------------------------------------------------------------------------------------------------- void onDeviceTick(PyObject* callable) { boost::python::call<void>(callable); } //-------------------------------------------------------------------------------------------------- void onDeviceDisconnected(PyObject* callable) { boost::python::call<void>(callable); } //-------------------------------------------------------------------------------------------------- BOOST_PYTHON_MODULE(pycabl) { enum_<DeviceDescriptor::Type>("DeviceDescriptorType") .value("USB", DeviceDescriptor::Type::USB) .value("MIDI", DeviceDescriptor::Type::MIDI) .value("HID", DeviceDescriptor::Type::HID) .value("Unknown", DeviceDescriptor::Type::Unknown) ; //-------------------------------------------------------------------------------------------------- #define M_BTN_DEF(item) value(#item, Device::Button::item) enum_<Device::Button>("Button") .M_BTN_DEF(Control).M_BTN_DEF(Step).M_BTN_DEF(Browse).M_BTN_DEF(Sampling) .M_BTN_DEF(BrowseLeft).M_BTN_DEF(BrowseRight).M_BTN_DEF(AutoWrite).M_BTN_DEF(F2) .M_BTN_DEF(All).M_BTN_DEF(F1).M_BTN_DEF(Snap).M_BTN_DEF(DisplayButton1) .M_BTN_DEF(DisplayButton2).M_BTN_DEF(DisplayButton3).M_BTN_DEF(DisplayButton4) .M_BTN_DEF(DisplayButton5).M_BTN_DEF(DisplayButton6).M_BTN_DEF(DisplayButton7) .M_BTN_DEF(DisplayButton8).M_BTN_DEF(Scene).M_BTN_DEF(Pattern).M_BTN_DEF(PadMode) .M_BTN_DEF(Keyboard).M_BTN_DEF(View).M_BTN_DEF(Navigate).M_BTN_DEF(Duplicate) .M_BTN_DEF(Select).M_BTN_DEF(Solo).M_BTN_DEF(Mute).M_BTN_DEF(Volume).M_BTN_DEF(Swing) .M_BTN_DEF(Tempo).M_BTN_DEF(MasterLeft).M_BTN_DEF(MasterRight).M_BTN_DEF(Enter) .M_BTN_DEF(Tap).M_BTN_DEF(NoteRepeat).M_BTN_DEF(Group).M_BTN_DEF(GroupA) .M_BTN_DEF(GroupB).M_BTN_DEF(GroupC).M_BTN_DEF(GroupD).M_BTN_DEF(GroupE) .M_BTN_DEF(GroupF).M_BTN_DEF(GroupG).M_BTN_DEF(GroupH).M_BTN_DEF(Restart) .M_BTN_DEF(Loop).M_BTN_DEF(TransportLeft).M_BTN_DEF(TransportRight).M_BTN_DEF(Grid) .M_BTN_DEF(Play).M_BTN_DEF(Rec).M_BTN_DEF(Erase).M_BTN_DEF(Shift).M_BTN_DEF(F3) .M_BTN_DEF(Nav).M_BTN_DEF(Main).M_BTN_DEF(MainEncoder).M_BTN_DEF(Scale).M_BTN_DEF(Scales) .M_BTN_DEF(Arp).M_BTN_DEF(Rwd).M_BTN_DEF(Ffw).M_BTN_DEF(Stop).M_BTN_DEF(PageLeft) .M_BTN_DEF(PageRight).M_BTN_DEF(PresetUp).M_BTN_DEF(Instance).M_BTN_DEF(PresetDown) .M_BTN_DEF(Back).M_BTN_DEF(NavigateUp).M_BTN_DEF(NavigateLeft).M_BTN_DEF(NavigateDown) .M_BTN_DEF(NavigateRight).M_BTN_DEF(OctaveUp).M_BTN_DEF(OctaveDown).M_BTN_DEF(TouchEncoder1) .M_BTN_DEF(TouchEncoder2).M_BTN_DEF(TouchEncoder3).M_BTN_DEF(TouchEncoder4) .M_BTN_DEF(TouchEncoder5).M_BTN_DEF(TouchEncoder6).M_BTN_DEF(TouchEncoder7) .M_BTN_DEF(TouchEncoder8).M_BTN_DEF(TouchEncoder9).M_BTN_DEF(TouchEncoderMain) .M_BTN_DEF(TouchEncoderMain2).M_BTN_DEF(Size).M_BTN_DEF(Type).M_BTN_DEF(Reverse) .M_BTN_DEF(Capture).M_BTN_DEF(Quant).M_BTN_DEF(Quantize).M_BTN_DEF(Sync) .M_BTN_DEF(Pad1).M_BTN_DEF(Pad2).M_BTN_DEF(Pad3).M_BTN_DEF(Pad4).M_BTN_DEF(Pad5) .M_BTN_DEF(Pad6).M_BTN_DEF(Pad7).M_BTN_DEF(Pad8).M_BTN_DEF(Pad9).M_BTN_DEF( Pad10) .M_BTN_DEF(Pad11).M_BTN_DEF(Pad12).M_BTN_DEF(Pad13).M_BTN_DEF(Pad14).M_BTN_DEF(Pad15) .M_BTN_DEF(Pad16).M_BTN_DEF(Stop1).M_BTN_DEF(Stop2).M_BTN_DEF(Stop3).M_BTN_DEF(Stop4) .M_BTN_DEF(Btn1Row1).M_BTN_DEF(Btn2Row1).M_BTN_DEF(Btn3Row1).M_BTN_DEF(Btn4Row1) .M_BTN_DEF(Btn5Row1).M_BTN_DEF(Btn6Row1).M_BTN_DEF(Btn7Row1).M_BTN_DEF(Btn8Row1) .M_BTN_DEF(Btn1Row2).M_BTN_DEF(Btn2Row2).M_BTN_DEF(Btn3Row2).M_BTN_DEF(Btn4Row2) .M_BTN_DEF(Btn5Row2).M_BTN_DEF(Btn6Row2).M_BTN_DEF(Btn7Row2).M_BTN_DEF(Btn8Row2) .M_BTN_DEF(Grid1_4).M_BTN_DEF(Grid1_4T).M_BTN_DEF(Grid1_8).M_BTN_DEF(Grid1_8T) .M_BTN_DEF(Grid1_16).M_BTN_DEF(Grid1_16T).M_BTN_DEF(Grid1_32).M_BTN_DEF(Grid1_32T) .M_BTN_DEF(TapTempo).M_BTN_DEF(Metronome).M_BTN_DEF(TouchStripTap).M_BTN_DEF(Master) .M_BTN_DEF(Setup).M_BTN_DEF(Layout).M_BTN_DEF(Convert).M_BTN_DEF(Note).M_BTN_DEF(Session) .M_BTN_DEF(AddEffect).M_BTN_DEF(AddTrack).M_BTN_DEF(Repeat).M_BTN_DEF(Accent) .M_BTN_DEF(User).M_BTN_DEF(In).M_BTN_DEF(Out).M_BTN_DEF(New).M_BTN_DEF(Automation) .M_BTN_DEF(FixedLength).M_BTN_DEF(Device).M_BTN_DEF(Track).M_BTN_DEF(Clip) .M_BTN_DEF(PanSend).M_BTN_DEF(Double).M_BTN_DEF(Delete).M_BTN_DEF(Undo) .M_BTN_DEF(Unknown) ; #undef M_BTN_DEF //-------------------------------------------------------------------------------------------------- #define M_ENCODER_DEF(item) value(#item, Device::Encoder::item) enum_<Device::Encoder>("Encoder") .M_ENCODER_DEF(Main).M_ENCODER_DEF(Volume).M_ENCODER_DEF(Tempo).M_ENCODER_DEF(Main2) .M_ENCODER_DEF(Swing).M_ENCODER_DEF(Encoder1).M_ENCODER_DEF(Encoder2).M_ENCODER_DEF(Encoder3) .M_ENCODER_DEF(Encoder4).M_ENCODER_DEF(Encoder5).M_ENCODER_DEF(Encoder6) .M_ENCODER_DEF(Encoder7).M_ENCODER_DEF(Encoder8).M_ENCODER_DEF(Encoder9) .M_ENCODER_DEF(Unknown) ; #undef M_ENCODER_DEF //-------------------------------------------------------------------------------------------------- #define M_PAD_DEF(item) value(#item, Device::Pad::item) enum_<Device::Pad>("Pad") .M_PAD_DEF(Pad1 ).M_PAD_DEF(Pad2 ).M_PAD_DEF(Pad3 ).M_PAD_DEF(Pad4 ) .M_PAD_DEF(Pad5 ).M_PAD_DEF(Pad6 ).M_PAD_DEF(Pad7 ).M_PAD_DEF(Pad8 ) .M_PAD_DEF(Pad9 ).M_PAD_DEF(Pad10).M_PAD_DEF(Pad11).M_PAD_DEF(Pad12) .M_PAD_DEF(Pad13).M_PAD_DEF(Pad14).M_PAD_DEF(Pad15).M_PAD_DEF(Pad16) .M_PAD_DEF(Pad17).M_PAD_DEF(Pad18).M_PAD_DEF(Pad19).M_PAD_DEF(Pad20) .M_PAD_DEF(Pad21).M_PAD_DEF(Pad22).M_PAD_DEF(Pad23).M_PAD_DEF(Pad24) .M_PAD_DEF(Pad25).M_PAD_DEF(Pad26).M_PAD_DEF(Pad27).M_PAD_DEF(Pad28) .M_PAD_DEF(Pad29).M_PAD_DEF(Pad30).M_PAD_DEF(Pad31).M_PAD_DEF(Pad32) .M_PAD_DEF(Pad33).M_PAD_DEF(Pad34).M_PAD_DEF(Pad35).M_PAD_DEF(Pad36) .M_PAD_DEF(Pad37).M_PAD_DEF(Pad38).M_PAD_DEF(Pad39).M_PAD_DEF(Pad40) .M_PAD_DEF(Pad41).M_PAD_DEF(Pad42).M_PAD_DEF(Pad43).M_PAD_DEF(Pad44) .M_PAD_DEF(Pad45).M_PAD_DEF(Pad46).M_PAD_DEF(Pad47).M_PAD_DEF(Pad48) .M_PAD_DEF(Pad49).M_PAD_DEF(Pad50).M_PAD_DEF(Pad51).M_PAD_DEF(Pad52) .M_PAD_DEF(Pad53).M_PAD_DEF(Pad54).M_PAD_DEF(Pad55).M_PAD_DEF(Pad56) .M_PAD_DEF(Pad57).M_PAD_DEF(Pad58).M_PAD_DEF(Pad59).M_PAD_DEF(Pad60) .M_PAD_DEF(Pad61).M_PAD_DEF(Pad62).M_PAD_DEF(Pad63).M_PAD_DEF(Pad64) .M_PAD_DEF(Unknown) ; #undef M_PAD_DEF //-------------------------------------------------------------------------------------------------- #define M_KEY_DEF(item) value(#item, Device::Key::item) enum_<Device::Key>("Key") .M_KEY_DEF(Key1 ).M_KEY_DEF(Key2 ).M_KEY_DEF(Key3 ).M_KEY_DEF(Key4 ) .M_KEY_DEF(Key5 ).M_KEY_DEF(Key6 ).M_KEY_DEF(Key7 ).M_KEY_DEF(Key8 ) .M_KEY_DEF(Key9 ).M_KEY_DEF(Key10 ).M_KEY_DEF(Key11 ).M_KEY_DEF(Key12 ) .M_KEY_DEF(Key13 ).M_KEY_DEF(Key14 ).M_KEY_DEF(Key15 ).M_KEY_DEF(Key16 ) .M_KEY_DEF(Key17 ).M_KEY_DEF(Key18 ).M_KEY_DEF(Key19 ).M_KEY_DEF(Key20 ) .M_KEY_DEF(Key21 ).M_KEY_DEF(Key22 ).M_KEY_DEF(Key23 ).M_KEY_DEF(Key24 ) .M_KEY_DEF(Key25 ).M_KEY_DEF(Key26 ).M_KEY_DEF(Key27 ).M_KEY_DEF(Key28 ) .M_KEY_DEF(Key29 ).M_KEY_DEF(Key30 ).M_KEY_DEF(Key31 ).M_KEY_DEF(Key32 ) .M_KEY_DEF(Key33 ).M_KEY_DEF(Key34 ).M_KEY_DEF(Key35 ).M_KEY_DEF(Key36 ) .M_KEY_DEF(Key37 ).M_KEY_DEF(Key38 ).M_KEY_DEF(Key39 ).M_KEY_DEF(Key40 ) .M_KEY_DEF(Key41 ).M_KEY_DEF(Key42 ).M_KEY_DEF(Key43 ).M_KEY_DEF(Key44 ) .M_KEY_DEF(Key45 ).M_KEY_DEF(Key46 ).M_KEY_DEF(Key47 ).M_KEY_DEF(Key48 ) .M_KEY_DEF(Key49 ).M_KEY_DEF(Key50 ).M_KEY_DEF(Key51 ).M_KEY_DEF(Key52 ) .M_KEY_DEF(Key53 ).M_KEY_DEF(Key54 ).M_KEY_DEF(Key55 ).M_KEY_DEF(Key56 ) .M_KEY_DEF(Key57 ).M_KEY_DEF(Key58 ).M_KEY_DEF(Key59 ).M_KEY_DEF(Key60 ) .M_KEY_DEF(Key61 ).M_KEY_DEF(Key62 ).M_KEY_DEF(Key63 ).M_KEY_DEF(Key64 ) .M_KEY_DEF(Key65 ).M_KEY_DEF(Key66 ).M_KEY_DEF(Key67 ).M_KEY_DEF(Key68 ) .M_KEY_DEF(Key69 ).M_KEY_DEF(Key70 ).M_KEY_DEF(Key71 ).M_KEY_DEF(Key72 ) .M_KEY_DEF(Key73 ).M_KEY_DEF(Key74 ).M_KEY_DEF(Key75 ).M_KEY_DEF(Key76 ) .M_KEY_DEF(Key77 ).M_KEY_DEF(Key78 ).M_KEY_DEF(Key79 ).M_KEY_DEF(Key80 ) .M_KEY_DEF(Key81 ).M_KEY_DEF(Key82 ).M_KEY_DEF(Key83 ).M_KEY_DEF(Key84 ) .M_KEY_DEF(Key85 ).M_KEY_DEF(Key86 ).M_KEY_DEF(Key87 ).M_KEY_DEF(Key88 ) .M_KEY_DEF(Key89 ).M_KEY_DEF(Key90 ).M_KEY_DEF(Key91 ).M_KEY_DEF(Key92 ) .M_KEY_DEF(Key93 ).M_KEY_DEF(Key94 ).M_KEY_DEF(Key95 ).M_KEY_DEF(Key96 ) .M_KEY_DEF(Key97 ).M_KEY_DEF(Key98 ).M_KEY_DEF(Key99 ).M_KEY_DEF(Key100) .M_KEY_DEF(Key101).M_KEY_DEF(Key102).M_KEY_DEF(Key103).M_KEY_DEF(Key104) .M_KEY_DEF(Key105).M_KEY_DEF(Key106).M_KEY_DEF(Key107).M_KEY_DEF(Key108) .M_KEY_DEF(Key109).M_KEY_DEF(Key110).M_KEY_DEF(Key111).M_KEY_DEF(Key112) .M_KEY_DEF(Key113).M_KEY_DEF(Key114).M_KEY_DEF(Key115).M_KEY_DEF(Key116) .M_KEY_DEF(Key117).M_KEY_DEF(Key118).M_KEY_DEF(Key119).M_KEY_DEF(Key120) .M_KEY_DEF(Key121).M_KEY_DEF(Key122).M_KEY_DEF(Key123).M_KEY_DEF(Key124) .M_KEY_DEF(Key125).M_KEY_DEF(Key126).M_KEY_DEF(Key127).M_KEY_DEF(Key128) .M_KEY_DEF(Unknown) ; #undef M_KEY_DEF //-------------------------------------------------------------------------------------------------- #define M_POT_DEF(item) value(#item, Device::Potentiometer::item) enum_<Device::Potentiometer>("Potentiometer") .M_POT_DEF(CenterDetented1).M_POT_DEF(CenterDetented2).M_POT_DEF(CenterDetented3) .M_POT_DEF(CenterDetented4).M_POT_DEF(CenterDetented5).M_POT_DEF(CenterDetented6) .M_POT_DEF(CenterDetented7).M_POT_DEF(CenterDetented8) .M_POT_DEF(Fader1 ).M_POT_DEF(Fader2 ).M_POT_DEF(Fader3 ).M_POT_DEF(Fader4 ) .M_POT_DEF(Fader5 ).M_POT_DEF(Fader6 ).M_POT_DEF(Fader7 ).M_POT_DEF(Fader8 ) .M_POT_DEF(Fader9 ).M_POT_DEF(Fader10).M_POT_DEF(Fader11).M_POT_DEF(Fader12) .M_POT_DEF(Fader13).M_POT_DEF(Fader14).M_POT_DEF(Fader15).M_POT_DEF(Fader16) .M_POT_DEF(Unknown) ; #undef M_POT_DEF //-------------------------------------------------------------------------------------------------- class_<DeviceFactory, std::shared_ptr<DeviceFactory>, boost::noncopyable >("DeviceFactory",no_init) .def("instance",&deviceFactory ) .staticmethod("instance") ; //-------------------------------------------------------------------------------------------------- class_<ClientSingle, boost::noncopyable>("ClientSingle") .def("enumerateDevices",&enumerateDevices).staticmethod("enumerateDevices") .def("registerCallbacks", &registerClientCallbacks, args("onConnect","onTick","onDisconnect")) .def("connect", &ClientSingle::connect) .def("run",&ClientSingle::run) .def("stop",&ClientSingle::stop) ; //-------------------------------------------------------------------------------------------------- class_<DeviceDescriptor>("DeviceDescriptor", init<std::string, DeviceDescriptor::Type, DeviceDescriptor::tVendorId, DeviceDescriptor::tProductId>()) .def(self_ns::str(self_ns::self)) .def("getName",&DeviceDescriptor::getName, return_value_policy<copy_const_reference>()) .def("getType",&DeviceDescriptor::getType) .def("getVendorId",&DeviceDescriptor::getVendorId) .def("getProductId",&DeviceDescriptor::getProductId) .def( "getSerialNumber", &DeviceDescriptor::getSerialNumber, return_value_policy<copy_const_reference>() ) ; //-------------------------------------------------------------------------------------------------- class_<util::LedColor>("LedColor", init<uint8_t>()) .def(init<uint8_t, uint8_t, uint8_t>()) .def(init<uint8_t, uint8_t, uint8_t, uint8_t>()) .def(self_ns::str(self_ns::self)) .def("getRGBColor",&util::LedColor::getRGBColor) .def("getRed",&util::LedColor::getRed) .def("getGreen",&util::LedColor::getGreen) .def("getBlue",&util::LedColor::getBlue) .def("getMono",&util::LedColor::getMono) ; //-------------------------------------------------------------------------------------------------- class_<util::RGBColor>("RGBColor", init<uint8_t, uint8_t, uint8_t>()) .def(self_ns::str(self_ns::self)) .def("distance",&util::RGBColor::distance) .def("getValue",&util::RGBColor::getValue) ; //-------------------------------------------------------------------------------------------------- } } // cabl } // sl <|endoftext|>
<commit_before>/* * Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com> * Copyright (C) 2004,2005,2007 Brad Hards <bradh@frogmouth.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "qca_basic.h" #include "qcaprovider.h" #include <QMutexLocker> #include <QtCore/QtGlobal> namespace QCA { // from qca_core.cpp QMutex *global_random_mutex(); Random *global_random(); //---------------------------------------------------------------------------- // Random //---------------------------------------------------------------------------- Random::Random(const QString &provider) :Algorithm("random", provider) { } uchar Random::nextByte() { return (uchar)(nextBytes(1)[0]); } SecureArray Random::nextBytes(int size) { return static_cast<RandomContext *>(context())->nextBytes(size); } uchar Random::randomChar() { QMutexLocker locker(global_random_mutex()); return global_random()->nextByte(); } int Random::randomInt() { QMutexLocker locker(global_random_mutex()); SecureArray a = global_random()->nextBytes(sizeof(int)); int x; memcpy(&x, a.data(), a.size()); return x; } SecureArray Random::randomArray(int size) { QMutexLocker locker(global_random_mutex()); return global_random()->nextBytes(size); } //---------------------------------------------------------------------------- // Hash //---------------------------------------------------------------------------- Hash::Hash(const QString &type, const QString &provider) :Algorithm(type, provider) { } void Hash::clear() { static_cast<HashContext *>(context())->clear(); } void Hash::update(const SecureArray &a) { static_cast<HashContext *>(context())->update(a); } void Hash::update(const QByteArray &a) { update( SecureArray( a ) ); } void Hash::update(const char *data, int len) { if ( len < 0 ) len = qstrlen( data ); if ( 0 == len ) return; update(QByteArray::fromRawData(data, len)); } // Reworked from KMD5, from KDE's kdelibs void Hash::update(QIODevice &file) { char buffer[1024]; int len; while ((len=file.read(reinterpret_cast<char*>(buffer), sizeof(buffer))) > 0) update(buffer, len); } SecureArray Hash::final() { return static_cast<HashContext *>(context())->final(); } SecureArray Hash::hash(const SecureArray &a) { return process(a); } QString Hash::hashToString(const SecureArray &a) { return arrayToHex(hash(a)); } //---------------------------------------------------------------------------- // Cipher //---------------------------------------------------------------------------- class Cipher::Private { public: Direction dir; SymmetricKey key; InitializationVector iv; bool ok, done; }; Cipher::Cipher( const QString &type, Mode m, Padding pad, Direction dir, const SymmetricKey &key, const InitializationVector &iv, const QString &provider ) :Algorithm(withAlgorithms( type, m, pad ), provider) { d = new Private; if(!key.isEmpty()) setup(dir, key, iv); } Cipher::Cipher(const Cipher &from) :Algorithm(from), Filter(from) { d = new Private(*from.d); } Cipher::~Cipher() { delete d; } Cipher & Cipher::operator=(const Cipher &from) { Algorithm::operator=(from); *d = *from.d; return *this; } KeyLength Cipher::keyLength() const { return static_cast<const CipherContext *>(context())->keyLength(); } bool Cipher::validKeyLength(int n) const { KeyLength len = keyLength(); return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0)); } unsigned int Cipher::blockSize() const { return static_cast<const CipherContext *>(context())->blockSize(); } void Cipher::clear() { d->done = false; static_cast<CipherContext *>(context())->setup(d->dir, d->key, d->iv); } SecureArray Cipher::update(const SecureArray &a) { SecureArray out; if(d->done) return out; d->ok = static_cast<CipherContext *>(context())->update(a, &out); return out; } SecureArray Cipher::final() { SecureArray out; if(d->done) return out; d->done = true; d->ok = static_cast<CipherContext *>(context())->final(&out); return out; } bool Cipher::ok() const { return d->ok; } void Cipher::setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv) { d->dir = dir; d->key = key; d->iv = iv; clear(); } QString Cipher::withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType) { QString mode; switch(modeType) { case CBC: mode = "cbc"; break; case CFB: mode = "cfb"; break; case OFB: mode = "ofb"; break; case ECB: mode = "ecb"; break; default: Q_ASSERT(0); } // do the default if(paddingType == DefaultPadding) { // logic from Botan if(modeType == CBC) paddingType = PKCS7; else paddingType = NoPadding; } QString pad; if(paddingType == NoPadding) pad = ""; else pad = "pkcs7"; QString result = cipherType + '-' + mode; if(!pad.isEmpty()) result += QString("-") + pad; return result; } //---------------------------------------------------------------------------- // MessageAuthenticationCode //---------------------------------------------------------------------------- class MessageAuthenticationCode::Private { public: SymmetricKey key; bool done; SecureArray buf; }; MessageAuthenticationCode::MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider) :Algorithm(type, provider) { d = new Private; setup(key); } MessageAuthenticationCode::MessageAuthenticationCode(const MessageAuthenticationCode &from) :Algorithm(from), BufferedComputation(from) { d = new Private(*from.d); } MessageAuthenticationCode::~MessageAuthenticationCode() { delete d; } MessageAuthenticationCode & MessageAuthenticationCode::operator=(const MessageAuthenticationCode &from) { Algorithm::operator=(from); *d = *from.d; return *this; } KeyLength MessageAuthenticationCode::keyLength() const { return static_cast<const MACContext *>(context())->keyLength(); } bool MessageAuthenticationCode::validKeyLength(int n) const { KeyLength len = keyLength(); return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0)); } void MessageAuthenticationCode::clear() { d->done = false; static_cast<MACContext *>(context())->setup(d->key); } void MessageAuthenticationCode::update(const SecureArray &a) { if(d->done) return; static_cast<MACContext *>(context())->update(a); } SecureArray MessageAuthenticationCode::final() { if(!d->done) { d->done = true; static_cast<MACContext *>(context())->final(&d->buf); } return d->buf; } void MessageAuthenticationCode::setup(const SymmetricKey &key) { d->key = key; clear(); } //---------------------------------------------------------------------------- // Key Derivation Function //---------------------------------------------------------------------------- KeyDerivationFunction::KeyDerivationFunction(const QString &type, const QString &provider) :Algorithm(type, provider) { } KeyDerivationFunction::KeyDerivationFunction(const KeyDerivationFunction &from) :Algorithm(from) { } KeyDerivationFunction::~KeyDerivationFunction() { } KeyDerivationFunction & KeyDerivationFunction::operator=(const KeyDerivationFunction &from) { Algorithm::operator=(from); return *this; } SymmetricKey KeyDerivationFunction::makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) { return static_cast<KDFContext *>(context())->makeKey(secret, salt, keyLength, iterationCount); } QString KeyDerivationFunction::withAlgorithm(const QString &kdfType, const QString &algType) { return (kdfType + '(' + algType + ')'); } } <commit_msg>don't need QtCore prefix<commit_after>/* * Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com> * Copyright (C) 2004,2005,2007 Brad Hards <bradh@frogmouth.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "qca_basic.h" #include "qcaprovider.h" #include <QMutexLocker> #include <QtGlobal> namespace QCA { // from qca_core.cpp QMutex *global_random_mutex(); Random *global_random(); //---------------------------------------------------------------------------- // Random //---------------------------------------------------------------------------- Random::Random(const QString &provider) :Algorithm("random", provider) { } uchar Random::nextByte() { return (uchar)(nextBytes(1)[0]); } SecureArray Random::nextBytes(int size) { return static_cast<RandomContext *>(context())->nextBytes(size); } uchar Random::randomChar() { QMutexLocker locker(global_random_mutex()); return global_random()->nextByte(); } int Random::randomInt() { QMutexLocker locker(global_random_mutex()); SecureArray a = global_random()->nextBytes(sizeof(int)); int x; memcpy(&x, a.data(), a.size()); return x; } SecureArray Random::randomArray(int size) { QMutexLocker locker(global_random_mutex()); return global_random()->nextBytes(size); } //---------------------------------------------------------------------------- // Hash //---------------------------------------------------------------------------- Hash::Hash(const QString &type, const QString &provider) :Algorithm(type, provider) { } void Hash::clear() { static_cast<HashContext *>(context())->clear(); } void Hash::update(const SecureArray &a) { static_cast<HashContext *>(context())->update(a); } void Hash::update(const QByteArray &a) { update( SecureArray( a ) ); } void Hash::update(const char *data, int len) { if ( len < 0 ) len = qstrlen( data ); if ( 0 == len ) return; update(QByteArray::fromRawData(data, len)); } // Reworked from KMD5, from KDE's kdelibs void Hash::update(QIODevice &file) { char buffer[1024]; int len; while ((len=file.read(reinterpret_cast<char*>(buffer), sizeof(buffer))) > 0) update(buffer, len); } SecureArray Hash::final() { return static_cast<HashContext *>(context())->final(); } SecureArray Hash::hash(const SecureArray &a) { return process(a); } QString Hash::hashToString(const SecureArray &a) { return arrayToHex(hash(a)); } //---------------------------------------------------------------------------- // Cipher //---------------------------------------------------------------------------- class Cipher::Private { public: Direction dir; SymmetricKey key; InitializationVector iv; bool ok, done; }; Cipher::Cipher( const QString &type, Mode m, Padding pad, Direction dir, const SymmetricKey &key, const InitializationVector &iv, const QString &provider ) :Algorithm(withAlgorithms( type, m, pad ), provider) { d = new Private; if(!key.isEmpty()) setup(dir, key, iv); } Cipher::Cipher(const Cipher &from) :Algorithm(from), Filter(from) { d = new Private(*from.d); } Cipher::~Cipher() { delete d; } Cipher & Cipher::operator=(const Cipher &from) { Algorithm::operator=(from); *d = *from.d; return *this; } KeyLength Cipher::keyLength() const { return static_cast<const CipherContext *>(context())->keyLength(); } bool Cipher::validKeyLength(int n) const { KeyLength len = keyLength(); return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0)); } unsigned int Cipher::blockSize() const { return static_cast<const CipherContext *>(context())->blockSize(); } void Cipher::clear() { d->done = false; static_cast<CipherContext *>(context())->setup(d->dir, d->key, d->iv); } SecureArray Cipher::update(const SecureArray &a) { SecureArray out; if(d->done) return out; d->ok = static_cast<CipherContext *>(context())->update(a, &out); return out; } SecureArray Cipher::final() { SecureArray out; if(d->done) return out; d->done = true; d->ok = static_cast<CipherContext *>(context())->final(&out); return out; } bool Cipher::ok() const { return d->ok; } void Cipher::setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv) { d->dir = dir; d->key = key; d->iv = iv; clear(); } QString Cipher::withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType) { QString mode; switch(modeType) { case CBC: mode = "cbc"; break; case CFB: mode = "cfb"; break; case OFB: mode = "ofb"; break; case ECB: mode = "ecb"; break; default: Q_ASSERT(0); } // do the default if(paddingType == DefaultPadding) { // logic from Botan if(modeType == CBC) paddingType = PKCS7; else paddingType = NoPadding; } QString pad; if(paddingType == NoPadding) pad = ""; else pad = "pkcs7"; QString result = cipherType + '-' + mode; if(!pad.isEmpty()) result += QString("-") + pad; return result; } //---------------------------------------------------------------------------- // MessageAuthenticationCode //---------------------------------------------------------------------------- class MessageAuthenticationCode::Private { public: SymmetricKey key; bool done; SecureArray buf; }; MessageAuthenticationCode::MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider) :Algorithm(type, provider) { d = new Private; setup(key); } MessageAuthenticationCode::MessageAuthenticationCode(const MessageAuthenticationCode &from) :Algorithm(from), BufferedComputation(from) { d = new Private(*from.d); } MessageAuthenticationCode::~MessageAuthenticationCode() { delete d; } MessageAuthenticationCode & MessageAuthenticationCode::operator=(const MessageAuthenticationCode &from) { Algorithm::operator=(from); *d = *from.d; return *this; } KeyLength MessageAuthenticationCode::keyLength() const { return static_cast<const MACContext *>(context())->keyLength(); } bool MessageAuthenticationCode::validKeyLength(int n) const { KeyLength len = keyLength(); return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0)); } void MessageAuthenticationCode::clear() { d->done = false; static_cast<MACContext *>(context())->setup(d->key); } void MessageAuthenticationCode::update(const SecureArray &a) { if(d->done) return; static_cast<MACContext *>(context())->update(a); } SecureArray MessageAuthenticationCode::final() { if(!d->done) { d->done = true; static_cast<MACContext *>(context())->final(&d->buf); } return d->buf; } void MessageAuthenticationCode::setup(const SymmetricKey &key) { d->key = key; clear(); } //---------------------------------------------------------------------------- // Key Derivation Function //---------------------------------------------------------------------------- KeyDerivationFunction::KeyDerivationFunction(const QString &type, const QString &provider) :Algorithm(type, provider) { } KeyDerivationFunction::KeyDerivationFunction(const KeyDerivationFunction &from) :Algorithm(from) { } KeyDerivationFunction::~KeyDerivationFunction() { } KeyDerivationFunction & KeyDerivationFunction::operator=(const KeyDerivationFunction &from) { Algorithm::operator=(from); return *this; } SymmetricKey KeyDerivationFunction::makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) { return static_cast<KDFContext *>(context())->makeKey(secret, salt, keyLength, iterationCount); } QString KeyDerivationFunction::withAlgorithm(const QString &kdfType, const QString &algType) { return (kdfType + '(' + algType + ')'); } } <|endoftext|>
<commit_before>/* * Yelly Database Scripts * Copyright (C) 2006-2008 U2 Team <http://www.undzwei.eu/> * Copyright (C) 2007-2008 Yelly Team * Copyright (C) 2009 WhyScripts Team <http://www.whydb.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" // quest #8304 - Dearest Natalia class SCRIPT_DECL DearestNatalia1 : public GossipScript { public: void GossipHello(Object* pObject, Player* Plr) { GossipMenu* Menu; QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7736, Plr); if(en && en->GetMobCount(1) < en->GetQuest()->required_mobcount[1]) Menu->AddItem(0, "Hello, Rutgar. The Commander has sent me here to gather some information about his missing wife.", 3); Menu->SendTo(Plr); } void GossipSelectOption(Object* pObject, Player* Plr, uint32 Id, uint32 IntId, const char* Code) { GossipMenu* Menu; switch(IntId) { case 0: GossipHello(pObject, Plr); break; case 3: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7755, Plr); Menu->AddItem(0, "That sounds dangerous.", 4); Menu->SendTo(Plr); } break; case 4: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7756, Plr); Menu->AddItem(0, "What happened to her after that?", 5); Menu->SendTo(Plr); } break; case 5: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7757, Plr); Menu->AddItem(0, "Natalia?", 6); Menu->SendTo(Plr); } break; case 6: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7758, Plr); Menu->AddItem(0, "What demands?", 7); Menu->SendTo(Plr); } break; case 7: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7759, Plr); Menu->AddItem(0, "Lost it? What do you mean?", 8); Menu->SendTo(Plr); } break; case 8: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7760, Plr); Menu->AddItem(0, "Possessed by what?", 9); Menu->SendTo(Plr); } break; case 9: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7761, Plr); Menu->AddItem(0, "I'll be back once I straighten this mess out.", 10); Menu->SendTo(Plr); } break; case 10: { QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); if(en && en->GetMobCount(1) < en->GetQuest()->required_mobcount[1]) { en->SetMobCount(1, 1); en->SendUpdateAddKill(1); en->UpdatePlayerFields(); } } break; } } }; class SCRIPT_DECL DearestNatalia2 : public GossipScript { public: void GossipHello(Object* pObject, Player* Plr) { GossipMenu* Menu; QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7735, Plr); // you need to speak to Rutgar first !! if(en && (en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) && (en->GetMobCount(1) == 1)) Menu->AddItem(0, "Hello, Frankal. I've heard that you might have some information as to the whereabouts of Mistress Natalia Mar'alith.", 3); Menu->SendTo(Plr); } void GossipSelectOption(Object* pObject, Player* Plr, uint32 Id, uint32 IntId, const char* Code) { GossipMenu* Menu; switch(IntId) { case 0: GossipHello(pObject, Plr); break; case 3: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7762, Plr); Menu->AddItem(0, "That's what I like to hear.", 4); Menu->SendTo(Plr); } break; case 4: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7763, Plr); Menu->AddItem(0, "That's odd.", 5); Menu->SendTo(Plr); } break; case 5: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7764, Plr); Menu->AddItem(0, "You couldn't handle a lone night elf priestess?", 6); Menu->SendTo(Plr); } break; case 6: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7765, Plr); Menu->AddItem(0, "I've been meaning to ask you about that monkey.", 7); Menu->SendTo(Plr); } break; case 7: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7766, Plr); Menu->AddItem(0, "Then what?", 8); Menu->SendTo(Plr); } break; case 8: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7767, Plr); Menu->AddItem(0, "What a story! So she went into Hive'Regal and that was the last you saw of her?", 9); Menu->SendTo(Plr); } break; case 9: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7768, Plr); Menu->AddItem(0, "Thanks for the information, Frankal.", 10); Menu->SendTo(Plr); } break; case 10: { QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { en->SetMobCount(0, 1); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); } } break; } } }; #define GOSSIP1 "What do you know of it" #define GOSSIP2 "I am listening, Demitrian." #define GOSSIP3 "Continue, please." #define GOSSIP4 "A battle?" #define GOSSIP5 "<Nod>" #define GOSSIP6 "Caught unaware? How?" #define GOSSIP7 "o what did Ragnaros do next?" class highlord_demitrianGossip : public GossipScript { public: void GossipHello(Object* pObject, Player* pPlayer) { //Send quests and gossip menu. Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6842, pPlayer->GetSession()->language); sQuestMgr.FillQuestMenu(TO_CREATURE(pObject), pPlayer, menu); if (pPlayer->HasItemCount(18563, 1, false) && pPlayer->HasItemCount(18564, 1, false)) { if (pPlayer->HasItemCount(19016, 0, false)) { menu.AddItem(0, GOSSIP1, 1); } else { sQuestMgr.FillQuestMenu(TO_CREATURE(pObject), pPlayer, menu); } } menu.Send(pPlayer); }; void GossipHello1(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6843, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP2, 2); menu.Send(pPlayer); }; void GossipHello2(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6844, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP3, 3); menu.Send(pPlayer); }; void GossipHello3(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6867, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP4, 4); menu.Send(pPlayer); }; void GossipHello4(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6868, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP5, 5); menu.Send(pPlayer); }; void GossipHello5(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6869, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP6, 6); menu.Send(pPlayer); }; void GossipHello6(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6870, pPlayer->GetSession()->language); menu.Send(pPlayer); }; void GossipSelectOption(Object* pObject, Player* pPlayer, uint32 Id, uint32 IntId, const char* Code) { switch(IntId) { case 1: GossipHello1(pObject, pPlayer); break; case 2: GossipHello2(pObject, pPlayer); break; case 3: GossipHello3(pObject, pPlayer); break; case 4: GossipHello4(pObject, pPlayer); break; case 5: GossipHello5(pObject, pPlayer); break; case 6: GossipHello6(pObject, pPlayer); sEAS.AddItem(19016, pPlayer); pPlayer->Gossip_Complete(); break; }; }; }; class Thunderan : public QuestScript { public: void OnQuestComplete(Player* mTarget, QuestLogEntry* qLogEntry) { sEAS.SpawnCreature(mTarget, 14435, -6241, 1715, 4.8, 0.605017,0, 1); } }; void SetupSilithus(ScriptMgr* mgr) { GossipScript* dearestNatalia1 = new DearestNatalia1(); GossipScript* dearestNatalia2 = new DearestNatalia2(); mgr->register_gossip_script(15170, dearestNatalia1); mgr->register_gossip_script(15171, dearestNatalia2); mgr->register_creature_gossip(14347, new highlord_demitrianGossip); mgr->register_quest_script(7786, new Thunderan); } <commit_msg>added missing gossip option<commit_after>/* * Yelly Database Scripts * Copyright (C) 2006-2008 U2 Team <http://www.undzwei.eu/> * Copyright (C) 2007-2008 Yelly Team * Copyright (C) 2009 WhyScripts Team <http://www.whydb.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" // quest #8304 - Dearest Natalia class SCRIPT_DECL DearestNatalia1 : public GossipScript { public: void GossipHello(Object* pObject, Player* Plr) { GossipMenu* Menu; QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7736, Plr); if(en && en->GetMobCount(1) < en->GetQuest()->required_mobcount[1]) Menu->AddItem(0, "Hello, Rutgar. The Commander has sent me here to gather some information about his missing wife.", 3); Menu->SendTo(Plr); } void GossipSelectOption(Object* pObject, Player* Plr, uint32 Id, uint32 IntId, const char* Code) { GossipMenu* Menu; switch(IntId) { case 0: GossipHello(pObject, Plr); break; case 3: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7755, Plr); Menu->AddItem(0, "That sounds dangerous.", 4); Menu->SendTo(Plr); } break; case 4: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7756, Plr); Menu->AddItem(0, "What happened to her after that?", 5); Menu->SendTo(Plr); } break; case 5: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7757, Plr); Menu->AddItem(0, "Natalia?", 6); Menu->SendTo(Plr); } break; case 6: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7758, Plr); Menu->AddItem(0, "What demands?", 7); Menu->SendTo(Plr); } break; case 7: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7759, Plr); Menu->AddItem(0, "Lost it? What do you mean?", 8); Menu->SendTo(Plr); } break; case 8: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7760, Plr); Menu->AddItem(0, "Possessed by what?", 9); Menu->SendTo(Plr); } break; case 9: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7761, Plr); Menu->AddItem(0, "I'll be back once I straighten this mess out.", 10); Menu->SendTo(Plr); } break; case 10: { QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); if(en && en->GetMobCount(1) < en->GetQuest()->required_mobcount[1]) { en->SetMobCount(1, 1); en->SendUpdateAddKill(1); en->UpdatePlayerFields(); } } break; } } }; class SCRIPT_DECL DearestNatalia2 : public GossipScript { public: void GossipHello(Object* pObject, Player* Plr) { GossipMenu* Menu; QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7735, Plr); // you need to speak to Rutgar first !! if(en && (en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) && (en->GetMobCount(1) == 1)) Menu->AddItem(0, "Hello, Frankal. I've heard that you might have some information as to the whereabouts of Mistress Natalia Mar'alith.", 3); Menu->SendTo(Plr); } void GossipSelectOption(Object* pObject, Player* Plr, uint32 Id, uint32 IntId, const char* Code) { GossipMenu* Menu; switch(IntId) { case 0: GossipHello(pObject, Plr); break; case 3: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7762, Plr); Menu->AddItem(0, "That's what I like to hear.", 4); Menu->SendTo(Plr); } break; case 4: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7763, Plr); Menu->AddItem(0, "That's odd.", 5); Menu->SendTo(Plr); } break; case 5: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7764, Plr); Menu->AddItem(0, "You couldn't handle a lone night elf priestess?", 6); Menu->SendTo(Plr); } break; case 6: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7765, Plr); Menu->AddItem(0, "I've been meaning to ask you about that monkey.", 7); Menu->SendTo(Plr); } break; case 7: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7766, Plr); Menu->AddItem(0, "Then what?", 8); Menu->SendTo(Plr); } break; case 8: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7767, Plr); Menu->AddItem(0, "What a story! So she went into Hive'Regal and that was the last you saw of her?", 9); Menu->SendTo(Plr); } break; case 9: { objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7768, Plr); Menu->AddItem(0, "Thanks for the information, Frankal.", 10); Menu->SendTo(Plr); } break; case 10: { QuestLogEntry* en = Plr->GetQuestLogForEntry(8304); if(en && en->GetMobCount(0) < en->GetQuest()->required_mobcount[0]) { en->SetMobCount(0, 1); en->SendUpdateAddKill(0); en->UpdatePlayerFields(); } } break; } } }; #define GOSSIP1 "What do you know of it" #define GOSSIP2 "I am listening, Demitrian." #define GOSSIP3 "Continue, please." #define GOSSIP4 "A battle?" #define GOSSIP5 "<Nod>" #define GOSSIP6 "Caught unaware? How?" #define GOSSIP7 "o what did Ragnaros do next?" class highlord_demitrianGossip : public GossipScript { public: void GossipHello(Object* pObject, Player* pPlayer) { //Send quests and gossip menu. Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6812, pPlayer->GetSession()->language); sQuestMgr.FillQuestMenu(TO_CREATURE(pObject), pPlayer, menu); if (pPlayer->HasItemCount(18563, 1, false) && pPlayer->HasItemCount(18564, 1, false)) { if (pPlayer->HasItemCount(19016, 0, false)) { menu.AddItem(0, GOSSIP1, 1); } } menu.Send(pPlayer); }; void GossipHello1(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6842, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP2, 2); menu.Send(pPlayer); }; void GossipHello2(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6843, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP3, 3); menu.Send(pPlayer); }; void GossipHello3(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6844, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP4, 4); menu.Send(pPlayer); }; void GossipHello4(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6867, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP5, 5); menu.Send(pPlayer); }; void GossipHello5(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6868, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP6, 6); menu.Send(pPlayer); }; void GossipHello6(Object* pObject, Player* pPlayer) { Arcemu::Gossip::Menu menu(pObject->GetGUID(), 6869, pPlayer->GetSession()->language); menu.AddItem(0, GOSSIP7, 7); menu.Send(pPlayer); }; void GossipSelectOption(Object* pObject, Player* pPlayer, uint32 Id, uint32 IntId, const char* Code) { switch(IntId) { case 1: GossipHello1(pObject, pPlayer); break; case 2: GossipHello2(pObject, pPlayer); break; case 3: GossipHello3(pObject, pPlayer); break; case 4: GossipHello4(pObject, pPlayer); break; case 5: GossipHello5(pObject, pPlayer); break; case 6: GossipHello6(pObject, pPlayer); break; case 7: sEAS.AddItem(19016, pPlayer); pPlayer->Gossip_Complete(); break; }; }; }; class Thunderan : public QuestScript { public: void OnQuestComplete(Player* mTarget, QuestLogEntry* qLogEntry) { sEAS.SpawnCreature(mTarget, 14435, -6241, 1715, 4.8, 0.605017,0, 1); } }; void SetupSilithus(ScriptMgr* mgr) { GossipScript* dearestNatalia1 = new DearestNatalia1(); GossipScript* dearestNatalia2 = new DearestNatalia2(); mgr->register_gossip_script(15170, dearestNatalia1); mgr->register_gossip_script(15171, dearestNatalia2); mgr->register_creature_gossip(14347, new highlord_demitrianGossip); mgr->register_quest_script(7786, new Thunderan); } <|endoftext|>
<commit_before>#include "Shooter.h" #include "Commands/SpinUp.h" #include "Commands/SpinDown.h" #include <math.h> namespace subsystems { using SpinUp = commands::SpinUp; using SpinDown = commands::SpinDown; // Constructor: Shooter::Shooter() : Subsystem("Shooter") { top_roller_ = new CANTalon(6); state_ = State_t::OFF; mode_ = Mode_t::VELOCITY; max_velocity_ = 30; allowed_error_ = 0.1; } // Destructor: Shooter::~Shooter() { delete top_roller_; } // Main functions: void Shooter::Initialize() { top_roller_->SetFeedbackDevice(CANTalon::QuadEncoder); top_roller_->ConfigEncoderCodesPerRev(2); top_roller_->SetInverted(true); top_roller_->SetSensorDirection(true); top_roller_->SelectProfileSlot(0); top_roller_->SetVoltageRampRate(0.0); top_roller_->SetCloseLoopRampRate(0.0); // Set max and min voltage ouput, dissalows negative voltage top_roller_->ConfigNominalOutputVoltage(0.0, 0.0); top_roller_->ConfigPeakOutputVoltage(0.0, -12.0); } void Shooter::SpinUp(double speed) { if (mode_ == Mode_t::VELOCITY) { top_roller_->Set(max_velocity_ * speed); } else if (mode_ == Mode_t::VBUS) { top_roller_->Set(speed); } } void Shooter::SpinDown() { top_roller_->Set(0.0); } void Shooter::EmergencyStop() { top_roller_->StopMotor(); } double Shooter::GetMaxVelocity() const { return max_velocity_; } void Shooter::SetMaxVelocity(double max_velocity) { max_velocity_ = max_velocity; } // Error functions: double Shooter::GetErr() const { return top_roller_->GetSetpoint() - top_roller_->Get(); } void Shooter::SetAllowedError(double err) { allowed_error_ = err; } double Shooter::GetAllowedError() const { return allowed_error_; } bool Shooter::IsAllowable() const { return (fabs(GetErr()) > fabs(allowed_error_)); } // State functions: Shooter::State_t Shooter::GetState() const { return state_; } void Shooter::SetState(State_t state) { state_ = state; } // Control mode functions: Shooter::Mode_t Shooter::GetMode() const { return mode_; } void Shooter::SetMode(Mode_t mode) { if (mode_ != mode) { mode_ = mode; if (mode_ == Mode_t::VELOCITY) top_roller_->SetControlMode(CANTalon::ControlMode::kSpeed); else if (mode_ == Mode_t::VBUS) top_roller_->SetControlMode(CANTalon::ControlMode::kPercentVbus); } } // Command functions: SpinUp* Shooter::MakeSpinUp() { return new commands::SpinUp(this, 1.0); } SpinDown* Shooter::MakeSpinDown() { return new commands::SpinDown(this); } } // end namespace subsystems <commit_msg>Bugfix: Mode set in constructor.<commit_after>#include "Shooter.h" #include "Commands/SpinUp.h" #include "Commands/SpinDown.h" #include <math.h> namespace subsystems { using SpinUp = commands::SpinUp; using SpinDown = commands::SpinDown; // Constructor: Shooter::Shooter() : Subsystem("Shooter") { top_roller_ = new CANTalon(6); state_ = State_t::OFF; mode_ = Mode_t::VBUS; SetMode(Mode_t::VELOCITY); max_velocity_ = 30; allowed_error_ = 0.1; } // Destructor: Shooter::~Shooter() { delete top_roller_; } // Main functions: void Shooter::Initialize() { top_roller_->SetFeedbackDevice(CANTalon::QuadEncoder); top_roller_->ConfigEncoderCodesPerRev(2); top_roller_->SetInverted(true); top_roller_->SetSensorDirection(true); top_roller_->SelectProfileSlot(0); top_roller_->SetVoltageRampRate(0.0); top_roller_->SetCloseLoopRampRate(0.0); // Set max and min voltage ouput, dissalows negative voltage top_roller_->ConfigNominalOutputVoltage(0.0, 0.0); top_roller_->ConfigPeakOutputVoltage(0.0, -12.0); } void Shooter::SpinUp(double speed) { if (mode_ == Mode_t::VELOCITY) { top_roller_->Set(max_velocity_ * speed); } else if (mode_ == Mode_t::VBUS) { top_roller_->Set(speed); } } void Shooter::SpinDown() { top_roller_->Set(0.0); } void Shooter::EmergencyStop() { top_roller_->StopMotor(); } double Shooter::GetMaxVelocity() const { return max_velocity_; } void Shooter::SetMaxVelocity(double max_velocity) { max_velocity_ = max_velocity; } // Error functions: double Shooter::GetErr() const { return top_roller_->GetSetpoint() - top_roller_->Get(); } void Shooter::SetAllowedError(double err) { allowed_error_ = err; } double Shooter::GetAllowedError() const { return allowed_error_; } bool Shooter::IsAllowable() const { return (fabs(GetErr()) > fabs(allowed_error_)); } // State functions: Shooter::State_t Shooter::GetState() const { return state_; } void Shooter::SetState(State_t state) { state_ = state; } // Control mode functions: Shooter::Mode_t Shooter::GetMode() const { return mode_; } void Shooter::SetMode(Mode_t mode) { if (mode_ != mode) { mode_ = mode; if (mode_ == Mode_t::VELOCITY) top_roller_->SetControlMode(CANTalon::ControlMode::kSpeed); else if (mode_ == Mode_t::VBUS) top_roller_->SetControlMode(CANTalon::ControlMode::kPercentVbus); } } // Command functions: SpinUp* Shooter::MakeSpinUp() { return new commands::SpinUp(this, 1.0); } SpinDown* Shooter::MakeSpinDown() { return new commands::SpinDown(this); } } // end namespace subsystems <|endoftext|>
<commit_before>#include "include/Text/textcontroller.h" #include <iostream> #include <fstream> #include <QFile> #include <QTextStream> #include <stdexcept> #include <regex> #include <sstream> using namespace std; TextController::TextController(const std::string& dataFolderPath): dataFolderPath(dataFolderPath), dataFilesIndex("files.index") { } const std::vector<std::vector<double>> TextController::getGlobalVector() { vector<string> files = importFiles(); vector<map<string, int>> map = createGlobalMap(files); return createGlobalVector(map); } void TextController::addSubFolder(const string &folderName) { dataSubFolder.push_back(folderName); } void TextController::addTag(const string &tag) { tagList.push_back(tag); } const std::vector<std::string> TextController::importFiles() { vector<string> files; for (string& folderName : dataSubFolder) { cout << endl << "Import files from folder " << dataFolderPath + folderName; getFiles(files, (folderName + "/") ); } cout << endl << files.size() << " files imported" << endl; return files; } void TextController::getFiles(vector<string>& files, const string &prefix) { string path = dataFolderPath + prefix + dataFilesIndex; QFile file( QString(path.c_str()) ); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) throw invalid_argument( "Unable to open file" ); QString line; QTextStream in(&file); in.setCodec("UTF-8"); while (!in.atEnd()) { line = in.readLine(); files.push_back(readFile(dataFolderPath + prefix + line.toLocal8Bit().constData())); } file.close(); } const std::string TextController::readFile(const string& path) { QFile file( QString(path.c_str()) ); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) throw invalid_argument( "Unable to open file" ); QString line; string strLine; string strFile = ""; QTextStream in(&file); in.setCodec("UTF-8"); while (!in.atEnd()) { line = in.readLine(); strLine = line.toLocal8Bit().constData(); if (keepLine(strLine)) { strFile.append(strLine); strFile.append("\n"); } } file.close(); return strFile; } bool TextController::keepLine(const std::string& line) { bool flag = false; for (string& tag : tagList) { std::size_t found = line.find(tag); if (found!=std::string::npos) { flag = true; break; } } return flag; } const std::vector<std::map<std::string, int>> TextController::createGlobalMap(const std::vector<std::string>& fileVector) { vector<map<string, int>> vectorOfMap; map<string, int> localMap; string line; for(const string& file : fileVector) { localMap.clear(); istringstream strstr(file); while(getline(strstr, line)) { unsigned found = line.rfind("\t"); localMap[line.substr(found+1)]+=1; } vectorOfMap.push_back(localMap); } return vectorOfMap; } const std::vector<std::vector<double> > TextController::createGlobalVector(const std::vector<std::map<string, int> > &globalMap) { map<string, int> templateMap; for(const map<string,int>& map : globalMap) { templateMap.insert(map.begin(), map.end()); } resetToZero(templateMap); vector<vector<double>> globalVector; vector<double> localVector; cout <<"Starting vector creation (takes a few minutes)" << endl; for(map<string,int> map : globalMap) { map.insert(templateMap.begin(), templateMap.end()); for(auto& i : map) localVector.push_back(static_cast<double>(i.second)); globalVector.push_back(vector<double>(localVector)); resetToZero(templateMap); localVector.clear(); } return globalVector; } void TextController::resetToZero(std::map<string, int>& map) { for(auto& i : map) i.second=0; } <commit_msg>MOD: Change Qt objects to standard C++ once<commit_after>#include "include/Text/textcontroller.h" #include <iostream> #include <fstream> #include <QFile> #include <QTextStream> #include <stdexcept> #include <regex> #include <sstream> using namespace std; TextController::TextController(const std::string& dataFolderPath): dataFolderPath(dataFolderPath), dataFilesIndex("files.index") { } const std::vector<std::vector<double>> TextController::getGlobalVector() { vector<string> files = importFiles(); vector<map<string, int>> map = createGlobalMap(files); return createGlobalVector(map); } void TextController::addSubFolder(const string &folderName) { dataSubFolder.push_back(folderName); } void TextController::addTag(const string &tag) { tagList.push_back(tag); } const std::vector<std::string> TextController::importFiles() { vector<string> files; for (string& folderName : dataSubFolder) { cout << endl << "Import files from folder " << dataFolderPath + folderName; getFiles(files, (folderName + "/") ); } cout << endl << files.size() << " files imported" << endl; return files; } void TextController::getFiles(vector<string>& files, const string &prefix) { string path = dataFolderPath + prefix + dataFilesIndex; string line; ifstream file (path); if (file.is_open()) { while ( getline (file,line) ) { files.push_back(readFile(dataFolderPath + prefix + line)); } } file.close(); } const std::string TextController::readFile(const string& path) { string line; string strFile = ""; ifstream file (path); if (file.is_open()) { while ( getline (file,line) ) { if (keepLine(line)) { strFile.append(line); strFile.append("\n"); } } file.close(); } file.close(); return strFile; } bool TextController::keepLine(const std::string& line) { bool flag = false; for (string& tag : tagList) { std::size_t found = line.find(tag); if (found!=std::string::npos) { flag = true; break; } } return flag; } const std::vector<std::map<std::string, int>> TextController::createGlobalMap(const std::vector<std::string>& fileVector) { vector<map<string, int>> vectorOfMap; map<string, int> localMap; string line; for(const string& file : fileVector) { localMap.clear(); istringstream strstr(file); while(getline(strstr, line)) { unsigned found = line.rfind("\t"); localMap[line.substr(found+1)]+=1; } vectorOfMap.push_back(localMap); } return vectorOfMap; } const std::vector<std::vector<double> > TextController::createGlobalVector(const std::vector<std::map<string, int> > &globalMap) { map<string, int> templateMap; for(const map<string,int>& map : globalMap) { templateMap.insert(map.begin(), map.end()); } resetToZero(templateMap); vector<vector<double>> globalVector; vector<double> localVector; cout <<"Starting vector creation (takes a few minutes)" << endl; for(map<string,int> map : globalMap) { map.insert(templateMap.begin(), templateMap.end()); for(auto& i : map) localVector.push_back(static_cast<double>(i.second)); globalVector.push_back(vector<double>(localVector)); resetToZero(templateMap); localVector.clear(); } return globalVector; } void TextController::resetToZero(std::map<string, int>& map) { for(auto& i : map) i.second=0; } <|endoftext|>
<commit_before>#include "DebugDrawing.hpp" #include <glm/gtc/matrix_transform.hpp> #include "Shader/Shader.hpp" #include "Shader/ShaderProgram.hpp" #include "DebugDrawing.vert.hpp" #include "DebugDrawing.frag.hpp" #include "glm/gtc/constants.hpp" #define BUFFER_OFFSET(i) ((char *)nullptr + (i)) using namespace Video; DebugDrawing::DebugDrawing() { Shader* vertexShader = new Shader(DEBUGDRAWING_VERT, DEBUGDRAWING_VERT_LENGTH, GL_VERTEX_SHADER); Shader* fragmentShader = new Shader(DEBUGDRAWING_FRAG, DEBUGDRAWING_FRAG_LENGTH, GL_FRAGMENT_SHADER); shaderProgram = new ShaderProgram({ vertexShader, fragmentShader }); delete vertexShader; delete fragmentShader; // Create point vertex array. glBindVertexArray(0); glm::vec3 point(0.f, 0.f, 0.f); CreateVertexArray(&point, 1, pointVertexBuffer, pointVertexArray); // Create line vertex array. glm::vec3 line[2]; line[0] = glm::vec3(0.f, 0.f, 0.f); line[1] = glm::vec3(1.f, 1.f, 1.f); CreateVertexArray(line, 2, lineVertexBuffer, lineVertexArray); // Create cuboid vertex array. glm::vec3 box[24]; box[0] = glm::vec3(-0.5f, -0.5f, -0.5f); box[1] = glm::vec3(0.5f, -0.5f, -0.5f); box[2] = glm::vec3(0.5f, -0.5f, -0.5f); box[3] = glm::vec3(0.5f, 0.5f, -0.5f); box[4] = glm::vec3(0.5f, 0.5f, -0.5f); box[5] = glm::vec3(-0.5f, 0.5f, -0.5f); box[6] = glm::vec3(0.5f, 0.5f, -0.5f); box[7] = glm::vec3(0.5f, 0.5f, 0.5f); box[8] = glm::vec3(0.5f, 0.5f, 0.5f); box[9] = glm::vec3(0.5f, -0.5f, 0.5f); box[10] = glm::vec3(0.5f, -0.5f, 0.5f); box[11] = glm::vec3(0.5f, -0.5f, -0.5f); box[12] = glm::vec3(-0.5f, 0.5f, -0.5f); box[13] = glm::vec3(-0.5f, 0.5f, 0.5f); box[14] = glm::vec3(-0.5f, 0.5f, 0.5f); box[15] = glm::vec3(-0.5f, -0.5f, 0.5f); box[16] = glm::vec3(-0.5f, 0.5f, -0.5f); box[17] = glm::vec3(-0.5f, 0.5f, -0.5f); box[18] = glm::vec3(-0.5f, 0.5f, 0.5f); box[19] = glm::vec3(-0.5f, -0.5f, -0.5f); box[20] = glm::vec3(-0.5f, 0.5f, 0.5f); box[21] = glm::vec3(0.5f, 0.5f, 0.5f); box[22] = glm::vec3(-0.5f, -0.5f, 0.5f); box[23] = glm::vec3(0.5f, -0.5f, 0.5f); CreateVertexArray(box, 24, cuboidVertexBuffer, cuboidVertexArray); // Create plane vertex array. glm::vec3 plane[8]; plane[0] = glm::vec3(-1.f, -1.f, 0.f); plane[1] = glm::vec3(1.f, -1.f, 0.f); plane[2] = glm::vec3(1.f, -1.f, 0.f); plane[3] = glm::vec3(1.f, 1.f, 0.f); plane[4] = glm::vec3(1.f, 1.f, 0.f); plane[5] = glm::vec3(-1.f, 1.f, 0.f); plane[6] = glm::vec3(-1.f, 1.f, 0.f); plane[7] = glm::vec3(-1.f, -1.f, 0.f); CreateVertexArray(plane, 8, planeVertexBuffer, planeVertexArray); // Create circle vertex array. glm::vec3* circle; CreateCircle(circle, circleVertexCount, 25); CreateVertexArray(circle, circleVertexCount, circleVertexBuffer, circleVertexArray); delete[] circle; // Create sphere vertex array. glm::vec3* sphere; CreateSphere(sphere, sphereVertexCount, 14); CreateVertexArray(sphere, sphereVertexCount, sphereVertexBuffer, sphereVertexArray); delete[] sphere; } DebugDrawing::~DebugDrawing() { glDeleteBuffers(1, &cuboidVertexBuffer); glDeleteVertexArrays(1, &cuboidVertexArray); glDeleteBuffers(1, &pointVertexBuffer); glDeleteVertexArrays(1, &pointVertexArray); glDeleteBuffers(1, &lineVertexBuffer); glDeleteVertexArrays(1, &lineVertexArray); glDeleteBuffers(1, &planeVertexBuffer); glDeleteVertexArrays(1, &planeVertexArray); glDeleteBuffers(1, &circleVertexBuffer); glDeleteVertexArrays(1, &circleVertexArray); glDeleteBuffers(1, &sphereVertexBuffer); glDeleteVertexArrays(1, &sphereVertexArray); delete shaderProgram; } void DebugDrawing::StartDebugDrawing(const glm::mat4& viewProjectionMatrix) { shaderProgram->Use(); glUniformMatrix4fv(shaderProgram->GetUniformLocation("viewProjection"), 1, GL_FALSE, &viewProjectionMatrix[0][0]); } void DebugDrawing::DrawPoint(const Point& point) { BindVertexArray(pointVertexArray); glm::mat4 model(glm::translate(glm::mat4(), point.position)); glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); point.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &point.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), point.size); glDrawArrays(GL_POINTS, 0, 1); } void DebugDrawing::DrawLine(const Line& line) { BindVertexArray(lineVertexArray); glm::mat4 model(glm::translate(glm::mat4(), line.startPosition) * glm::scale(glm::mat4(), line.endPosition - line.startPosition)); glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); line.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &line.color[0]); glLineWidth(line.width); glDrawArrays(GL_LINES, 0, 2); } void DebugDrawing::DrawCuboid(const Cuboid& cuboid) { BindVertexArray(cuboidVertexArray); glm::mat4 model(cuboid.matrix * glm::scale(glm::mat4(), cuboid.dimensions)); glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); cuboid.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &cuboid.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(cuboid.lineWidth); glDrawArrays(GL_LINES, 0, 24); } void DebugDrawing::DrawPlane(const Plane& plane) { BindVertexArray(planeVertexArray); glm::mat4 model(glm::scale(glm::mat4(), glm::vec3(plane.size * 0.5f, 1.f))); float yaw = atan2(plane.normal.x, plane.normal.z); float pitch = atan2(plane.normal.y, sqrt(plane.normal.x * plane.normal.x + plane.normal.z * plane.normal.z)); model = glm::rotate(glm::mat4(), yaw, glm::vec3(0.f, 1.f, 0.f)) * model; model = glm::rotate(glm::mat4(), pitch, glm::vec3(1.f, 0.f, 0.f)) * model; model = glm::translate(glm::mat4(), plane.position) * model; glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); plane.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &plane.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(plane.lineWidth); glDrawArrays(GL_LINES, 0, 8); } void DebugDrawing::DrawCircle(const Circle& circle) { BindVertexArray(circleVertexArray); glm::mat4 model(glm::scale(glm::mat4(), glm::vec3(circle.radius, circle.radius, circle.radius))); float yaw = atan2(circle.normal.x, circle.normal.z); float pitch = atan2(circle.normal.y, sqrt(circle.normal.x * circle.normal.x + circle.normal.z * circle.normal.z)); model = glm::rotate(glm::mat4(), yaw, glm::vec3(0.f, 1.f, 0.f)) * model; model = glm::rotate(glm::mat4(), pitch, glm::vec3(1.f, 0.f, 0.f)) * model; model = glm::translate(glm::mat4(), circle.position) * model; glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); circle.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &circle.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(circle.lineWidth); glDrawArrays(GL_LINES, 0, circleVertexCount); } void DebugDrawing::DrawSphere(const Sphere& sphere) { BindVertexArray(sphereVertexArray); glm::mat4 model(glm::scale(glm::mat4(), glm::vec3(sphere.radius, sphere.radius, sphere.radius))); model = glm::translate(glm::mat4(), sphere.position) * model; glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); sphere.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &sphere.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(sphere.lineWidth); glDrawArrays(GL_LINES, 0, sphereVertexCount); } void DebugDrawing::EndDebugDrawing() { glEnable(GL_DEPTH_TEST); BindVertexArray(0); } void DebugDrawing::BindVertexArray(GLuint vertexArray) { if (boundVertexArray != vertexArray) { glBindVertexArray(vertexArray); boundVertexArray = vertexArray; } } void DebugDrawing::CreateVertexArray(const glm::vec3* positions, unsigned int positionCount, GLuint& vertexBuffer, GLuint& vertexArray) { glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, positionCount * sizeof(glm::vec3), positions, GL_STATIC_DRAW); glGenVertexArrays(1, &vertexArray); glBindVertexArray(vertexArray); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), BUFFER_OFFSET(0)); glBindVertexArray(0); } void DebugDrawing::CreateCircle(glm::vec3*& positions, unsigned int& vertexCount, unsigned int detail) { vertexCount = detail * 2; positions = new glm::vec3[vertexCount]; unsigned int i = 0; for (unsigned int j = 0; j <= detail; ++j) { float angle = static_cast<float>(j) / detail * 2.0f * glm::pi<float>(); positions[i++] = glm::vec3(cos(angle), sin(angle), 0.0f); if (j > 0 && j < detail) positions[i++] = glm::vec3(cos(angle), sin(angle), 0.0f); } } // Create UV-sphere with given number of parallel and meridian lines. void DebugDrawing::CreateSphere(glm::vec3*& positions, unsigned int& vertexCount, unsigned int detail) { vertexCount = detail * (4 * detail - 2); positions = new glm::vec3[vertexCount]; // Horizontal lines (meridians). unsigned int i = 0; for (unsigned int m = 1; m < detail; ++m) { float meridian = glm::pi<float>() * m / detail; for (unsigned int p = 0; p <= detail; ++p) { float parallel = 2.0f * glm::pi<float>() * p / detail; float angle = glm::pi<float>() * 0.5f - meridian; float y = sin(angle); float x = cos(angle); positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); if (p > 0 && p < detail) positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); } } // Vertical lines (parallels). for (unsigned int p = 0; p < detail; ++p) { float parallel = 2.0f * glm::pi<float>() * p / detail; for (unsigned int m = 0; m <= detail; ++m) { float meridian = glm::pi<float>() * m / detail; float angle = glm::pi<float>() * 0.5f - meridian; float y = sin(angle); float x = cos(angle); positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); if (m > 0 && m < detail) positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); } } } <commit_msg>Fix cuboid geometry<commit_after>#include "DebugDrawing.hpp" #include <glm/gtc/matrix_transform.hpp> #include "Shader/Shader.hpp" #include "Shader/ShaderProgram.hpp" #include "DebugDrawing.vert.hpp" #include "DebugDrawing.frag.hpp" #include "glm/gtc/constants.hpp" #define BUFFER_OFFSET(i) ((char *)nullptr + (i)) using namespace Video; DebugDrawing::DebugDrawing() { Shader* vertexShader = new Shader(DEBUGDRAWING_VERT, DEBUGDRAWING_VERT_LENGTH, GL_VERTEX_SHADER); Shader* fragmentShader = new Shader(DEBUGDRAWING_FRAG, DEBUGDRAWING_FRAG_LENGTH, GL_FRAGMENT_SHADER); shaderProgram = new ShaderProgram({ vertexShader, fragmentShader }); delete vertexShader; delete fragmentShader; // Create point vertex array. glBindVertexArray(0); glm::vec3 point(0.f, 0.f, 0.f); CreateVertexArray(&point, 1, pointVertexBuffer, pointVertexArray); // Create line vertex array. glm::vec3 line[2]; line[0] = glm::vec3(0.f, 0.f, 0.f); line[1] = glm::vec3(1.f, 1.f, 1.f); CreateVertexArray(line, 2, lineVertexBuffer, lineVertexArray); // Create cuboid vertex array. glm::vec3 box[24]; box[0] = glm::vec3(-0.5f, -0.5f, -0.5f); box[1] = glm::vec3(0.5f, -0.5f, -0.5f); box[2] = glm::vec3(0.5f, -0.5f, -0.5f); box[3] = glm::vec3(0.5f, 0.5f, -0.5f); box[4] = glm::vec3(0.5f, 0.5f, -0.5f); box[5] = glm::vec3(-0.5f, 0.5f, -0.5f); box[6] = glm::vec3(0.5f, 0.5f, -0.5f); box[7] = glm::vec3(0.5f, 0.5f, 0.5f); box[8] = glm::vec3(0.5f, 0.5f, 0.5f); box[9] = glm::vec3(0.5f, -0.5f, 0.5f); box[10] = glm::vec3(0.5f, -0.5f, 0.5f); box[11] = glm::vec3(0.5f, -0.5f, -0.5f); box[12] = glm::vec3(-0.5f, 0.5f, -0.5f); box[13] = glm::vec3(-0.5f, 0.5f, 0.5f); box[14] = glm::vec3(-0.5f, 0.5f, 0.5f); box[15] = glm::vec3(-0.5f, -0.5f, 0.5f); box[16] = glm::vec3(-0.5f, 0.5f, -0.5f); box[17] = glm::vec3(-0.5f, -0.5f, -0.5f); box[18] = glm::vec3(-0.5f, -0.5f, 0.5f); box[19] = glm::vec3(-0.5f, -0.5f, -0.5f); box[20] = glm::vec3(-0.5f, 0.5f, 0.5f); box[21] = glm::vec3(0.5f, 0.5f, 0.5f); box[22] = glm::vec3(-0.5f, -0.5f, 0.5f); box[23] = glm::vec3(0.5f, -0.5f, 0.5f); CreateVertexArray(box, 24, cuboidVertexBuffer, cuboidVertexArray); // Create plane vertex array. glm::vec3 plane[8]; plane[0] = glm::vec3(-1.f, -1.f, 0.f); plane[1] = glm::vec3(1.f, -1.f, 0.f); plane[2] = glm::vec3(1.f, -1.f, 0.f); plane[3] = glm::vec3(1.f, 1.f, 0.f); plane[4] = glm::vec3(1.f, 1.f, 0.f); plane[5] = glm::vec3(-1.f, 1.f, 0.f); plane[6] = glm::vec3(-1.f, 1.f, 0.f); plane[7] = glm::vec3(-1.f, -1.f, 0.f); CreateVertexArray(plane, 8, planeVertexBuffer, planeVertexArray); // Create circle vertex array. glm::vec3* circle; CreateCircle(circle, circleVertexCount, 25); CreateVertexArray(circle, circleVertexCount, circleVertexBuffer, circleVertexArray); delete[] circle; // Create sphere vertex array. glm::vec3* sphere; CreateSphere(sphere, sphereVertexCount, 14); CreateVertexArray(sphere, sphereVertexCount, sphereVertexBuffer, sphereVertexArray); delete[] sphere; } DebugDrawing::~DebugDrawing() { glDeleteBuffers(1, &cuboidVertexBuffer); glDeleteVertexArrays(1, &cuboidVertexArray); glDeleteBuffers(1, &pointVertexBuffer); glDeleteVertexArrays(1, &pointVertexArray); glDeleteBuffers(1, &lineVertexBuffer); glDeleteVertexArrays(1, &lineVertexArray); glDeleteBuffers(1, &planeVertexBuffer); glDeleteVertexArrays(1, &planeVertexArray); glDeleteBuffers(1, &circleVertexBuffer); glDeleteVertexArrays(1, &circleVertexArray); glDeleteBuffers(1, &sphereVertexBuffer); glDeleteVertexArrays(1, &sphereVertexArray); delete shaderProgram; } void DebugDrawing::StartDebugDrawing(const glm::mat4& viewProjectionMatrix) { shaderProgram->Use(); glUniformMatrix4fv(shaderProgram->GetUniformLocation("viewProjection"), 1, GL_FALSE, &viewProjectionMatrix[0][0]); } void DebugDrawing::DrawPoint(const Point& point) { BindVertexArray(pointVertexArray); glm::mat4 model(glm::translate(glm::mat4(), point.position)); glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); point.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &point.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), point.size); glDrawArrays(GL_POINTS, 0, 1); } void DebugDrawing::DrawLine(const Line& line) { BindVertexArray(lineVertexArray); glm::mat4 model(glm::translate(glm::mat4(), line.startPosition) * glm::scale(glm::mat4(), line.endPosition - line.startPosition)); glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); line.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &line.color[0]); glLineWidth(line.width); glDrawArrays(GL_LINES, 0, 2); } void DebugDrawing::DrawCuboid(const Cuboid& cuboid) { BindVertexArray(cuboidVertexArray); glm::mat4 model(cuboid.matrix * glm::scale(glm::mat4(), cuboid.dimensions)); glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); cuboid.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &cuboid.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(cuboid.lineWidth); glDrawArrays(GL_LINES, 0, 24); } void DebugDrawing::DrawPlane(const Plane& plane) { BindVertexArray(planeVertexArray); glm::mat4 model(glm::scale(glm::mat4(), glm::vec3(plane.size * 0.5f, 1.f))); float yaw = atan2(plane.normal.x, plane.normal.z); float pitch = atan2(plane.normal.y, sqrt(plane.normal.x * plane.normal.x + plane.normal.z * plane.normal.z)); model = glm::rotate(glm::mat4(), yaw, glm::vec3(0.f, 1.f, 0.f)) * model; model = glm::rotate(glm::mat4(), pitch, glm::vec3(1.f, 0.f, 0.f)) * model; model = glm::translate(glm::mat4(), plane.position) * model; glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); plane.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &plane.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(plane.lineWidth); glDrawArrays(GL_LINES, 0, 8); } void DebugDrawing::DrawCircle(const Circle& circle) { BindVertexArray(circleVertexArray); glm::mat4 model(glm::scale(glm::mat4(), glm::vec3(circle.radius, circle.radius, circle.radius))); float yaw = atan2(circle.normal.x, circle.normal.z); float pitch = atan2(circle.normal.y, sqrt(circle.normal.x * circle.normal.x + circle.normal.z * circle.normal.z)); model = glm::rotate(glm::mat4(), yaw, glm::vec3(0.f, 1.f, 0.f)) * model; model = glm::rotate(glm::mat4(), pitch, glm::vec3(1.f, 0.f, 0.f)) * model; model = glm::translate(glm::mat4(), circle.position) * model; glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); circle.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &circle.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(circle.lineWidth); glDrawArrays(GL_LINES, 0, circleVertexCount); } void DebugDrawing::DrawSphere(const Sphere& sphere) { BindVertexArray(sphereVertexArray); glm::mat4 model(glm::scale(glm::mat4(), glm::vec3(sphere.radius, sphere.radius, sphere.radius))); model = glm::translate(glm::mat4(), sphere.position) * model; glUniformMatrix4fv(shaderProgram->GetUniformLocation("model"), 1, GL_FALSE, &model[0][0]); sphere.depthTesting ? glEnable(GL_DEPTH_TEST) : glDisable(GL_DEPTH_TEST); glUniform3fv(shaderProgram->GetUniformLocation("color"), 1, &sphere.color[0]); glUniform1f(shaderProgram->GetUniformLocation("size"), 10.f); glLineWidth(sphere.lineWidth); glDrawArrays(GL_LINES, 0, sphereVertexCount); } void DebugDrawing::EndDebugDrawing() { glEnable(GL_DEPTH_TEST); BindVertexArray(0); } void DebugDrawing::BindVertexArray(GLuint vertexArray) { if (boundVertexArray != vertexArray) { glBindVertexArray(vertexArray); boundVertexArray = vertexArray; } } void DebugDrawing::CreateVertexArray(const glm::vec3* positions, unsigned int positionCount, GLuint& vertexBuffer, GLuint& vertexArray) { glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, positionCount * sizeof(glm::vec3), positions, GL_STATIC_DRAW); glGenVertexArrays(1, &vertexArray); glBindVertexArray(vertexArray); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), BUFFER_OFFSET(0)); glBindVertexArray(0); } void DebugDrawing::CreateCircle(glm::vec3*& positions, unsigned int& vertexCount, unsigned int detail) { vertexCount = detail * 2; positions = new glm::vec3[vertexCount]; unsigned int i = 0; for (unsigned int j = 0; j <= detail; ++j) { float angle = static_cast<float>(j) / detail * 2.0f * glm::pi<float>(); positions[i++] = glm::vec3(cos(angle), sin(angle), 0.0f); if (j > 0 && j < detail) positions[i++] = glm::vec3(cos(angle), sin(angle), 0.0f); } } // Create UV-sphere with given number of parallel and meridian lines. void DebugDrawing::CreateSphere(glm::vec3*& positions, unsigned int& vertexCount, unsigned int detail) { vertexCount = detail * (4 * detail - 2); positions = new glm::vec3[vertexCount]; // Horizontal lines (meridians). unsigned int i = 0; for (unsigned int m = 1; m < detail; ++m) { float meridian = glm::pi<float>() * m / detail; for (unsigned int p = 0; p <= detail; ++p) { float parallel = 2.0f * glm::pi<float>() * p / detail; float angle = glm::pi<float>() * 0.5f - meridian; float y = sin(angle); float x = cos(angle); positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); if (p > 0 && p < detail) positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); } } // Vertical lines (parallels). for (unsigned int p = 0; p < detail; ++p) { float parallel = 2.0f * glm::pi<float>() * p / detail; for (unsigned int m = 0; m <= detail; ++m) { float meridian = glm::pi<float>() * m / detail; float angle = glm::pi<float>() * 0.5f - meridian; float y = sin(angle); float x = cos(angle); positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); if (m > 0 && m < detail) positions[i++] = glm::vec3(x * cos(parallel), y, x * sin(parallel)); } } } <|endoftext|>
<commit_before>#include "Target.hpp" #include <opencv2/opencv.hpp> #include <math.h> #include <iostream> Target::Target(std::vector<std::vector<cv::Point> > contour) { if(contour.size() > 1) { edgeL = contour[0]; edgeR = contour[1]; } else { edgeL = contour[0]; edgeR = contour[0]; } //splits the inputted vector into two shapes again } void Target::setTar(bool tar) { Tar = tar; } bool Target::getTar() { return Tar; } double Target::getHeight() { return fabs(getTopPoint().y - getBottomPoint().y); } double Target::getWidth() { return fabs(getRightPoint().x - getLeftPoint().x); } //True if Gears, False if Boilers bool Target::getType() { if (edgeL != edgeR) { return true; } if (getHeight() < getWidth()) { return false; } } /* bool Target::isInitialized() { std::cout << "EDGE" << edge; if (edge.size() == 0) { return false; } return true; } */ void Target::printPoints() //debugging { std::cout << "TopPoint: " << getTopPoint().y << std::endl; std::cout << "BottomPoint: " << getBottomPoint().y << std::endl; std::cout << "LeftPoint: " << getLeftPoint().x << std::endl; std::cout << "RightPoint: " << getRightPoint().x << std::endl; std::cout << "LeftRightPoint: " << getLeftRightPoint().x << std::endl; std::cout << "RightLeftPoint: " << getRightLeftPoint().x << std::endl; std::cout << "Height: " << getHeight() << std::endl; std::cout << "Width: " << getWidth() << std::endl; } cv::Point Target::getCenter()//finds center point of target { cv::Point center((getLeftPoint().x + getRightPoint().x)/2, (getTopPoint().y + getBottomPoint().y)/2); return center; } cv::Point Target::getTopPoint() { cv::Point max = edgeL[0]; for(unsigned int i = 0; i < edgeL.size(); i++) { if(edgeL[i].y > max.y) { max = edgeL[i]; } } return max; } cv::Point Target::getBottomPoint() { cv::Point min = edgeL[0]; for(unsigned int i = 0; i < edgeL.size(); i++) { if(edgeL[i].y < min.y) { min = edgeL[i]; } } return min; } cv::Point Target::getLeftPoint() { cv::Point min = edgeL[0]; for(unsigned int i = 0; i < edgeL.size(); i++) { if(edgeL[i].x < min.x) { min = edgeL[i]; } } return min; } // Uses the right shape for right most point in order to pretend like it's one big shape cv::Point Target::getRightPoint() { cv::Point max = edgeR[0]; for(unsigned int i = 0; i < edgeR.size(); i++) { if(edgeR[i].x > max.x) { max = edgeR[i]; } } return max; } //Right-most point of left shape cv::Point Target::getLeftRightPoint() { cv::Point max = edgeL[0]; for(unsigned int i = 0; i < edgeL.size(); i++) { if(edgeL[i].x > max.x) { max = edgeL[i]; } } return max; } //Left-most point of right shape cv::Point Target::getRightLeftPoint() { cv::Point min = edgeR[0]; for(unsigned int i = 0; i < edgeR.size(); i++) { if(edgeR[i].x < min.x) { min = edgeR[i]; } } return min; } <commit_msg>Deleting old files<commit_after><|endoftext|>
<commit_before>#include <zip_longest.hpp> #include "helpers.hpp" #include <vector> #include <tuple> #include <string> #include <iterator> #include <utility> #include <iterator> #include <sstream> #include <iostream> #include "catch.hpp" using iter::zip_longest; // reopening boost is the only way I can find that gets this to print namespace boost { template <typename T> std::ostream& operator<<(std::ostream& out, const optional<T>& opt) { if (opt) { out << "Just " << *opt; } else { out << "Nothing"; } return out; } } template <typename... Ts> using const_opt_tuple = std::tuple<boost::optional<const Ts&>...>; TEST_CASE("zip longest: correctly detects longest at any position", "[zip_longest]") { const std::vector<int> ivec{2, 4, 6, 8, 10, 12}; const std::vector<std::string> svec{"abc", "def", "xyz"}; const std::string str{"hello"}; SECTION("longest first") { using TP = const_opt_tuple<int, std::string, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(ivec, svec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{ivec[0]}, {svec[0]}, {str[0]}}, TP{{ivec[1]}, {svec[1]}, {str[1]}}, TP{{ivec[2]}, {svec[2]}, {str[2]}}, TP{{ivec[3]}, {}, {str[3]}}, TP{{ivec[4]}, {}, {str[4]}}, TP{{ivec[5]}, {}, {} } }; REQUIRE( results == rc ); } SECTION("longest in middle") { using TP = const_opt_tuple<std::string, int, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, ivec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {ivec[0]}, {str[0]}}, TP{{svec[1]}, {ivec[1]}, {str[1]}}, TP{{svec[2]}, {ivec[2]}, {str[2]}}, TP{{}, {ivec[3]}, {str[3]}}, TP{{}, {ivec[4]}, {str[4]}}, TP{{}, {ivec[5]}, {} } }; REQUIRE( results == rc ); } SECTION("longest at end") { using TP = const_opt_tuple<std::string, char, int>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, str, ivec); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {str[0]}, {ivec[0]}}, TP{{svec[1]}, {str[1]}, {ivec[1]}}, TP{{svec[2]}, {str[2]}, {ivec[2]}}, TP{{}, {str[3]}, {ivec[3]}}, TP{{}, {str[4]}, {ivec[4]}}, TP{{}, {}, {ivec[5]}} }; REQUIRE( results == rc ); } } TEST_CASE("zip longest: when all are empty, terminates right away", "[zip_longest]") { const std::vector<int> ivec{}; const std::vector<std::string> svec{}; const std::string str{}; auto zl = zip_longest(ivec, svec, str); REQUIRE( std::begin(zl) == std::end(zl) ); } TEST_CASE("zip longest: can modify zipped sequences", "[zip_longest]") { std::vector<int> ns1 = {1, 2, 3}; std::vector<int> ns2 = {10, 11, 12}; for (auto&& t : zip_longest(ns1, ns2)) { *std::get<0>(t) = -1; *std::get<1>(t) = -1; } std::vector<int> vc = {-1, -1, -1}; REQUIRE( ns1 == vc ); REQUIRE( ns2 == vc ); } <commit_msg>tests that zip_longest moves and binds correctly<commit_after>#include <zip_longest.hpp> #include "helpers.hpp" #include <vector> #include <tuple> #include <string> #include <iterator> #include <utility> #include <iterator> #include <sstream> #include <iostream> #include "catch.hpp" using iter::zip_longest; // reopening boost is the only way I can find that gets this to print namespace boost { template <typename T> std::ostream& operator<<(std::ostream& out, const optional<T>& opt) { if (opt) { out << "Just " << *opt; } else { out << "Nothing"; } return out; } } template <typename... Ts> using const_opt_tuple = std::tuple<boost::optional<const Ts&>...>; TEST_CASE("zip longest: correctly detects longest at any position", "[zip_longest]") { const std::vector<int> ivec{2, 4, 6, 8, 10, 12}; const std::vector<std::string> svec{"abc", "def", "xyz"}; const std::string str{"hello"}; SECTION("longest first") { using TP = const_opt_tuple<int, std::string, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(ivec, svec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{ivec[0]}, {svec[0]}, {str[0]}}, TP{{ivec[1]}, {svec[1]}, {str[1]}}, TP{{ivec[2]}, {svec[2]}, {str[2]}}, TP{{ivec[3]}, {}, {str[3]}}, TP{{ivec[4]}, {}, {str[4]}}, TP{{ivec[5]}, {}, {} } }; REQUIRE( results == rc ); } SECTION("longest in middle") { using TP = const_opt_tuple<std::string, int, char>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, ivec, str); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {ivec[0]}, {str[0]}}, TP{{svec[1]}, {ivec[1]}, {str[1]}}, TP{{svec[2]}, {ivec[2]}, {str[2]}}, TP{{}, {ivec[3]}, {str[3]}}, TP{{}, {ivec[4]}, {str[4]}}, TP{{}, {ivec[5]}, {} } }; REQUIRE( results == rc ); } SECTION("longest at end") { using TP = const_opt_tuple<std::string, char, int>; using ResVec = std::vector<TP>; auto zl = zip_longest(svec, str, ivec); ResVec results(std::begin(zl), std::end(zl)); ResVec rc = { TP{{svec[0]}, {str[0]}, {ivec[0]}}, TP{{svec[1]}, {str[1]}, {ivec[1]}}, TP{{svec[2]}, {str[2]}, {ivec[2]}}, TP{{}, {str[3]}, {ivec[3]}}, TP{{}, {str[4]}, {ivec[4]}}, TP{{}, {}, {ivec[5]}} }; REQUIRE( results == rc ); } } TEST_CASE("zip longest: when all are empty, terminates right away", "[zip_longest]") { const std::vector<int> ivec{}; const std::vector<std::string> svec{}; const std::string str{}; auto zl = zip_longest(ivec, svec, str); REQUIRE( std::begin(zl) == std::end(zl) ); } TEST_CASE("zip longest: can modify zipped sequences", "[zip_longest]") { std::vector<int> ns1 = {1, 2, 3}; std::vector<int> ns2 = {10, 11, 12}; for (auto&& t : zip_longest(ns1, ns2)) { *std::get<0>(t) = -1; *std::get<1>(t) = -1; } std::vector<int> vc = {-1, -1, -1}; REQUIRE( ns1 == vc ); REQUIRE( ns2 == vc ); } TEST_CASE("zip_longest: binds to lvalues, moves rvalues", "[zip_longest]") { itertest::BasicIterable<char> b1{'x', 'y', 'z'}; itertest::BasicIterable<char> b2{'a', 'b'}; SECTION("bind to first, moves second") { zip_longest(b1, std::move(b2)); } SECTION("move first, bind to second") { zip_longest(std::move(b2), b1); } REQUIRE_FALSE( b1.was_moved_from() ); REQUIRE( b2.was_moved_from() ); } <|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 "google/fhir/fhir_package.h" #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include "google/protobuf/text_format.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "google/fhir/json/fhir_json.h" #include "google/fhir/json/json_sax_handler.h" #include "google/fhir/status/status.h" #include "proto/google/fhir/proto/r4/core/resources/structure_definition.pb.h" #include "proto/google/fhir/proto/r4/core/resources/value_set.pb.h" #include "libarchive/archive.h" #include "libarchive/archive_entry.h" namespace google::fhir { namespace { // Adds the resource described by `resource_json` found within `parent_resource` // to the appropriate ResourceCollection of the given `fhir_package`. Allows the // resource to subsequently be retrieved by its URL from the FhirPackage. // In the case where `resource_json` is located inside a bundle, // `parent_resource` will be the bundle containing the resource. Otherwise, // `resource_json` and `parent_resource` will be the same JSON object. // If the JSON is not a FHIR resource, or not a resource type tracked by the // PackageManager, does nothing and returns an OK status. absl::Status MaybeAddResourceToFhirPackage( std::shared_ptr<const internal::FhirJson> parent_resource, const internal::FhirJson& resource_json, FhirPackage& fhir_package) { if (!resource_json.isObject()) { // Not a json object - definitly not a resource. return absl::OkStatus(); } absl::StatusOr<const std::string> resource_type = GetResourceType(resource_json); if (!resource_type.ok()) { // If no resource type key was found, this is not a FHIR resource. Ignore. // Return status failure for any other kind of failure. return absl::IsNotFound(resource_type.status()) ? absl::OkStatus() : resource_type.status(); } if (*resource_type == "ValueSet") { FHIR_RETURN_IF_ERROR( fhir_package.value_sets.Put(parent_resource, resource_json)); } else if (*resource_type == "CodeSystem") { FHIR_RETURN_IF_ERROR( fhir_package.code_systems.Put(parent_resource, resource_json)); } else if (*resource_type == "StructureDefinition") { FHIR_RETURN_IF_ERROR( fhir_package.structure_definitions.Put(parent_resource, resource_json)); } else if (*resource_type == "SearchParameter") { FHIR_RETURN_IF_ERROR( fhir_package.search_parameters.Put(parent_resource, resource_json)); } else if (*resource_type == "Bundle") { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* entries, resource_json.get("entry")); FHIR_ASSIGN_OR_RETURN(int num_entries, entries->arraySize()); for (int i = 0; i < num_entries; ++i) { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* entry, entries->get(i)); FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* resource, entry->get("resource")); FHIR_RETURN_IF_ERROR(MaybeAddResourceToFhirPackage( parent_resource, *resource, fhir_package)); } } // We got a resource type, but it's not one of the ones we track. Ignore. return absl::OkStatus(); } absl::Status MaybeAddEntryToFhirPackage(absl::string_view entry_name, absl::string_view resource_json, FhirPackage& fhir_package) { if (!absl::EndsWith(entry_name, ".json")) { return absl::OkStatus(); } auto parsed_json = std::make_unique<internal::FhirJson>(); FHIR_RETURN_IF_ERROR( internal::ParseJsonValue(std::string(resource_json), *parsed_json)); internal::FhirJson const* parsed_json_ptr = parsed_json.get(); return MaybeAddResourceToFhirPackage(std::move(parsed_json), *parsed_json_ptr, fhir_package); } // Opens the archive for reading at `archive_file_path` and returns a unique // pointer to the archive. The unique pointer will close and free the archive // when it is destructed. absl::StatusOr<std::unique_ptr<archive, decltype(&archive_read_free)>> OpenArchive(absl::string_view archive_file_path) { // archive_read_free itself calls archive_read_close, so no further cleanup is // required by the caller. std::unique_ptr<archive, decltype(&archive_read_free)> archive( archive_read_new(), &archive_read_free); archive_read_support_filter_all(archive.get()); archive_read_support_format_all(archive.get()); int archive_open_error = archive_read_open_filename( archive.get(), std::string(archive_file_path).c_str(), /*block_size=*/1024); if (archive_open_error != ARCHIVE_OK) { return absl::InvalidArgumentError(absl::StrFormat( "Unable to open archive %s, error code: %d %s.", archive_file_path, archive_open_error, archive_error_string(archive.get()))); } return std::move(archive); } absl::Status LoadPackage(absl::string_view archive_file_path, std::function<absl::Status( absl::string_view entry_name, absl::string_view contents, FhirPackage& package)> handle_entry, FhirPackage& fhir_package) { // The FHIR_ASSIGN_OR_RETURN macro expansion doesn't parse correctly without // placing the type inside a 'using' statement. using archive_ptr = std::unique_ptr<archive, decltype(&archive_read_free)>; FHIR_ASSIGN_OR_RETURN(archive_ptr archive, OpenArchive(archive_file_path)); absl::Status all_errors; archive_entry* entry; while (true) { int read_next_status = archive_read_next_header(archive.get(), &entry); if (read_next_status == ARCHIVE_EOF) { break; } else if (read_next_status == ARCHIVE_RETRY) { continue; } else if (read_next_status != ARCHIVE_OK && read_next_status != ARCHIVE_WARN) { return absl::InvalidArgumentError(absl::StrFormat( "Unable to read archive %s, error code: %d %s.", archive_file_path, read_next_status, archive_error_string(archive.get()))); } std::string entry_name = archive_entry_pathname(entry); // Ignore deprecated package_info data. if (absl::EndsWith(entry_name, "package_info.prototxt") || absl::EndsWith(entry_name, "package_info.textproto")) { continue; } int64 length = archive_entry_size(entry); std::string contents(length, '\0'); int64 read = archive_read_data(archive.get(), &contents[0], length); if (read < length) { return absl::InvalidArgumentError( absl::StrFormat("Unable to read entry %s from archive %s.", entry_name, archive_file_path)); } absl::Status entry_status = handle_entry(entry_name, contents, fhir_package); if (!entry_status.ok()) { // Concatenate all errors founds while processing the package. std::string error_message = absl::StrFormat("Unhandled JSON entry %s due to error: %s.", entry_name, entry_status.message()); if (all_errors.ok()) { all_errors = absl::InvalidArgumentError(absl::StrCat( "Error(s) encountered during parsing: ", error_message)); } else { all_errors = absl::Status( all_errors.code(), absl::StrCat(all_errors.message(), "; ", error_message)); } } } return all_errors; } // Concatenates error messages from the two statuses into a single status. If // one status is ok, returns the other. If both are not ok, returns a new error // with the code of the first status. absl::Status ConcatErrors(const absl::Status& status1, const absl::Status& status2) { if (status1.ok()) { return status2; } else if (status2.ok()) { return status1; } else { return absl::Status(status1.code(), absl::StrCat(status1.message(), "; ", status2.message())); } } } // namespace namespace internal { absl::StatusOr<const FhirJson*> FindResourceInBundle( absl::string_view uri, const FhirJson& bundle_json) { FHIR_ASSIGN_OR_RETURN(const FhirJson* entries, bundle_json.get("entry")); FHIR_ASSIGN_OR_RETURN(int num_entries, entries->arraySize()); for (int i = 0; i < num_entries; ++i) { FHIR_ASSIGN_OR_RETURN(const FhirJson* entry, entries->get(i)); FHIR_ASSIGN_OR_RETURN(const FhirJson* resource, entry->get("resource")); FHIR_ASSIGN_OR_RETURN(std::string resource_type, internal::GetResourceType(*resource)); if (resource_type == "Bundle") { // If the resource is a bundle, recursively search through it. absl::StatusOr<const FhirJson*> bundle_json = FindResourceInBundle(uri, *resource); if (bundle_json.ok()) { // We found the resource! return bundle_json; } else if (bundle_json.status().code() != absl::StatusCode::kNotFound) { // We encountered a parsing error in the bundle to report. return bundle_json.status(); } } else { FHIR_ASSIGN_OR_RETURN(std::string resource_url, internal::GetResourceUrl(*resource)); // Found the resource! if (uri == resource_url) { return resource; } } } return absl::NotFoundError(absl::StrFormat("%s not present in bundle.", uri)); } absl::StatusOr<std::string> GetResourceType(const FhirJson& parsed_json) { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* resource_type_json, parsed_json.get("resourceType")); return resource_type_json->asString(); } absl::StatusOr<std::string> GetResourceUrl(const FhirJson& parsed_json) { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* resource_url_json, parsed_json.get("url")); FHIR_ASSIGN_OR_RETURN(const std::string url, resource_url_json->asString()); if (url.empty()) { return absl::InvalidArgumentError(absl::StrFormat("URL is empty")); } return url; } } // namespace internal absl::StatusOr<std::unique_ptr<FhirPackage>> FhirPackage::Load( absl::string_view archive_file_path) { // We can't use make_unique here because the constructor is private. auto fhir_package = absl::WrapUnique(new FhirPackage()); FHIR_RETURN_IF_ERROR(LoadPackage(archive_file_path, &MaybeAddEntryToFhirPackage, *fhir_package)); return std::move(fhir_package); } absl::StatusOr<std::unique_ptr<FhirPackage>> FhirPackage::Load( absl::string_view archive_file_path, std::function<absl::Status(absl::string_view entry_name, absl::string_view contents, FhirPackage& package)> handle_entry) { // We can't use make_unique here because the constructor is private. auto fhir_package = absl::WrapUnique(new FhirPackage()); // Create a lambda which calls the default MaybeAddEntryToFhirPackage handler // and also calls the user-provided `handle_entry` function. auto handle_entry_wrapper = [&handle_entry](absl::string_view entry_name, absl::string_view contents, FhirPackage& package) { absl::Status add_entry_status = MaybeAddEntryToFhirPackage(entry_name, contents, package); absl::Status handle_entry_status = handle_entry(entry_name, contents, package); return ConcatErrors(add_entry_status, handle_entry_status); }; FHIR_RETURN_IF_ERROR( LoadPackage(archive_file_path, handle_entry_wrapper, *fhir_package)); return std::move(fhir_package); } void FhirPackageManager::AddPackage(std::unique_ptr<FhirPackage> package) { packages_.push_back(std::move(package)); } absl::Status FhirPackageManager::AddPackageAtPath(absl::string_view path) { FHIR_ASSIGN_OR_RETURN(std::unique_ptr<FhirPackage> package, FhirPackage::Load(path)); AddPackage(std::move(package)); return absl::OkStatus(); } } // namespace google::fhir <commit_msg>Include Archive Path in Parsing Error Message<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 "google/fhir/fhir_package.h" #include <functional> #include <memory> #include <optional> #include <string> #include <utility> #include "google/protobuf/text_format.h" #include "absl/status/status.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "google/fhir/json/fhir_json.h" #include "google/fhir/json/json_sax_handler.h" #include "google/fhir/status/status.h" #include "proto/google/fhir/proto/r4/core/resources/structure_definition.pb.h" #include "proto/google/fhir/proto/r4/core/resources/value_set.pb.h" #include "libarchive/archive.h" #include "libarchive/archive_entry.h" namespace google::fhir { namespace { // Adds the resource described by `resource_json` found within `parent_resource` // to the appropriate ResourceCollection of the given `fhir_package`. Allows the // resource to subsequently be retrieved by its URL from the FhirPackage. // In the case where `resource_json` is located inside a bundle, // `parent_resource` will be the bundle containing the resource. Otherwise, // `resource_json` and `parent_resource` will be the same JSON object. // If the JSON is not a FHIR resource, or not a resource type tracked by the // PackageManager, does nothing and returns an OK status. absl::Status MaybeAddResourceToFhirPackage( std::shared_ptr<const internal::FhirJson> parent_resource, const internal::FhirJson& resource_json, FhirPackage& fhir_package) { if (!resource_json.isObject()) { // Not a json object - definitly not a resource. return absl::OkStatus(); } absl::StatusOr<const std::string> resource_type = GetResourceType(resource_json); if (!resource_type.ok()) { // If no resource type key was found, this is not a FHIR resource. Ignore. // Return status failure for any other kind of failure. return absl::IsNotFound(resource_type.status()) ? absl::OkStatus() : resource_type.status(); } if (*resource_type == "ValueSet") { FHIR_RETURN_IF_ERROR( fhir_package.value_sets.Put(parent_resource, resource_json)); } else if (*resource_type == "CodeSystem") { FHIR_RETURN_IF_ERROR( fhir_package.code_systems.Put(parent_resource, resource_json)); } else if (*resource_type == "StructureDefinition") { FHIR_RETURN_IF_ERROR( fhir_package.structure_definitions.Put(parent_resource, resource_json)); } else if (*resource_type == "SearchParameter") { FHIR_RETURN_IF_ERROR( fhir_package.search_parameters.Put(parent_resource, resource_json)); } else if (*resource_type == "Bundle") { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* entries, resource_json.get("entry")); FHIR_ASSIGN_OR_RETURN(int num_entries, entries->arraySize()); for (int i = 0; i < num_entries; ++i) { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* entry, entries->get(i)); FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* resource, entry->get("resource")); FHIR_RETURN_IF_ERROR(MaybeAddResourceToFhirPackage( parent_resource, *resource, fhir_package)); } } // We got a resource type, but it's not one of the ones we track. Ignore. return absl::OkStatus(); } absl::Status MaybeAddEntryToFhirPackage(absl::string_view entry_name, absl::string_view resource_json, FhirPackage& fhir_package) { if (!absl::EndsWith(entry_name, ".json")) { return absl::OkStatus(); } auto parsed_json = std::make_unique<internal::FhirJson>(); FHIR_RETURN_IF_ERROR( internal::ParseJsonValue(std::string(resource_json), *parsed_json)); internal::FhirJson const* parsed_json_ptr = parsed_json.get(); return MaybeAddResourceToFhirPackage(std::move(parsed_json), *parsed_json_ptr, fhir_package); } // Opens the archive for reading at `archive_file_path` and returns a unique // pointer to the archive. The unique pointer will close and free the archive // when it is destructed. absl::StatusOr<std::unique_ptr<archive, decltype(&archive_read_free)>> OpenArchive(absl::string_view archive_file_path) { // archive_read_free itself calls archive_read_close, so no further cleanup is // required by the caller. std::unique_ptr<archive, decltype(&archive_read_free)> archive( archive_read_new(), &archive_read_free); archive_read_support_filter_all(archive.get()); archive_read_support_format_all(archive.get()); int archive_open_error = archive_read_open_filename( archive.get(), std::string(archive_file_path).c_str(), /*block_size=*/1024); if (archive_open_error != ARCHIVE_OK) { return absl::InvalidArgumentError(absl::StrFormat( "Unable to open archive %s, error code: %d %s.", archive_file_path, archive_open_error, archive_error_string(archive.get()))); } return std::move(archive); } absl::Status LoadPackage(absl::string_view archive_file_path, std::function<absl::Status( absl::string_view entry_name, absl::string_view contents, FhirPackage& package)> handle_entry, FhirPackage& fhir_package) { // The FHIR_ASSIGN_OR_RETURN macro expansion doesn't parse correctly without // placing the type inside a 'using' statement. using archive_ptr = std::unique_ptr<archive, decltype(&archive_read_free)>; FHIR_ASSIGN_OR_RETURN(archive_ptr archive, OpenArchive(archive_file_path)); absl::Status all_errors; archive_entry* entry; while (true) { int read_next_status = archive_read_next_header(archive.get(), &entry); if (read_next_status == ARCHIVE_EOF) { break; } else if (read_next_status == ARCHIVE_RETRY) { continue; } else if (read_next_status != ARCHIVE_OK && read_next_status != ARCHIVE_WARN) { return absl::InvalidArgumentError(absl::StrFormat( "Unable to read archive %s, error code: %d %s.", archive_file_path, read_next_status, archive_error_string(archive.get()))); } std::string entry_name = archive_entry_pathname(entry); // Ignore deprecated package_info data. if (absl::EndsWith(entry_name, "package_info.prototxt") || absl::EndsWith(entry_name, "package_info.textproto")) { continue; } int64 length = archive_entry_size(entry); std::string contents(length, '\0'); int64 read = archive_read_data(archive.get(), &contents[0], length); if (read < length) { return absl::InvalidArgumentError( absl::StrFormat("Unable to read entry %s from archive %s.", entry_name, archive_file_path)); } absl::Status entry_status = handle_entry(entry_name, contents, fhir_package); if (!entry_status.ok()) { // Concatenate all errors founds while processing the package. std::string error_message = absl::StrFormat("Unhandled JSON entry %s due to error: %s.", entry_name, entry_status.message()); if (all_errors.ok()) { all_errors = absl::InvalidArgumentError( absl::StrCat("Error(s) encountered during parsing of ", archive_file_path, ": ", error_message)); } else { all_errors = absl::Status( all_errors.code(), absl::StrCat(all_errors.message(), "; ", error_message)); } } } return all_errors; } // Concatenates error messages from the two statuses into a single status. If // one status is ok, returns the other. If both are not ok, returns a new error // with the code of the first status. absl::Status ConcatErrors(const absl::Status& status1, const absl::Status& status2) { if (status1.ok()) { return status2; } else if (status2.ok()) { return status1; } else { return absl::Status(status1.code(), absl::StrCat(status1.message(), "; ", status2.message())); } } } // namespace namespace internal { absl::StatusOr<const FhirJson*> FindResourceInBundle( absl::string_view uri, const FhirJson& bundle_json) { FHIR_ASSIGN_OR_RETURN(const FhirJson* entries, bundle_json.get("entry")); FHIR_ASSIGN_OR_RETURN(int num_entries, entries->arraySize()); for (int i = 0; i < num_entries; ++i) { FHIR_ASSIGN_OR_RETURN(const FhirJson* entry, entries->get(i)); FHIR_ASSIGN_OR_RETURN(const FhirJson* resource, entry->get("resource")); FHIR_ASSIGN_OR_RETURN(std::string resource_type, internal::GetResourceType(*resource)); if (resource_type == "Bundle") { // If the resource is a bundle, recursively search through it. absl::StatusOr<const FhirJson*> bundle_json = FindResourceInBundle(uri, *resource); if (bundle_json.ok()) { // We found the resource! return bundle_json; } else if (bundle_json.status().code() != absl::StatusCode::kNotFound) { // We encountered a parsing error in the bundle to report. return bundle_json.status(); } } else { FHIR_ASSIGN_OR_RETURN(std::string resource_url, internal::GetResourceUrl(*resource)); // Found the resource! if (uri == resource_url) { return resource; } } } return absl::NotFoundError(absl::StrFormat("%s not present in bundle.", uri)); } absl::StatusOr<std::string> GetResourceType(const FhirJson& parsed_json) { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* resource_type_json, parsed_json.get("resourceType")); return resource_type_json->asString(); } absl::StatusOr<std::string> GetResourceUrl(const FhirJson& parsed_json) { FHIR_ASSIGN_OR_RETURN(const internal::FhirJson* resource_url_json, parsed_json.get("url")); FHIR_ASSIGN_OR_RETURN(const std::string url, resource_url_json->asString()); if (url.empty()) { return absl::InvalidArgumentError(absl::StrFormat("URL is empty")); } return url; } } // namespace internal absl::StatusOr<std::unique_ptr<FhirPackage>> FhirPackage::Load( absl::string_view archive_file_path) { // We can't use make_unique here because the constructor is private. auto fhir_package = absl::WrapUnique(new FhirPackage()); FHIR_RETURN_IF_ERROR(LoadPackage(archive_file_path, &MaybeAddEntryToFhirPackage, *fhir_package)); return std::move(fhir_package); } absl::StatusOr<std::unique_ptr<FhirPackage>> FhirPackage::Load( absl::string_view archive_file_path, std::function<absl::Status(absl::string_view entry_name, absl::string_view contents, FhirPackage& package)> handle_entry) { // We can't use make_unique here because the constructor is private. auto fhir_package = absl::WrapUnique(new FhirPackage()); // Create a lambda which calls the default MaybeAddEntryToFhirPackage handler // and also calls the user-provided `handle_entry` function. auto handle_entry_wrapper = [&handle_entry](absl::string_view entry_name, absl::string_view contents, FhirPackage& package) { absl::Status add_entry_status = MaybeAddEntryToFhirPackage(entry_name, contents, package); absl::Status handle_entry_status = handle_entry(entry_name, contents, package); return ConcatErrors(add_entry_status, handle_entry_status); }; FHIR_RETURN_IF_ERROR( LoadPackage(archive_file_path, handle_entry_wrapper, *fhir_package)); return std::move(fhir_package); } void FhirPackageManager::AddPackage(std::unique_ptr<FhirPackage> package) { packages_.push_back(std::move(package)); } absl::Status FhirPackageManager::AddPackageAtPath(absl::string_view path) { FHIR_ASSIGN_OR_RETURN(std::unique_ptr<FhirPackage> package, FhirPackage::Load(path)); AddPackage(std::move(package)); return absl::OkStatus(); } } // namespace google::fhir <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUITreeItem.cpp created: 5-13-07 author: Jonathan Welch (Based on Code by David Durant) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUI/widgets/Tree.h" #include "CEGUI/widgets/TreeItem.h" #include "CEGUI/System.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Image.h" #include "CEGUI/FontManager.h" #include "CEGUI/Font.h" #include "CEGUI/Window.h" #include <algorithm> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUI/FribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUI/MinibidiVisualMapping.h" #else #include "CEGUI/BidiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// BasicRenderedStringParser TreeItem::d_stringParser; /************************************************************************* Constants *************************************************************************/ const Colour TreeItem::DefaultSelectionColour = 0xFF4444AA; const Colour TreeItem::DefaultTextColour = 0xFFFFFFFF; /************************************************************************* Base class constructor *************************************************************************/ TreeItem::TreeItem(const String& text, uint item_id, void* item_data, bool disabled, bool auto_delete) : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_itemID(item_id), d_itemData(item_data), d_selected(false), d_disabled(disabled), d_autoDelete(auto_delete), d_buttonLocation(Rectf(0, 0, 0, 0)), d_owner(0), d_selectCols(DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour), d_selectBrush(0), d_textCols(DefaultTextColour, DefaultTextColour, DefaultTextColour, DefaultTextColour), d_font(0), d_iconImage(0), d_isOpen(false), d_renderedStringValid(false) { setText(text); } //----------------------------------------------------------------------------// TreeItem::~TreeItem(void) { CEGUI_DELETE_AO d_bidiVisualMapping; } /************************************************************************* Set the selection highlighting brush image. *************************************************************************/ void TreeItem::setSelectionBrushImage(const String& name) { setSelectionBrushImage( &ImageManager::getSingleton().get(name)); } /************************************************************************* Return a ColourRect object describing the colours in 'cols' after having their alpha component modulated by the value 'alpha'. *************************************************************************/ ColourRect TreeItem::getModulateAlphaColourRect(const ColourRect& cols, float alpha) const { return ColourRect ( calculateModulatedAlphaColour(cols.d_top_left, alpha), calculateModulatedAlphaColour(cols.d_top_right, alpha), calculateModulatedAlphaColour(cols.d_bottom_left, alpha), calculateModulatedAlphaColour(cols.d_bottom_right, alpha) ); } /************************************************************************* Return a colour value describing the colour specified by 'col' after having its alpha component modulated by the value 'alpha'. *************************************************************************/ Colour TreeItem::calculateModulatedAlphaColour(Colour col, float alpha) const { Colour temp(col); temp.setAlpha(temp.getAlpha() * alpha); return temp; } /************************************************************************* Return a pointer to the font being used by this TreeItem *************************************************************************/ const Font* TreeItem::getFont(void) const { // prefer out own font if (d_font != 0) return d_font; // try our owner window's font setting // (may be null if owner uses non existant default font) else if (d_owner != 0) return d_owner->getFont(); // no owner, just use the default (which may be NULL anyway) else return System::getSingleton().getDefaultFont(); } /************************************************************************* Set the font to be used by this TreeItem *************************************************************************/ void TreeItem::setFont(const String& font_name) { setFont(&FontManager::getSingleton().get(font_name)); } //----------------------------------------------------------------------------// void TreeItem::setFont(const Font* font) { d_font = font; d_renderedStringValid = false; } //----------------------------------------------------------------------------// /************************************************************************* Return the rendered pixel size of this tree item. *************************************************************************/ Sizef TreeItem::getPixelSize(void) const { const Font* fnt = getFont(); if (!fnt) return Sizef(0, 0); if (!d_renderedStringValid) parseTextString(); Sizef sz(0.0f, 0.0f); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { const Sizef line_sz(d_renderedString.getPixelSize(i)); sz.d_height += line_sz.d_height; if (line_sz.d_width > sz.d_width) sz.d_width = line_sz.d_width; } return sz; } /************************************************************************* Add the given TreeItem to this item's list. *************************************************************************/ void TreeItem::addItem(TreeItem* item) { if (item != 0) { Tree* parentWindow = (Tree*)getOwnerWindow(); // establish ownership item->setOwnerWindow(parentWindow); // if sorting is enabled, re-sort the tree if (parentWindow->isSortEnabled()) { d_listItems.insert( std::upper_bound(d_listItems.begin(), d_listItems.end(), item, &lbi_less), item); } // not sorted, just stick it on the end. else { d_listItems.push_back(item); } WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } /************************************************************************* Remove the given TreeItem from this item's list. *************************************************************************/ void TreeItem::removeItem(const TreeItem* item) { if (item) { Tree* parentWindow = (Tree*)getOwnerWindow(); LBItemList::iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); if (pos != d_listItems.end()) { (*pos)->setOwnerWindow(0); d_listItems.erase(pos); if (item == parentWindow->d_lastSelected) parentWindow->d_lastSelected = 0; if (item->isAutoDeleted()) CEGUI_DELETE_AO item; WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } } TreeItem *TreeItem::getTreeItemFromIndex(size_t itemIndex) { if (itemIndex > d_listItems.size()) return 0; return d_listItems[itemIndex]; } /************************************************************************* Draw the tree item in its current state. *************************************************************************/ void TreeItem::draw(GeometryBuffer& buffer, const Rectf& targetRect, float alpha, const Rectf* clipper) const { Rectf finalRect(targetRect); if (d_iconImage != 0) { Rectf finalPos(finalRect); finalPos.setWidth(targetRect.getHeight()); finalPos.setHeight(targetRect.getHeight()); d_iconImage->render(buffer, finalPos, clipper, ColourRect(Colour(1,1,1,alpha))); finalRect.d_min.d_x += targetRect.getHeight(); } if (d_selected && d_selectBrush != 0) d_selectBrush->render(buffer, finalRect, clipper, getModulateAlphaColourRect(d_selectCols, alpha)); const Font* font = getFont(); if (!font) return; Vector2f draw_pos(finalRect.getPosition()); draw_pos.d_y -= (font->getLineSpacing() - font->getBaseline()) * 0.5f; if (!d_renderedStringValid) parseTextString(); const ColourRect final_colours( getModulateAlphaColourRect(ColourRect(0xFFFFFFFF), alpha)); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { d_renderedString.draw(i, buffer, draw_pos, &final_colours, clipper, 0.0f); draw_pos.d_y += d_renderedString.getPixelSize(i).d_height; } } /************************************************************************* Set the colours used for selection highlighting. *************************************************************************/ void TreeItem::setSelectionColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_selectCols.d_top_left = top_left_colour; d_selectCols.d_top_right = top_right_colour; d_selectCols.d_bottom_left = bottom_left_colour; d_selectCols.d_bottom_right = bottom_right_colour; } /************************************************************************* Set the colours used for text rendering. *************************************************************************/ void TreeItem::setTextColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_textCols.d_top_left = top_left_colour; d_textCols.d_top_right = top_right_colour; d_textCols.d_bottom_left = bottom_left_colour; d_textCols.d_bottom_right = bottom_right_colour; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::setText( const String& text ) { d_textLogical = text; d_bidiDataValid = false; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::parseTextString() const { d_renderedString = d_stringParser.parse(getTextVisual(), const_cast<Font*>(getFont()), &d_textCols); d_renderedStringValid = true; } //----------------------------------------------------------------------------// const String& TreeItem::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>Auto delete tree item's children upon destruction<commit_after>/*********************************************************************** filename: CEGUITreeItem.cpp created: 5-13-07 author: Jonathan Welch (Based on Code by David Durant) *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "CEGUI/widgets/Tree.h" #include "CEGUI/widgets/TreeItem.h" #include "CEGUI/System.h" #include "CEGUI/ImageManager.h" #include "CEGUI/Image.h" #include "CEGUI/FontManager.h" #include "CEGUI/Font.h" #include "CEGUI/Window.h" #include <algorithm> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUI/FribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUI/MinibidiVisualMapping.h" #else #include "CEGUI/BidiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// BasicRenderedStringParser TreeItem::d_stringParser; /************************************************************************* Constants *************************************************************************/ const Colour TreeItem::DefaultSelectionColour = 0xFF4444AA; const Colour TreeItem::DefaultTextColour = 0xFFFFFFFF; /************************************************************************* Base class constructor *************************************************************************/ TreeItem::TreeItem(const String& text, uint item_id, void* item_data, bool disabled, bool auto_delete) : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(CEGUI_NEW_AO MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_itemID(item_id), d_itemData(item_data), d_selected(false), d_disabled(disabled), d_autoDelete(auto_delete), d_buttonLocation(Rectf(0, 0, 0, 0)), d_owner(0), d_selectCols(DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour, DefaultSelectionColour), d_selectBrush(0), d_textCols(DefaultTextColour, DefaultTextColour, DefaultTextColour, DefaultTextColour), d_font(0), d_iconImage(0), d_isOpen(false), d_renderedStringValid(false) { setText(text); } //----------------------------------------------------------------------------// TreeItem::~TreeItem(void) { // delete any items we are supposed to for (size_t i = 0; i < getItemCount(); ++i) { // if item is supposed to be deleted by us if (d_listItems[i]->isAutoDeleted()) { // clean up this item. CEGUI_DELETE_AO d_listItems[i]; } } CEGUI_DELETE_AO d_bidiVisualMapping; } /************************************************************************* Set the selection highlighting brush image. *************************************************************************/ void TreeItem::setSelectionBrushImage(const String& name) { setSelectionBrushImage( &ImageManager::getSingleton().get(name)); } /************************************************************************* Return a ColourRect object describing the colours in 'cols' after having their alpha component modulated by the value 'alpha'. *************************************************************************/ ColourRect TreeItem::getModulateAlphaColourRect(const ColourRect& cols, float alpha) const { return ColourRect ( calculateModulatedAlphaColour(cols.d_top_left, alpha), calculateModulatedAlphaColour(cols.d_top_right, alpha), calculateModulatedAlphaColour(cols.d_bottom_left, alpha), calculateModulatedAlphaColour(cols.d_bottom_right, alpha) ); } /************************************************************************* Return a colour value describing the colour specified by 'col' after having its alpha component modulated by the value 'alpha'. *************************************************************************/ Colour TreeItem::calculateModulatedAlphaColour(Colour col, float alpha) const { Colour temp(col); temp.setAlpha(temp.getAlpha() * alpha); return temp; } /************************************************************************* Return a pointer to the font being used by this TreeItem *************************************************************************/ const Font* TreeItem::getFont(void) const { // prefer out own font if (d_font != 0) return d_font; // try our owner window's font setting // (may be null if owner uses non existant default font) else if (d_owner != 0) return d_owner->getFont(); // no owner, just use the default (which may be NULL anyway) else return System::getSingleton().getDefaultFont(); } /************************************************************************* Set the font to be used by this TreeItem *************************************************************************/ void TreeItem::setFont(const String& font_name) { setFont(&FontManager::getSingleton().get(font_name)); } //----------------------------------------------------------------------------// void TreeItem::setFont(const Font* font) { d_font = font; d_renderedStringValid = false; } //----------------------------------------------------------------------------// /************************************************************************* Return the rendered pixel size of this tree item. *************************************************************************/ Sizef TreeItem::getPixelSize(void) const { const Font* fnt = getFont(); if (!fnt) return Sizef(0, 0); if (!d_renderedStringValid) parseTextString(); Sizef sz(0.0f, 0.0f); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { const Sizef line_sz(d_renderedString.getPixelSize(i)); sz.d_height += line_sz.d_height; if (line_sz.d_width > sz.d_width) sz.d_width = line_sz.d_width; } return sz; } /************************************************************************* Add the given TreeItem to this item's list. *************************************************************************/ void TreeItem::addItem(TreeItem* item) { if (item != 0) { Tree* parentWindow = (Tree*)getOwnerWindow(); // establish ownership item->setOwnerWindow(parentWindow); // if sorting is enabled, re-sort the tree if (parentWindow->isSortEnabled()) { d_listItems.insert( std::upper_bound(d_listItems.begin(), d_listItems.end(), item, &lbi_less), item); } // not sorted, just stick it on the end. else { d_listItems.push_back(item); } WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } /************************************************************************* Remove the given TreeItem from this item's list. *************************************************************************/ void TreeItem::removeItem(const TreeItem* item) { if (item) { Tree* parentWindow = (Tree*)getOwnerWindow(); LBItemList::iterator pos = std::find(d_listItems.begin(), d_listItems.end(), item); if (pos != d_listItems.end()) { (*pos)->setOwnerWindow(0); d_listItems.erase(pos); if (item == parentWindow->d_lastSelected) parentWindow->d_lastSelected = 0; if (item->isAutoDeleted()) CEGUI_DELETE_AO item; WindowEventArgs args(parentWindow); parentWindow->onListContentsChanged(args); } } } TreeItem *TreeItem::getTreeItemFromIndex(size_t itemIndex) { if (itemIndex > d_listItems.size()) return 0; return d_listItems[itemIndex]; } /************************************************************************* Draw the tree item in its current state. *************************************************************************/ void TreeItem::draw(GeometryBuffer& buffer, const Rectf& targetRect, float alpha, const Rectf* clipper) const { Rectf finalRect(targetRect); if (d_iconImage != 0) { Rectf finalPos(finalRect); finalPos.setWidth(targetRect.getHeight()); finalPos.setHeight(targetRect.getHeight()); d_iconImage->render(buffer, finalPos, clipper, ColourRect(Colour(1,1,1,alpha))); finalRect.d_min.d_x += targetRect.getHeight(); } if (d_selected && d_selectBrush != 0) d_selectBrush->render(buffer, finalRect, clipper, getModulateAlphaColourRect(d_selectCols, alpha)); const Font* font = getFont(); if (!font) return; Vector2f draw_pos(finalRect.getPosition()); draw_pos.d_y -= (font->getLineSpacing() - font->getBaseline()) * 0.5f; if (!d_renderedStringValid) parseTextString(); const ColourRect final_colours( getModulateAlphaColourRect(ColourRect(0xFFFFFFFF), alpha)); for (size_t i = 0; i < d_renderedString.getLineCount(); ++i) { d_renderedString.draw(i, buffer, draw_pos, &final_colours, clipper, 0.0f); draw_pos.d_y += d_renderedString.getPixelSize(i).d_height; } } /************************************************************************* Set the colours used for selection highlighting. *************************************************************************/ void TreeItem::setSelectionColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_selectCols.d_top_left = top_left_colour; d_selectCols.d_top_right = top_right_colour; d_selectCols.d_bottom_left = bottom_left_colour; d_selectCols.d_bottom_right = bottom_right_colour; } /************************************************************************* Set the colours used for text rendering. *************************************************************************/ void TreeItem::setTextColours(Colour top_left_colour, Colour top_right_colour, Colour bottom_left_colour, Colour bottom_right_colour) { d_textCols.d_top_left = top_left_colour; d_textCols.d_top_right = top_right_colour; d_textCols.d_bottom_left = bottom_left_colour; d_textCols.d_bottom_right = bottom_right_colour; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::setText( const String& text ) { d_textLogical = text; d_bidiDataValid = false; d_renderedStringValid = false; } //----------------------------------------------------------------------------// void TreeItem::parseTextString() const { d_renderedString = d_stringParser.parse(getTextVisual(), const_cast<Font*>(getFont()), &d_textCols); d_renderedStringValid = true; } //----------------------------------------------------------------------------// const String& TreeItem::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #include "../precompiled.hpp" #include "abstract_stream_socket.hpp" #include "socket_address.hpp" #include "../static/network_driver.hpp" #include "../utilities.hpp" namespace poseidon { Abstract_Stream_Socket:: ~Abstract_Stream_Socket() { } IO_Result Abstract_Stream_Socket:: do_call_stream_preshutdown_nolock() noexcept try { // Call `do_stream_preshutdown_nolock()`, ignoring any exeptions. return this->do_stream_preshutdown_nolock(); } catch(const exception& stdex) { POSEIDON_LOG_WARN("Failed to perform graceful shutdown on stream socket: $1\n" "[exception class `$2`]", stdex.what(), typeid(stdex).name()); return io_result_eof; } IO_Result Abstract_Stream_Socket:: do_async_shutdown_nolock() noexcept { switch(this->m_cstate) { case connection_state_initial: case connection_state_connecting: // Shut down the connection. Discard pending data. ::shutdown(this->get_fd(), SHUT_RDWR); this->m_cstate = connection_state_closed; POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (not established): $1", this); return io_result_eof; case connection_state_established: case connection_state_closing: { // Ensure pending data are delivered. if(this->m_wqueue.size()) { this->m_cstate = connection_state_closing; POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (data pending): $1", this); return io_result_not_eof; } // Pending data have been cleared. Try shutting down. auto io_res = this->do_call_stream_preshutdown_nolock(); if(io_res != io_result_eof) { this->m_cstate = connection_state_closing; POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (preshutdown pending): $1", this); return io_res; } // Shutdown completed. ::shutdown(this->get_fd(), SHUT_RDWR); this->m_cstate = connection_state_closed; POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (pending data clear): $1", this); return io_result_eof; } case connection_state_closed: // Do nothing. return io_result_eof; default: ROCKET_ASSERT(false); } } IO_Result Abstract_Stream_Socket:: do_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size) { lock.assign(this->m_mutex); // If the stream is in CLOSED state, fail. if(this->m_cstate == connection_state_closed) return io_result_eof; // Try reading some bytes. auto io_res = this->do_stream_read_nolock(hint, size); if(io_res < 0) return io_res; if(io_res == io_result_eof) { this->do_async_shutdown_nolock(); return io_result_eof; } // Process the data that have been read. lock.unlock(); this->do_on_async_receive(hint, static_cast<size_t>(io_res)); lock.assign(this->m_mutex); return io_res; } size_t Abstract_Stream_Socket:: do_write_queue_size(Si_Mutex::unique_lock& lock) const { lock.assign(this->m_mutex); // Get the size of pending data. size_t size = this->m_wqueue.size(); if(size != 0) return size; // If a shutdown request is pending, report at least one byte. if(this->m_cstate == connection_state_closing) return 1; // There is nothing to write. return 0; } IO_Result Abstract_Stream_Socket:: do_on_async_poll_write(Si_Mutex::unique_lock& lock, void* /*hint*/, size_t /*size*/) { lock.assign(this->m_mutex); // If the stream is in CLOSED state, fail. if(this->m_cstate == connection_state_closed) return io_result_eof; // If the stream is in CONNECTING state, mark it ESTABLISHED. if(this->m_cstate < connection_state_established) { this->m_cstate = connection_state_established; lock.unlock(); this->do_on_async_establish(); lock.assign(this->m_mutex); } // Try writing some bytes. size_t size = this->m_wqueue.size(); if(size == 0) { if(this->m_cstate <= connection_state_established) return io_result_eof; // Shut down the connection completely now. return this->do_async_shutdown_nolock(); } auto io_res = this->do_stream_write_nolock(this->m_wqueue.data(), size); if(io_res < 0) return io_res; // Remove data that have been written. this->m_wqueue.discard(static_cast<size_t>(io_res)); return io_res; } void Abstract_Stream_Socket:: do_on_async_poll_shutdown(int err) { Si_Mutex::unique_lock lock(this->m_mutex); this->m_cstate = connection_state_closed; lock.unlock(); this->do_on_async_shutdown(err); } void Abstract_Stream_Socket:: do_async_connect(const Socket_Address& addr) { // Lock the stream and examine connection state. Si_Mutex::unique_lock lock(this->m_mutex); if(this->m_cstate != connection_state_initial) POSEIDON_THROW("another connection already in progress or established"); // Initiate the connection. this->do_stream_preconnect_nolock(); // No matter whether `::connect()` succeeds or fails with `EINPROGRESS`, the current // socket is set to the CONNECTING state. if(::connect(this->get_fd(), addr.data(), addr.size()) != 0) { int err = errno; if(err != EINPROGRESS) POSEIDON_THROW("failed to initiate connection to '$2'\n" "[`connect()` failed: $1]", noadl::format_errno(err), addr); } this->m_cstate = connection_state_connecting; } Socket_Address Abstract_Stream_Socket:: get_remote_address() const { // Try getting the remote address. Socket_Address::storage_type addrst; Socket_Address::size_type addrlen = sizeof(addrst); if(::getpeername(this->get_fd(), addrst, &addrlen) != 0) POSEIDON_THROW("could not get remote socket address\n" "[`getpeername()` failed: $1]", noadl::format_errno(errno)); return { addrst, addrlen }; } bool Abstract_Stream_Socket:: async_send(const void* data, size_t size) { Si_Mutex::unique_lock lock(this->m_mutex); if(this->m_cstate > connection_state_established) return false; // Append data to the write queue. this->m_wqueue.putn(static_cast<const char*>(data), size); lock.unlock(); // Notify the driver about availability of outgoing data. Network_Driver::notify_writable_internal(this); return true; } bool Abstract_Stream_Socket:: async_shutdown() noexcept { Si_Mutex::unique_lock lock(this->m_mutex); if(this->m_cstate > connection_state_established) return false; // Initiate asynchronous shutdown. this->do_async_shutdown_nolock(); lock.unlock(); // Notify the driver about availability of outgoing data. Network_Driver::notify_writable_internal(this); return true; } } // namespace poseidon <commit_msg>network/abstract_stream_socket: Cleanup<commit_after>// This file is part of Poseidon. // Copyleft 2020, LH_Mouse. All wrongs reserved. #include "../precompiled.hpp" #include "abstract_stream_socket.hpp" #include "socket_address.hpp" #include "../static/network_driver.hpp" #include "../utilities.hpp" namespace poseidon { Abstract_Stream_Socket:: ~Abstract_Stream_Socket() { } IO_Result Abstract_Stream_Socket:: do_call_stream_preshutdown_nolock() noexcept try { // Call `do_stream_preshutdown_nolock()`, ignoring any exeptions. return this->do_stream_preshutdown_nolock(); } catch(const exception& stdex) { POSEIDON_LOG_WARN("Failed to perform graceful shutdown on stream socket: $1\n" "[exception class `$2`]", stdex.what(), typeid(stdex).name()); return io_result_eof; } IO_Result Abstract_Stream_Socket:: do_async_shutdown_nolock() noexcept { switch(this->m_cstate) { case connection_state_initial: case connection_state_connecting: // Shut down the connection. Discard pending data. ::shutdown(this->get_fd(), SHUT_RDWR); this->m_cstate = connection_state_closed; POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (not established): $1", this); return io_result_eof; case connection_state_established: { // Ensure pending data are delivered. if(this->m_wqueue.size()) { ::shutdown(this->get_fd(), SHUT_RD); this->m_cstate = connection_state_closing; POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (data pending): $1", this); return io_result_not_eof; } // Wait for shutdown. auto io_res = this->do_call_stream_preshutdown_nolock(); if(io_res != io_result_eof) { ::shutdown(this->get_fd(), SHUT_RD); this->m_cstate = connection_state_closing; POSEIDON_LOG_TRACE("Marked stream socket as CLOSING (preshutdown pending): $1", this); return io_res; } // Close the connection. ::shutdown(this->get_fd(), SHUT_RDWR); this->m_cstate = connection_state_closed; POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (pending data clear): $1", this); return io_result_eof; } case connection_state_closing: { // Ensure pending data are delivered. if(this->m_wqueue.size()) return io_result_not_eof; // Wait for shutdown. auto io_res = this->do_call_stream_preshutdown_nolock(); if(io_res != io_result_eof) return io_res; // Close the connection. ::shutdown(this->get_fd(), SHUT_RDWR); this->m_cstate = connection_state_closed; POSEIDON_LOG_TRACE("Marked stream socket as CLOSED (pending data clear): $1", this); return io_result_eof; } case connection_state_closed: // Do nothing. return io_result_eof; default: ROCKET_ASSERT(false); } } IO_Result Abstract_Stream_Socket:: do_on_async_poll_read(Si_Mutex::unique_lock& lock, void* hint, size_t size) { lock.assign(this->m_mutex); // If the stream is in CLOSED state, fail. if(this->m_cstate == connection_state_closed) return io_result_eof; // Try reading some bytes. auto io_res = this->do_stream_read_nolock(hint, size); if(io_res < 0) return io_res; if(io_res == io_result_eof) { this->do_async_shutdown_nolock(); return io_result_eof; } // Process the data that have been read. lock.unlock(); this->do_on_async_receive(hint, static_cast<size_t>(io_res)); lock.assign(this->m_mutex); return io_res; } size_t Abstract_Stream_Socket:: do_write_queue_size(Si_Mutex::unique_lock& lock) const { lock.assign(this->m_mutex); // Get the size of pending data. size_t size = this->m_wqueue.size(); if(size != 0) return size; // If a shutdown request is pending, report at least one byte. if(this->m_cstate == connection_state_closing) return 1; // There is nothing to write. return 0; } IO_Result Abstract_Stream_Socket:: do_on_async_poll_write(Si_Mutex::unique_lock& lock, void* /*hint*/, size_t /*size*/) { lock.assign(this->m_mutex); // If the stream is in CLOSED state, fail. if(this->m_cstate == connection_state_closed) return io_result_eof; // If the stream is in CONNECTING state, mark it ESTABLISHED. if(this->m_cstate < connection_state_established) { this->m_cstate = connection_state_established; lock.unlock(); this->do_on_async_establish(); lock.assign(this->m_mutex); } // Try writing some bytes. size_t size = this->m_wqueue.size(); if(size == 0) { if(this->m_cstate <= connection_state_established) return io_result_eof; // Shut down the connection completely now. return this->do_async_shutdown_nolock(); } auto io_res = this->do_stream_write_nolock(this->m_wqueue.data(), size); if(io_res < 0) return io_res; // Remove data that have been written. this->m_wqueue.discard(static_cast<size_t>(io_res)); return io_res; } void Abstract_Stream_Socket:: do_on_async_poll_shutdown(int err) { Si_Mutex::unique_lock lock(this->m_mutex); this->m_cstate = connection_state_closed; lock.unlock(); this->do_on_async_shutdown(err); } void Abstract_Stream_Socket:: do_async_connect(const Socket_Address& addr) { // Lock the stream and examine connection state. Si_Mutex::unique_lock lock(this->m_mutex); if(this->m_cstate != connection_state_initial) POSEIDON_THROW("another connection already in progress or established"); // Initiate the connection. this->do_stream_preconnect_nolock(); // No matter whether `::connect()` succeeds or fails with `EINPROGRESS`, the current // socket is set to the CONNECTING state. if(::connect(this->get_fd(), addr.data(), addr.size()) != 0) { int err = errno; if(err != EINPROGRESS) POSEIDON_THROW("failed to initiate connection to '$2'\n" "[`connect()` failed: $1]", noadl::format_errno(err), addr); } this->m_cstate = connection_state_connecting; } Socket_Address Abstract_Stream_Socket:: get_remote_address() const { // Try getting the remote address. Socket_Address::storage_type addrst; Socket_Address::size_type addrlen = sizeof(addrst); if(::getpeername(this->get_fd(), addrst, &addrlen) != 0) POSEIDON_THROW("could not get remote socket address\n" "[`getpeername()` failed: $1]", noadl::format_errno(errno)); return { addrst, addrlen }; } bool Abstract_Stream_Socket:: async_send(const void* data, size_t size) { Si_Mutex::unique_lock lock(this->m_mutex); if(this->m_cstate > connection_state_established) return false; // Append data to the write queue. this->m_wqueue.putn(static_cast<const char*>(data), size); lock.unlock(); // Notify the driver about availability of outgoing data. Network_Driver::notify_writable_internal(this); return true; } bool Abstract_Stream_Socket:: async_shutdown() noexcept { Si_Mutex::unique_lock lock(this->m_mutex); if(this->m_cstate > connection_state_established) return false; // Initiate asynchronous shutdown. this->do_async_shutdown_nolock(); lock.unlock(); // Notify the driver about availability of outgoing data. Network_Driver::notify_writable_internal(this); return true; } } // namespace poseidon <|endoftext|>
<commit_before>/* Forecast class provides weather conditions for 3 next days */ #ifndef FORECAST_HPP #define FORECAST_HPP #include "weather.hpp" namespace wunderground { class Forecast:public Weather { public: Forecast()=default; Forecast(std::string); /* load and parse xml file with all weather data param city: city name for which you want weather data param state: state name */ virtual void loadData(std::string city,std::string state); std::list<std::pair<std::string ,std::string>> conditions(); /* Returns specified condition for specified day e.g. getCondition("temperature","monday"); param condition: high temperature, low temperature, weather, precipitation, wind speed, wind direction, humidity param day: one of 7 weekdays */ std::string getCondition(std::string condition,std::string day); /* prints all data for 3 days in pairs. e.g. weather clear */ void printConditions(); /* all data is saved in this list */ std::list<std::pair<std::string,std::string>> lista; }; } #endif // FORECAST_HPP <commit_msg>Update forecast.hpp<commit_after>/* Forecast class provides weather conditions for 3 next days */ #ifndef FORECAST_HPP #define FORECAST_HPP #include "weather.hpp" namespace wunderground { class Forecast:public Weather { public: Forecast()=default; Forecast(std::string); /* load and parse xml file with all weather data param city: city name for which you want weather data param state: state name */ virtual void loadData(std::string city,std::string state); /* Returns specified condition for specified day e.g. getCondition("temperature","monday"); param condition: high temperature, low temperature, weather, precipitation, wind speed, wind direction, humidity param day: one of 7 weekdays */ std::string getCondition(std::string condition,std::string day); }; } #endif // FORECAST_HPP <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __PROVISIONER_PATHS_HPP__ #define __PROVISIONER_PATHS_HPP__ #include <string> #include <mesos/mesos.hpp> #include <stout/hashmap.hpp> #include <stout/hashset.hpp> #include <stout/try.hpp> namespace mesos { namespace internal { namespace slave { namespace provisioner { namespace paths { // The provisioner rootfs directory is as follows: // <work_dir> ('--work_dir' flag) // |-- provisioner // |-- containers // |-- <container_id> // |-- backends // |-- <backend> (copy, bind, etc.) // |-- rootfses // |-- <rootfs_id> (the rootfs) // |-- containers (nested sub-containers) // |-- <container_id> // |-- backends // |-- <backend> (copy, bind, etc.) // |-- rootfses // |-- <rootfs_id> (the rootfs) // // There can be multiple backends due to the change of backend flags. // Under each backend a rootfs is identified by the 'rootfs_id' which // is a UUID. std::string getContainerDir( const std::string& provisionerDir, const ContainerID& containerId); std::string getContainerRootfsDir( const std::string& provisionerDir, const ContainerID& containerId, const std::string& backend, const std::string& rootfsId); // Recursively "ls" the container directory and return a map of // backend -> {rootfsId, ...} Try<hashmap<std::string, hashset<std::string>>> listContainerRootfses( const std::string& provisionerDir, const ContainerID& containerId); // Return a set of container IDs. Try<hashset<ContainerID>> listContainers( const std::string& provisionerDir); std::string getBackendDir( const std::string& provisionerDir, const ContainerID& containerId, const std::string& backend); } // namespace paths { } // namespace provisioner { } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __PROVISIONER_PATHS_HPP__ <commit_msg>Adjusted the comment to avoid using sub-containers.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __PROVISIONER_PATHS_HPP__ #define __PROVISIONER_PATHS_HPP__ #include <string> #include <mesos/mesos.hpp> #include <stout/hashmap.hpp> #include <stout/hashset.hpp> #include <stout/try.hpp> namespace mesos { namespace internal { namespace slave { namespace provisioner { namespace paths { // The provisioner rootfs directory is as follows: // <work_dir> ('--work_dir' flag) // |-- provisioner // |-- containers // |-- <container_id> // |-- backends // |-- <backend> (copy, bind, etc.) // |-- rootfses // |-- <rootfs_id> (the rootfs) // |-- containers (nested containers) // |-- <container_id> // |-- backends // |-- <backend> (copy, bind, etc.) // |-- rootfses // |-- <rootfs_id> (the rootfs) // // There can be multiple backends due to the change of backend flags. // Under each backend a rootfs is identified by the 'rootfs_id' which // is a UUID. std::string getContainerDir( const std::string& provisionerDir, const ContainerID& containerId); std::string getContainerRootfsDir( const std::string& provisionerDir, const ContainerID& containerId, const std::string& backend, const std::string& rootfsId); // Recursively "ls" the container directory and return a map of // backend -> {rootfsId, ...} Try<hashmap<std::string, hashset<std::string>>> listContainerRootfses( const std::string& provisionerDir, const ContainerID& containerId); // Return a set of container IDs. Try<hashset<ContainerID>> listContainers( const std::string& provisionerDir); std::string getBackendDir( const std::string& provisionerDir, const ContainerID& containerId, const std::string& backend); } // namespace paths { } // namespace provisioner { } // namespace slave { } // namespace internal { } // namespace mesos { #endif // __PROVISIONER_PATHS_HPP__ <|endoftext|>
<commit_before> #include "slg/Window.hpp" #include <GL/glew.h> #include <GL/glfw.h> #include <cassert> namespace slg { static Window * currentWindow = 0; // -- Callbacks -- void mouseButton(int button, int state) { if (currentWindow) currentWindow->input().setMouseButton(button, state == GLFW_PRESS); } void mousePosition(int x, int y) { if (currentWindow) currentWindow->input().setMousePos(x, y); } void windowResized(int width, int height) { if (currentWindow) currentWindow->resize(width, height); } // -- Window -- Window::Window(int width, int height) { assert(!currentWindow && "We may only have one window active at all times"); currentWindow = this; glfwInit(); glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 0); glfwOpenWindow(width, height, 8, 8, 8, 8, 24, 0, GLFW_WINDOW); glfwSetMouseButtonCallback(&mouseButton); glfwSetMousePosCallback(&mousePosition); glfwSetWindowSizeCallback(&windowResized); glewInit(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); for (int texUnit = 0; texUnit < 4; ++texUnit) { glActiveTexture(GL_TEXTURE0 + texUnit); glEnable(GL_TEXTURE_2D); } glActiveTexture(GL_TEXTURE0); } Window::~Window() { currentWindow = 0; glfwTerminate(); } void Window::run() { glfwSetTime(0.0); m_lastTimeStamp = 0.0; m_totalTime = 0.0; // Call resize before we start { int width, height; glfwGetWindowSize(&width, &height); resize(width, height); } bool running = true; while (running) { running = step(); } } bool Window::step() { double timeStamp = glfwGetTime(); double dt = timeStamp - m_lastTimeStamp; m_lastTimeStamp = timeStamp; m_totalTime += dt; bool continueOn = update(dt); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); paint(); glfwSwapBuffers(); return continueOn && glfwGetWindowParam(GLFW_OPENED); } void Window::setTitle(std::string const& title) { glfwSetWindowTitle(title.c_str()); } } <commit_msg>Removed clear call<commit_after> #include "slg/Window.hpp" #include <GL/glew.h> #include <GL/glfw.h> #include <cassert> namespace slg { static Window * currentWindow = 0; // -- Callbacks -- void mouseButton(int button, int state) { if (currentWindow) currentWindow->input().setMouseButton(button, state == GLFW_PRESS); } void mousePosition(int x, int y) { if (currentWindow) currentWindow->input().setMousePos(x, y); } void windowResized(int width, int height) { if (currentWindow) currentWindow->resize(width, height); } // -- Window -- Window::Window(int width, int height) { assert(!currentWindow && "We may only have one window active at all times"); currentWindow = this; glfwInit(); glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 0); glfwOpenWindow(width, height, 8, 8, 8, 8, 24, 0, GLFW_WINDOW); glfwSetMouseButtonCallback(&mouseButton); glfwSetMousePosCallback(&mousePosition); glfwSetWindowSizeCallback(&windowResized); glewInit(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); for (int texUnit = 0; texUnit < 4; ++texUnit) { glActiveTexture(GL_TEXTURE0 + texUnit); glEnable(GL_TEXTURE_2D); } glActiveTexture(GL_TEXTURE0); } Window::~Window() { currentWindow = 0; glfwTerminate(); } void Window::run() { glfwSetTime(0.0); m_lastTimeStamp = 0.0; m_totalTime = 0.0; // Call resize before we start { int width, height; glfwGetWindowSize(&width, &height); resize(width, height); } bool running = true; while (running) { running = step(); } } bool Window::step() { double timeStamp = glfwGetTime(); double dt = timeStamp - m_lastTimeStamp; m_lastTimeStamp = timeStamp; m_totalTime += dt; bool continueOn = update(dt); paint(); glfwSwapBuffers(); return continueOn && glfwGetWindowParam(GLFW_OPENED); } void Window::setTitle(std::string const& title) { glfwSetWindowTitle(title.c_str()); } } <|endoftext|>
<commit_before>#ifndef _ZEROMQ_HPP_ #define _ZEROMQ_HPP_ #include <Rcpp.h> #include <chrono> #include <string> #include <thread> #include <unordered_map> #include "zmq.hpp" #include "MonitoredSocket.hpp" typedef std::chrono::high_resolution_clock Time; typedef std::chrono::milliseconds ms; int pending_interrupt(); class ZeroMQ { public: ZeroMQ(zmq::context_t * ctx_) : ctx(ctx_), sockets() {} ZeroMQ(int threads=1) : ctx(new zmq::context_t(threads)), sockets() {} ~ZeroMQ() { for (auto & it: sockets) { delete it.second; } ctx->close(); delete ctx; } ZeroMQ(const ZeroMQ &) = delete; ZeroMQ & operator=(ZeroMQ const &) = delete; // convenience functions to quickly create and add sockets std::string listen(Rcpp::CharacterVector addrs, std::string socket_type="ZMQ_REP", std::string sid="default") { auto * ms = new MonitoredSocket(ctx, str2socket(socket_type), sid); auto bound_endpoint = ms->listen(addrs); sockets.emplace(sid, std::move(ms)); return bound_endpoint; } void connect(std::string address, std::string socket_type="ZMQ_REQ", std::string sid="default") { auto * ms = new MonitoredSocket(ctx, str2socket(socket_type), sid); ms->sock.connect(address); sockets.emplace(sid, std::move(ms)); } void disconnect(std::string sid="default") { auto * ms = find_socket(sid); delete ms; std::cerr << "erasing both\n" << std::flush; sockets.erase(sid); } void send(SEXP data, std::string sid="default", bool dont_wait=false, bool send_more=false) { auto * ms = find_socket(sid); ms->send(data, dont_wait, send_more); } SEXP receive(std::string sid="default", bool dont_wait=false, bool unserialize=true) { auto * ms = find_socket(sid); return ms->receive(dont_wait, unserialize); } void add_socket(MonitoredSocket * ms, std::string sid="default") { sockets.emplace(sid, std::move(ms)); } Rcpp::IntegerVector poll(Rcpp::CharacterVector sids, int timeout=-1) { auto nsock = sids.length(); auto pitems = std::vector<zmq::pollitem_t>(nsock*2); for (int i = 0; i < nsock; i++) { auto * ms = find_socket(Rcpp::as<std::string>(sids[i])); pitems[i].socket = ms->sock; pitems[i].events = ZMQ_POLLIN; // | ZMQ_POLLOUT; // ssh_proxy XREP/XREQ has 2200 pitems[i+nsock].socket = ms->mon; pitems[i+nsock].events = ZMQ_POLLIN; } auto start = Time::now(); int total_sock_ev = 0; auto result = Rcpp::IntegerVector(nsock); do { try { zmq::poll(pitems, timeout); } catch(zmq::error_t const & e) { if (errno != EINTR || pending_interrupt()) Rf_error(e.what()); if (timeout != -1) { ms dt = std::chrono::duration_cast<ms>(Time::now() - start); timeout = timeout - dt.count(); if (timeout <= 0) break; } } //TODO: handle events internally, protected: virtual, and override in ClusterMQ class // remove as much as possible Rcpp from ZeroMQ class (SEXP -> void*, std::string overload?) for (int i = 0; i < nsock; i++) { result[i] = pitems[i].revents; total_sock_ev += pitems[i].revents; if (pitems[i+nsock].revents > 0) { auto * ms = find_socket(Rcpp::as<std::string>(sids[i])); //fixme: 2x iteration ms->handle_monitor_event(); } } } while(total_sock_ev == 0); return result; } protected: zmq::context_t * ctx; std::unordered_map<std::string, MonitoredSocket*> sockets; int str2socket(std::string str) { if (str == "ZMQ_REP") { return ZMQ_REP; } else if (str == "ZMQ_REQ") { return ZMQ_REQ; } else if (str == "ZMQ_XREP") { return ZMQ_XREP; } else if (str == "ZMQ_XREQ") { return ZMQ_XREQ; } else { Rcpp::exception(("Invalid socket type: " + str).c_str()); } return -1; } MonitoredSocket * find_socket(std::string socket_id) { auto socket_iter = sockets.find(socket_id); if (socket_iter == sockets.end()) Rf_error("Trying to access non-existing socket: ", socket_id.c_str()); return socket_iter->second; } }; #endif // _ZEROMQ_HPP_ <commit_msg>simplify socket indexing (lookup only once)<commit_after>#ifndef _ZEROMQ_HPP_ #define _ZEROMQ_HPP_ #include <Rcpp.h> #include <chrono> #include <string> #include <thread> #include <unordered_map> #include "zmq.hpp" #include "MonitoredSocket.hpp" typedef std::chrono::high_resolution_clock Time; typedef std::chrono::milliseconds ms; int pending_interrupt(); class ZeroMQ { public: ZeroMQ(zmq::context_t * ctx_) : ctx(ctx_), sockets() {} ZeroMQ(int threads=1) : ctx(new zmq::context_t(threads)), sockets() {} ~ZeroMQ() { for (auto & it: sockets) { delete it.second; } ctx->close(); delete ctx; } ZeroMQ(const ZeroMQ &) = delete; ZeroMQ & operator=(ZeroMQ const &) = delete; // convenience functions to quickly create and add sockets std::string listen(Rcpp::CharacterVector addrs, std::string socket_type="ZMQ_REP", std::string sid="default") { auto * ms = new MonitoredSocket(ctx, str2socket(socket_type), sid); auto bound_endpoint = ms->listen(addrs); sockets.emplace(sid, std::move(ms)); return bound_endpoint; } void connect(std::string address, std::string socket_type="ZMQ_REQ", std::string sid="default") { auto * ms = new MonitoredSocket(ctx, str2socket(socket_type), sid); ms->sock.connect(address); sockets.emplace(sid, std::move(ms)); } void disconnect(std::string sid="default") { auto * ms = find_socket(sid); delete ms; std::cerr << "erasing both\n" << std::flush; sockets.erase(sid); } void send(SEXP data, std::string sid="default", bool dont_wait=false, bool send_more=false) { auto * ms = find_socket(sid); ms->send(data, dont_wait, send_more); } SEXP receive(std::string sid="default", bool dont_wait=false, bool unserialize=true) { auto * ms = find_socket(sid); return ms->receive(dont_wait, unserialize); } void add_socket(MonitoredSocket * ms, std::string sid="default") { sockets.emplace(sid, std::move(ms)); } Rcpp::IntegerVector poll(Rcpp::CharacterVector sids, int timeout=-1) { auto nsock = sids.length(); auto pitems = std::vector<zmq::pollitem_t>(nsock*2); auto monsocks = std::vector<MonitoredSocket*>(nsock); for (int i = 0; i < nsock; i++) { monsocks[i] = find_socket(Rcpp::as<std::string>(sids[i])); pitems[i].socket = monsocks[i]->sock; pitems[i].events = ZMQ_POLLIN; // | ZMQ_POLLOUT; // ssh_proxy XREP/XREQ has 2200 pitems[i+nsock].socket = monsocks[i]->mon; pitems[i+nsock].events = ZMQ_POLLIN; } auto start = Time::now(); int total_sock_ev = 0; auto result = Rcpp::IntegerVector(nsock); do { try { zmq::poll(pitems, timeout); } catch(zmq::error_t const & e) { if (errno != EINTR || pending_interrupt()) Rf_error(e.what()); if (timeout != -1) { ms dt = std::chrono::duration_cast<ms>(Time::now() - start); timeout = timeout - dt.count(); if (timeout <= 0) break; } } //TODO: remove Rcpp from ZeroMQ class (SEXP -> void*, std::string overload?) for (int i = 0; i < nsock; i++) { result[i] = pitems[i].revents; total_sock_ev += pitems[i].revents; for (int j = 0; j < pitems[i+nsock].revents; j++) monsocks[i]->handle_monitor_event(); } } while(total_sock_ev == 0); return result; } protected: zmq::context_t * ctx; std::unordered_map<std::string, MonitoredSocket*> sockets; int str2socket(std::string str) { if (str == "ZMQ_REP") { return ZMQ_REP; } else if (str == "ZMQ_REQ") { return ZMQ_REQ; } else if (str == "ZMQ_XREP") { return ZMQ_XREP; } else if (str == "ZMQ_XREQ") { return ZMQ_XREQ; } else { Rcpp::exception(("Invalid socket type: " + str).c_str()); } return -1; } MonitoredSocket * find_socket(std::string socket_id) { auto socket_iter = sockets.find(socket_id); if (socket_iter == sockets.end()) Rf_error("Trying to access non-existing socket: ", socket_id.c_str()); return socket_iter->second; } }; #endif // _ZEROMQ_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLTableShapeImportHelper.cxx,v $ * * $Revision: 1.21 $ * * last change: $Author: sab $ $Date: 2002-05-29 11:32:52 $ * * 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 _SC_XMLTABLESHAPEIMPORTHELPER_HXX #include "XMLTableShapeImportHelper.hxx" #endif #ifndef SC_XMLIMPRT_HXX #include "xmlimprt.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #ifndef SC_DRWLAYER_HXX #include "drwlayer.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _SVX_UNOSHAPE_HXX #include <svx/unoshape.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #define SC_LAYERID "LayerID" using namespace ::com::sun::star; using namespace xmloff::token; XMLTableShapeImportHelper::XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper ) : XMLShapeImportHelper(rImp, rImp.GetModel(), pImpMapper ) { } XMLTableShapeImportHelper::~XMLTableShapeImportHelper() { } void XMLTableShapeImportHelper::SetLayer(uno::Reference<drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const { if (sType.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.ControlShape")))) nLayerID = SC_LAYER_CONTROLS; if (nLayerID != -1) { uno::Reference< beans::XPropertySet > xShapeProp( rShape, uno::UNO_QUERY ); if( xShapeProp.is() ) xShapeProp->setPropertyValue(OUString( RTL_CONSTASCII_USTRINGPARAM( SC_LAYERID ) ), uno::makeAny(nLayerID) ); } } void XMLTableShapeImportHelper::finishShape( uno::Reference< drawing::XShape >& rShape, const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Reference< drawing::XShapes >& rShapes ) { XMLShapeImportHelper::finishShape( rShape, xAttrList, rShapes ); static_cast<ScXMLImport&>(mrImporter).LockSolarMutex(); if (rShapes == static_cast<ScXMLImport&>(mrImporter).GetTables().GetCurrentXShapes()) { Rectangle* pRect = NULL; sal_Int32 nEndX(-1); sal_Int32 nEndY(-1); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; table::CellAddress aEndCell; rtl::OUString* pRangeList = NULL; sal_Int16 nLayerID(-1); for( sal_Int16 i=0; i < nAttrCount; i++ ) { const rtl::OUString& rAttrName = xAttrList->getNameByIndex( i ); const rtl::OUString& rValue = xAttrList->getValueByIndex( i ); rtl::OUString aLocalName; sal_uInt16 nPrefix = static_cast<ScXMLImport&>(mrImporter).GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); if(nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_END_CELL_ADDRESS)) { sal_Int32 nOffset(0); ScXMLConverter::GetAddressFromString(aEndCell, rValue, static_cast<ScXMLImport&>(mrImporter).GetDocument(), nOffset); } else if (IsXMLToken(aLocalName, XML_END_X)) static_cast<ScXMLImport&>(mrImporter).GetMM100UnitConverter().convertMeasure(nEndX, rValue); else if (IsXMLToken(aLocalName, XML_END_Y)) static_cast<ScXMLImport&>(mrImporter).GetMM100UnitConverter().convertMeasure(nEndY, rValue); else if (IsXMLToken(aLocalName, XML_TABLE_BACKGROUND)) if (IsXMLToken(rValue, XML_TRUE)) nLayerID = SC_LAYER_BACK; } else if(nPrefix == XML_NAMESPACE_DRAW) { if (IsXMLToken(aLocalName, XML_NOTIFY_ON_UPDATE_OF_RANGES)) pRangeList = new rtl::OUString(rValue); } } SetLayer(rShape, nLayerID, rShape->getShapeType()); if (!bOnTable) { static_cast<ScXMLImport&>(mrImporter).GetTables().AddShape(rShape, pRangeList, aStartCell, aEndCell, nEndX, nEndY); SvxShape* pShapeImp = SvxShape::getImplementation(rShape); if (pShapeImp) { SdrObject *pSdrObj = pShapeImp->GetSdrObject(); if (pSdrObj) ScDrawLayer::SetAnchor(pSdrObj, SCA_CELL); } } else { SvxShape* pShapeImp = SvxShape::getImplementation(rShape); if (pShapeImp) { SdrObject *pSdrObj = pShapeImp->GetSdrObject(); if (pSdrObj) ScDrawLayer::SetAnchor(pSdrObj, SCA_PAGE); } } } else //#99532# this are grouped shapes which should also get the layerid { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; sal_Int16 nLayerID(-1); for( sal_Int16 i=0; i < nAttrCount; i++ ) { const rtl::OUString& rAttrName = xAttrList->getNameByIndex( i ); const rtl::OUString& rValue = xAttrList->getValueByIndex( i ); rtl::OUString aLocalName; sal_uInt16 nPrefix = static_cast<ScXMLImport&>(mrImporter).GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); if(nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_TABLE_BACKGROUND)) if (IsXMLToken(rValue, XML_TRUE)) nLayerID = SC_LAYER_BACK; } } SetLayer(rShape, nLayerID, rShape->getShapeType()); } static_cast<ScXMLImport&>(mrImporter).UnlockSolarMutex(); } <commit_msg>INTEGRATION: CWS dr12 (1.21.280); FILE MERGED 2004/07/23 20:58:25 sab 1.21.280.1: #i21253#; add formatted notes<commit_after>/************************************************************************* * * $RCSfile: XMLTableShapeImportHelper.cxx,v $ * * $Revision: 1.22 $ * * last change: $Author: hr $ $Date: 2004-09-08 13:49:51 $ * * 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 _SC_XMLTABLESHAPEIMPORTHELPER_HXX #include "XMLTableShapeImportHelper.hxx" #endif #ifndef SC_XMLIMPRT_HXX #include "xmlimprt.hxx" #endif #ifndef _SC_XMLCONVERTER_HXX #include "XMLConverter.hxx" #endif #ifndef SC_DRWLAYER_HXX #include "drwlayer.hxx" #endif #ifndef SC_XMLANNOI_HXX #include "xmlannoi.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _SVX_UNOSHAPE_HXX #include <svx/unoshape.hxx> #endif #ifndef _SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_ #include <com/sun/star/drawing/XShape.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_ #include <com/sun/star/drawing/XShapes.hpp> #endif #define SC_LAYERID "LayerID" using namespace ::com::sun::star; using namespace xmloff::token; XMLTableShapeImportHelper::XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper ) : XMLShapeImportHelper(rImp, rImp.GetModel(), pImpMapper ), bOnTable(sal_False), pAnnotationContext(NULL) { } XMLTableShapeImportHelper::~XMLTableShapeImportHelper() { } void XMLTableShapeImportHelper::SetLayer(uno::Reference<drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const { if (sType.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.ControlShape")))) nLayerID = SC_LAYER_CONTROLS; if (nLayerID != -1) { uno::Reference< beans::XPropertySet > xShapeProp( rShape, uno::UNO_QUERY ); if( xShapeProp.is() ) xShapeProp->setPropertyValue(OUString( RTL_CONSTASCII_USTRINGPARAM( SC_LAYERID ) ), uno::makeAny(nLayerID) ); } } void XMLTableShapeImportHelper::finishShape( uno::Reference< drawing::XShape >& rShape, const uno::Reference< xml::sax::XAttributeList >& xAttrList, uno::Reference< drawing::XShapes >& rShapes ) { XMLShapeImportHelper::finishShape( rShape, xAttrList, rShapes ); static_cast<ScXMLImport&>(mrImporter).LockSolarMutex(); if (rShapes == static_cast<ScXMLImport&>(mrImporter).GetTables().GetCurrentXShapes()) { if (!pAnnotationContext) { Rectangle* pRect = NULL; sal_Int32 nEndX(-1); sal_Int32 nEndY(-1); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; table::CellAddress aEndCell; rtl::OUString* pRangeList = NULL; sal_Int16 nLayerID(-1); for( sal_Int16 i=0; i < nAttrCount; i++ ) { const rtl::OUString& rAttrName = xAttrList->getNameByIndex( i ); const rtl::OUString& rValue = xAttrList->getValueByIndex( i ); rtl::OUString aLocalName; sal_uInt16 nPrefix = static_cast<ScXMLImport&>(mrImporter).GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); if(nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_END_CELL_ADDRESS)) { sal_Int32 nOffset(0); ScXMLConverter::GetAddressFromString(aEndCell, rValue, static_cast<ScXMLImport&>(mrImporter).GetDocument(), nOffset); } else if (IsXMLToken(aLocalName, XML_END_X)) static_cast<ScXMLImport&>(mrImporter).GetMM100UnitConverter().convertMeasure(nEndX, rValue); else if (IsXMLToken(aLocalName, XML_END_Y)) static_cast<ScXMLImport&>(mrImporter).GetMM100UnitConverter().convertMeasure(nEndY, rValue); else if (IsXMLToken(aLocalName, XML_TABLE_BACKGROUND)) if (IsXMLToken(rValue, XML_TRUE)) nLayerID = SC_LAYER_BACK; } else if(nPrefix == XML_NAMESPACE_DRAW) { if (IsXMLToken(aLocalName, XML_NOTIFY_ON_UPDATE_OF_RANGES)) pRangeList = new rtl::OUString(rValue); } } SetLayer(rShape, nLayerID, rShape->getShapeType()); if (!bOnTable) { static_cast<ScXMLImport&>(mrImporter).GetTables().AddShape(rShape, pRangeList, aStartCell, aEndCell, nEndX, nEndY); SvxShape* pShapeImp = SvxShape::getImplementation(rShape); if (pShapeImp) { SdrObject *pSdrObj = pShapeImp->GetSdrObject(); if (pSdrObj) ScDrawLayer::SetAnchor(pSdrObj, SCA_CELL); } } else { SvxShape* pShapeImp = SvxShape::getImplementation(rShape); if (pShapeImp) { SdrObject *pSdrObj = pShapeImp->GetSdrObject(); if (pSdrObj) ScDrawLayer::SetAnchor(pSdrObj, SCA_PAGE); } } } else // shape is annotation { pAnnotationContext->SetShape(rShape, rShapes); } } else //#99532# this are grouped shapes which should also get the layerid { sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; sal_Int16 nLayerID(-1); for( sal_Int16 i=0; i < nAttrCount; i++ ) { const rtl::OUString& rAttrName = xAttrList->getNameByIndex( i ); const rtl::OUString& rValue = xAttrList->getValueByIndex( i ); rtl::OUString aLocalName; sal_uInt16 nPrefix = static_cast<ScXMLImport&>(mrImporter).GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); if(nPrefix == XML_NAMESPACE_TABLE) { if (IsXMLToken(aLocalName, XML_TABLE_BACKGROUND)) if (IsXMLToken(rValue, XML_TRUE)) nLayerID = SC_LAYER_BACK; } } SetLayer(rShape, nLayerID, rShape->getShapeType()); } static_cast<ScXMLImport&>(mrImporter).UnlockSolarMutex(); } <|endoftext|>
<commit_before><commit_msg>Fix compilation error when OSL_DEBUG_LEVEL > 0<commit_after><|endoftext|>
<commit_before>#include "GaussianSmoothingFilter.hpp" #include "Exception.hpp" #include "DeviceManager.hpp" #include "Image.hpp" #include "DynamicImage.hpp" using namespace fast; void GaussianSmoothingFilter::setInput(ImageData::pointer input) { mInput = input; mIsModified = true; addParent(input); if(input->isDynamicData()) { mTempOutput = DynamicImage::New(); } else { mTempOutput = Image::New(); input->retain(mDevice); } mOutput = mTempOutput; } void GaussianSmoothingFilter::setDevice(ExecutionDevice::pointer device) { mDevice = device; mIsModified = true; mRecreateMask = true; } void GaussianSmoothingFilter::setMaskSize(unsigned char maskSize) { if(maskSize % 2 != 1) throw Exception("Mask size of GaussianSmoothingFilter must be odd."); mMaskSize = maskSize; mIsModified = true; mRecreateMask = true; } void GaussianSmoothingFilter::setStandardDeviation(float stdDev) { if(stdDev <= 0) throw Exception("Standard deviation of GaussianSmoothingFilter can't be less than 0."); mStdDev = stdDev; mIsModified = true; mRecreateMask = true; } ImageData::pointer GaussianSmoothingFilter::getOutput() { if(!mInput.isValid()) { throw Exception("Must call setInput before getOutput in GaussianSmoothingFilter"); } if(mTempOutput.isValid()) { mTempOutput->setParent(mPtr.lock()); ImageData::pointer newSmartPtr; newSmartPtr.swap(mTempOutput); return newSmartPtr; } else { return mOutput.lock(); } } GaussianSmoothingFilter::GaussianSmoothingFilter() { mDevice = DeviceManager::getInstance().getDefaultComputationDevice(); mStdDev = 1.0f; mMaskSize = 3; mIsModified = true; mRecreateMask = true; mDimensionCLCodeCompiledFor = 0; } GaussianSmoothingFilter::~GaussianSmoothingFilter() { delete[] mMask; } // TODO have to set mRecreateMask to true if input change dimension void GaussianSmoothingFilter::createMask(Image::pointer input) { if(!mRecreateMask) return; unsigned char halfSize = (mMaskSize-1)/2; float sum = 0.0f; if(input->getDimensions() == 2) { mMask = new float[mMaskSize*mMaskSize]; for(int x = -halfSize; x <= halfSize; x++) { for(int y = -halfSize; y <= halfSize; y++) { float value = exp(-(float)(x*x+y*y)/(2.0f*mStdDev*mStdDev)); mMask[x+halfSize+(y+halfSize)*mMaskSize] = value; sum += value; }} for(int i = 0; i < mMaskSize*mMaskSize; i++) mMask[i] /= sum; } else if(input->getDimensions() == 3) { mMask = new float[mMaskSize*mMaskSize*mMaskSize]; for(int x = -halfSize; x <= halfSize; x++) { for(int y = -halfSize; y <= halfSize; y++) { for(int z = -halfSize; z <= halfSize; z++) { float value = exp(-(float)(x*x+y*y+z*z)/(2.0f*mStdDev*mStdDev)); mMask[x+halfSize+(y+halfSize)*mMaskSize+(z+halfSize)*mMaskSize*mMaskSize] = value; sum += value; }}} for(int i = 0; i < mMaskSize*mMaskSize*mMaskSize; i++) mMask[i] /= sum; } if(!mDevice->isHost()) { OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); unsigned int bufferSize = input->getDimensions() == 2 ? mMaskSize*mMaskSize : mMaskSize*mMaskSize*mMaskSize; mCLMask = cl::Buffer( device->getContext(), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float)*bufferSize, mMask ); } mRecreateMask = false; } void GaussianSmoothingFilter::recompileOpenCLCode(Image::pointer input) { // Check if there is a need to recompile OpenCL code if(input->getDimensions() == mDimensionCLCodeCompiledFor && input->getDataType() == mTypeCLCodeCompiledFor) return; OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); std::string buildOptions = ""; if(input->getDataType() == TYPE_FLOAT) { buildOptions = "-DTYPE_FLOAT"; } else if(input->getDataType() == TYPE_INT8 || input->getDataType() == TYPE_INT16) { buildOptions = "-DTYPE_INT"; } else { buildOptions = "-DTYPE_UINT"; } std::string filename; if(input->getDimensions() == 2) { filename = "Algorithms/GaussianSmoothingFilter2D.cl"; } else { filename = "Algorithms/GaussianSmoothingFilter3D.cl"; } int programNr = device->createProgramFromSource(std::string(FAST_ROOT_DIR) + filename, buildOptions); mKernel = cl::Kernel(device->getProgram(programNr), "gaussianSmoothing"); mDimensionCLCodeCompiledFor = input->getDimensions(); mTypeCLCodeCompiledFor = input->getDataType(); } template <class T> void executeAlgorithmOnHost(Image::pointer input, Image::pointer output, float * mask, unsigned char maskSize) { // TODO: this method currently only processes the first component unsigned int nrOfComponents = input->getNrOfComponents(); ImageAccess inputAccess = input->getImageAccess(ACCESS_READ); ImageAccess outputAccess = output->getImageAccess(ACCESS_READ_WRITE); T * inputData = (T*)inputAccess.get(); T * outputData = (T*)outputAccess.get(); const unsigned char halfSize = (maskSize-1)/2; unsigned int width = input->getWidth(); unsigned int height = input->getHeight(); if(input->getDimensions() == 3) { unsigned int depth = input->getDepth(); for(unsigned int z = halfSize; z < depth-halfSize; z++) { for(unsigned int y = halfSize; y < height-halfSize; y++) { for(unsigned int x = halfSize; x < width-halfSize; x++) { double sum = 0.0; for(int c = -halfSize; c <= halfSize; c++) { for(int b = -halfSize; b <= halfSize; b++) { for(int a = -halfSize; a <= halfSize; a++) { sum += mask[a+halfSize+(b+halfSize)*maskSize+(c+halfSize)*maskSize*maskSize]* inputData[(x+a)*nrOfComponents+(y+b)*nrOfComponents*width+(z+c)*nrOfComponents*width*height]; }}} outputData[x*nrOfComponents+y*nrOfComponents*width+z*nrOfComponents*width*height] = (T)sum; }}} } else { for(unsigned int y = halfSize; y < height-halfSize; y++) { for(unsigned int x = halfSize; x < width-halfSize; x++) { double sum = 0.0; for(int b = -halfSize; b <= halfSize; b++) { for(int a = -halfSize; a <= halfSize; a++) { sum += mask[a+halfSize+(b+halfSize)*maskSize]* inputData[(x+a)*nrOfComponents+(y+b)*nrOfComponents*width]; }} outputData[x*nrOfComponents+y*nrOfComponents*width] = (T)sum; }} } } void GaussianSmoothingFilter::execute() { Image::pointer input; if(!mInput.isValid()) { throw Exception("No input supplied to GaussianSmoothingFilter"); } if(!mOutput.lock().isValid()) { // output object is no longer valid return; } if(mInput->isDynamicData()) { input = DynamicImage::pointer(mInput)->getNextFrame(); } else { input = mInput; } Image::pointer output; if(mInput->isDynamicData()) { output = Image::New(); DynamicImage::pointer(mOutput)->addFrame(output); } else { output = Image::pointer(mOutput); } // Initialize output image if(input->getDimensions() == 2) { output->create2DImage(input->getWidth(), input->getHeight(), input->getDataType(), input->getNrOfComponents(), mDevice); } else { output->create3DImage(input->getWidth(), input->getHeight(), input->getDepth(), input->getDataType(), input->getNrOfComponents(), mDevice); } createMask(input); if(mDevice->isHost()) { switch(input->getDataType()) { fastSwitchTypeMacro(executeAlgorithmOnHost<FAST_TYPE>(input, output, mMask, mMaskSize)); } } else { OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); recompileOpenCLCode(input); cl::NDRange globalSize; if(input->getDimensions() == 2) { globalSize = cl::NDRange(input->getWidth(),input->getHeight()); OpenCLImageAccess2D inputAccess = input->getOpenCLImageAccess2D(ACCESS_READ, device); OpenCLImageAccess2D outputAccess = output->getOpenCLImageAccess2D(ACCESS_READ_WRITE, device); mKernel.setArg(0, *inputAccess.get()); mKernel.setArg(2, *outputAccess.get()); } else { globalSize = cl::NDRange(input->getWidth(),input->getHeight(),input->getDepth()); OpenCLImageAccess3D inputAccess = input->getOpenCLImageAccess3D(ACCESS_READ, device); OpenCLImageAccess3D outputAccess = output->getOpenCLImageAccess3D(ACCESS_READ_WRITE, device); mKernel.setArg(0, *inputAccess.get()); mKernel.setArg(2, *outputAccess.get()); } mKernel.setArg(1, mCLMask); mKernel.setArg(3, mMaskSize); device->getCommandQueue().enqueueNDRangeKernel( mKernel, cl::NullRange, globalSize, cl::NullRange ); } if(!mInput->isDynamicData()) mInput->release(mDevice); // Update the timestamp of the output data output->updateModifiedTimestamp(); } void GaussianSmoothingFilter::waitToFinish() { if(!mDevice->isHost()) { OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); device->getCommandQueue().finish(); } } <commit_msg>fixed possible seg fault and one sanity check in GaussianSmoothingFilter<commit_after>#include "GaussianSmoothingFilter.hpp" #include "Exception.hpp" #include "DeviceManager.hpp" #include "Image.hpp" #include "DynamicImage.hpp" using namespace fast; void GaussianSmoothingFilter::setInput(ImageData::pointer input) { mInput = input; mIsModified = true; addParent(input); if(input->isDynamicData()) { mTempOutput = DynamicImage::New(); DynamicImage::pointer(mTempOutput)->setStreamingMode(DynamicImage::pointer(mInput)->getStreamingMode()); } else { mTempOutput = Image::New(); input->retain(mDevice); } mOutput = mTempOutput; } void GaussianSmoothingFilter::setDevice(ExecutionDevice::pointer device) { mDevice = device; mIsModified = true; mRecreateMask = true; } void GaussianSmoothingFilter::setMaskSize(unsigned char maskSize) { if(maskSize <= 0) throw Exception("Mask size of GaussianSmoothingFilter can't be less than 0."); if(maskSize % 2 != 1) throw Exception("Mask size of GaussianSmoothingFilter must be odd."); mMaskSize = maskSize; mIsModified = true; mRecreateMask = true; } void GaussianSmoothingFilter::setStandardDeviation(float stdDev) { if(stdDev <= 0) throw Exception("Standard deviation of GaussianSmoothingFilter can't be less than 0."); mStdDev = stdDev; mIsModified = true; mRecreateMask = true; } ImageData::pointer GaussianSmoothingFilter::getOutput() { if(!mInput.isValid()) { throw Exception("Must call setInput before getOutput in GaussianSmoothingFilter"); } if(mTempOutput.isValid()) { mTempOutput->setParent(mPtr.lock()); ImageData::pointer newSmartPtr; newSmartPtr.swap(mTempOutput); return newSmartPtr; } else { return mOutput.lock(); } } GaussianSmoothingFilter::GaussianSmoothingFilter() { mDevice = DeviceManager::getInstance().getDefaultComputationDevice(); mStdDev = 1.0f; mMaskSize = 3; mIsModified = true; mRecreateMask = true; mDimensionCLCodeCompiledFor = 0; mMask = NULL; } GaussianSmoothingFilter::~GaussianSmoothingFilter() { delete[] mMask; } // TODO have to set mRecreateMask to true if input change dimension void GaussianSmoothingFilter::createMask(Image::pointer input) { if(!mRecreateMask) return; unsigned char halfSize = (mMaskSize-1)/2; float sum = 0.0f; if(input->getDimensions() == 2) { mMask = new float[mMaskSize*mMaskSize]; for(int x = -halfSize; x <= halfSize; x++) { for(int y = -halfSize; y <= halfSize; y++) { float value = exp(-(float)(x*x+y*y)/(2.0f*mStdDev*mStdDev)); mMask[x+halfSize+(y+halfSize)*mMaskSize] = value; sum += value; }} for(int i = 0; i < mMaskSize*mMaskSize; i++) mMask[i] /= sum; } else if(input->getDimensions() == 3) { mMask = new float[mMaskSize*mMaskSize*mMaskSize]; for(int x = -halfSize; x <= halfSize; x++) { for(int y = -halfSize; y <= halfSize; y++) { for(int z = -halfSize; z <= halfSize; z++) { float value = exp(-(float)(x*x+y*y+z*z)/(2.0f*mStdDev*mStdDev)); mMask[x+halfSize+(y+halfSize)*mMaskSize+(z+halfSize)*mMaskSize*mMaskSize] = value; sum += value; }}} for(int i = 0; i < mMaskSize*mMaskSize*mMaskSize; i++) mMask[i] /= sum; } if(!mDevice->isHost()) { OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); unsigned int bufferSize = input->getDimensions() == 2 ? mMaskSize*mMaskSize : mMaskSize*mMaskSize*mMaskSize; mCLMask = cl::Buffer( device->getContext(), CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(float)*bufferSize, mMask ); } mRecreateMask = false; } void GaussianSmoothingFilter::recompileOpenCLCode(Image::pointer input) { // Check if there is a need to recompile OpenCL code if(input->getDimensions() == mDimensionCLCodeCompiledFor && input->getDataType() == mTypeCLCodeCompiledFor) return; OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); std::string buildOptions = ""; if(input->getDataType() == TYPE_FLOAT) { buildOptions = "-DTYPE_FLOAT"; } else if(input->getDataType() == TYPE_INT8 || input->getDataType() == TYPE_INT16) { buildOptions = "-DTYPE_INT"; } else { buildOptions = "-DTYPE_UINT"; } std::string filename; if(input->getDimensions() == 2) { filename = "Algorithms/GaussianSmoothingFilter2D.cl"; } else { filename = "Algorithms/GaussianSmoothingFilter3D.cl"; } int programNr = device->createProgramFromSource(std::string(FAST_ROOT_DIR) + filename, buildOptions); mKernel = cl::Kernel(device->getProgram(programNr), "gaussianSmoothing"); mDimensionCLCodeCompiledFor = input->getDimensions(); mTypeCLCodeCompiledFor = input->getDataType(); } template <class T> void executeAlgorithmOnHost(Image::pointer input, Image::pointer output, float * mask, unsigned char maskSize) { // TODO: this method currently only processes the first component unsigned int nrOfComponents = input->getNrOfComponents(); ImageAccess inputAccess = input->getImageAccess(ACCESS_READ); ImageAccess outputAccess = output->getImageAccess(ACCESS_READ_WRITE); T * inputData = (T*)inputAccess.get(); T * outputData = (T*)outputAccess.get(); const unsigned char halfSize = (maskSize-1)/2; unsigned int width = input->getWidth(); unsigned int height = input->getHeight(); if(input->getDimensions() == 3) { unsigned int depth = input->getDepth(); for(unsigned int z = halfSize; z < depth-halfSize; z++) { for(unsigned int y = halfSize; y < height-halfSize; y++) { for(unsigned int x = halfSize; x < width-halfSize; x++) { double sum = 0.0; for(int c = -halfSize; c <= halfSize; c++) { for(int b = -halfSize; b <= halfSize; b++) { for(int a = -halfSize; a <= halfSize; a++) { sum += mask[a+halfSize+(b+halfSize)*maskSize+(c+halfSize)*maskSize*maskSize]* inputData[(x+a)*nrOfComponents+(y+b)*nrOfComponents*width+(z+c)*nrOfComponents*width*height]; }}} outputData[x*nrOfComponents+y*nrOfComponents*width+z*nrOfComponents*width*height] = (T)sum; }}} } else { for(unsigned int y = halfSize; y < height-halfSize; y++) { for(unsigned int x = halfSize; x < width-halfSize; x++) { double sum = 0.0; for(int b = -halfSize; b <= halfSize; b++) { for(int a = -halfSize; a <= halfSize; a++) { sum += mask[a+halfSize+(b+halfSize)*maskSize]* inputData[(x+a)*nrOfComponents+(y+b)*nrOfComponents*width]; }} outputData[x*nrOfComponents+y*nrOfComponents*width] = (T)sum; }} } } void GaussianSmoothingFilter::execute() { Image::pointer input; if(!mInput.isValid()) { throw Exception("No input supplied to GaussianSmoothingFilter"); } if(!mOutput.lock().isValid()) { // output object is no longer valid return; } if(mInput->isDynamicData()) { input = DynamicImage::pointer(mInput)->getNextFrame(); } else { input = mInput; } Image::pointer output; if(mInput->isDynamicData()) { output = Image::New(); DynamicImage::pointer(mOutput)->addFrame(output); } else { output = Image::pointer(mOutput); } // Initialize output image if(input->getDimensions() == 2) { output->create2DImage(input->getWidth(), input->getHeight(), input->getDataType(), input->getNrOfComponents(), mDevice); } else { output->create3DImage(input->getWidth(), input->getHeight(), input->getDepth(), input->getDataType(), input->getNrOfComponents(), mDevice); } createMask(input); if(mDevice->isHost()) { switch(input->getDataType()) { fastSwitchTypeMacro(executeAlgorithmOnHost<FAST_TYPE>(input, output, mMask, mMaskSize)); } } else { OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); recompileOpenCLCode(input); cl::NDRange globalSize; if(input->getDimensions() == 2) { globalSize = cl::NDRange(input->getWidth(),input->getHeight()); OpenCLImageAccess2D inputAccess = input->getOpenCLImageAccess2D(ACCESS_READ, device); OpenCLImageAccess2D outputAccess = output->getOpenCLImageAccess2D(ACCESS_READ_WRITE, device); mKernel.setArg(0, *inputAccess.get()); mKernel.setArg(2, *outputAccess.get()); } else { globalSize = cl::NDRange(input->getWidth(),input->getHeight(),input->getDepth()); OpenCLImageAccess3D inputAccess = input->getOpenCLImageAccess3D(ACCESS_READ, device); OpenCLImageAccess3D outputAccess = output->getOpenCLImageAccess3D(ACCESS_READ_WRITE, device); mKernel.setArg(0, *inputAccess.get()); mKernel.setArg(2, *outputAccess.get()); } mKernel.setArg(1, mCLMask); mKernel.setArg(3, mMaskSize); device->getCommandQueue().enqueueNDRangeKernel( mKernel, cl::NullRange, globalSize, cl::NullRange ); } if(!mInput->isDynamicData()) mInput->release(mDevice); // Update the timestamp of the output data output->updateModifiedTimestamp(); } void GaussianSmoothingFilter::waitToFinish() { if(!mDevice->isHost()) { OpenCLDevice::pointer device = boost::static_pointer_cast<OpenCLDevice>(mDevice); device->getCommandQueue().finish(); } } <|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 "chrome/common/chrome_constants.h" namespace chrome { // The following should not be used for UI strings; they are meant // for system strings only. UI changes should be made in the GRD. const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe"; #if defined(GOOGLE_CHROME_BUILD) const wchar_t kBrowserAppName[] = L"Chrome"; const char kStatsFilename[] = "ChromeStats"; #else const wchar_t kBrowserAppName[] = L"Chromium"; const char kStatsFilename[] = "ChromiumStats"; #endif const wchar_t kExternalTabWindowClass[] = L"Chrome_ExternalTabContainer"; const wchar_t kMessageWindowClass[] = L"Chrome_MessageWindow"; const wchar_t kCrashReportLog[] = L"Reported Crashes.txt"; const wchar_t kTestingInterfaceDLL[] = L"testing_interface.dll"; const wchar_t kNotSignedInProfile[] = L"Default"; const wchar_t kNotSignedInID[] = L"not-signed-in"; const wchar_t kBrowserResourcesDll[] = L"chrome.dll"; // filenames const wchar_t kArchivedHistoryFilename[] = L"Archived History"; const wchar_t kCacheDirname[] = L"Cache"; const wchar_t kChromePluginDataDirname[] = L"Plugin Data"; const wchar_t kCookieFilename[] = L"Cookies"; const wchar_t kHistoryFilename[] = L"History"; const wchar_t kLocalStateFilename[] = L"Local State"; const wchar_t kPreferencesFilename[] = L"Preferences"; const wchar_t kSafeBrowsingFilename[] = L"Safe Browsing"; const wchar_t kThumbnailsFilename[] = L"Thumbnails"; const wchar_t kUserDataDirname[] = L"User Data"; const wchar_t kWebDataFilename[] = L"Web Data"; const wchar_t kBookmarksFileName[] = L"Bookmarks"; const wchar_t kHistoryBookmarksFileName[] = L"Bookmarks From History"; const wchar_t kCustomDictionaryFileName[] = L"Custom Dictionary.txt"; // Note, this shouldn't go above 64. See bug 535234. const unsigned int kMaxRendererProcessCount = 20; const int kStatsMaxThreads = 32; const int kStatsMaxCounters = 300; // We don't enable record mode in the released product because users could // potentially be tricked into running a product in record mode without // knowing it. Enable in debug builds. Playback mode is allowed always, // because it is useful for testing and not hazardous by itself. #ifndef NDEBUG const bool kRecordModeEnabled = true; #else const bool kRecordModeEnabled = false; #endif } <commit_msg>Rev stats file name to handle backwards incompatibility<commit_after>// 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 "chrome/common/chrome_constants.h" namespace chrome { // The following should not be used for UI strings; they are meant // for system strings only. UI changes should be made in the GRD. const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe"; #if defined(GOOGLE_CHROME_BUILD) const wchar_t kBrowserAppName[] = L"Chrome"; const char kStatsFilename[] = "ChromeStats2"; #else const wchar_t kBrowserAppName[] = L"Chromium"; const char kStatsFilename[] = "ChromiumStats2"; #endif const wchar_t kExternalTabWindowClass[] = L"Chrome_ExternalTabContainer"; const wchar_t kMessageWindowClass[] = L"Chrome_MessageWindow"; const wchar_t kCrashReportLog[] = L"Reported Crashes.txt"; const wchar_t kTestingInterfaceDLL[] = L"testing_interface.dll"; const wchar_t kNotSignedInProfile[] = L"Default"; const wchar_t kNotSignedInID[] = L"not-signed-in"; const wchar_t kBrowserResourcesDll[] = L"chrome.dll"; // filenames const wchar_t kArchivedHistoryFilename[] = L"Archived History"; const wchar_t kCacheDirname[] = L"Cache"; const wchar_t kChromePluginDataDirname[] = L"Plugin Data"; const wchar_t kCookieFilename[] = L"Cookies"; const wchar_t kHistoryFilename[] = L"History"; const wchar_t kLocalStateFilename[] = L"Local State"; const wchar_t kPreferencesFilename[] = L"Preferences"; const wchar_t kSafeBrowsingFilename[] = L"Safe Browsing"; const wchar_t kThumbnailsFilename[] = L"Thumbnails"; const wchar_t kUserDataDirname[] = L"User Data"; const wchar_t kWebDataFilename[] = L"Web Data"; const wchar_t kBookmarksFileName[] = L"Bookmarks"; const wchar_t kHistoryBookmarksFileName[] = L"Bookmarks From History"; const wchar_t kCustomDictionaryFileName[] = L"Custom Dictionary.txt"; // Note, this shouldn't go above 64. See bug 535234. const unsigned int kMaxRendererProcessCount = 20; const int kStatsMaxThreads = 32; const int kStatsMaxCounters = 300; // We don't enable record mode in the released product because users could // potentially be tricked into running a product in record mode without // knowing it. Enable in debug builds. Playback mode is allowed always, // because it is useful for testing and not hazardous by itself. #ifndef NDEBUG const bool kRecordModeEnabled = true; #else const bool kRecordModeEnabled = false; #endif } <|endoftext|>
<commit_before>/* Copyright 2014 Dietrich Epp. This file is part of Dreamless. Dreamless is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include "analytics.hpp" #include "curl.hpp" #include "json.hpp" #include "sg/atomic.h" #include "sg/cvar.h" #include "sg/entry.h" #include "sg/log.h" #include "sg/thread.h" #include "sg/version.h" #include <vector> #include <memory> #if defined SG_THREAD_PTHREAD # include <pthread.h> # include <sys/time.h> # include <unistd.h> #elif defined SG_THREAD_WINDOWS # include <windows.h> #else # error "Unknown threading system" #endif namespace Analytics { namespace { // Only send analytics if at least 5 seconds were spent in the level. const int MIN_LEVEL_TIME = 5 * 1000; // Max retries before the analytics are shut down. const int MAX_RETRIES = 2; // Delay between retries, in seconds. const int RETRY_DELAY = 10; // Wait at most five seconds to shut down. const int SHUTDOWN_WAIT = 5; sg_logger *logger; std::vector<Level> queue; bool is_started, request_stop, is_stopped; struct Start { std::string computer_id; std::string game_version; std::string os_version; }; std::string to_json(const Start &s) { JSON j; j.put_string("computerId", s.computer_id); j.put_string("gameVersion", s.game_version); j.put_string("osVersion", s.os_version); return j.to_string(); } const char STATUS_NAME[STATUS_COUNT][12] = { "inProgress", "skipNext", "skipPrev", "restart", "success" }; std::string status_name(Status status) { int idx = static_cast<int>(status); if (idx < 0 || idx >= STATUS_COUNT) sg_sys_abort("invalid level status"); return STATUS_NAME[idx]; } std::string to_json(const Level &l, const std::string &sid) { JSON j; j.put_string("sessionId", sid); j.put_int("index", l.index); j.put_int("level", l.level); j.put_int("timeStart", l.time_start); if (l.time_wake == -1) j.put_null("timeWake"); else j.put_int("timeWake", l.time_wake); j.put_int("timeEnd", l.time_end); j.put_int("actionCount", l.action_count); j.put_bool("talkedToShadow", l.talked_to_shadow); j.put_string("status", status_name(l.status)); return j.to_string(); } #if defined SG_THREAD_PTHREAD namespace PThread { pthread_mutex_t mutex; pthread_cond_t cond; pthread_t thread; typedef std::pair<std::string, Start> Arg; void *worker(void *arg) { int r; std::string endpoint, session_id; { std::unique_ptr<Arg> a(reinterpret_cast<Arg *>(arg)); endpoint = a->first; auto json = to_json(a->second); for (int retry = 0; ; retry++) { if (retry > 0) { sg_logs(logger, SG_LOG_WARN, "Retrying request..."); sleep(RETRY_DELAY); } auto result = Curl::post(endpoint + "start", json); if (result.first) { session_id = result.second; break; } if (retry >= MAX_RETRIES) { sg_logs(logger, SG_LOG_ERROR, "Too many analytics failures."); is_stopped = true; return nullptr; } } } r = pthread_mutex_lock(&mutex); if (r) abort(); is_started = true; r = pthread_mutex_unlock(&mutex); if (r) abort(); sg_logs(logger, SG_LOG_INFO, "Analyticts startup successful."); while (true) { r = pthread_mutex_lock(&mutex); if (r) abort(); while (queue.empty() && !request_stop) { r = pthread_cond_wait(&cond, &mutex); if (r) abort(); } Level level; bool done = queue.empty(); if (!done) { level = queue.front(); queue.erase(queue.begin()); } r = pthread_mutex_unlock(&mutex); if (r) abort(); if (done) break; auto json = to_json(level, session_id); int i; for (i = 0; i < MAX_RETRIES; i++) { if (i > 0) { sg_logs(logger, SG_LOG_WARN, "Retrying request..."); sleep(RETRY_DELAY); } auto result = Curl::post(endpoint + "level", json); if (result.first && result.second == "ok") break; } if (i == MAX_RETRIES) { sg_logs(logger, SG_LOG_ERROR, "Too many analytics failures."); break; } sg_logs(logger, SG_LOG_INFO, "Post successful."); } sg_logs(logger, SG_LOG_INFO, "Shutting down analytics."); r = pthread_mutex_lock(&mutex); if (r) abort(); is_stopped = true; pthread_cond_broadcast(&cond); r = pthread_mutex_unlock(&mutex); if (r) abort(); return nullptr; } void start_worker(const std::string &endpoint, const Start &start) { int r; pthread_mutexattr_t mattr; r = pthread_mutexattr_init(&mattr); if (r) abort(); r = pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_NORMAL); if (r) abort(); r = pthread_mutex_init(&mutex, &mattr); if (r) abort(); r = pthread_mutexattr_destroy(&mattr); if (r) abort(); r = pthread_cond_init(&cond, nullptr); if (r) abort(); pthread_attr_t threadattr; r = pthread_attr_init(&threadattr); if (r) abort(); r = pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED); if (r) abort(); Arg *arg = new Arg(endpoint, start); r = pthread_create(&thread, &threadattr, worker, reinterpret_cast<void *>(arg)); if (r) abort(); pthread_attr_destroy(&threadattr); } void stop_worker() { int r; r = pthread_mutex_lock(&mutex); if (r) abort(); if (is_started) { request_stop = true; r = pthread_cond_broadcast(&cond); if (r) abort(); timeval tv; gettimeofday(&tv, nullptr); timespec ts; ts.tv_sec = tv.tv_sec + SHUTDOWN_WAIT; ts.tv_nsec = tv.tv_usec * 1000; while (!is_stopped) { r = pthread_cond_timedwait(&cond, &mutex, &ts); if (r == ETIMEDOUT) { sg_logs(logger, SG_LOG_ERROR, "Analytics timed out."); break; } if (r) abort(); } } r = pthread_mutex_unlock(&mutex); if (r) abort(); } void submit_level(const Level &level) { int r; r = pthread_mutex_lock(&mutex); if (r) abort(); if (!is_stopped) { if (!queue.empty() && queue.back().index == level.index) queue.back() = level; else queue.push_back(level); r = pthread_cond_broadcast(&cond); if (r) abort(); } r = pthread_mutex_unlock(&mutex); if (r) abort(); } } using PThread::start_worker; using PThread::stop_worker; using PThread::submit_level; #elif defined SG_THREAD_WINDOWS using Windows::start_worker; using Windows::stop_worker; using Windows::submit_level; #else # error "Unknown threading system" #endif } void Level::submit() const { if (time_end < MIN_LEVEL_TIME) return; submit_level(*this); } void Analytics::init() { Curl::init(); logger = sg_logger_get("analytics"); std::string endpoint; { const char *uri; if (!sg_cvar_gets("analytics", "uri", &uri)) uri = "http://analytics.moria.us/dreamless/"; endpoint = uri; } Start s; { char buf[64]; sg_version_machineid(buf, sizeof(buf)); s.computer_id = buf; s.game_version = "Dreamless/"; s.game_version += SG_APP_VERSION; s.game_version += " (SGLib/"; s.game_version += SG_SG_VERSION; s.game_version += ')'; buf[0] = '\0'; sg_version_os(buf, sizeof(buf)); s.os_version = buf; } start_worker(endpoint, s); } void Analytics::finish() { stop_worker(); } } <commit_msg>Port analytics code to Windows<commit_after>/* Copyright 2014 Dietrich Epp. This file is part of Dreamless. Dreamless is licensed under the terms of the 2-clause BSD license. For more information, see LICENSE.txt. */ #include "analytics.hpp" #include "curl.hpp" #include "json.hpp" #include "sg/atomic.h" #include "sg/cvar.h" #include "sg/entry.h" #include "sg/log.h" #include "sg/thread.h" #include "sg/version.h" #include <vector> #include <memory> #if defined SG_THREAD_PTHREAD # include <pthread.h> # include <sys/time.h> # include <unistd.h> #elif defined SG_THREAD_WINDOWS # include <windows.h> #else # error "Unknown threading system" #endif namespace Analytics { namespace { // Only send analytics if at least 5 seconds were spent in the level. const int MIN_LEVEL_TIME = 5 * 1000; // Max retries before the analytics are shut down. const int MAX_RETRIES = 2; // Delay between retries, in seconds. const int RETRY_DELAY = 10; // Wait at most five seconds to shut down. const int SHUTDOWN_WAIT = 5; sg_logger *logger; std::vector<Level> queue; struct Start { std::string computer_id; std::string game_version; std::string os_version; }; std::string to_json(const Start &s) { JSON j; j.put_string("computerId", s.computer_id); j.put_string("gameVersion", s.game_version); j.put_string("osVersion", s.os_version); return j.to_string(); } const char STATUS_NAME[STATUS_COUNT][12] = { "inProgress", "skipNext", "skipPrev", "restart", "success" }; std::string status_name(Status status) { int idx = static_cast<int>(status); if (idx < 0 || idx >= STATUS_COUNT) sg_sys_abort("invalid level status"); return STATUS_NAME[idx]; } std::string to_json(const Level &l, const std::string &sid) { JSON j; j.put_string("sessionId", sid); j.put_int("index", l.index); j.put_int("level", l.level); j.put_int("timeStart", l.time_start); if (l.time_wake == -1) j.put_null("timeWake"); else j.put_int("timeWake", l.time_wake); j.put_int("timeEnd", l.time_end); j.put_int("actionCount", l.action_count); j.put_bool("talkedToShadow", l.talked_to_shadow); j.put_string("status", status_name(l.status)); return j.to_string(); } typedef std::pair<std::string, Start> Arg; #if defined SG_THREAD_PTHREAD namespace PThread { pthread_mutex_t mutex; pthread_cond_t cond; pthread_t thread; bool is_started, request_stop, is_stopped; void *worker(void *arg) { int r; std::string endpoint, session_id; { std::unique_ptr<Arg> a(reinterpret_cast<Arg *>(arg)); endpoint = a->first; auto json = to_json(a->second); for (int retry = 0; ; retry++) { if (retry > 0) { sg_logs(logger, SG_LOG_WARN, "Retrying request..."); sleep(RETRY_DELAY); } auto result = Curl::post(endpoint + "start", json); if (result.first) { session_id = result.second; break; } if (retry >= MAX_RETRIES) { sg_logs(logger, SG_LOG_ERROR, "Too many analytics failures."); is_stopped = true; return nullptr; } } } r = pthread_mutex_lock(&mutex); if (r) abort(); is_started = true; r = pthread_mutex_unlock(&mutex); if (r) abort(); sg_logs(logger, SG_LOG_INFO, "Analytics startup successful."); while (true) { r = pthread_mutex_lock(&mutex); if (r) abort(); while (queue.empty() && !request_stop) { r = pthread_cond_wait(&cond, &mutex); if (r) abort(); } Level level; bool done = queue.empty(); if (!done) { level = queue.front(); queue.erase(queue.begin()); } r = pthread_mutex_unlock(&mutex); if (r) abort(); if (done) break; auto json = to_json(level, session_id); int i; for (i = 0; i < MAX_RETRIES; i++) { if (i > 0) { sg_logs(logger, SG_LOG_WARN, "Retrying request..."); sleep(RETRY_DELAY); } auto result = Curl::post(endpoint + "level", json); if (result.first && result.second == "ok") break; } if (i == MAX_RETRIES) { sg_logs(logger, SG_LOG_ERROR, "Too many analytics failures."); break; } sg_logs(logger, SG_LOG_INFO, "Post successful."); } sg_logs(logger, SG_LOG_INFO, "Shutting down analytics."); r = pthread_mutex_lock(&mutex); if (r) abort(); is_stopped = true; pthread_cond_broadcast(&cond); r = pthread_mutex_unlock(&mutex); if (r) abort(); return nullptr; } void start_worker(const std::string &endpoint, const Start &start) { int r; pthread_mutexattr_t mattr; r = pthread_mutexattr_init(&mattr); if (r) abort(); r = pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_NORMAL); if (r) abort(); r = pthread_mutex_init(&mutex, &mattr); if (r) abort(); r = pthread_mutexattr_destroy(&mattr); if (r) abort(); r = pthread_cond_init(&cond, nullptr); if (r) abort(); pthread_attr_t threadattr; r = pthread_attr_init(&threadattr); if (r) abort(); r = pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED); if (r) abort(); Arg *arg = new Arg(endpoint, start); r = pthread_create(&thread, &threadattr, worker, reinterpret_cast<void *>(arg)); if (r) abort(); pthread_attr_destroy(&threadattr); } void stop_worker() { int r; r = pthread_mutex_lock(&mutex); if (r) abort(); if (is_started) { request_stop = true; r = pthread_cond_broadcast(&cond); if (r) abort(); timeval tv; gettimeofday(&tv, nullptr); timespec ts; ts.tv_sec = tv.tv_sec + SHUTDOWN_WAIT; ts.tv_nsec = tv.tv_usec * 1000; while (!is_stopped) { r = pthread_cond_timedwait(&cond, &mutex, &ts); if (r == ETIMEDOUT) { sg_logs(logger, SG_LOG_ERROR, "Analytics timed out."); break; } if (r) abort(); } } r = pthread_mutex_unlock(&mutex); if (r) abort(); } void submit_level(const Level &level) { int r; r = pthread_mutex_lock(&mutex); if (r) abort(); if (!is_stopped) { if (!queue.empty() && queue.back().index == level.index) queue.back() = level; else queue.push_back(level); r = pthread_cond_broadcast(&cond); if (r) abort(); } r = pthread_mutex_unlock(&mutex); if (r) abort(); } } using PThread::start_worker; using PThread::stop_worker; using PThread::submit_level; #elif defined SG_THREAD_WINDOWS namespace Windows { CRITICAL_SECTION lock; bool is_started, request_stop, is_stopped; HANDLE has_data, has_stopped; static DWORD WINAPI worker(void *param) { BOOL r; std::string endpoint, session_id; { std::unique_ptr<Arg> a(reinterpret_cast<Arg *>(param)); endpoint = a->first; auto json = to_json(a->second); for (int retry = 0;; retry++) { if (retry > 0) { sg_logs(logger, SG_LOG_WARN, "Retrying request..."); Sleep(RETRY_DELAY * 1000); } auto result = Curl::post(endpoint + "start", json); if (result.first) { session_id = result.second; break; } if (retry >= MAX_RETRIES) { sg_logs(logger, SG_LOG_ERROR, "Too many analytics failures."); is_stopped = true; r = SetEvent(has_stopped); if (!r) abort(); return 0; } } } EnterCriticalSection(&lock); is_started = true; LeaveCriticalSection(&lock); sg_logs(logger, SG_LOG_INFO, "Analytics startup successful."); while (true) { EnterCriticalSection(&lock); while (queue.empty() && !request_stop) { LeaveCriticalSection(&lock); r = WaitForSingleObject(has_data, INFINITE); EnterCriticalSection(&lock); } Level level; bool done = queue.empty(); if (!done) { level = queue.front(); queue.erase(queue.begin()); } LeaveCriticalSection(&lock); if (done) break; auto json = to_json(level, session_id); int i; for (i = 0; i < MAX_RETRIES; i++) { if (i > 0) { sg_logs(logger, SG_LOG_WARN, "Retrying request..."); Sleep(RETRY_DELAY * 1000); } auto result = Curl::post(endpoint + "level", json); if (result.first && result.second == "ok") break; } if (i == MAX_RETRIES) { sg_logs(logger, SG_LOG_ERROR, "Too many analytics failures."); break; } sg_logs(logger, SG_LOG_INFO, "Post successful."); } sg_logs(logger, SG_LOG_INFO, "Shutting down analytics."); EnterCriticalSection(&lock); is_stopped = true; r = SetEvent(has_stopped); if (!r) abort(); LeaveCriticalSection(&lock); return 0; } void start_worker(const std::string &endpoint, const Start &start) { InitializeCriticalSection(&lock); has_data = CreateEvent(nullptr, TRUE, FALSE, nullptr); if (!has_data) abort(); has_stopped = CreateEvent(nullptr, TRUE, FALSE, nullptr); if (!has_stopped) abort(); Arg *arg = new Arg(endpoint, start); HANDLE thread = CreateThread(nullptr, 0, worker, reinterpret_cast<void *>(arg), 0, NULL); } void stop_worker() { BOOL r; bool do_wait; EnterCriticalSection(&lock); do_wait = is_started; if (do_wait) { request_stop = true; r = SetEvent(has_data); } LeaveCriticalSection(&lock); WaitForSingleObject(has_stopped, SHUTDOWN_WAIT * 1000); } void submit_level(const Level &level) { EnterCriticalSection(&lock); if (!is_stopped) { if (!queue.empty() && queue.back().index == level.index) queue.back() = level; else queue.push_back(level); BOOL r = SetEvent(has_data); if (!r) abort(); } LeaveCriticalSection(&lock); } } using Windows::start_worker; using Windows::stop_worker; using Windows::submit_level; #else # error "Unknown threading system" #endif } void Level::submit() const { if (time_end < MIN_LEVEL_TIME) return; submit_level(*this); } void Analytics::init() { Curl::init(); logger = sg_logger_get("analytics"); std::string endpoint; { const char *uri; if (!sg_cvar_gets("analytics", "uri", &uri)) uri = "http://analytics.moria.us/dreamless/"; endpoint = uri; } Start s; { char buf[64]; sg_version_machineid(buf, sizeof(buf)); s.computer_id = buf; s.game_version = "Dreamless/"; s.game_version += SG_APP_VERSION; s.game_version += " (SGLib/"; s.game_version += SG_SG_VERSION; s.game_version += ')'; buf[0] = '\0'; sg_version_os(buf, sizeof(buf)); s.os_version = buf; } start_worker(endpoint, s); } void Analytics::finish() { stop_worker(); } } <|endoftext|>
<commit_before>/*************************************************************************** * @file main.cpp * @author Alan.W * @date 26 Feb 2014 * @remark This code is for the exercises from C++ Primer 5th Edition * @note ***************************************************************************/ //! //! //! Exercise 16.60: //! Explain how make_shared (§ 12.1.1, p. 451) works. //! // make_shared shoudl be a variadic template member which forward all of fun's arguments to // the underlying functions that allocate and initializes an object in dynamic memory and // return a shared_ptr. //! //! Exercise 16.61: //! Define your own version of make_shared. //! #include <iostream> #include <memory> //! ex 16.61 my version makeshared template <typename T, typename ... Args> std::shared_ptr<T> wy_make_shared(Args&&...); int main() { auto p = wy_make_shared<int>(42); std::cout << *p << std::endl; auto p2= wy_make_shared<std::string>(10,'c'); std::cout << *p2 << std::endl; } template <typename T, typename ... Args> inline std::shared_ptr<T> wy_make_shared(Args&&... args) { std::shared_ptr<T> ret( new T(std::forward<Args>(args)...)); return ret; } <commit_msg>refactored<commit_after>/*************************************************************************** * @file main.cpp * @author Yue Wang * @date 26 Feb 2014 * Aug 2015 * @remark This code is for the exercises from C++ Primer 5th Edition * @note ***************************************************************************/ //! //! //! Exercise 16.60: //! Explain how make_shared (§ 12.1.1, p. 451) works. //! // make_shared shoudl be a variadic template member which forward all of fun's arguments to // the underlying functions that allocate and initializes an object in dynamic memory and // return a shared_ptr. //! //! Exercise 16.61: //! Define your own version of make_shared. //! #include <iostream> #include <memory> #include <string> namespace ch16 { template <typename T, typename ... Args> auto make_shared(Args&&... args) -> std::shared_ptr<T> { return std::shared_ptr<T>(new T(std::forward<Args>(args)...)); } } struct Foo { explicit Foo(int b) : bar(b){} int bar; }; int main() { auto num = ch16::make_shared<int>(42); std::cout << *num << std::endl; auto str = ch16::make_shared<std::string>(10, 'c'); std::cout << *str << std::endl; auto foo = ch16::make_shared<Foo>(99); std::cout << foo->bar << std::endl; return 0; } <|endoftext|>
<commit_before><commit_msg>WaE: unused variable 'itEnd'<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ddelink.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2004-10-04 20:05:39 $ * * 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 SC_DDELINK_HXX #define SC_DDELINK_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef _SVT_BROADCAST_HXX #include <svtools/broadcast.hxx> #endif #ifndef SC_MATRIX_HXX #include "scmatrix.hxx" #endif class ScDocument; class ScMultipleReadHeader; class ScMultipleWriteHeader; class SvStream; class ScDdeLink : public ::sfx2::SvBaseLink, public SvtBroadcaster //class ScDdeLink : public ::so3::SvBaseLink, public SvtBroadcaster { private: static BOOL bIsInUpdate; ScDocument* pDoc; String aAppl; // Verbindungsdaten String aTopic; String aItem; BYTE nMode; // Zahlformat-Modus BOOL bNeedUpdate; // wird gesetzt, wenn Update nicht moeglich war ScMatrixRef pResult; // Ergebnis public: TYPEINFO(); ScDdeLink( ScDocument* pD, const String& rA, const String& rT, const String& rI, BYTE nM ); ScDdeLink( ScDocument* pD, SvStream& rStream, ScMultipleReadHeader& rHdr ); ScDdeLink( ScDocument* pD, const ScDdeLink& rOther ); virtual ~ScDdeLink(); void Store( SvStream& rStream, ScMultipleWriteHeader& rHdr ) const; // von SvBaseLink ueberladen: virtual void DataChanged( const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); void NewData(SCSIZE nCols, SCSIZE nRows); // von SvtBroadcaster ueberladen: virtual void ListenersGone(); // fuer Interpreter: const ScMatrix* GetResult() const { return pResult; } void SetResult( ScMatrix* pRes ) { pResult = pRes; } // XML and Excel import after NewData() ScMatrixRef GetModifiableResult() { return pResult; } const String& GetAppl() const { return aAppl; } const String& GetTopic() const { return aTopic; } const String& GetItem() const { return aItem; } BYTE GetMode() const { return nMode; } void ResetValue(); // Wert zuruecksetzen void TryUpdate(); BOOL NeedsUpdate() const { return bNeedUpdate; } static BOOL IsInUpdate() { return bIsInUpdate; } }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.8.326); FILE MERGED 2005/09/05 15:01:48 rt 1.8.326.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ddelink.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:33:44 $ * * 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 SC_DDELINK_HXX #define SC_DDELINK_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef _SVT_BROADCAST_HXX #include <svtools/broadcast.hxx> #endif #ifndef SC_MATRIX_HXX #include "scmatrix.hxx" #endif class ScDocument; class ScMultipleReadHeader; class ScMultipleWriteHeader; class SvStream; class ScDdeLink : public ::sfx2::SvBaseLink, public SvtBroadcaster //class ScDdeLink : public ::so3::SvBaseLink, public SvtBroadcaster { private: static BOOL bIsInUpdate; ScDocument* pDoc; String aAppl; // Verbindungsdaten String aTopic; String aItem; BYTE nMode; // Zahlformat-Modus BOOL bNeedUpdate; // wird gesetzt, wenn Update nicht moeglich war ScMatrixRef pResult; // Ergebnis public: TYPEINFO(); ScDdeLink( ScDocument* pD, const String& rA, const String& rT, const String& rI, BYTE nM ); ScDdeLink( ScDocument* pD, SvStream& rStream, ScMultipleReadHeader& rHdr ); ScDdeLink( ScDocument* pD, const ScDdeLink& rOther ); virtual ~ScDdeLink(); void Store( SvStream& rStream, ScMultipleWriteHeader& rHdr ) const; // von SvBaseLink ueberladen: virtual void DataChanged( const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); void NewData(SCSIZE nCols, SCSIZE nRows); // von SvtBroadcaster ueberladen: virtual void ListenersGone(); // fuer Interpreter: const ScMatrix* GetResult() const { return pResult; } void SetResult( ScMatrix* pRes ) { pResult = pRes; } // XML and Excel import after NewData() ScMatrixRef GetModifiableResult() { return pResult; } const String& GetAppl() const { return aAppl; } const String& GetTopic() const { return aTopic; } const String& GetItem() const { return aItem; } BYTE GetMode() const { return nMode; } void ResetValue(); // Wert zuruecksetzen void TryUpdate(); BOOL NeedsUpdate() const { return bNeedUpdate; } static BOOL IsInUpdate() { return bIsInUpdate; } }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ddelink.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2004-03-08 11:45:28 $ * * 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 SC_DDELINK_HXX #define SC_DDELINK_HXX #ifndef _LNKBASE_HXX //autogen #include <so3/lnkbase.hxx> #endif #ifndef _SFXBRDCST_HXX //autogen #include <svtools/brdcst.hxx> #endif #ifndef SC_MATRIX_HXX #include "scmatrix.hxx" #endif class ScDocument; class ScMultipleReadHeader; class ScMultipleWriteHeader; class ScDdeLink : public ::so3::SvBaseLink, public SfxBroadcaster { private: static BOOL bIsInUpdate; ScDocument* pDoc; String aAppl; // Verbindungsdaten String aTopic; String aItem; BYTE nMode; // Zahlformat-Modus BOOL bNeedUpdate; // wird gesetzt, wenn Update nicht moeglich war ScMatrixRef pResult; // Ergebnis public: TYPEINFO(); ScDdeLink( ScDocument* pD, const String& rA, const String& rT, const String& rI, BYTE nM ); ScDdeLink( ScDocument* pD, SvStream& rStream, ScMultipleReadHeader& rHdr ); ScDdeLink( ScDocument* pD, const ScDdeLink& rOther ); virtual ~ScDdeLink(); void Store( SvStream& rStream, ScMultipleWriteHeader& rHdr ) const; // von SvBaseLink ueberladen: virtual void DataChanged( const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); void NewData(USHORT nCols, USHORT nRows); // von SfxBroadcaster ueberladen: virtual void ListenersGone(); // fuer Interpreter: const ScMatrix* GetResult() const { return pResult; } void SetResult( ScMatrix* pRes ) { pResult = pRes; } // XML and Excel import after NewData() ScMatrixRef GetModifiableResult() { return pResult; } const String& GetAppl() const { return aAppl; } const String& GetTopic() const { return aTopic; } const String& GetItem() const { return aItem; } BYTE GetMode() const { return nMode; } void ResetValue(); // Wert zuruecksetzen void TryUpdate(); BOOL NeedsUpdate() const { return bNeedUpdate; } static BOOL IsInUpdate() { return bIsInUpdate; } }; #endif <commit_msg>INTEGRATION: CWS rowlimit (1.5.338); FILE MERGED 2004/04/07 14:44:18 er 1.5.338.5: #i1967# #i5062# replace Sfx(Broadcaster|Listener) with Svt(Broadcaster|Listener) for mass objects like formula cells 2004/03/17 12:24:57 er 1.5.338.4: #i1967# type correctness (ScMatrix parameters are SCSIZE now) 2004/03/15 17:37:02 er 1.5.338.3: RESYNC: (1.5-1.6); FILE MERGED 2004/01/13 13:38:07 er 1.5.338.2: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2003/11/28 19:47:47 er 1.5.338.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>/************************************************************************* * * $RCSfile: ddelink.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2004-06-04 10:31:02 $ * * 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 SC_DDELINK_HXX #define SC_DDELINK_HXX #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _LNKBASE_HXX //autogen #include <so3/lnkbase.hxx> #endif #ifndef _SVT_BROADCAST_HXX #include <svtools/broadcast.hxx> #endif #ifndef SC_MATRIX_HXX #include "scmatrix.hxx" #endif class ScDocument; class ScMultipleReadHeader; class ScMultipleWriteHeader; class SvStream; class ScDdeLink : public ::so3::SvBaseLink, public SvtBroadcaster { private: static BOOL bIsInUpdate; ScDocument* pDoc; String aAppl; // Verbindungsdaten String aTopic; String aItem; BYTE nMode; // Zahlformat-Modus BOOL bNeedUpdate; // wird gesetzt, wenn Update nicht moeglich war ScMatrixRef pResult; // Ergebnis public: TYPEINFO(); ScDdeLink( ScDocument* pD, const String& rA, const String& rT, const String& rI, BYTE nM ); ScDdeLink( ScDocument* pD, SvStream& rStream, ScMultipleReadHeader& rHdr ); ScDdeLink( ScDocument* pD, const ScDdeLink& rOther ); virtual ~ScDdeLink(); void Store( SvStream& rStream, ScMultipleWriteHeader& rHdr ) const; // von SvBaseLink ueberladen: virtual void DataChanged( const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); void NewData(SCSIZE nCols, SCSIZE nRows); // von SvtBroadcaster ueberladen: virtual void ListenersGone(); // fuer Interpreter: const ScMatrix* GetResult() const { return pResult; } void SetResult( ScMatrix* pRes ) { pResult = pRes; } // XML and Excel import after NewData() ScMatrixRef GetModifiableResult() { return pResult; } const String& GetAppl() const { return aAppl; } const String& GetTopic() const { return aTopic; } const String& GetItem() const { return aItem; } BYTE GetMode() const { return nMode; } void ResetValue(); // Wert zuruecksetzen void TryUpdate(); BOOL NeedsUpdate() const { return bNeedUpdate; } static BOOL IsInUpdate() { return bIsInUpdate; } }; #endif <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.1.0, packaged on March, 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ #include "glc_worldhandle.h" #include "glc_structreference.h" #include <QSet> GLC_WorldHandle::GLC_WorldHandle() : m_Collection() , m_NumberOfWorld(1) , m_OccurenceHash() { } GLC_WorldHandle::~GLC_WorldHandle() { } // Return the list of instance QList<GLC_StructInstance*> GLC_WorldHandle::instances() const { QSet<GLC_StructInstance*> instancesSet; QHash<GLC_uint, GLC_StructOccurence*>::const_iterator iOccurence= m_OccurenceHash.constBegin(); while (iOccurence != m_OccurenceHash.constEnd()) { instancesSet.insert(iOccurence.value()->structInstance()); ++iOccurence; } return instancesSet.toList(); } // Return the list of Reference QList<GLC_StructReference*> GLC_WorldHandle::references() const { QSet<GLC_StructReference*> referencesSet; QHash<GLC_uint, GLC_StructOccurence*>::const_iterator iOccurence= m_OccurenceHash.constBegin(); while (iOccurence != m_OccurenceHash.constEnd()) { referencesSet.insert(iOccurence.value()->structReference()); ++iOccurence; } return referencesSet.toList(); } // An Occurence has been added void GLC_WorldHandle::addOccurence(GLC_StructOccurence* pOccurence, bool isSelected, GLuint shaderId) { Q_ASSERT(not m_OccurenceHash.contains(pOccurence->id())); m_OccurenceHash.insert(pOccurence->id(), pOccurence); // Add instance representation in the collection if (pOccurence->hasRepresentation()) { GLC_Instance representation(pOccurence->structReference()->instanceRepresentation()); // Force instance representation id representation.setId(pOccurence->id()); if (0 != shaderId) m_Collection.bindShader(shaderId); m_Collection.add(representation, shaderId); if (isSelected) { qDebug() << pOccurence->name() << "selected"; m_Collection.select(pOccurence->id()); } } } // An Occurence has been removed void GLC_WorldHandle::removeOccurence(GLC_StructOccurence* pOccurence) { Q_ASSERT(m_OccurenceHash.contains(pOccurence->id())); m_OccurenceHash.remove(pOccurence->id()); // Remove instance representation from the collection if (pOccurence->hasRepresentation()) { //qDebug() << "Remove " << pOccurence->name(); m_Collection.remove(pOccurence->id()); } } <commit_msg>Refactoring : renaming GLC_Instance to GLC_3DViewInstance.<commit_after>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) Version 1.1.0, packaged on March, 2009. http://glc-lib.sourceforge.net GLC-lib 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. GLC-lib 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 GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ #include "glc_worldhandle.h" #include "glc_structreference.h" #include <QSet> GLC_WorldHandle::GLC_WorldHandle() : m_Collection() , m_NumberOfWorld(1) , m_OccurenceHash() { } GLC_WorldHandle::~GLC_WorldHandle() { } // Return the list of instance QList<GLC_StructInstance*> GLC_WorldHandle::instances() const { QSet<GLC_StructInstance*> instancesSet; QHash<GLC_uint, GLC_StructOccurence*>::const_iterator iOccurence= m_OccurenceHash.constBegin(); while (iOccurence != m_OccurenceHash.constEnd()) { instancesSet.insert(iOccurence.value()->structInstance()); ++iOccurence; } return instancesSet.toList(); } // Return the list of Reference QList<GLC_StructReference*> GLC_WorldHandle::references() const { QSet<GLC_StructReference*> referencesSet; QHash<GLC_uint, GLC_StructOccurence*>::const_iterator iOccurence= m_OccurenceHash.constBegin(); while (iOccurence != m_OccurenceHash.constEnd()) { referencesSet.insert(iOccurence.value()->structReference()); ++iOccurence; } return referencesSet.toList(); } // An Occurence has been added void GLC_WorldHandle::addOccurence(GLC_StructOccurence* pOccurence, bool isSelected, GLuint shaderId) { Q_ASSERT(not m_OccurenceHash.contains(pOccurence->id())); m_OccurenceHash.insert(pOccurence->id(), pOccurence); // Add instance representation in the collection if (pOccurence->hasRepresentation()) { GLC_3DViewInstance representation(pOccurence->structReference()->instanceRepresentation()); // Force instance representation id representation.setId(pOccurence->id()); if (0 != shaderId) m_Collection.bindShader(shaderId); m_Collection.add(representation, shaderId); if (isSelected) { qDebug() << pOccurence->name() << "selected"; m_Collection.select(pOccurence->id()); } } } // An Occurence has been removed void GLC_WorldHandle::removeOccurence(GLC_StructOccurence* pOccurence) { Q_ASSERT(m_OccurenceHash.contains(pOccurence->id())); m_OccurenceHash.remove(pOccurence->id()); // Remove instance representation from the collection if (pOccurence->hasRepresentation()) { //qDebug() << "Remove " << pOccurence->name(); m_Collection.remove(pOccurence->id()); } } <|endoftext|>
<commit_before>/* ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <arpa/inet.h> #include <climits> #include <cstdio> #include <cstdlib> #include <limits> #include <memory> #include <QDir> #include <QMutexLocker> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/file/stream.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::file; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] filename Filename. * @param[in] mode Open mode. * @param[in] is_temporary Create temporary path base on the filename. */ stream::stream( std::string const& path, unsigned long long max_size) : _max_size(max_size), _path(path), _process_in(true), _process_out(true) { if ((max_size <= 2 * sizeof(uint32_t)) || (max_size > static_cast<unsigned long long>( std::numeric_limits<long>::max()))) _max_size = std::numeric_limits<long>::max(); _open_first_write(); _open_first_read(); } /** * Destructor. */ stream::~stream() {} /** * @brief Get stream's maximum size. * * This size is used to determine the maximum file size that a file can * have. After this limit, the next file (<file>, <file>1, <file>2, * ...) will be opened. * * @return Max size in bytes. */ unsigned long long stream::get_max_size() const throw () { return (_max_size); } /** * Set processing flags. * * @param[in] in Set to true to process input events. * @param[in] out Set to true to process output events. */ void stream::process(bool in, bool out) { QMutexLocker lock(&_mutex); _process_in = in; _process_out = in || !out; return ; } /** * Read data from the file. * * @param[out] d Bunch of data. */ void stream::read(misc::shared_ptr<io::data>& d) { // Lock mutex. d.clear(); QMutexLocker lock(&_mutex); // Check that read should be done. if (!_process_in || !_rfile.data()) throw (io::exceptions::shutdown(!_process_in, !_process_out) << "file stream is shutdown"); // Seek to position. _rfile->seek(_roffset); // Build data array. std::auto_ptr<io::raw> data(new io::raw); data->resize(BUFSIZ); // Read data. unsigned long rb; try { rb = _rfile->read(data->QByteArray::data(), data->size()); } catch (io::exceptions::shutdown const& e) { (void)e; if (_wid == _rid) { _rfile->close(); _rfile.clear(); std::string file_path(_file_path(_rid)); logging::info(logging::high) << "file: end of last file '" << file_path.c_str() << "' reached, closing and erasing file"; ::remove(file_path.c_str()); throw ; } _open_next_read(); rb = _rfile->read(data->QByteArray::data(), data->size()); } // Process data. logging::debug(logging::low) << "file: read " << rb << " bytes from '" << _file_path(_rid).c_str() << "'"; data->resize(rb); _roffset += rb; d = misc::shared_ptr<io::data>(data.release()); // Erase read data. _rfile->seek(0); union { char bytes[2 * sizeof(uint32_t)]; uint32_t integers[2]; } header; header.integers[0] = htonl(_roffset / 4294967296ull); header.integers[1] = htonl(_roffset % 4294967296ull); unsigned int written(0); while (written != sizeof(header.bytes)) written += _rfile->write( header.bytes + written, sizeof(header.bytes) - written); return ; } /** * Generate statistics about file processing. * * @param[out] buffer Output buffer. */ void stream::statistics(std::string& buffer) const { std::ostringstream oss; oss << "file_read_path=" << _file_path(_rid) << "\n" << "file_read_offset=" << _roffset << "\n" << "file_write_path=" << _file_path(_wid) << "\n" << "file_write_offset=" << _woffset << "\n" << "file_max_size="; if (_max_size != std::numeric_limits<long>::max()) oss << _max_size; else oss << "unlimited"; oss << "\n"; buffer.append(oss.str()); return ; } /** * Write data to the file. * * @param[in] d Data to write. * * @return Number of events acknowledged (1). */ unsigned int stream::write(misc::shared_ptr<io::data> const& d) { // Check that data exists and should be processed. if (!_process_out) throw (io::exceptions::shutdown(!_process_in, !_process_out) << "file stream is shutdown"); if (d.isNull()) return (1); if (d->type() == io::events::data_type<io::events::internal, 1>::value) { // Lock mutex. QMutexLocker lock(&_mutex); // Seek to end of file if necessary. _wfile->seek(_woffset); // Get data. char const* memory; unsigned int size; { io::raw* data(static_cast<io::raw*>(d.data())); memory = data->QByteArray::data(); size = data->size(); } // Debug message. logging::debug(logging::low) << "file: write request of " << size << " bytes for '" << _file_path(_wid).c_str() << "'"; // Write data. while (size > 0) { if (_woffset == _max_size) _open_next_write(); unsigned long max_write(_max_size - _woffset); if (size < max_write) max_write = size; unsigned long wb(_wfile->write(memory, max_write)); size -= wb; _woffset += wb; memory += wb; } } else logging::info(logging::low) << "file: write request with " \ "invalid data (" << d->type() << ")"; return (1); } /************************************** * * * Private Methods * * * **************************************/ /** * Get the file path matching the ID. * * @param[in] id Current ID. */ std::string stream::_file_path(unsigned int id) const { if (id) { std::ostringstream oss; oss << _path << id; return (oss.str()); } return (_path); } /** * Open the first readable file. */ void stream::_open_first_read() { // Get path components. QString base_dir; QString base_name; { size_t last_slash(_path.find_last_of('/')); if (last_slash == std::string::npos) { base_dir = "."; base_name = _path.c_str(); } else { base_dir = _path.substr(0, last_slash).c_str(); base_name = _path.substr(last_slash + 1).c_str(); } } // Browse directory. QStringList entries; { QStringList filters; filters << base_name + "*"; QDir dir(base_dir); entries = dir.entryList(filters); } // Find minimum value. unsigned int min(UINT_MAX); for (QStringList::iterator it(entries.begin()), end(entries.end()); it != end; ++it) { it->remove(0, base_name.size()); unsigned int i(it->toUInt()); if (i < min) min = i; } // If no file was found this is an error. if (UINT_MAX == min) throw (io::exceptions::shutdown(true, true) << "cannot find file entry in '" << qPrintable(base_dir) << "' matching '" << qPrintable(base_name) << "'"); // Open file. _rid = min - 1; _open_next_read(); return ; } /** * Open the first writable file. */ void stream::_open_first_write() { // Get path components. QString base_dir; QString base_name; { size_t last_slash(_path.find_last_of('/')); if (last_slash == std::string::npos) { base_dir = "."; base_name = _path.c_str(); } else { base_dir = _path.substr(0, last_slash).c_str(); base_name = _path.substr(last_slash + 1).c_str(); } } // Browse directory. QStringList entries; { QStringList filters; filters << base_name + "*"; QDir dir(base_dir); entries = dir.entryList(filters); } // Find maximum value. unsigned int max(0); for (QStringList::iterator it(entries.begin()), end(entries.end()); it != end; ++it) { it->remove(0, base_name.size()); unsigned int i(it->toUInt()); if (i > max) max = i; } _wid = max - 1; // Open file. _open_next_write(false); return ; } /** * Open the next readable file. */ void stream::_open_next_read() { // Did we reached the write file ? if (_rid + 1 == _wid) { _rfile = _wfile; _rfile->seek(0); } else { // Open file. std::string file_path(_file_path(_rid + 1)); { misc::shared_ptr<cfile> new_file(new cfile); new_file->open(file_path.c_str(), "r+"); _rfile = new_file; } } // Remove previous file. std::string file_path(_file_path(_rid)); logging::info(logging::high) << "file: end of file '" << file_path.c_str() << "' reached, erasing file"; ::remove(file_path.c_str()); // Adjust current index. ++_rid; // Get read offset. union { char bytes[2 * sizeof(uint32_t)]; uint32_t integers[2]; } header; unsigned int size(0); while (size != sizeof(header)) size += _rfile->read(header.bytes + size, sizeof(header) - size); _roffset = ntohl(header.integers[0]) * 4294967296ull + ntohl(header.integers[1]); return ; } /** * Open the next writable file. * * @param[in] truncate true to truncate file. */ void stream::_open_next_write(bool truncate) { // Open file. std::string file_path(_file_path(_wid + 1)); logging::info(logging::high) << "file: opening new file '" << file_path.c_str() << "'"; { misc::shared_ptr<cfile> new_file(new cfile); if (truncate) new_file->open(file_path.c_str(), "w+"); else { try { new_file->open(file_path.c_str(), "r+"); } catch (exceptions::msg const& e) { new_file->open(file_path.c_str(), "w+"); } } _wfile = new_file; } // Position. _wfile->seek(0, SEEK_END); _woffset = _wfile->tell(); // Adjust current index. ++_wid; if (_woffset < static_cast<long>(2 * sizeof(uint32_t))) { // Rewind to file beginning. _wfile->seek(0); // Write read offset. union { char bytes[2 * sizeof(uint32_t)]; uint32_t integers[2]; } header; header.integers[0] = 0; header.integers[1] = htonl(2 * sizeof(uint32_t)); unsigned int size(0); while (size < sizeof(header)) size += _wfile->write(header.bytes + size, sizeof(header) - size); // Set current offset. _woffset = 2 * sizeof(uint32_t); } return ; } <commit_msg>file: add percentage of the file(s) processed to statistics.<commit_after>/* ** Copyright 2011-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker 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 Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <arpa/inet.h> #include <climits> #include <cstdio> #include <cstdlib> #include <iomanip> #include <limits> #include <memory> #include <QDir> #include <QMutexLocker> #include <sstream> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/file/stream.hh" #include "com/centreon/broker/io/events.hh" #include "com/centreon/broker/io/exceptions/shutdown.hh" #include "com/centreon/broker/io/raw.hh" #include "com/centreon/broker/logging/logging.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::file; /************************************** * * * Public Methods * * * **************************************/ /** * Constructor. * * @param[in] filename Filename. * @param[in] mode Open mode. * @param[in] is_temporary Create temporary path base on the filename. */ stream::stream( std::string const& path, unsigned long long max_size) : _max_size(max_size), _path(path), _process_in(true), _process_out(true) { if ((max_size <= 2 * sizeof(uint32_t)) || (max_size > static_cast<unsigned long long>( std::numeric_limits<long>::max()))) _max_size = std::numeric_limits<long>::max(); _open_first_write(); _open_first_read(); } /** * Destructor. */ stream::~stream() {} /** * @brief Get stream's maximum size. * * This size is used to determine the maximum file size that a file can * have. After this limit, the next file (<file>, <file>1, <file>2, * ...) will be opened. * * @return Max size in bytes. */ unsigned long long stream::get_max_size() const throw () { return (_max_size); } /** * Set processing flags. * * @param[in] in Set to true to process input events. * @param[in] out Set to true to process output events. */ void stream::process(bool in, bool out) { QMutexLocker lock(&_mutex); _process_in = in; _process_out = in || !out; return ; } /** * Read data from the file. * * @param[out] d Bunch of data. */ void stream::read(misc::shared_ptr<io::data>& d) { // Lock mutex. d.clear(); QMutexLocker lock(&_mutex); // Check that read should be done. if (!_process_in || !_rfile.data()) throw (io::exceptions::shutdown(!_process_in, !_process_out) << "file stream is shutdown"); // Seek to position. _rfile->seek(_roffset); // Build data array. std::auto_ptr<io::raw> data(new io::raw); data->resize(BUFSIZ); // Read data. unsigned long rb; try { rb = _rfile->read(data->QByteArray::data(), data->size()); } catch (io::exceptions::shutdown const& e) { (void)e; if (_wid == _rid) { _rfile->close(); _rfile.clear(); std::string file_path(_file_path(_rid)); logging::info(logging::high) << "file: end of last file '" << file_path.c_str() << "' reached, closing and erasing file"; ::remove(file_path.c_str()); throw ; } _open_next_read(); rb = _rfile->read(data->QByteArray::data(), data->size()); } // Process data. logging::debug(logging::low) << "file: read " << rb << " bytes from '" << _file_path(_rid).c_str() << "'"; data->resize(rb); _roffset += rb; d = misc::shared_ptr<io::data>(data.release()); // Erase read data. _rfile->seek(0); union { char bytes[2 * sizeof(uint32_t)]; uint32_t integers[2]; } header; header.integers[0] = htonl(_roffset / 4294967296ull); header.integers[1] = htonl(_roffset % 4294967296ull); unsigned int written(0); while (written != sizeof(header.bytes)) written += _rfile->write( header.bytes + written, sizeof(header.bytes) - written); return ; } /** * Generate statistics about file processing. * * @param[out] buffer Output buffer. */ void stream::statistics(std::string& buffer) const { std::ostringstream oss; oss << "file_read_path=" << _file_path(_rid) << "\n" << "file_read_offset=" << _roffset << "\n" << "file_write_path=" << _file_path(_wid) << "\n" << "file_write_offset=" << _woffset << "\n" << "file_max_size="; if (_max_size != std::numeric_limits<long>::max()) oss << _max_size; else oss << "unlimited"; oss << "\n"; oss << "file_percent_processed=" << std::fixed << std::setprecision(1); if ((_rid != _wid) && (_max_size == std::numeric_limits<long>::max())) oss << "unknown\n"; else oss << (_roffset * 100.0) / (_woffset + (_wid - _rid) * _max_size) << "%\n"; buffer.append(oss.str()); return ; } /** * Write data to the file. * * @param[in] d Data to write. * * @return Number of events acknowledged (1). */ unsigned int stream::write(misc::shared_ptr<io::data> const& d) { // Check that data exists and should be processed. if (!_process_out) throw (io::exceptions::shutdown(!_process_in, !_process_out) << "file stream is shutdown"); if (d.isNull()) return (1); if (d->type() == io::events::data_type<io::events::internal, 1>::value) { // Lock mutex. QMutexLocker lock(&_mutex); // Seek to end of file if necessary. _wfile->seek(_woffset); // Get data. char const* memory; unsigned int size; { io::raw* data(static_cast<io::raw*>(d.data())); memory = data->QByteArray::data(); size = data->size(); } // Debug message. logging::debug(logging::low) << "file: write request of " << size << " bytes for '" << _file_path(_wid).c_str() << "'"; // Write data. while (size > 0) { if (_woffset == _max_size) _open_next_write(); unsigned long max_write(_max_size - _woffset); if (size < max_write) max_write = size; unsigned long wb(_wfile->write(memory, max_write)); size -= wb; _woffset += wb; memory += wb; } } else logging::info(logging::low) << "file: write request with " \ "invalid data (" << d->type() << ")"; return (1); } /************************************** * * * Private Methods * * * **************************************/ /** * Get the file path matching the ID. * * @param[in] id Current ID. */ std::string stream::_file_path(unsigned int id) const { if (id) { std::ostringstream oss; oss << _path << id; return (oss.str()); } return (_path); } /** * Open the first readable file. */ void stream::_open_first_read() { // Get path components. QString base_dir; QString base_name; { size_t last_slash(_path.find_last_of('/')); if (last_slash == std::string::npos) { base_dir = "."; base_name = _path.c_str(); } else { base_dir = _path.substr(0, last_slash).c_str(); base_name = _path.substr(last_slash + 1).c_str(); } } // Browse directory. QStringList entries; { QStringList filters; filters << base_name + "*"; QDir dir(base_dir); entries = dir.entryList(filters); } // Find minimum value. unsigned int min(UINT_MAX); for (QStringList::iterator it(entries.begin()), end(entries.end()); it != end; ++it) { it->remove(0, base_name.size()); unsigned int i(it->toUInt()); if (i < min) min = i; } // If no file was found this is an error. if (UINT_MAX == min) throw (io::exceptions::shutdown(true, true) << "cannot find file entry in '" << qPrintable(base_dir) << "' matching '" << qPrintable(base_name) << "'"); // Open file. _rid = min - 1; _open_next_read(); return ; } /** * Open the first writable file. */ void stream::_open_first_write() { // Get path components. QString base_dir; QString base_name; { size_t last_slash(_path.find_last_of('/')); if (last_slash == std::string::npos) { base_dir = "."; base_name = _path.c_str(); } else { base_dir = _path.substr(0, last_slash).c_str(); base_name = _path.substr(last_slash + 1).c_str(); } } // Browse directory. QStringList entries; { QStringList filters; filters << base_name + "*"; QDir dir(base_dir); entries = dir.entryList(filters); } // Find maximum value. unsigned int max(0); for (QStringList::iterator it(entries.begin()), end(entries.end()); it != end; ++it) { it->remove(0, base_name.size()); unsigned int i(it->toUInt()); if (i > max) max = i; } _wid = max - 1; // Open file. _open_next_write(false); return ; } /** * Open the next readable file. */ void stream::_open_next_read() { // Did we reached the write file ? if (_rid + 1 == _wid) { _rfile = _wfile; _rfile->seek(0); } else { // Open file. std::string file_path(_file_path(_rid + 1)); { misc::shared_ptr<cfile> new_file(new cfile); new_file->open(file_path.c_str(), "r+"); _rfile = new_file; } } // Remove previous file. std::string file_path(_file_path(_rid)); logging::info(logging::high) << "file: end of file '" << file_path.c_str() << "' reached, erasing file"; ::remove(file_path.c_str()); // Adjust current index. ++_rid; // Get read offset. union { char bytes[2 * sizeof(uint32_t)]; uint32_t integers[2]; } header; unsigned int size(0); while (size != sizeof(header)) size += _rfile->read(header.bytes + size, sizeof(header) - size); _roffset = ntohl(header.integers[0]) * 4294967296ull + ntohl(header.integers[1]); return ; } /** * Open the next writable file. * * @param[in] truncate true to truncate file. */ void stream::_open_next_write(bool truncate) { // Open file. std::string file_path(_file_path(_wid + 1)); logging::info(logging::high) << "file: opening new file '" << file_path.c_str() << "'"; { misc::shared_ptr<cfile> new_file(new cfile); if (truncate) new_file->open(file_path.c_str(), "w+"); else { try { new_file->open(file_path.c_str(), "r+"); } catch (exceptions::msg const& e) { new_file->open(file_path.c_str(), "w+"); } } _wfile = new_file; } // Position. _wfile->seek(0, SEEK_END); _woffset = _wfile->tell(); // Adjust current index. ++_wid; if (_woffset < static_cast<long>(2 * sizeof(uint32_t))) { // Rewind to file beginning. _wfile->seek(0); // Write read offset. union { char bytes[2 * sizeof(uint32_t)]; uint32_t integers[2]; } header; header.integers[0] = 0; header.integers[1] = htonl(2 * sizeof(uint32_t)); unsigned int size(0); while (size < sizeof(header)) size += _wfile->write(header.bytes + size, sizeof(header) - size); // Set current offset. _woffset = 2 * sizeof(uint32_t); } return ; } <|endoftext|>
<commit_before><commit_msg>Fix first run ui hanging. The threads need to get started earlier.<commit_after><|endoftext|>
<commit_before><commit_msg>[gtk] avoid dcheck crash when making browser window very narrow<commit_after><|endoftext|>
<commit_before><commit_msg>Gtk: fix reference counting/destruction of GtkMenu* in MenuGtk. <commit_after><|endoftext|>
<commit_before> // -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <jgallagher@opendap.org> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPYRIGHT URI/MIT 1997-1999 // Please read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // jhrg,jimg James Gallagher <jgallagher@gso.uri.edu> // This is the source to `geturl'; a simple tool to exercise the Connect // class. It can be used to get naked URLs as well as the DAP2 DAS and DDS // objects. jhrg. #include "config.h" static char rcsid[] not_used = { "$Id$" }; #include <stdio.h> #ifdef WIN32 #include <io.h> #include <fcntl.h> #endif #include <GetOpt.h> #include <string> #include "AISConnect.h" #include "Response.h" #include "StdinResponse.h" using std::cerr; using std::endl; const char *version = "$Revision$"; extern int dods_keep_temps; // defined in HTTPResponse.h void usage(string name) { cerr << "Usage: " << name << endl; cerr << " [idDaxAVvks] [-B <db>][-c <expr>][-m <num>] <url> [<url> ...]" << endl; cerr << " [Vvks] <file> [<file> ...]" << endl; cerr << endl; cerr << "In the first form of the command, dereference the URL and" << endl; cerr << "perform the requested operations. This includes routing" << endl; cerr << "the returned information through the DAP processing" << endl; cerr << "library (parsing the returned objects, et c.). If none" << endl; cerr << "of a, d, or D are used with a URL, then the DAP library" << endl; cerr << "routines are NOT used and the URLs contents are dumped" << endl; cerr << "to standard output." << endl; cerr << endl; cerr << "In the second form of the command, assume the files are" << endl; cerr << "DataDDS objects (stored in files or read from pipes)" << endl; cerr << "and process them as if -D were given. In this case the" << endl; cerr << "information *must* contain valid MIME header in order" << endl; cerr << "to be processed." << endl; cerr << endl; cerr << "Options:" << endl; cerr << " i: For each URL, get the server version." << endl; cerr << " d: For each URL, get the the DDS." << endl; cerr << " a: For each URL, get the the DAS." << endl; cerr << " A: Use the AIS for DAS objects." << endl; cerr << " D: For each URL, get the the DataDDS." << endl; cerr << " x: For each URL, get the DDX object. Does not get data." << endl; cerr << " X: Build a DDX in getdap using the DDS and DAS." << endl; cerr << " B: <AIS xml dataBase>. Overrides .dodsrc." << endl; cerr << " v: Verbose." << endl; cerr << " V: Version." << endl; cerr << " c: <expr> is a contraint expression. Used with -D." << endl; cerr << " NB: You can use a `?' for the CE also." << endl; cerr << " k: Keep temporary files created by libdap core\n" << endl; cerr << " m: Request the same URL <num> times." << endl; cerr << " z: Ask the server to compress data." << endl; cerr << " s: Print Sequences using numbered rows." << endl; } bool read_data(FILE * fp) { if (!fp) { fprintf(stderr, "geturl: Whoa!!! Null stream pointer.\n"); return false; } // Changed from a loop that used getc() to one that uses fread(). getc() // worked fine for transfers of text information, but *not* for binary // transfers. fread() will handle both. char c; while (fp && !feof(fp) && fread(&c, 1, 1, fp)) printf("%c", c); // stick with stdio return true; } static void print_data(DDS & dds, bool print_rows = false) { fprintf(stdout, "The data:\n"); for (DDS::Vars_iter i = dds.var_begin(); i != dds.var_end(); i++) { BaseType *v = *i; if (print_rows && (*i)->type() == dods_sequence_c) dynamic_cast < Sequence * >(*i)->print_val_by_rows(stdout); else v->print_val(stdout); } fprintf(stdout, "\n"); fflush(stdout); } int main(int argc, char *argv[]) { GetOpt getopt(argc, argv, "idaDxXAVvkB:c:m:zsh?"); int option_char; bool get_das = false; bool get_dds = false; bool get_data = false; bool get_ddx = false; bool build_ddx = false; bool get_version = false; bool cexpr = false; bool verbose = false; bool multi = false; bool accept_deflate = false; bool print_rows = false; bool use_ais = false; int times = 1; string expr = ""; string ais_db = ""; #ifdef WIN32 _setmode(_fileno(stdout), _O_BINARY); #endif while ((option_char = getopt()) != EOF) switch (option_char) { case 'd': get_dds = true; break; case 'a': get_das = true; break; case 'D': get_data = true; break; case 'x': get_ddx = true; break; case 'X': build_ddx = true; break; case 'A': use_ais = true; break; case 'V': fprintf(stderr, "geturl version: %s\n", version); exit(0); case 'i': get_version = true; break; case 'v': verbose = true; break; case 'k': dods_keep_temps = 1; break; // keep_temp is in Connect.cc case 'c': cexpr = true; expr = getopt.optarg; break; case 'm': multi = true; times = atoi(getopt.optarg); break; case 'B': use_ais = true; ais_db = getopt.optarg; break; case 'z': accept_deflate = true; break; case 's': print_rows = true; break; case 'h': case '?': default: usage(argv[0]); exit(1); break; } try { // If after processing all the command line options there is nothing // left (no URL or file) assume that we should read from stdin. for (int i = getopt.optind; i < argc; ++i) { if (verbose) fprintf(stderr, "Fetching: %s\n", argv[i]); string name = argv[i]; Connect *url = 0;; if (use_ais) { if (!ais_db.empty()) url = new AISConnect(name, ais_db); else url = new AISConnect(name); } else { url = new Connect(name); } // This overrides the value set in the .dodsrc file. if (accept_deflate) url->set_accept_deflate(accept_deflate); if (url->is_local()) { if (verbose) { fprintf(stderr, "Assuming that the argument %s is a file that contains a DAP2 data object; decoding.\n", argv[i]); } Response *r = 0; BaseTypeFactory factory; DataDDS dds(&factory); try { if (strcmp(argv[i], "-") == 0) { r = new StdinResponse(stdin); if (!r->get_stream()) throw Error("Could not open standard input."); url->read_data(dds, r); } else { r = new Response(fopen(argv[i], "r")); if (!r->get_stream()) throw Error(string("The input source: ") + string(argv[i]) + string(" could not be opened")); url->read_data_no_mime(dds, r); } } catch(Error & e) { cerr << e.get_error_message() << endl; delete r; r = 0; delete url; url = 0; break; } if (verbose) fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); print_data(dds, print_rows); } else if (get_version) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->request_protocol().c_str(), url->get_version().c_str()); } else if (get_das) { for (int j = 0; j < times; ++j) { DAS das; try { url->request_das(das); } catch(Error & e) { cerr << e.get_error_message() << endl; delete url; url = 0; continue; } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "DAS:\n"); } das.print(stdout); } } else if (get_dds) { for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DDS dds(&factory); try { url->request_dds(dds); } catch(Error & e) { cerr << e.get_error_message() << endl; delete url; url = 0; continue; // Goto the next URL or exit the loop. } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "DDS:\n"); } dds.print(stdout); } } else if (get_ddx) { for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DDS dds(&factory); try { url->request_ddx(dds); } catch(Error & e) { cerr << e.get_error_message() << endl; continue; // Goto the next URL or exit the loop. } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "DDX:\n"); } dds.print_xml(stdout, false, "geturl; no blob yet"); } } else if (build_ddx) { for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DDS dds(&factory); try { url->request_dds(dds); DAS das; url->request_das(das); dds.transfer_attributes(&das); } catch(Error & e) { cerr << e.get_error_message() << endl; continue; // Goto the next URL or exit the loop. } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "Client-built DDX:\n"); } dds.print_xml(stdout, false, "geturl; no blob yet"); } } else if (get_data) { if (expr.empty() && name.find('?') == string::npos) expr = ""; for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DataDDS dds(&factory); try { DBG(cerr << "URL: " << url->URL(false) << endl); DBG(cerr << "CE: " << expr << endl); url->request_data(dds, expr); if (verbose) fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); print_data(dds, print_rows); } catch(Error & e) { cerr << e.get_error_message() << endl; delete url; url = 0; continue; } } } else { // if (!get_das && !get_dds && !get_data) // This code uses HTTPConnect::fetch_url which cannot be // accessed using an instance of Connect. So some of the // options supported by other URLs won't work here (e.g., the // verbose option doesn't show the server version number). HTTPConnect http(RCReader::instance()); // This overrides the value set in the .dodsrc file. if (accept_deflate) http.set_accept_deflate(accept_deflate); string url_string = argv[i]; for (int j = 0; j < times; ++j) { try { Response *r = http.fetch_url(url_string); if (!read_data(r->get_stream())) { continue; } delete r; r = 0; } catch(Error & e) { cerr << e.get_error_message() << endl; continue; } } } delete url; url = 0; } } catch(Error &e) { cerr << e.get_error_message() << endl; return 1; } catch(exception &e) { cerr << "C++ library exception: " << e.what() << endl; return 1; } return 0; } <commit_msg>getdap.cc: Fixed a bug where the constraint expression passed in using -c was not used when getting either a DDS or a DDX (but it was used when getting data).<commit_after> // -*- mode: c++; c-basic-offset:4 -*- // This file is part of libdap, A C++ implementation of the OPeNDAP Data // Access Protocol. // Copyright (c) 2002,2003 OPeNDAP, Inc. // Author: James Gallagher <jgallagher@opendap.org> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. // (c) COPYRIGHT URI/MIT 1997-1999 // Please read the full copyright statement in the file COPYRIGHT_URI. // // Authors: // jhrg,jimg James Gallagher <jgallagher@gso.uri.edu> // This is the source to `geturl'; a simple tool to exercise the Connect // class. It can be used to get naked URLs as well as the DAP2 DAS and DDS // objects. jhrg. #include "config.h" static char rcsid[] not_used = { "$Id$" }; #include <stdio.h> #ifdef WIN32 #include <io.h> #include <fcntl.h> #endif #include <GetOpt.h> #include <string> #include "AISConnect.h" #include "Response.h" #include "StdinResponse.h" using std::cerr; using std::endl; const char *version = "$Revision$"; extern int dods_keep_temps; // defined in HTTPResponse.h void usage(string name) { cerr << "Usage: " << name << endl; cerr << " [idDaxAVvks] [-B <db>][-c <expr>][-m <num>] <url> [<url> ...]" << endl; cerr << " [Vvks] <file> [<file> ...]" << endl; cerr << endl; cerr << "In the first form of the command, dereference the URL and" << endl; cerr << "perform the requested operations. This includes routing" << endl; cerr << "the returned information through the DAP processing" << endl; cerr << "library (parsing the returned objects, et c.). If none" << endl; cerr << "of a, d, or D are used with a URL, then the DAP library" << endl; cerr << "routines are NOT used and the URLs contents are dumped" << endl; cerr << "to standard output." << endl; cerr << endl; cerr << "In the second form of the command, assume the files are" << endl; cerr << "DataDDS objects (stored in files or read from pipes)" << endl; cerr << "and process them as if -D were given. In this case the" << endl; cerr << "information *must* contain valid MIME header in order" << endl; cerr << "to be processed." << endl; cerr << endl; cerr << "Options:" << endl; cerr << " i: For each URL, get the server version." << endl; cerr << " d: For each URL, get the the DDS." << endl; cerr << " a: For each URL, get the the DAS." << endl; cerr << " A: Use the AIS for DAS objects." << endl; cerr << " D: For each URL, get the the DataDDS." << endl; cerr << " x: For each URL, get the DDX object. Does not get data." << endl; cerr << " X: Build a DDX in getdap using the DDS and DAS." << endl; cerr << " B: <AIS xml dataBase>. Overrides .dodsrc." << endl; cerr << " v: Verbose." << endl; cerr << " V: Version." << endl; cerr << " c: <expr> is a contraint expression. Used with -D." << endl; cerr << " NB: You can use a `?' for the CE also." << endl; cerr << " k: Keep temporary files created by libdap core\n" << endl; cerr << " m: Request the same URL <num> times." << endl; cerr << " z: Ask the server to compress data." << endl; cerr << " s: Print Sequences using numbered rows." << endl; } bool read_data(FILE * fp) { if (!fp) { fprintf(stderr, "geturl: Whoa!!! Null stream pointer.\n"); return false; } // Changed from a loop that used getc() to one that uses fread(). getc() // worked fine for transfers of text information, but *not* for binary // transfers. fread() will handle both. char c; while (fp && !feof(fp) && fread(&c, 1, 1, fp)) printf("%c", c); // stick with stdio return true; } static void print_data(DDS & dds, bool print_rows = false) { fprintf(stdout, "The data:\n"); for (DDS::Vars_iter i = dds.var_begin(); i != dds.var_end(); i++) { BaseType *v = *i; if (print_rows && (*i)->type() == dods_sequence_c) dynamic_cast < Sequence * >(*i)->print_val_by_rows(stdout); else v->print_val(stdout); } fprintf(stdout, "\n"); fflush(stdout); } int main(int argc, char *argv[]) { GetOpt getopt(argc, argv, "idaDxXAVvkB:c:m:zsh?"); int option_char; bool get_das = false; bool get_dds = false; bool get_data = false; bool get_ddx = false; bool build_ddx = false; bool get_version = false; bool cexpr = false; bool verbose = false; bool multi = false; bool accept_deflate = false; bool print_rows = false; bool use_ais = false; int times = 1; string expr = ""; string ais_db = ""; #ifdef WIN32 _setmode(_fileno(stdout), _O_BINARY); #endif while ((option_char = getopt()) != EOF) switch (option_char) { case 'd': get_dds = true; break; case 'a': get_das = true; break; case 'D': get_data = true; break; case 'x': get_ddx = true; break; case 'X': build_ddx = true; break; case 'A': use_ais = true; break; case 'V': fprintf(stderr, "geturl version: %s\n", version); exit(0); case 'i': get_version = true; break; case 'v': verbose = true; break; case 'k': dods_keep_temps = 1; break; // keep_temp is in Connect.cc case 'c': cexpr = true; expr = getopt.optarg; break; case 'm': multi = true; times = atoi(getopt.optarg); break; case 'B': use_ais = true; ais_db = getopt.optarg; break; case 'z': accept_deflate = true; break; case 's': print_rows = true; break; case 'h': case '?': default: usage(argv[0]); exit(1); break; } try { // If after processing all the command line options there is nothing // left (no URL or file) assume that we should read from stdin. for (int i = getopt.optind; i < argc; ++i) { if (verbose) fprintf(stderr, "Fetching: %s\n", argv[i]); string name = argv[i]; Connect *url = 0;; if (use_ais) { if (!ais_db.empty()) url = new AISConnect(name, ais_db); else url = new AISConnect(name); } else { url = new Connect(name); } // This overrides the value set in the .dodsrc file. if (accept_deflate) url->set_accept_deflate(accept_deflate); if (url->is_local()) { if (verbose) { fprintf(stderr, "Assuming that the argument %s is a file that contains a DAP2 data object; decoding.\n", argv[i]); } Response *r = 0; BaseTypeFactory factory; DataDDS dds(&factory); try { if (strcmp(argv[i], "-") == 0) { r = new StdinResponse(stdin); if (!r->get_stream()) throw Error("Could not open standard input."); url->read_data(dds, r); } else { r = new Response(fopen(argv[i], "r")); if (!r->get_stream()) throw Error(string("The input source: ") + string(argv[i]) + string(" could not be opened")); url->read_data_no_mime(dds, r); } } catch(Error & e) { cerr << e.get_error_message() << endl; delete r; r = 0; delete url; url = 0; break; } if (verbose) fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); print_data(dds, print_rows); } else if (get_version) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->request_protocol().c_str(), url->get_version().c_str()); } else if (get_das) { for (int j = 0; j < times; ++j) { DAS das; try { url->request_das(das); } catch(Error & e) { cerr << e.get_error_message() << endl; delete url; url = 0; continue; } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "DAS:\n"); } das.print(stdout); } } else if (get_dds) { for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DDS dds(&factory); try { url->request_dds(dds, expr); } catch(Error & e) { cerr << e.get_error_message() << endl; delete url; url = 0; continue; // Goto the next URL or exit the loop. } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "DDS:\n"); } dds.print(stdout); } } else if (get_ddx) { for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DDS dds(&factory); try { url->request_ddx(dds, expr); } catch(Error & e) { cerr << e.get_error_message() << endl; continue; // Goto the next URL or exit the loop. } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "DDX:\n"); } dds.print_xml(stdout, false, "geturl; no blob yet"); } } else if (build_ddx) { for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DDS dds(&factory); try { url->request_dds(dds); DAS das; url->request_das(das); dds.transfer_attributes(&das); } catch(Error & e) { cerr << e.get_error_message() << endl; continue; // Goto the next URL or exit the loop. } if (verbose) { fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); fprintf(stderr, "Client-built DDX:\n"); } dds.print_xml(stdout, false, "geturl; no blob yet"); } } else if (get_data) { #if 0 if (expr.empty() && name.find('?') == string::npos) expr = ""; #endif for (int j = 0; j < times; ++j) { BaseTypeFactory factory; DataDDS dds(&factory); try { DBG(cerr << "URL: " << url->URL(false) << endl); DBG(cerr << "CE: " << expr << endl); url->request_data(dds, expr); if (verbose) fprintf(stderr, "DAP version: %s, Server version: %s\n", url->get_protocol().c_str(), url->get_version().c_str()); print_data(dds, print_rows); } catch(Error & e) { cerr << e.get_error_message() << endl; delete url; url = 0; continue; } } } else { // if (!get_das && !get_dds && !get_data) This code uses // HTTPConnect::fetch_url which cannot be accessed using an // instance of Connect. So some of the options supported by // other URLs won't work here (e.g., the verbose option // doesn't show the server version number). HTTPConnect http(RCReader::instance()); // This overrides the value set in the .dodsrc file. if (accept_deflate) http.set_accept_deflate(accept_deflate); string url_string = argv[i]; for (int j = 0; j < times; ++j) { try { Response *r = http.fetch_url(url_string); if (!read_data(r->get_stream())) { continue; } delete r; r = 0; } catch(Error & e) { cerr << e.get_error_message() << endl; continue; } } } delete url; url = 0; } } catch(Error &e) { cerr << e.get_error_message() << endl; return 1; } catch(exception &e) { cerr << "C++ library exception: " << e.what() << endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include <sim/constants.h> #include <sim/mysql.h> #include <simlib/filesystem.h> #include <simlib/process.h> #include <simlib/sim/problem_package.h> #include <simlib/spawner.h> #include <simlib/time.h> using std::string; using std::vector; /** * @brief Displays help */ static void help(const char* program_name) { if (program_name == nullptr) program_name = "backup"; printf("Usage: %s [options]\n", program_name); puts("Make a backup of solutions and database contents"); } int main2(int argc, char** argv) { if (argc != 1) { help(argc > 0 ? argv[0] : nullptr); return 1; } chdirToExecDir(); #define MYSQL_CNF ".mysql.cnf" FileRemover mysql_cnf_guard; // Get connection auto conn = MySQL::make_conn_with_credential_file(".db.config"); FileDescriptor fd {MYSQL_CNF, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_0600}; if (fd == -1) { errlog("Failed to open file `" MYSQL_CNF "`: open()", errmsg()); return 1; } mysql_cnf_guard.reset(MYSQL_CNF); writeAll_throw(fd, intentionalUnsafeStringView( concat("[client]\nuser=", conn.impl()->user, "\npassword=", conn.impl()->passwd, "\nuser=", conn.impl()->user, "\n"))); auto run_command = [](vector<string> args) { auto es = Spawner::run(args[0], args); if (es.si.code != CLD_EXITED or es.si.status != 0) { errlog(args[0], " failed: ", es.message); exit(1); } }; // Remove temporary internal files that were not removed (e.g. a problem // adding job was canceled between the first and second stage while it was // pending) { using namespace std::chrono; using namespace std::chrono_literals; auto transaction = conn.start_transaction(); auto stmt = conn.prepare( "SELECT tmp_file_id FROM jobs " "WHERE tmp_file_id IS NOT NULL AND status IN (" JSTATUS_DONE_STR "," JSTATUS_FAILED_STR "," JSTATUS_CANCELED_STR ")"); stmt.bindAndExecute(); uint64_t tmp_file_id; stmt.res_bind_all(tmp_file_id); auto deleter = conn.prepare("DELETE FROM internal_files WHERE id=?"); // Remove jobs temporary internal files while (stmt.next()) { auto file_path = internal_file_path(tmp_file_id); if (access(file_path, F_OK) == 0 and system_clock::now() - get_modification_time(file_path) > 2h) { deleter.bindAndExecute(tmp_file_id); (void)unlink(file_path); } } // Remove internal files that do not have an entry in internal_files sim::PackageContents fc; fc.load_from_directory(INTERNAL_FILES_DIR); AVLDictSet<std::string> orphaned_files; fc.for_each_with_prefix("", [&](StringView file) { orphaned_files.emplace(file.to_string()); }); stmt = conn.prepare("SELECT id FROM internal_files"); stmt.bindAndExecute(); InplaceBuff<32> file_id; stmt.res_bind_all(file_id); while (stmt.next()) orphaned_files.erase(file_id); // Remove orphaned files that are older than 2h (not to delete files // that are just created but not committed) orphaned_files.for_each([&](std::string const& file) { struct stat64 st; auto file_path = concat(INTERNAL_FILES_DIR, file); if (stat64(file_path.to_cstr().data(), &st)) { if (errno == ENOENT) return; THROW("stat64", errmsg()); } if (system_clock::now() - get_modification_time(st) > 2h) { stdlog("Deleting: ", file); (void)unlink(file_path); } }); transaction.commit(); } FileRemover mysql_dump_guard {"dump.sql"}; run_command({ "mysqldump", "--defaults-file=" MYSQL_CNF, "--result-file=dump.sql", "--single-transaction", conn.impl()->db, }); run_command({"git", "init"}); run_command({"git", "config", "--local", "user.name", "Sim backuper"}); run_command({"git", "add", "--verbose", "static"}); run_command({"git", "add", "--verbose", "dump.sql"}); run_command({"git", "add", "--verbose", "internal_files/"}); run_command({"git", "add", "--verbose", "logs/"}); run_command({"git", "commit", "-m", concat_tostr("Backup ", mysql_date())}); return 0; } int main(int argc, char** argv) { try { return main2(argc, argv); } catch (const std::exception& e) { ERRLOG_CATCH(e); return 1; } } <commit_msg>backup: dump.sql is not removed and sim.conf and .db.config are backuped<commit_after>#include <sim/constants.h> #include <sim/mysql.h> #include <simlib/filesystem.h> #include <simlib/process.h> #include <simlib/sim/problem_package.h> #include <simlib/spawner.h> #include <simlib/time.h> using std::string; using std::vector; /** * @brief Displays help */ static void help(const char* program_name) { if (program_name == nullptr) program_name = "backup"; printf("Usage: %s [options]\n", program_name); puts("Make a backup of solutions and database contents"); } int main2(int argc, char** argv) { if (argc != 1) { help(argc > 0 ? argv[0] : nullptr); return 1; } chdirToExecDir(); #define MYSQL_CNF ".mysql.cnf" FileRemover mysql_cnf_guard; // Get connection auto conn = MySQL::make_conn_with_credential_file(".db.config"); FileDescriptor fd {MYSQL_CNF, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, S_0600}; if (fd == -1) { errlog("Failed to open file `" MYSQL_CNF "`: open()", errmsg()); return 1; } mysql_cnf_guard.reset(MYSQL_CNF); writeAll_throw(fd, intentionalUnsafeStringView( concat("[client]\nuser=", conn.impl()->user, "\npassword=", conn.impl()->passwd, "\nuser=", conn.impl()->user, "\n"))); auto run_command = [](vector<string> args) { auto es = Spawner::run(args[0], args); if (es.si.code != CLD_EXITED or es.si.status != 0) { errlog(args[0], " failed: ", es.message); exit(1); } }; // Remove temporary internal files that were not removed (e.g. a problem // adding job was canceled between the first and second stage while it was // pending) { using namespace std::chrono; using namespace std::chrono_literals; auto transaction = conn.start_transaction(); auto stmt = conn.prepare( "SELECT tmp_file_id FROM jobs " "WHERE tmp_file_id IS NOT NULL AND status IN (" JSTATUS_DONE_STR "," JSTATUS_FAILED_STR "," JSTATUS_CANCELED_STR ")"); stmt.bindAndExecute(); uint64_t tmp_file_id; stmt.res_bind_all(tmp_file_id); auto deleter = conn.prepare("DELETE FROM internal_files WHERE id=?"); // Remove jobs temporary internal files while (stmt.next()) { auto file_path = internal_file_path(tmp_file_id); if (access(file_path, F_OK) == 0 and system_clock::now() - get_modification_time(file_path) > 2h) { deleter.bindAndExecute(tmp_file_id); (void)unlink(file_path); } } // Remove internal files that do not have an entry in internal_files sim::PackageContents fc; fc.load_from_directory(INTERNAL_FILES_DIR); AVLDictSet<std::string> orphaned_files; fc.for_each_with_prefix("", [&](StringView file) { orphaned_files.emplace(file.to_string()); }); stmt = conn.prepare("SELECT id FROM internal_files"); stmt.bindAndExecute(); InplaceBuff<32> file_id; stmt.res_bind_all(file_id); while (stmt.next()) orphaned_files.erase(file_id); // Remove orphaned files that are older than 2h (not to delete files // that are just created but not committed) orphaned_files.for_each([&](std::string const& file) { struct stat64 st; auto file_path = concat(INTERNAL_FILES_DIR, file); if (stat64(file_path.to_cstr().data(), &st)) { if (errno == ENOENT) return; THROW("stat64", errmsg()); } if (system_clock::now() - get_modification_time(st) > 2h) { stdlog("Deleting: ", file); (void)unlink(file_path); } }); transaction.commit(); } run_command({ "mysqldump", "--defaults-file=" MYSQL_CNF, "--result-file=dump.sql", "--single-transaction", conn.impl()->db, }); if (chmod("dump.sql", S_0600)) THROW("chmod()", errmsg()); run_command({"git", "init"}); run_command({"git", "config", "--local", "user.name", "Sim backuper"}); run_command({"git", "add", "--verbose", "sim.conf", ".db.config"}); run_command({"git", "add", "--verbose", "static"}); run_command({"git", "add", "--verbose", "dump.sql"}); run_command({"git", "add", "--verbose", "internal_files/"}); run_command({"git", "add", "--verbose", "logs/"}); run_command({"git", "commit", "-m", concat_tostr("Backup ", mysql_date())}); return 0; } int main(int argc, char** argv) { try { return main2(argc, argv); } catch (const std::exception& e) { ERRLOG_CATCH(e); return 1; } } <|endoftext|>
<commit_before>#include <string.h> #include <stdio.h> #include <inttypes.h> #include <stdlib.h> #include <assert.h> static const char b58_tbl[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool bcn_decode_b58( unsigned char **data, size_t *datalen, const unsigned char *str, size_t strlen ) { int zeroes = 0; int i = 0; unsigned char *b256; int ch, carry, j, slen, dlen, b256len; *data = NULL; *datalen = 0; assert(str != NULL); slen = (int)strlen; if (slen == 0) return true; for (i = 0; i < slen; i++) { if (str[i] != '1') break; zeroes++; } b256len = slen * 733 / 1000 + 1; b256 = (unsigned char *)malloc(b256len); if (b256 == NULL) return false; memset(b256, 0, b256len); for (; i < slen; i++) { ch = str[i]; // Big switch statement taken // from breadwallet code. switch (ch) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ch -= '1'; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': ch += 9 - 'A'; break; case 'J': case 'K': case 'L': case 'M': case 'N': ch += 17 - 'J'; break; case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': ch += 22 - 'P'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': ch += 33 - 'a'; break; case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': ch += 44 - 'm'; break; default: ch = UINT32_MAX; } if (ch >= 58) { free(b256); return false; } carry = ch; for (j = b256len - 1; j >= 0; j--) { carry += 58 * b256[j]; b256[j] = carry % 256; carry = carry / 256; } assert(carry == 0); } i = 0; while (i < b256len && b256[i] == 0) i++; dlen = zeroes + (b256len - i); *data = (unsigned char *)malloc(dlen); if (*data == NULL) { free(b256); return false; } for (j = 0; j < zeroes; j++) (*data)[j] = 0; while (i < b256len) (*data)[j++] = b256[i++]; *datalen = (size_t)dlen; free(b256); return true; } bool bcn_encode_b58( unsigned char **str, size_t *strlen, const unsigned char *data, size_t datalen ) { int zeroes = 0; int length = 0; unsigned char *b58; int b58len; int i, carry, j, k; int dlen = (int)datalen; *str = NULL; *strlen = 0; assert(data != NULL); if (dlen == 0) return true; for (i = 0; i < dlen; i++) { if (data[i] != 0) break; zeroes++; } b58len = dlen * 138 / 100 + 1 + 1; b58 = (unsigned char *)malloc(b58len); if (b58 == NULL) return false; memset(b58, 0, b58len); for (; i < dlen; i++) { carry = data[i]; j = 0; for (k = b58len - 1; k >= 0; k--, j++) { if (carry == 0 && j >= length) break; carry += 256 * b58[k]; b58[k] = carry % 58; carry = carry / 58; } assert(carry == 0); length = j; } i = b58len - length; while (i < b58len && b58[i] == 0) i++; *str = (unsigned char *)malloc(zeroes + (b58len - i)); if (*str == NULL) { free(b58); return false; } for (j = 0; j < zeroes; j++) (*str)[j] = '1'; for (; i < b58len; i++) (*str)[j++] = b58_tbl[b58[i]]; (*str)[j] = 0; *strlen = (size_t)j; free(b58); return true; } <commit_msg>base58: consistency.<commit_after>#include <string.h> #include <stdio.h> #include <inttypes.h> #include <stdlib.h> #include <assert.h> static const char b58_tbl[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool bcn_decode_b58( unsigned char **data, size_t *datalen, const unsigned char *str, size_t strlen ) { int zeroes = 0; int i = 0; unsigned char *b256; int ch, carry, j, slen, dlen, b256len; *data = NULL; *datalen = 0; assert(str != NULL); slen = (int)strlen; if (slen == 0) return true; for (i = 0; i < slen; i++) { if (str[i] != '1') break; zeroes++; } b256len = slen * 733 / 1000 + 1; b256 = (unsigned char *)malloc(b256len); if (b256 == NULL) return false; memset(b256, 0, b256len); for (; i < slen; i++) { ch = str[i]; // Big switch statement taken // from breadwallet code. switch (ch) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ch -= '1'; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': ch += 9 - 'A'; break; case 'J': case 'K': case 'L': case 'M': case 'N': ch += 17 - 'J'; break; case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': ch += 22 - 'P'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': ch += 33 - 'a'; break; case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': ch += 44 - 'm'; break; default: ch = UINT32_MAX; } if (ch >= 58) { free(b256); return false; } carry = ch; for (j = b256len - 1; j >= 0; j--) { carry += 58 * b256[j]; b256[j] = carry % 256; carry = carry / 256; } assert(carry == 0); } i = 0; while (i < b256len && b256[i] == 0) i++; dlen = zeroes + (b256len - i); *data = (unsigned char *)malloc(dlen); if (*data == NULL) { free(b256); return false; } for (j = 0; j < zeroes; j++) (*data)[j] = 0; while (i < b256len) (*data)[j++] = b256[i++]; assert(j == dlen); *datalen = (size_t)j; free(b256); return true; } bool bcn_encode_b58( unsigned char **str, size_t *strlen, const unsigned char *data, size_t datalen ) { int zeroes = 0; int length = 0; unsigned char *b58; int b58len; int i, carry, j, k; int dlen = (int)datalen; *str = NULL; *strlen = 0; assert(data != NULL); if (dlen == 0) return true; for (i = 0; i < dlen; i++) { if (data[i] != 0) break; zeroes++; } b58len = dlen * 138 / 100 + 1 + 1; b58 = (unsigned char *)malloc(b58len); if (b58 == NULL) return false; memset(b58, 0, b58len); for (; i < dlen; i++) { carry = data[i]; j = 0; for (k = b58len - 1; k >= 0; k--, j++) { if (carry == 0 && j >= length) break; carry += 256 * b58[k]; b58[k] = carry % 58; carry = carry / 58; } assert(carry == 0); length = j; } i = b58len - length; while (i < b58len && b58[i] == 0) i++; *str = (unsigned char *)malloc(zeroes + (b58len - i)); if (*str == NULL) { free(b58); return false; } for (j = 0; j < zeroes; j++) (*str)[j] = '1'; for (; i < b58len; i++) (*str)[j++] = b58_tbl[b58[i]]; (*str)[j] = 0; *strlen = (size_t)j; free(b58); return true; } <|endoftext|>
<commit_before><commit_msg>Remove chrome://apps from chrome-urls on ChromeOS.<commit_after><|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/searchlib/docstore/logdatastore.h> #include <vespa/searchlib/index/dummyfileheadercontext.h> #include <vespa/vespalib/util/closure.h> #include <vespa/vespalib/util/closuretask.h> #include <vespa/searchlib/transactionlog/nosyncproxy.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <vespa/vespalib/data/databuffer.h> #include <vespa/fastos/app.h> #include <unistd.h> #include <vespa/log/log.h> LOG_SETUP("documentstore.benchmark"); using namespace search; class BenchmarkDataStoreApp : public FastOS_Application { void usage(); int benchmark(const vespalib::string & directory, size_t numReads, size_t numThreads, size_t perChunk, const vespalib::string & readType); int Main() override; void read(size_t numReads, size_t perChunk, const IDataStore * dataStore); }; void BenchmarkDataStoreApp::usage() { printf("Usage: %s <direcory> <numreads> <numthreads> <objects per read> <normal,directio,mmap,mlock>\n", _argv[0]); fflush(stdout); } int BenchmarkDataStoreApp::Main() { if (_argc >= 2) { size_t numThreads(16); size_t numReads(1000000); size_t perChunk(1); vespalib::string readType("directio"); vespalib::string directory(_argv[1]); if (_argc >= 3) { numReads = strtoul(_argv[2], NULL, 0); if (_argc >= 4) { numThreads = strtoul(_argv[3], NULL, 0); if (_argc >= 5) { perChunk = strtoul(_argv[4], NULL, 0); if (_argc >= 5) { readType = _argv[5]; } } } } return benchmark(directory, numReads, numThreads, perChunk, readType); } else { fprintf(stderr, "Too few arguments\n"); usage(); return 1; } return 0; } void BenchmarkDataStoreApp::read(size_t numReads, size_t perChunk, const IDataStore * dataStore) { vespalib::DataBuffer buf; struct random_data rstate; char state[8]; memset(state, 0, sizeof(state)); memset(&rstate, 0, sizeof(rstate)); const size_t docIdLimit(dataStore->getDocIdLimit()); assert(docIdLimit > 0); initstate_r(getpid(), state, sizeof(state), &rstate); assert(srandom_r(getpid(), &rstate) == 0); int32_t rnd(0); for ( size_t i(0); i < numReads; i++) { random_r(&rstate, &rnd); uint32_t lid(rnd%docIdLimit); for (uint32_t j(lid); j < std::min(docIdLimit, lid+perChunk); j++) { dataStore->read(j, buf); buf.clear(); } } } int BenchmarkDataStoreApp::benchmark(const vespalib::string & dir, size_t numReads, size_t numThreads, size_t perChunk, const vespalib::string & readType) { int retval(0); LogDataStore::Config config; GrowStrategy growStrategy; TuneFileSummary tuning; if (readType == "directio") { tuning._randRead.setWantDirectIO(); } else if (readType == "normal") { tuning._randRead.setWantNormal(); } else if (readType == "mmap") { tuning._randRead.setWantMemoryMap(); } search::index::DummyFileHeaderContext fileHeaderContext; vespalib::ThreadStackExecutor executor(1, 128*1024); transactionlog::NoSyncProxy noTlSyncer; LogDataStore store(executor, dir, config, growStrategy, tuning, fileHeaderContext, noTlSyncer, NULL, true); vespalib::ThreadStackExecutor bmPool(numThreads, 128*1024); LOG(info, "Start read benchmark with %lu threads doing %lu reads in chunks of %lu reads. Totally %lu objects", numThreads, numReads, perChunk, numThreads * numReads * perChunk); for (size_t i(0); i < numThreads; i++) { bmPool.execute(vespalib::makeTask(vespalib::makeClosure(this, &BenchmarkDataStoreApp::read, numReads, perChunk, static_cast<const IDataStore *>(&store)))); } bmPool.sync(); LOG(info, "Benchmark done."); return retval; } FASTOS_MAIN(BenchmarkDataStoreApp); <commit_msg>Use simple standard pseudorandom generator.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/searchlib/docstore/logdatastore.h> #include <vespa/searchlib/index/dummyfileheadercontext.h> #include <vespa/vespalib/util/closure.h> #include <vespa/vespalib/util/closuretask.h> #include <vespa/searchlib/transactionlog/nosyncproxy.h> #include <vespa/vespalib/util/threadstackexecutor.h> #include <vespa/vespalib/data/databuffer.h> #include <vespa/fastos/app.h> #include <unistd.h> #include <random> #include <vespa/log/log.h> LOG_SETUP("documentstore.benchmark"); using namespace search; class BenchmarkDataStoreApp : public FastOS_Application { void usage(); int benchmark(const vespalib::string & directory, size_t numReads, size_t numThreads, size_t perChunk, const vespalib::string & readType); int Main() override; void read(size_t numReads, size_t perChunk, const IDataStore * dataStore); }; void BenchmarkDataStoreApp::usage() { printf("Usage: %s <direcory> <numreads> <numthreads> <objects per read> <normal,directio,mmap,mlock>\n", _argv[0]); fflush(stdout); } int BenchmarkDataStoreApp::Main() { if (_argc >= 2) { size_t numThreads(16); size_t numReads(1000000); size_t perChunk(1); vespalib::string readType("directio"); vespalib::string directory(_argv[1]); if (_argc >= 3) { numReads = strtoul(_argv[2], NULL, 0); if (_argc >= 4) { numThreads = strtoul(_argv[3], NULL, 0); if (_argc >= 5) { perChunk = strtoul(_argv[4], NULL, 0); if (_argc >= 5) { readType = _argv[5]; } } } } return benchmark(directory, numReads, numThreads, perChunk, readType); } else { fprintf(stderr, "Too few arguments\n"); usage(); return 1; } return 0; } void BenchmarkDataStoreApp::read(size_t numReads, size_t perChunk, const IDataStore * dataStore) { vespalib::DataBuffer buf; std::minstd_rand rng; const size_t docIdLimit(dataStore->getDocIdLimit()); assert(docIdLimit > 0); rng.seed(getpid()); int32_t rnd(0); for ( size_t i(0); i < numReads; i++) { rnd = rng(); uint32_t lid(rnd%docIdLimit); for (uint32_t j(lid); j < std::min(docIdLimit, lid+perChunk); j++) { dataStore->read(j, buf); buf.clear(); } } } int BenchmarkDataStoreApp::benchmark(const vespalib::string & dir, size_t numReads, size_t numThreads, size_t perChunk, const vespalib::string & readType) { int retval(0); LogDataStore::Config config; GrowStrategy growStrategy; TuneFileSummary tuning; if (readType == "directio") { tuning._randRead.setWantDirectIO(); } else if (readType == "normal") { tuning._randRead.setWantNormal(); } else if (readType == "mmap") { tuning._randRead.setWantMemoryMap(); } search::index::DummyFileHeaderContext fileHeaderContext; vespalib::ThreadStackExecutor executor(1, 128*1024); transactionlog::NoSyncProxy noTlSyncer; LogDataStore store(executor, dir, config, growStrategy, tuning, fileHeaderContext, noTlSyncer, NULL, true); vespalib::ThreadStackExecutor bmPool(numThreads, 128*1024); LOG(info, "Start read benchmark with %lu threads doing %lu reads in chunks of %lu reads. Totally %lu objects", numThreads, numReads, perChunk, numThreads * numReads * perChunk); for (size_t i(0); i < numThreads; i++) { bmPool.execute(vespalib::makeTask(vespalib::makeClosure(this, &BenchmarkDataStoreApp::read, numReads, perChunk, static_cast<const IDataStore *>(&store)))); } bmPool.sync(); LOG(info, "Benchmark done."); return retval; } FASTOS_MAIN(BenchmarkDataStoreApp); <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlock(reservekey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks..."); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } pblocktemplate = CreateNewBlock(reservekey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; CCoinsViewCache &view = *pcoinsTip; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int64_t nSigOps = tx.GetLegacySigOpCount(); if (tx.HaveInputs(view)) { entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(view) - tx.GetValueOut()))); nSigOps += tx.GetP2SHSigOpCount(view); } entry.push_back(Pair("sigops", nSigOps)); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } bool fAccepted = ProcessBlock(NULL, &pblock); if (!fAccepted) return "rejected"; return Value::null; } <commit_msg>use fee/sigop data in BlockTemplate struct instead of (not always correctly) calculating it ourselves<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlock(reservekey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Bitcoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Bitcoin is downloading blocks..."); static CReserveKey reservekey(pwalletMain); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } pblocktemplate = CreateNewBlock(reservekey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); entry.push_back(Pair("fee", pblocktemplate->vTxFees[&tx - pblock->vtx.data()])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[&tx - pblock->vtx.data()])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } bool fAccepted = ProcessBlock(NULL, &pblock); if (!fAccepted) return "rejected"; return Value::null; } <|endoftext|>
<commit_before>/* * MotorConfigurations.cpp * * Created on: 18.02.2015 * Author: lutz */ #include "MotorConfigurations.h" #include <iostream> #include <fstream> #include <assert.h> #include "json/json.h" MotorConfigurationsManager::MotorConfigurationsManager(std::string filename) : m_filename(filename) { std::stringstream strStream; strStream << std::ifstream(filename).rdbuf(); std::string str = strStream.str(); Json::Value rootNode; Json::Reader jsonReader; jsonReader.parse(str, rootNode); Json::Value motorsArray = rootNode["motors"]; if (not motorsArray.isArray()) { motorsArray = Json::Value(Json::arrayValue); } for (uint32_t i(0); i < motorsArray.size(); ++i) { Json::Value &motorNode = motorsArray[i]; MotorConfiguration config; dynamixel::motorID id; if (not motorNode["id"].empty() && motorNode["id"].isUInt()) { id = motorNode["id"].asUInt(); assert(id < 254 && "no valid motor id set in file"); } else { assert(false && "no motor id set in file"); } if (not motorNode["baudrate"].empty() && motorNode["baudrate"].isUInt()) { config.baudrate = motorNode["baudrate"].asUInt(); } if (not motorNode["offset"].empty() && motorNode["offset"].isInt()) { config.offset = motorNode["offset"].asInt(); } if (not motorNode["name"].empty() && motorNode["name"].isString()) { config.name = motorNode["name"].asString(); } if (not motorNode["bus"].empty() && motorNode["bus"].isString()) { config.bus = motorNode["bus"].asString(); } motorConfigs[id] = config; } } MotorConfiguration& MotorConfigurationsManager::operator[](dynamixel::motorID id) { assert(id < 254 && "request for invalid motorID"); return motorConfigs[id]; } MotorConfiguration const& MotorConfigurationsManager::operator[](dynamixel::motorID id) const { assert(id < 254 && "request for invalid motorID"); return motorConfigs.at(id); } MotorConfigurationsManager::~MotorConfigurationsManager() { } void MotorConfigurationsManager::save() { Json::Value rootNode; Json::StyledWriter jsonWriter; Json::Value motorArray(Json::arrayValue); for (auto const& config : motorConfigs) { Json::Value motor; motor["id"] = config.first; motor["baudrate"] = config.second.baudrate; motor["offset"] = config.second.offset; motor["name"] = config.second.name; motor["bus"] = config.second.bus; motorArray.append(motor); } rootNode["motors"] = motorArray; std::string jsonString = jsonWriter.write(rootNode); std::ofstream oFile(m_filename); oFile << jsonString; oFile.close(); } <commit_msg>default to dynamixel bus<commit_after>/* * MotorConfigurations.cpp * * Created on: 18.02.2015 * Author: lutz */ #include "MotorConfigurations.h" #include <iostream> #include <fstream> #include <assert.h> #include <json/json.h> MotorConfigurationsManager::MotorConfigurationsManager(std::string filename) : m_filename(filename) { std::stringstream strStream; strStream << std::ifstream(filename).rdbuf(); std::string str = strStream.str(); Json::Value rootNode; Json::Reader jsonReader; jsonReader.parse(str, rootNode); Json::Value motorsArray = rootNode["motors"]; if (not motorsArray.isArray()) { motorsArray = Json::Value(Json::arrayValue); } for (uint32_t i(0); i < motorsArray.size(); ++i) { Json::Value &motorNode = motorsArray[i]; MotorConfiguration config; dynamixel::motorID id; if (not motorNode["id"].empty() && motorNode["id"].isUInt()) { id = motorNode["id"].asUInt(); assert(id < 254 && "no valid motor id set in file"); } else { assert(false && "no motor id set in file"); } if (not motorNode["baudrate"].empty() && motorNode["baudrate"].isUInt()) { config.baudrate = motorNode["baudrate"].asUInt(); } if (not motorNode["offset"].empty() && motorNode["offset"].isInt()) { config.offset = motorNode["offset"].asInt(); } if (not motorNode["name"].empty() && motorNode["name"].isString()) { config.name = motorNode["name"].asString(); } if (not motorNode["bus"].empty() && motorNode["bus"].isString()) { config.bus = motorNode["bus"].asString(); } if (config.bus == "") { config.bus = "dynamixel"; // default to dynamixel here } motorConfigs[id] = config; } } MotorConfiguration& MotorConfigurationsManager::operator[](dynamixel::motorID id) { assert(id < 254 && "request for invalid motorID"); return motorConfigs[id]; } MotorConfiguration const& MotorConfigurationsManager::operator[](dynamixel::motorID id) const { assert(id < 254 && "request for invalid motorID"); return motorConfigs.at(id); } MotorConfigurationsManager::~MotorConfigurationsManager() { } void MotorConfigurationsManager::save() { Json::Value rootNode; Json::StyledWriter jsonWriter; Json::Value motorArray(Json::arrayValue); for (auto const& config : motorConfigs) { Json::Value motor; motor["id"] = config.first; motor["baudrate"] = config.second.baudrate; motor["offset"] = config.second.offset; motor["name"] = config.second.name; motor["bus"] = config.second.bus; motorArray.append(motor); } rootNode["motors"] = motorArray; std::string jsonString = jsonWriter.write(rootNode); std::ofstream oFile(m_filename); oFile << jsonString; oFile.close(); } <|endoftext|>
<commit_before>#include <nan.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <v8.h> #include <algorithm> extern "C" { #include "rpi_ws281x/ws2811.h" } using namespace v8; #define DEFAULT_TARGET_FREQ 800000 #define DEFAULT_GPIO_PIN 18 #define DEFAULT_DMANUM 10 #define PARAM_FREQ 1 #define PARAM_DMANUM 2 #define PARAM_GPIONUM 3 #define PARAM_COUNT 4 #define PARAM_INVERT 5 #define PARAM_BRIGHTNESS 6 #define PARAM_STRIP_TYPE 7 ws2811_t ws281x; /** * ws281x.setParam(param:Number, value:Number) * wrap setting global params in ws2811_t */ void setParam(const Nan::FunctionCallbackInfo<v8::Value> &info) { if (info.Length() != 2) { Nan::ThrowTypeError("setParam(): expected two params"); return; } if (!info[0]->IsNumber()) { Nan::ThrowTypeError( "setParam(): expected argument 1 to be the parameter-id"); return; } if (!info[1]->IsNumber()) { Nan::ThrowTypeError("setParam(): expected argument 2 to be the value"); return; } const int param = Nan::To<int32_t>(info[0]).FromJust(); const int value = Nan::To<int32_t>(info[1]).FromJust(); switch (param) { case PARAM_FREQ: ws281x.freq = value; break; case PARAM_DMANUM: ws281x.dmanum = value; break; default: Nan::ThrowTypeError("setParam(): invalid parameter-id"); return; } } /** * ws281x.setChannelParam(channel:Number, param:Number, value:Number) * * wrap setting params in ws2811_channel_t */ void setChannelParam(const Nan::FunctionCallbackInfo<v8::Value> &info) { if (info.Length() != 3) { Nan::ThrowTypeError("setChannelParam(): missing argument"); return; } // retrieve channelNumber from argument 1 if (!info[0]->IsNumber()) { Nan::ThrowTypeError( "setChannelParam(): expected argument 1 to be the channel-number"); return; } const int channelNumber = Nan::To<int32_t>(info[0]).FromJust(); if (channelNumber > 1 || channelNumber < 0) { Nan::ThrowError("setChannelParam(): invalid chanel-number"); return; } if (!info[1]->IsNumber()) { Nan::ThrowTypeError( "setChannelParam(): expected argument 2 to be the parameter-id"); return; } if (!info[2]->IsNumber() && !info[2]->IsBoolean()) { Nan::ThrowTypeError( "setChannelParam(): expected argument 3 to be the value"); return; } ws2811_channel_t *channel = &ws281x.channel[channelNumber]; const int param = Nan::To<int32_t>(info[1]).FromJust(); const int value = Nan::To<int32_t>(info[2]).FromJust(); switch (param) { case PARAM_GPIONUM: channel->gpionum = value; break; case PARAM_COUNT: channel->count = value; break; case PARAM_INVERT: channel->invert = value; break; case PARAM_BRIGHTNESS: channel->brightness = (uint8_t)value; break; case PARAM_STRIP_TYPE: channel->strip_type = value; break; default: Nan::ThrowTypeError("setChannelParam(): invalid parameter-id"); return; } } /** * ws281x.setChannelData(channel:Number, buffer:Buffer) * * wrap copying data to ws2811_channel_t.leds */ void setChannelData(const Nan::FunctionCallbackInfo<v8::Value> &info) { if (info.Length() != 2) { Nan::ThrowTypeError("setChannelData(): missing argument."); return; } // retrieve channelNumber from argument 1 if (!info[0]->IsNumber()) { Nan::ThrowTypeError( "setChannelData(): expected argument 1 to be the channel-number."); return; } int channelNumber = Nan::To<int32_t>(info[0]).FromJust(); if (channelNumber > 1 || channelNumber < 0) { Nan::ThrowError("setChannelData(): invalid chanel-number"); return; } ws2811_channel_t channel = ws281x.channel[channelNumber]; // retrieve buffer from argument 2 if (!node::Buffer::HasInstance(info[1])) { Nan::ThrowTypeError("setChannelData(): expected argument 2 to be a Buffer"); return; } v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext(); auto buffer = info[1]->ToObject(context).ToLocalChecked(); uint32_t *data = (uint32_t *)node::Buffer::Data(buffer); if (channel.count == 0 || channel.leds == NULL) { Nan::ThrowError("setChannelData(): channel not ready"); return; } const int numBytes = std::min(node::Buffer::Length(buffer), sizeof(ws2811_led_t) * ws281x.channel[0].count); // FIXME: handle memcpy-result memcpy(channel.leds, data, numBytes); } /** * ws281x.init() * * wrap ws2811_init() */ void init(const Nan::FunctionCallbackInfo<v8::Value> &info) { ws2811_return_t ret; ret = ws2811_init(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } } /** * ws281x.render() * * wrap ws2811_wait() and ws2811_render() */ void render(const Nan::FunctionCallbackInfo<v8::Value> &info) { ws2811_return_t ret; ret = ws2811_wait(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } ret = ws2811_render(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } } /** * ws281x.finalize() * * wrap ws2811_wait() and ws2811_fini() */ void finalize(const Nan::FunctionCallbackInfo<v8::Value> &info) { ws2811_return_t ret; ret = ws2811_wait(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } ws2811_fini(&ws281x); } /** * initializes the module. */ void initialize(Local<Object> exports) { ws281x.freq = DEFAULT_TARGET_FREQ; ws281x.dmanum = DEFAULT_DMANUM; NAN_EXPORT(exports, setParam); NAN_EXPORT(exports, setChannelParam); NAN_EXPORT(exports, setChannelData); NAN_EXPORT(exports, init); NAN_EXPORT(exports, render); NAN_EXPORT(exports, finalize); } NODE_MODULE(rpi_ws281x, initialize) // vi: ts=2 sw=2 expandtab<commit_msg>fix: use correct channel-count when copying<commit_after>#include <nan.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <v8.h> #include <algorithm> extern "C" { #include "rpi_ws281x/ws2811.h" } using namespace v8; #define DEFAULT_TARGET_FREQ 800000 #define DEFAULT_GPIO_PIN 18 #define DEFAULT_DMANUM 10 #define PARAM_FREQ 1 #define PARAM_DMANUM 2 #define PARAM_GPIONUM 3 #define PARAM_COUNT 4 #define PARAM_INVERT 5 #define PARAM_BRIGHTNESS 6 #define PARAM_STRIP_TYPE 7 ws2811_t ws281x; /** * ws281x.setParam(param:Number, value:Number) * wrap setting global params in ws2811_t */ void setParam(const Nan::FunctionCallbackInfo<v8::Value> &info) { if (info.Length() != 2) { Nan::ThrowTypeError("setParam(): expected two params"); return; } if (!info[0]->IsNumber()) { Nan::ThrowTypeError( "setParam(): expected argument 1 to be the parameter-id"); return; } if (!info[1]->IsNumber()) { Nan::ThrowTypeError("setParam(): expected argument 2 to be the value"); return; } const int param = Nan::To<int32_t>(info[0]).FromJust(); const int value = Nan::To<int32_t>(info[1]).FromJust(); switch (param) { case PARAM_FREQ: ws281x.freq = value; break; case PARAM_DMANUM: ws281x.dmanum = value; break; default: Nan::ThrowTypeError("setParam(): invalid parameter-id"); return; } } /** * ws281x.setChannelParam(channel:Number, param:Number, value:Number) * * wrap setting params in ws2811_channel_t */ void setChannelParam(const Nan::FunctionCallbackInfo<v8::Value> &info) { if (info.Length() != 3) { Nan::ThrowTypeError("setChannelParam(): missing argument"); return; } // retrieve channelNumber from argument 1 if (!info[0]->IsNumber()) { Nan::ThrowTypeError( "setChannelParam(): expected argument 1 to be the channel-number"); return; } const int channelNumber = Nan::To<int32_t>(info[0]).FromJust(); if (channelNumber > 1 || channelNumber < 0) { Nan::ThrowError("setChannelParam(): invalid chanel-number"); return; } if (!info[1]->IsNumber()) { Nan::ThrowTypeError( "setChannelParam(): expected argument 2 to be the parameter-id"); return; } if (!info[2]->IsNumber() && !info[2]->IsBoolean()) { Nan::ThrowTypeError( "setChannelParam(): expected argument 3 to be the value"); return; } ws2811_channel_t *channel = &ws281x.channel[channelNumber]; const int param = Nan::To<int32_t>(info[1]).FromJust(); const int value = Nan::To<int32_t>(info[2]).FromJust(); switch (param) { case PARAM_GPIONUM: channel->gpionum = value; break; case PARAM_COUNT: channel->count = value; break; case PARAM_INVERT: channel->invert = value; break; case PARAM_BRIGHTNESS: channel->brightness = (uint8_t)value; break; case PARAM_STRIP_TYPE: channel->strip_type = value; break; default: Nan::ThrowTypeError("setChannelParam(): invalid parameter-id"); return; } } /** * ws281x.setChannelData(channel:Number, buffer:Buffer) * * wrap copying data to ws2811_channel_t.leds */ void setChannelData(const Nan::FunctionCallbackInfo<v8::Value> &info) { if (info.Length() != 2) { Nan::ThrowTypeError("setChannelData(): missing argument."); return; } // retrieve channelNumber from argument 1 if (!info[0]->IsNumber()) { Nan::ThrowTypeError( "setChannelData(): expected argument 1 to be the channel-number."); return; } int channelNumber = Nan::To<int32_t>(info[0]).FromJust(); if (channelNumber > 1 || channelNumber < 0) { Nan::ThrowError("setChannelData(): invalid chanel-number"); return; } ws2811_channel_t channel = ws281x.channel[channelNumber]; // retrieve buffer from argument 2 if (!node::Buffer::HasInstance(info[1])) { Nan::ThrowTypeError("setChannelData(): expected argument 2 to be a Buffer"); return; } v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext(); auto buffer = info[1]->ToObject(context).ToLocalChecked(); uint32_t *data = (uint32_t *)node::Buffer::Data(buffer); if (channel.count == 0 || channel.leds == NULL) { Nan::ThrowError("setChannelData(): channel not ready"); return; } const int numBytes = std::min(node::Buffer::Length(buffer), sizeof(ws2811_led_t) * channel.count); // FIXME: handle memcpy-result memcpy(channel.leds, data, numBytes); } /** * ws281x.init() * * wrap ws2811_init() */ void init(const Nan::FunctionCallbackInfo<v8::Value> &info) { ws2811_return_t ret; ret = ws2811_init(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } } /** * ws281x.render() * * wrap ws2811_wait() and ws2811_render() */ void render(const Nan::FunctionCallbackInfo<v8::Value> &info) { ws2811_return_t ret; ret = ws2811_wait(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } ret = ws2811_render(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } } /** * ws281x.finalize() * * wrap ws2811_wait() and ws2811_fini() */ void finalize(const Nan::FunctionCallbackInfo<v8::Value> &info) { ws2811_return_t ret; ret = ws2811_wait(&ws281x); if (ret != WS2811_SUCCESS) { Nan::ThrowError(ws2811_get_return_t_str(ret)); return; } ws2811_fini(&ws281x); } /** * initializes the module. */ void initialize(Local<Object> exports) { ws281x.freq = DEFAULT_TARGET_FREQ; ws281x.dmanum = DEFAULT_DMANUM; NAN_EXPORT(exports, setParam); NAN_EXPORT(exports, setChannelParam); NAN_EXPORT(exports, setChannelData); NAN_EXPORT(exports, init); NAN_EXPORT(exports, render); NAN_EXPORT(exports, finalize); } NODE_MODULE(rpi_ws281x, initialize) // vi: ts=2 sw=2 expandtab<|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ * $Log$ * Revision 1.5 2001/10/09 21:00:54 peiyongz * . init() take 1 arg, * . make inspectFacetBase() virtual to allow ListDTV provide its own method, * . reorganize init() into assignFacet(), inspectFacet(), inspectFacetBase() and * inheritFacet() to improve mantainability. * . macro to simplify code * . save get***() to temp vars * * Revision 1.4 2001/09/27 13:51:25 peiyongz * DTV Reorganization: ctor/init created to be used by derived class * * Revision 1.3 2001/09/24 15:30:16 peiyongz * DTV Reorganization: init() to be invoked from derived class' ctor to allow * correct resolution of virtual methods like assignAdditionalFacet(), * inheritAdditionalFacet(), etc. * * Revision 1.2 2001/09/19 18:48:27 peiyongz * DTV reorganization:getLength() added, move inline to class declaration to avoid inline * function interdependency. * * Revision 1.1 2001/09/18 14:45:04 peiyongz * DTV reorganization * */ #if !defined(ABSTRACT_STRING_VALIDATOR_HPP) #define ABSTRACT_STRING_VALIDATOR_HPP #include <validators/datatype/DatatypeValidator.hpp> class VALIDATORS_EXPORT AbstractStringValidator : public DatatypeValidator { public: // ----------------------------------------------------------------------- // Public ctor/dtor // ----------------------------------------------------------------------- /** @name Constructor. */ //@{ virtual ~AbstractStringValidator(); //@} // ----------------------------------------------------------------------- // Validation methods // ----------------------------------------------------------------------- /** @name Validation Function */ //@{ /** * validate that a string matches the boolean datatype * @param content A string containing the content to be validated * * @exception throws InvalidDatatypeException if the content is * is not valid. */ virtual void validate(const XMLCh* const content); //@} // ----------------------------------------------------------------------- // Compare methods // ----------------------------------------------------------------------- /** @name Compare Function */ //@{ virtual int compare(const XMLCh* const, const XMLCh* const); //@} protected: AbstractStringValidator(DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , const int finalSet , const ValidatorType type); void init(RefVectorOf<XMLCh>* const enums); // // Abstract interface // virtual void assignAdditionalFacet(const XMLCh* const key , const XMLCh* const value) = 0; virtual void inheritAdditionalFacet() = 0; virtual void checkAdditionalFacetConstraints() const = 0; virtual void checkAdditionalFacet(const XMLCh* const content) const = 0; virtual void checkValueSpace(const XMLCh* const content) = 0; virtual int getLength(const XMLCh* const content) const = 0; // // to Allow ListDTV to overwrite // virtual void inspectFacetBase(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- inline unsigned int getLength() const; inline unsigned int getMaxLength() const; inline unsigned int getMinLength() const; inline RefVectorOf<XMLCh>* getEnumeration() const; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- inline void setLength(unsigned int); inline void setMaxLength(unsigned int); inline void setMinLength(unsigned int); inline void setEnumeration(RefVectorOf<XMLCh>*, bool); private: void checkContent(const XMLCh* const content, bool asBase); void assignFacet(); void inspectFacet(); void inheritFacet(); // ----------------------------------------------------------------------- // Private data members // // ----------------------------------------------------------------------- unsigned int fLength; unsigned int fMaxLength; unsigned int fMinLength; bool fEnumerationInherited; RefVectorOf<XMLCh>* fEnumeration; }; // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- unsigned int AbstractStringValidator::getLength() const { return fLength; } unsigned int AbstractStringValidator::getMaxLength() const { return fMaxLength; } unsigned int AbstractStringValidator::getMinLength() const { return fMinLength; } RefVectorOf<XMLCh>* AbstractStringValidator:: getEnumeration() const { return fEnumeration; } // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- void AbstractStringValidator::setLength(unsigned int newLength) { fLength = newLength; } void AbstractStringValidator::setMaxLength(unsigned int newMaxLength) { fMaxLength = newMaxLength; } void AbstractStringValidator::setMinLength(unsigned int newMinLength) { fMinLength = newMinLength; } void AbstractStringValidator::setEnumeration(RefVectorOf<XMLCh>* enums , bool inherited) { if (enums) { if (fEnumeration && !fEnumerationInherited) delete fEnumeration; fEnumeration = enums; fEnumerationInherited = inherited; setFacetsDefined(DatatypeValidator::FACET_ENUMERATION); } } /** * End of file AbstractStringValidator.hpp */ #endif <commit_msg>Allow derived to overwrite inheritFacet()<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ * $Log$ * Revision 1.6 2001/10/11 19:32:12 peiyongz * Allow derived to overwrite inheritFacet() * * Revision 1.5 2001/10/09 21:00:54 peiyongz * . init() take 1 arg, * . make inspectFacetBase() virtual to allow ListDTV provide its own method, * . reorganize init() into assignFacet(), inspectFacet(), inspectFacetBase() and * inheritFacet() to improve mantainability. * . macro to simplify code * . save get***() to temp vars * * Revision 1.4 2001/09/27 13:51:25 peiyongz * DTV Reorganization: ctor/init created to be used by derived class * * Revision 1.3 2001/09/24 15:30:16 peiyongz * DTV Reorganization: init() to be invoked from derived class' ctor to allow * correct resolution of virtual methods like assignAdditionalFacet(), * inheritAdditionalFacet(), etc. * * Revision 1.2 2001/09/19 18:48:27 peiyongz * DTV reorganization:getLength() added, move inline to class declaration to avoid inline * function interdependency. * * Revision 1.1 2001/09/18 14:45:04 peiyongz * DTV reorganization * */ #if !defined(ABSTRACT_STRING_VALIDATOR_HPP) #define ABSTRACT_STRING_VALIDATOR_HPP #include <validators/datatype/DatatypeValidator.hpp> class VALIDATORS_EXPORT AbstractStringValidator : public DatatypeValidator { public: // ----------------------------------------------------------------------- // Public ctor/dtor // ----------------------------------------------------------------------- /** @name Constructor. */ //@{ virtual ~AbstractStringValidator(); //@} // ----------------------------------------------------------------------- // Validation methods // ----------------------------------------------------------------------- /** @name Validation Function */ //@{ /** * validate that a string matches the boolean datatype * @param content A string containing the content to be validated * * @exception throws InvalidDatatypeException if the content is * is not valid. */ virtual void validate(const XMLCh* const content); //@} // ----------------------------------------------------------------------- // Compare methods // ----------------------------------------------------------------------- /** @name Compare Function */ //@{ virtual int compare(const XMLCh* const, const XMLCh* const); //@} protected: AbstractStringValidator(DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , const int finalSet , const ValidatorType type); void init(RefVectorOf<XMLCh>* const enums); // // Abstract interface // virtual void assignAdditionalFacet(const XMLCh* const key , const XMLCh* const value) = 0; virtual void inheritAdditionalFacet() = 0; virtual void checkAdditionalFacetConstraints() const = 0; virtual void checkAdditionalFacet(const XMLCh* const content) const = 0; virtual void checkValueSpace(const XMLCh* const content) = 0; virtual int getLength(const XMLCh* const content) const = 0; // // to Allow ListDTV to overwrite // virtual void inspectFacetBase(); virtual void inheritFacet(); // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- inline unsigned int getLength() const; inline unsigned int getMaxLength() const; inline unsigned int getMinLength() const; inline RefVectorOf<XMLCh>* getEnumeration() const; // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- inline void setLength(unsigned int); inline void setMaxLength(unsigned int); inline void setMinLength(unsigned int); inline void setEnumeration(RefVectorOf<XMLCh>*, bool); private: void checkContent(const XMLCh* const content, bool asBase); void assignFacet(); void inspectFacet(); // ----------------------------------------------------------------------- // Private data members // // ----------------------------------------------------------------------- unsigned int fLength; unsigned int fMaxLength; unsigned int fMinLength; bool fEnumerationInherited; RefVectorOf<XMLCh>* fEnumeration; }; // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- unsigned int AbstractStringValidator::getLength() const { return fLength; } unsigned int AbstractStringValidator::getMaxLength() const { return fMaxLength; } unsigned int AbstractStringValidator::getMinLength() const { return fMinLength; } RefVectorOf<XMLCh>* AbstractStringValidator:: getEnumeration() const { return fEnumeration; } // ----------------------------------------------------------------------- // Setter methods // ----------------------------------------------------------------------- void AbstractStringValidator::setLength(unsigned int newLength) { fLength = newLength; } void AbstractStringValidator::setMaxLength(unsigned int newMaxLength) { fMaxLength = newMaxLength; } void AbstractStringValidator::setMinLength(unsigned int newMinLength) { fMinLength = newMinLength; } void AbstractStringValidator::setEnumeration(RefVectorOf<XMLCh>* enums , bool inherited) { if (enums) { if (fEnumeration && !fEnumerationInherited) delete fEnumeration; fEnumeration = enums; fEnumerationInherited = inherited; setFacetsDefined(DatatypeValidator::FACET_ENUMERATION); } } /** * End of file AbstractStringValidator.hpp */ #endif <|endoftext|>
<commit_before>#include "run_async.h" #include "duktapevm.h" #include "callback.h" #include <node.h> #include <v8.h> #include <string> #include <memory> #include <vector> using namespace v8; using node::FatalException; namespace { struct WorkRequest { WorkRequest(std::string functionName, std::string parameters, std::string script, Persistent<Function> callback): functionName(std::move(functionName)) ,parameters(std::move(parameters)) ,script(std::move(script)) ,callback(callback) ,hasError(false) ,returnValue() { }; ~WorkRequest() { for(auto& func : apiCallbackFunctions) { func.Dispose(); func.Clear(); } callback.Dispose(); callback.Clear(); } duktape::DuktapeVM vm; std::vector< Persistent<Function> > apiCallbackFunctions; // in std::string functionName; std::string parameters; std::string script; // out Persistent<Function> callback; bool hasError; std::string returnValue; }; struct ScopedUvWorkRequest { ScopedUvWorkRequest(uv_work_t* work): m_work(work) ,m_workRequest(static_cast<WorkRequest*> (m_work->data)) { } ~ScopedUvWorkRequest() { delete m_workRequest; delete m_work; } WorkRequest* getWorkRequest() { return m_workRequest; } private: uv_work_t* m_work; WorkRequest* m_workRequest; }; void UvAsyncCloseCB(uv_handle_s* handle) { delete (uv_async_t*) handle; } struct APICallbackSignaling { APICallbackSignaling(Persistent<Function> callback, std::string parameter, uv_async_cb cbFunc): callback(callback) ,parameter(parameter) ,returnValue("") ,cbFunc(cbFunc) ,async(new uv_async_t) { uv_mutex_init(&mutex); uv_cond_init(&cv); uv_async_init(uv_default_loop(), async, cbFunc); } ~APICallbackSignaling() { uv_mutex_destroy(&mutex); uv_cond_destroy(&cv); uv_close((uv_handle_t*) async, &UvAsyncCloseCB); } Persistent<Function> callback; std::string parameter; std::string returnValue; uv_cond_t cv; uv_mutex_t mutex; uv_async_cb cbFunc; // Has to be on heap, because of closing logic. uv_async_t* async; }; void callV8FunctionOnMainThread(uv_async_t* handle, int status) { auto signalData = static_cast<APICallbackSignaling*> (handle->data); uv_mutex_lock(&signalData->mutex); HandleScope scope; Handle<Value> argv[1]; argv[0] = String::New(signalData->parameter.c_str()); auto retVal = signalData->callback->Call(Context::GetCurrent()->Global(), 1, argv); String::Utf8Value retString(retVal); signalData->returnValue = std::string(*retString); uv_cond_signal(&signalData->cv); uv_mutex_unlock(&signalData->mutex); } void onWork(uv_work_t* req) { // Do not use scoped-wrapper as req is still needed in onWorkDone. WorkRequest* work = static_cast<WorkRequest*> (req->data); auto ret = work->vm.run(work->functionName, work->parameters, work->script); work->hasError = ret.errorCode != 0; work->returnValue = ret.value; } void onWorkDone(uv_work_t* req, int status) { ScopedUvWorkRequest uvReq(req); WorkRequest* work = uvReq.getWorkRequest(); HandleScope scope; Handle<Value> argv[2]; argv[0] = Boolean::New(work->hasError); argv[1] = String::New(work->returnValue.c_str()); TryCatch try_catch; work->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } scope.Close(Undefined()); } } // unnamed namespace namespace duktape { Handle<Value> run(const Arguments& args) { HandleScope scope; if(args.Length() < 5) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } if (!args[0]->IsString() || !args[1]->IsString() || !args[2]->IsString() || !args[4]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } String::Utf8Value functionName(args[0]->ToString()); String::Utf8Value parameters(args[1]->ToString()); String::Utf8Value script(args[2]->ToString()); Local<Function> returnCallback = Local<Function>::Cast(args[4]); WorkRequest* workReq = new WorkRequest( std::string(*functionName), std::string(*parameters), std::string(*script), Persistent<Function>::New(returnCallback)); // API Handling if(args[3]->IsObject()) { auto object = Handle<Object>::Cast(args[3]); auto properties = object->GetPropertyNames(); auto len = properties->Length(); for(unsigned int i = 0; i < len; ++i) { Local<Value> key = properties->Get(i); Local<Value> value = object->Get(key); if(!key->IsString() || !value->IsFunction()) { ThrowException(Exception::Error(String::New("Error in API-definition"))); return scope.Close(Undefined()); } auto apiCallbackFunc = Local<Function>::Cast(value); auto persistentApiCallbackFunc = Persistent<Function>::New(apiCallbackFunc); auto duktapeToNodeBridge = duktape::Callback([persistentApiCallbackFunc] (const std::string& parameter) -> std::string { // We're on not on libuv/V8 main thread. Signal main to run // callback function and wait for an answer. std::unique_ptr<APICallbackSignaling> cbsignaling(new APICallbackSignaling( persistentApiCallbackFunc, parameter, callV8FunctionOnMainThread)); uv_mutex_lock(&cbsignaling->mutex); cbsignaling->async->data = (void*) cbsignaling.get(); uv_async_send(cbsignaling->async); uv_cond_wait(&cbsignaling->cv, &cbsignaling->mutex); std::string retStr(cbsignaling->returnValue); uv_mutex_unlock(&cbsignaling->mutex); return retStr; }); // Switch ownership of Persistent-Function to workReq workReq->apiCallbackFunctions.push_back(persistentApiCallbackFunc); String::Utf8Value keyStr(key); workReq->vm.registerCallback(std::string(*keyStr), duktapeToNodeBridge); } } uv_work_t* req = new uv_work_t(); req->data = workReq; uv_queue_work(uv_default_loop(), req, onWork, onWorkDone); return scope.Close(Undefined()); } } // namespace duktape <commit_msg>Switched uv_close callback to use lambda.<commit_after>#include "run_async.h" #include "duktapevm.h" #include "callback.h" #include <node.h> #include <v8.h> #include <string> #include <memory> #include <vector> using namespace v8; using node::FatalException; namespace { struct WorkRequest { WorkRequest(std::string functionName, std::string parameters, std::string script, Persistent<Function> callback): functionName(std::move(functionName)) ,parameters(std::move(parameters)) ,script(std::move(script)) ,callback(callback) ,hasError(false) ,returnValue() { }; ~WorkRequest() { for(auto& func : apiCallbackFunctions) { func.Dispose(); func.Clear(); } callback.Dispose(); callback.Clear(); } duktape::DuktapeVM vm; std::vector< Persistent<Function> > apiCallbackFunctions; // in std::string functionName; std::string parameters; std::string script; // out Persistent<Function> callback; bool hasError; std::string returnValue; }; struct ScopedUvWorkRequest { ScopedUvWorkRequest(uv_work_t* work): m_work(work) ,m_workRequest(static_cast<WorkRequest*> (m_work->data)) { } ~ScopedUvWorkRequest() { delete m_workRequest; delete m_work; } WorkRequest* getWorkRequest() { return m_workRequest; } private: uv_work_t* m_work; WorkRequest* m_workRequest; }; struct APICallbackSignaling { APICallbackSignaling(Persistent<Function> callback, std::string parameter, uv_async_cb cbFunc): callback(callback) ,parameter(parameter) ,returnValue("") ,cbFunc(cbFunc) ,async(new uv_async_t) { uv_mutex_init(&mutex); uv_cond_init(&cv); uv_async_init(uv_default_loop(), async, cbFunc); } ~APICallbackSignaling() { uv_mutex_destroy(&mutex); uv_cond_destroy(&cv); uv_close((uv_handle_t*) async, [] (uv_handle_s* handle) { // "handle" is "async"-parameter passed to uv_close delete (uv_async_t*) handle; }); } Persistent<Function> callback; std::string parameter; std::string returnValue; uv_cond_t cv; uv_mutex_t mutex; uv_async_cb cbFunc; // Has to be on heap, because of closing logic. uv_async_t* async; }; void callV8FunctionOnMainThread(uv_async_t* handle, int status) { auto signalData = static_cast<APICallbackSignaling*> (handle->data); uv_mutex_lock(&signalData->mutex); HandleScope scope; Handle<Value> argv[1]; argv[0] = String::New(signalData->parameter.c_str()); auto retVal = signalData->callback->Call(Context::GetCurrent()->Global(), 1, argv); String::Utf8Value retString(retVal); signalData->returnValue = std::string(*retString); uv_cond_signal(&signalData->cv); uv_mutex_unlock(&signalData->mutex); } void onWork(uv_work_t* req) { // Do not use scoped-wrapper as req is still needed in onWorkDone. WorkRequest* work = static_cast<WorkRequest*> (req->data); auto ret = work->vm.run(work->functionName, work->parameters, work->script); work->hasError = ret.errorCode != 0; work->returnValue = ret.value; } void onWorkDone(uv_work_t* req, int status) { ScopedUvWorkRequest uvReq(req); WorkRequest* work = uvReq.getWorkRequest(); HandleScope scope; Handle<Value> argv[2]; argv[0] = Boolean::New(work->hasError); argv[1] = String::New(work->returnValue.c_str()); TryCatch try_catch; work->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } scope.Close(Undefined()); } } // unnamed namespace namespace duktape { Handle<Value> run(const Arguments& args) { HandleScope scope; if(args.Length() < 5) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } if (!args[0]->IsString() || !args[1]->IsString() || !args[2]->IsString() || !args[4]->IsFunction()) { ThrowException(Exception::TypeError(String::New("Wrong arguments"))); return scope.Close(Undefined()); } String::Utf8Value functionName(args[0]->ToString()); String::Utf8Value parameters(args[1]->ToString()); String::Utf8Value script(args[2]->ToString()); Local<Function> returnCallback = Local<Function>::Cast(args[4]); WorkRequest* workReq = new WorkRequest( std::string(*functionName), std::string(*parameters), std::string(*script), Persistent<Function>::New(returnCallback)); // API Handling if(args[3]->IsObject()) { auto object = Handle<Object>::Cast(args[3]); auto properties = object->GetPropertyNames(); auto len = properties->Length(); for(unsigned int i = 0; i < len; ++i) { Local<Value> key = properties->Get(i); Local<Value> value = object->Get(key); if(!key->IsString() || !value->IsFunction()) { ThrowException(Exception::Error(String::New("Error in API-definition"))); return scope.Close(Undefined()); } auto apiCallbackFunc = Local<Function>::Cast(value); auto persistentApiCallbackFunc = Persistent<Function>::New(apiCallbackFunc); auto duktapeToNodeBridge = duktape::Callback([persistentApiCallbackFunc] (const std::string& parameter) -> std::string { // We're on not on libuv/V8 main thread. Signal main to run // callback function and wait for an answer. std::unique_ptr<APICallbackSignaling> cbsignaling(new APICallbackSignaling( persistentApiCallbackFunc, parameter, callV8FunctionOnMainThread)); uv_mutex_lock(&cbsignaling->mutex); cbsignaling->async->data = (void*) cbsignaling.get(); uv_async_send(cbsignaling->async); uv_cond_wait(&cbsignaling->cv, &cbsignaling->mutex); std::string retStr(cbsignaling->returnValue); uv_mutex_unlock(&cbsignaling->mutex); return retStr; }); // Switch ownership of Persistent-Function to workReq workReq->apiCallbackFunctions.push_back(persistentApiCallbackFunc); String::Utf8Value keyStr(key); workReq->vm.registerCallback(std::string(*keyStr), duktapeToNodeBridge); } } uv_work_t* req = new uv_work_t(); req->data = workReq; uv_queue_work(uv_default_loop(), req, onWork, onWorkDone); return scope.Close(Undefined()); } } // namespace duktape <|endoftext|>
<commit_before><commit_msg>On 'window.print()' javascript command, print only the frame that is represented by 'window'.<commit_after><|endoftext|>
<commit_before><commit_msg>Mark NPAPIVisiblePluginTester.VerifyNPObjectLifetime as FLAKY.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 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/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/public/common/content_switches.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Smooth scrolling confuses the scrollbar test. launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 #if defined(OS_WIN) // It often takes too long time (and fails otherwise) on Windows. #define MAYBE_URLLoader DISABLED_URLLoader #else #define MAYBE_URLLoader FAILS_URLLoader #endif TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Crypto) TEST_PPAPI_OUT_OF_PROCESS(Crypto) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) #if !defined(OS_WIN) // Times out on Windows XP: http://crbug.com/95557 TEST_PPAPI_OUT_OF_PROCESS(PostMessage) #endif TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } #if defined(ADDRESS_SANITIZER) || defined(OS_MACOSX) #define MAYBE_FileIO DISABLED_FileIO #else #define MAYBE_FileIO FAILS_FileIO #endif TEST_F(OutOfProcessPPAPITest, MAYBE_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/96767 #if !defined(OS_MACOSX) TEST_F(PPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } // New implementation only honors fullscreen requests within a context of // a user gesture. Since we do not yet have an infrastructure for testing // those under ppapi_tests, the tests below time out when run automtically. // To test the code, run them manually following the directions here: // www.chromium.org/developers/design-documents/pepper-plugin-implementation // and click on the plugin area (gray square) to force fullscreen mode and // get the test unstuck. TEST_F(PPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } #endif #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84294 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } <commit_msg>Disable OutOfProcessPPAPITest.FileIO everywhere.<commit_after>// Copyright (c) 2011 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/file_util.h" #include "base/path_service.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/public/common/content_switches.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "net/test/test_server.h" #include "webkit/plugins/plugin_switches.h" namespace { // Platform-specific filename relative to the chrome executable. #if defined(OS_WIN) const wchar_t library_name[] = L"ppapi_tests.dll"; #elif defined(OS_MACOSX) const char library_name[] = "ppapi_tests.plugin"; #elif defined(OS_POSIX) const char library_name[] = "libppapi_tests.so"; #endif } // namespace // In-process plugin test runner. See OutOfProcessPPAPITest below for the // out-of-process version. class PPAPITest : public UITest { public: PPAPITest() { // Append the switch to register the pepper plugin. // library name = <out dir>/<test_name>.<library_extension> // MIME type = application/x-ppapi-<test_name> FilePath plugin_dir; PathService::Get(base::DIR_EXE, &plugin_dir); FilePath plugin_lib = plugin_dir.Append(library_name); EXPECT_TRUE(file_util::PathExists(plugin_lib)); FilePath::StringType pepper_plugin = plugin_lib.value(); pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests")); launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins, pepper_plugin); // The test sends us the result via a cookie. launch_arguments_.AppendSwitch(switches::kEnableFileCookies); // Some stuff is hung off of the testing interface which is not enabled // by default. launch_arguments_.AppendSwitch(switches::kEnablePepperTesting); // Smooth scrolling confuses the scrollbar test. launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling); } void RunTest(const std::string& test_case) { FilePath test_path; PathService::Get(base::DIR_SOURCE_ROOT, &test_path); test_path = test_path.Append(FILE_PATH_LITERAL("ppapi")); test_path = test_path.Append(FILE_PATH_LITERAL("tests")); test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html")); // Sanity check the file name. EXPECT_TRUE(file_util::PathExists(test_path)); GURL::Replacements replacements; std::string query("testcase="); query += test_case; replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size())); GURL test_url = net::FilePathToFileURL(test_path); RunTestURL(test_url.ReplaceComponents(replacements)); } void RunTestViaHTTP(const std::string& test_case) { net::TestServer test_server( net::TestServer::TYPE_HTTP, FilePath(FILE_PATH_LITERAL("ppapi/tests"))); ASSERT_TRUE(test_server.Start()); RunTestURL( test_server.GetURL("files/test_case.html?testcase=" + test_case)); } private: void RunTestURL(const GURL& test_url) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(test_url)); // See comment above TestingInstance in ppapi/test/testing_instance.h. // Basically it sets a series of numbered cookies. The value of "..." means // it's still working and we should continue to wait, any other value // indicates completion (in this case it will start with "PASS" or "FAIL"). // This keeps us from timing out on cookie waits for long tests. int progress_number = 0; std::string progress; while (true) { std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d", progress_number); progress = WaitUntilCookieNonEmpty(tab.get(), test_url, cookie_name.c_str(), TestTimeouts::large_test_timeout_ms()); if (progress != "...") break; progress_number++; } if (progress_number == 0) { // Failing the first time probably means the plugin wasn't loaded. ASSERT_FALSE(progress.empty()) << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is " << "built, in the right place, and doesn't have any missing symbols."; } else { ASSERT_FALSE(progress.empty()) << "Test timed out."; } EXPECT_STREQ("PASS", progress.c_str()); } }; // Variant of PPAPITest that runs plugins out-of-process to test proxy // codepaths. class OutOfProcessPPAPITest : public PPAPITest { public: OutOfProcessPPAPITest() { // Run PPAPI out-of-process to exercise proxy implementations. launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess); } }; // Use these macros to run the tests for a specific interface. // Most interfaces should be tested with both macros. #define TEST_PPAPI_IN_PROCESS(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTest(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTest(#test_name); \ } // Similar macros that test over HTTP. #define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \ TEST_F(PPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } #define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \ TEST_F(OutOfProcessPPAPITest, test_name) { \ RunTestViaHTTP(#test_name); \ } // // Interface tests. // TEST_PPAPI_IN_PROCESS(Broker) TEST_PPAPI_OUT_OF_PROCESS(Broker) TEST_PPAPI_IN_PROCESS(Core) TEST_PPAPI_OUT_OF_PROCESS(Core) TEST_PPAPI_IN_PROCESS(CursorControl) TEST_PPAPI_OUT_OF_PROCESS(CursorControl) TEST_PPAPI_IN_PROCESS(Instance) // http://crbug.com/91729 TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance) TEST_PPAPI_IN_PROCESS(Graphics2D) TEST_PPAPI_OUT_OF_PROCESS(Graphics2D) TEST_PPAPI_IN_PROCESS(ImageData) TEST_PPAPI_OUT_OF_PROCESS(ImageData) TEST_PPAPI_IN_PROCESS(Buffer) TEST_PPAPI_OUT_OF_PROCESS(Buffer) TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader) // http://crbug.com/89961 #if defined(OS_WIN) // It often takes too long time (and fails otherwise) on Windows. #define MAYBE_URLLoader DISABLED_URLLoader #else #define MAYBE_URLLoader FAILS_URLLoader #endif TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) { RunTestViaHTTP("URLLoader"); } TEST_PPAPI_IN_PROCESS(PaintAggregator) TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator) TEST_PPAPI_IN_PROCESS(Scrollbar) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) { RunTest("Scrollbar"); } TEST_PPAPI_IN_PROCESS(URLUtil) TEST_PPAPI_OUT_OF_PROCESS(URLUtil) TEST_PPAPI_IN_PROCESS(CharSet) TEST_PPAPI_OUT_OF_PROCESS(CharSet) TEST_PPAPI_IN_PROCESS(Crypto) TEST_PPAPI_OUT_OF_PROCESS(Crypto) TEST_PPAPI_IN_PROCESS(Var) // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Var) { RunTest("Var"); } TEST_PPAPI_IN_PROCESS(VarDeprecated) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated) // Windows defines 'PostMessage', so we have to undef it. #ifdef PostMessage #undef PostMessage #endif TEST_PPAPI_IN_PROCESS(PostMessage) #if !defined(OS_WIN) // Times out on Windows XP: http://crbug.com/95557 TEST_PPAPI_OUT_OF_PROCESS(PostMessage) #endif TEST_PPAPI_IN_PROCESS(Memory) TEST_PPAPI_OUT_OF_PROCESS(Memory) TEST_PPAPI_IN_PROCESS(VideoDecoder) TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder) // http://crbug.com/90039 and http://crbug.com/83443 (Mac) TEST_F(PPAPITest, FAILS_FileIO) { RunTestViaHTTP("FileIO"); } // http://crbug.com/101154 TEST_F(OutOfProcessPPAPITest, DISABLED_FileIO) { RunTestViaHTTP("FileIO"); } TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef) // Disabled because it times out: http://crbug.com/89961 //TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef) TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem) TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem) // http://crbug.com/96767 #if !defined(OS_MACOSX) TEST_F(PPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) { RunTestViaHTTP("FlashFullscreen"); } // New implementation only honors fullscreen requests within a context of // a user gesture. Since we do not yet have an infrastructure for testing // those under ppapi_tests, the tests below time out when run automtically. // To test the code, run them manually following the directions here: // www.chromium.org/developers/design-documents/pepper-plugin-implementation // and click on the plugin area (gray square) to force fullscreen mode and // get the test unstuck. TEST_F(PPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) { RunTestViaHTTP("Fullscreen"); } #endif #if defined(OS_POSIX) #define MAYBE_DirectoryReader FLAKY_DirectoryReader #else #define MAYBE_DirectoryReader DirectoryReader #endif // Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008 TEST_F(PPAPITest, MAYBE_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) { RunTestViaHTTP("DirectoryReader"); } #if defined(ENABLE_P2P_APIS) // Flaky. http://crbug.com/84294 TEST_F(PPAPITest, FLAKY_Transport) { RunTest("Transport"); } // http://crbug.com/89961 TEST_F(OutOfProcessPPAPITest, FAILS_Transport) { RunTestViaHTTP("Transport"); } #endif // ENABLE_P2P_APIS TEST_PPAPI_IN_PROCESS(UMA) // There is no proxy. TEST_F(OutOfProcessPPAPITest, FAILS_UMA) { RunTest("UMA"); } <|endoftext|>
<commit_before><commit_msg>Re-enabling worker fast tests (doing a more surgical disabling of just a single test).<commit_after><|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #if !defined(SCHEMASYMBOLS_HPP) #define SCHEMASYMBOLS_HPP #include <xercesc/util/XercesDefs.hpp> /* * Collection of symbols used to parse a Schema Grammar */ class VALIDATORS_EXPORT SchemaSymbols { public : // ----------------------------------------------------------------------- // Constant data // ----------------------------------------------------------------------- static const XMLCh fgURI_XSI[]; static const XMLCh fgURI_SCHEMAFORSCHEMA[]; static const XMLCh fgXSI_SCHEMALOCACTION[]; static const XMLCh fgXSI_NONAMESPACESCHEMALOCACTION[]; static const XMLCh fgXSI_TYPE[]; static const XMLCh fgELT_ALL[]; static const XMLCh fgELT_ANNOTATION[]; static const XMLCh fgELT_ANY[]; static const XMLCh fgELT_WILDCARD[]; static const XMLCh fgELT_ANYATTRIBUTE[]; static const XMLCh fgELT_APPINFO[]; static const XMLCh fgELT_ATTRIBUTE[]; static const XMLCh fgELT_ATTRIBUTEGROUP[]; static const XMLCh fgELT_CHOICE[]; static const XMLCh fgELT_COMPLEXTYPE[]; static const XMLCh fgELT_CONTENT[]; static const XMLCh fgELT_DOCUMENTATION[]; static const XMLCh fgELT_DURATION[]; static const XMLCh fgELT_ELEMENT[]; static const XMLCh fgELT_ENCODING[]; static const XMLCh fgELT_ENUMERATION[]; static const XMLCh fgELT_FIELD[]; static const XMLCh fgELT_WHITESPACE[]; static const XMLCh fgELT_GROUP[]; static const XMLCh fgELT_IMPORT[]; static const XMLCh fgELT_INCLUDE[]; static const XMLCh fgELT_REDEFINE[]; static const XMLCh fgELT_KEY[]; static const XMLCh fgELT_KEYREF[]; static const XMLCh fgELT_LENGTH[]; static const XMLCh fgELT_MAXEXCLUSIVE[]; static const XMLCh fgELT_MAXINCLUSIVE[]; static const XMLCh fgELT_MAXLENGTH[]; static const XMLCh fgELT_MINEXCLUSIVE[]; static const XMLCh fgELT_MININCLUSIVE[]; static const XMLCh fgELT_MINLENGTH[]; static const XMLCh fgELT_NOTATION[]; static const XMLCh fgELT_PATTERN[]; static const XMLCh fgELT_PERIOD[]; static const XMLCh fgELT_TOTALDIGITS[]; static const XMLCh fgELT_FRACTIONDIGITS[]; static const XMLCh fgELT_SCHEMA[]; static const XMLCh fgELT_SELECTOR[]; static const XMLCh fgELT_SEQUENCE[]; static const XMLCh fgELT_SIMPLETYPE[]; static const XMLCh fgELT_UNION[]; static const XMLCh fgELT_LIST[]; static const XMLCh fgELT_UNIQUE[]; static const XMLCh fgELT_COMPLEXCONTENT[]; static const XMLCh fgELT_SIMPLECONTENT[]; static const XMLCh fgELT_RESTRICTION[]; static const XMLCh fgELT_EXTENSION[]; static const XMLCh fgATT_ABSTRACT[]; static const XMLCh fgATT_ATTRIBUTEFORMDEFAULT[]; static const XMLCh fgATT_BASE[]; static const XMLCh fgATT_ITEMTYPE[]; static const XMLCh fgATT_MEMBERTYPES[]; static const XMLCh fgATT_BLOCK[]; static const XMLCh fgATT_BLOCKDEFAULT[]; static const XMLCh fgATT_CONTENT[]; static const XMLCh fgATT_DEFAULT[]; static const XMLCh fgATT_DERIVEDBY[]; static const XMLCh fgATT_ELEMENTFORMDEFAULT[]; static const XMLCh fgATT_SUBSTITUTIONGROUP[]; static const XMLCh fgATT_FINAL[]; static const XMLCh fgATT_FINALDEFAULT[]; static const XMLCh fgATT_FIXED[]; static const XMLCh fgATT_FORM[]; static const XMLCh fgATT_ID[]; static const XMLCh fgATT_MAXOCCURS[]; static const XMLCh fgATT_MINOCCURS[]; static const XMLCh fgATT_NAME[]; static const XMLCh fgATT_NAMESPACE[]; static const XMLCh fgATT_NILL[]; static const XMLCh fgATT_NILLABLE[]; static const XMLCh fgATT_PROCESSCONTENTS[]; static const XMLCh fgATT_REF[]; static const XMLCh fgATT_REFER[]; static const XMLCh fgATT_SCHEMALOCATION[]; static const XMLCh fgATT_SOURCE[]; static const XMLCh fgATT_SYSTEM[]; static const XMLCh fgATT_PUBLIC[]; static const XMLCh fgATT_TARGETNAMESPACE[]; static const XMLCh fgATT_TYPE[]; static const XMLCh fgATT_USE[]; static const XMLCh fgATT_VALUE[]; static const XMLCh fgATT_MIXED[]; static const XMLCh fgATT_VERSION[]; static const XMLCh fgATT_XPATH[]; static const XMLCh fgATTVAL_TWOPOUNDANY[]; static const XMLCh fgATTVAL_TWOPOUNDLOCAL[]; static const XMLCh fgATTVAL_TWOPOUNDOTHER[]; static const XMLCh fgATTVAL_TWOPOUNDTRAGETNAMESPACE[]; static const XMLCh fgATTVAL_POUNDALL[]; static const XMLCh fgATTVAL_BASE64[]; static const XMLCh fgATTVAL_BOOLEAN[]; static const XMLCh fgATTVAL_DEFAULT[]; static const XMLCh fgATTVAL_ELEMENTONLY[]; static const XMLCh fgATTVAL_EMPTY[]; static const XMLCh fgATTVAL_EXTENSION[]; static const XMLCh fgATTVAL_FALSE[]; static const XMLCh fgATTVAL_FIXED[]; static const XMLCh fgATTVAL_HEX[]; static const XMLCh fgATTVAL_ID[]; static const XMLCh fgATTVAL_LAX[]; static const XMLCh fgATTVAL_MAXLENGTH[]; static const XMLCh fgATTVAL_MINLENGTH[]; static const XMLCh fgATTVAL_MIXED[]; static const XMLCh fgATTVAL_NCNAME[]; static const XMLCh fgATTVAL_OPTIONAL[]; static const XMLCh fgATTVAL_PROHIBITED[]; static const XMLCh fgATTVAL_QNAME[]; static const XMLCh fgATTVAL_QUALIFIED[]; static const XMLCh fgATTVAL_REQUIRED[]; static const XMLCh fgATTVAL_RESTRICTION[]; static const XMLCh fgATTVAL_SKIP[]; static const XMLCh fgATTVAL_STRICT[]; static const XMLCh fgATTVAL_STRING[]; static const XMLCh fgATTVAL_TEXTONLY[]; static const XMLCh fgATTVAL_TIMEDURATION[]; static const XMLCh fgATTVAL_TRUE[]; static const XMLCh fgATTVAL_UNQUALIFIED[]; static const XMLCh fgATTVAL_URI[]; static const XMLCh fgATTVAL_URIREFERENCE[]; static const XMLCh fgATTVAL_SUBSTITUTIONGROUP[]; static const XMLCh fgATTVAL_SUBSTITUTION[]; static const XMLCh fgATTVAL_ANYTYPE[]; static const XMLCh fgWS_PRESERVE[]; static const XMLCh fgWS_COLLAPSE[]; static const XMLCh fgWS_REPLACE[]; static const XMLCh fgDT_STRING[]; static const XMLCh fgDT_TOKEN[]; static const XMLCh fgDT_LANGUAGE[]; static const XMLCh fgDT_NAME[]; static const XMLCh fgDT_NCNAME[]; static const XMLCh fgDT_INTEGER[]; static const XMLCh fgDT_DECIMAL[]; static const XMLCh fgDT_BOOLEAN[]; static const XMLCh fgDT_NONPOSITIVEINTEGER[]; static const XMLCh fgDT_NEGATIVEINTEGER[]; static const XMLCh fgDT_LONG[]; static const XMLCh fgDT_INT[]; static const XMLCh fgDT_SHORT[]; static const XMLCh fgDT_BYTE[]; static const XMLCh fgDT_NONNEGATIVEINTEGER[]; static const XMLCh fgDT_ULONG[]; static const XMLCh fgDT_UINT[]; static const XMLCh fgDT_USHORT[]; static const XMLCh fgDT_UBYTE[]; static const XMLCh fgDT_POSITIVEINTEGER[]; //datetime static const XMLCh fgDT_DATETIME[]; static const XMLCh fgDT_DATE[]; static const XMLCh fgDT_TIME[]; static const XMLCh fgDT_DURATION[]; static const XMLCh fgDT_DAY[]; static const XMLCh fgDT_MONTH[]; static const XMLCh fgDT_MONTHDAY[]; static const XMLCh fgDT_YEAR[]; static const XMLCh fgDT_YEARMONTH[]; static const XMLCh fgDT_BASE64BINARY[]; static const XMLCh fgDT_HEXBINARY[]; static const XMLCh fgDT_FLOAT[]; static const XMLCh fgDT_DOUBLE[]; static const XMLCh fgDT_URIREFERENCE[]; static const XMLCh fgDT_ANYURI[]; static const XMLCh fgDT_QNAME[]; static const XMLCh fgDT_NORMALIZEDSTRING[]; static const XMLCh fgDT_ANYSIMPLETYPE[]; static const XMLCh fgRegEx_XOption[]; static const XMLCh fgRedefIdentifier[]; static const int fgINT_MIN_VALUE; static const int fgINT_MAX_VALUE; enum { EMPTY_SET = 0, SUBSTITUTION = 1, EXTENSION = 2, RESTRICTION = 4, LIST = 8, UNION = 16, ENUMERATION = 32 }; // group orders enum { CHOICE = 0, SEQUENCE= 1, ALL = 2 }; enum { INFINITY = -2, UNBOUNDED = -1, NILLABLE = 1, ABSTRACT = 2, FIXED = 4 }; }; #endif /** * End of file SchemaSymbols.hpp */ <commit_msg>Fix bor bug 8301: INFINITY used as enum member.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #if !defined(SCHEMASYMBOLS_HPP) #define SCHEMASYMBOLS_HPP #include <xercesc/util/XercesDefs.hpp> /* * Collection of symbols used to parse a Schema Grammar */ class VALIDATORS_EXPORT SchemaSymbols { public : // ----------------------------------------------------------------------- // Constant data // ----------------------------------------------------------------------- static const XMLCh fgURI_XSI[]; static const XMLCh fgURI_SCHEMAFORSCHEMA[]; static const XMLCh fgXSI_SCHEMALOCACTION[]; static const XMLCh fgXSI_NONAMESPACESCHEMALOCACTION[]; static const XMLCh fgXSI_TYPE[]; static const XMLCh fgELT_ALL[]; static const XMLCh fgELT_ANNOTATION[]; static const XMLCh fgELT_ANY[]; static const XMLCh fgELT_WILDCARD[]; static const XMLCh fgELT_ANYATTRIBUTE[]; static const XMLCh fgELT_APPINFO[]; static const XMLCh fgELT_ATTRIBUTE[]; static const XMLCh fgELT_ATTRIBUTEGROUP[]; static const XMLCh fgELT_CHOICE[]; static const XMLCh fgELT_COMPLEXTYPE[]; static const XMLCh fgELT_CONTENT[]; static const XMLCh fgELT_DOCUMENTATION[]; static const XMLCh fgELT_DURATION[]; static const XMLCh fgELT_ELEMENT[]; static const XMLCh fgELT_ENCODING[]; static const XMLCh fgELT_ENUMERATION[]; static const XMLCh fgELT_FIELD[]; static const XMLCh fgELT_WHITESPACE[]; static const XMLCh fgELT_GROUP[]; static const XMLCh fgELT_IMPORT[]; static const XMLCh fgELT_INCLUDE[]; static const XMLCh fgELT_REDEFINE[]; static const XMLCh fgELT_KEY[]; static const XMLCh fgELT_KEYREF[]; static const XMLCh fgELT_LENGTH[]; static const XMLCh fgELT_MAXEXCLUSIVE[]; static const XMLCh fgELT_MAXINCLUSIVE[]; static const XMLCh fgELT_MAXLENGTH[]; static const XMLCh fgELT_MINEXCLUSIVE[]; static const XMLCh fgELT_MININCLUSIVE[]; static const XMLCh fgELT_MINLENGTH[]; static const XMLCh fgELT_NOTATION[]; static const XMLCh fgELT_PATTERN[]; static const XMLCh fgELT_PERIOD[]; static const XMLCh fgELT_TOTALDIGITS[]; static const XMLCh fgELT_FRACTIONDIGITS[]; static const XMLCh fgELT_SCHEMA[]; static const XMLCh fgELT_SELECTOR[]; static const XMLCh fgELT_SEQUENCE[]; static const XMLCh fgELT_SIMPLETYPE[]; static const XMLCh fgELT_UNION[]; static const XMLCh fgELT_LIST[]; static const XMLCh fgELT_UNIQUE[]; static const XMLCh fgELT_COMPLEXCONTENT[]; static const XMLCh fgELT_SIMPLECONTENT[]; static const XMLCh fgELT_RESTRICTION[]; static const XMLCh fgELT_EXTENSION[]; static const XMLCh fgATT_ABSTRACT[]; static const XMLCh fgATT_ATTRIBUTEFORMDEFAULT[]; static const XMLCh fgATT_BASE[]; static const XMLCh fgATT_ITEMTYPE[]; static const XMLCh fgATT_MEMBERTYPES[]; static const XMLCh fgATT_BLOCK[]; static const XMLCh fgATT_BLOCKDEFAULT[]; static const XMLCh fgATT_CONTENT[]; static const XMLCh fgATT_DEFAULT[]; static const XMLCh fgATT_DERIVEDBY[]; static const XMLCh fgATT_ELEMENTFORMDEFAULT[]; static const XMLCh fgATT_SUBSTITUTIONGROUP[]; static const XMLCh fgATT_FINAL[]; static const XMLCh fgATT_FINALDEFAULT[]; static const XMLCh fgATT_FIXED[]; static const XMLCh fgATT_FORM[]; static const XMLCh fgATT_ID[]; static const XMLCh fgATT_MAXOCCURS[]; static const XMLCh fgATT_MINOCCURS[]; static const XMLCh fgATT_NAME[]; static const XMLCh fgATT_NAMESPACE[]; static const XMLCh fgATT_NILL[]; static const XMLCh fgATT_NILLABLE[]; static const XMLCh fgATT_PROCESSCONTENTS[]; static const XMLCh fgATT_REF[]; static const XMLCh fgATT_REFER[]; static const XMLCh fgATT_SCHEMALOCATION[]; static const XMLCh fgATT_SOURCE[]; static const XMLCh fgATT_SYSTEM[]; static const XMLCh fgATT_PUBLIC[]; static const XMLCh fgATT_TARGETNAMESPACE[]; static const XMLCh fgATT_TYPE[]; static const XMLCh fgATT_USE[]; static const XMLCh fgATT_VALUE[]; static const XMLCh fgATT_MIXED[]; static const XMLCh fgATT_VERSION[]; static const XMLCh fgATT_XPATH[]; static const XMLCh fgATTVAL_TWOPOUNDANY[]; static const XMLCh fgATTVAL_TWOPOUNDLOCAL[]; static const XMLCh fgATTVAL_TWOPOUNDOTHER[]; static const XMLCh fgATTVAL_TWOPOUNDTRAGETNAMESPACE[]; static const XMLCh fgATTVAL_POUNDALL[]; static const XMLCh fgATTVAL_BASE64[]; static const XMLCh fgATTVAL_BOOLEAN[]; static const XMLCh fgATTVAL_DEFAULT[]; static const XMLCh fgATTVAL_ELEMENTONLY[]; static const XMLCh fgATTVAL_EMPTY[]; static const XMLCh fgATTVAL_EXTENSION[]; static const XMLCh fgATTVAL_FALSE[]; static const XMLCh fgATTVAL_FIXED[]; static const XMLCh fgATTVAL_HEX[]; static const XMLCh fgATTVAL_ID[]; static const XMLCh fgATTVAL_LAX[]; static const XMLCh fgATTVAL_MAXLENGTH[]; static const XMLCh fgATTVAL_MINLENGTH[]; static const XMLCh fgATTVAL_MIXED[]; static const XMLCh fgATTVAL_NCNAME[]; static const XMLCh fgATTVAL_OPTIONAL[]; static const XMLCh fgATTVAL_PROHIBITED[]; static const XMLCh fgATTVAL_QNAME[]; static const XMLCh fgATTVAL_QUALIFIED[]; static const XMLCh fgATTVAL_REQUIRED[]; static const XMLCh fgATTVAL_RESTRICTION[]; static const XMLCh fgATTVAL_SKIP[]; static const XMLCh fgATTVAL_STRICT[]; static const XMLCh fgATTVAL_STRING[]; static const XMLCh fgATTVAL_TEXTONLY[]; static const XMLCh fgATTVAL_TIMEDURATION[]; static const XMLCh fgATTVAL_TRUE[]; static const XMLCh fgATTVAL_UNQUALIFIED[]; static const XMLCh fgATTVAL_URI[]; static const XMLCh fgATTVAL_URIREFERENCE[]; static const XMLCh fgATTVAL_SUBSTITUTIONGROUP[]; static const XMLCh fgATTVAL_SUBSTITUTION[]; static const XMLCh fgATTVAL_ANYTYPE[]; static const XMLCh fgWS_PRESERVE[]; static const XMLCh fgWS_COLLAPSE[]; static const XMLCh fgWS_REPLACE[]; static const XMLCh fgDT_STRING[]; static const XMLCh fgDT_TOKEN[]; static const XMLCh fgDT_LANGUAGE[]; static const XMLCh fgDT_NAME[]; static const XMLCh fgDT_NCNAME[]; static const XMLCh fgDT_INTEGER[]; static const XMLCh fgDT_DECIMAL[]; static const XMLCh fgDT_BOOLEAN[]; static const XMLCh fgDT_NONPOSITIVEINTEGER[]; static const XMLCh fgDT_NEGATIVEINTEGER[]; static const XMLCh fgDT_LONG[]; static const XMLCh fgDT_INT[]; static const XMLCh fgDT_SHORT[]; static const XMLCh fgDT_BYTE[]; static const XMLCh fgDT_NONNEGATIVEINTEGER[]; static const XMLCh fgDT_ULONG[]; static const XMLCh fgDT_UINT[]; static const XMLCh fgDT_USHORT[]; static const XMLCh fgDT_UBYTE[]; static const XMLCh fgDT_POSITIVEINTEGER[]; //datetime static const XMLCh fgDT_DATETIME[]; static const XMLCh fgDT_DATE[]; static const XMLCh fgDT_TIME[]; static const XMLCh fgDT_DURATION[]; static const XMLCh fgDT_DAY[]; static const XMLCh fgDT_MONTH[]; static const XMLCh fgDT_MONTHDAY[]; static const XMLCh fgDT_YEAR[]; static const XMLCh fgDT_YEARMONTH[]; static const XMLCh fgDT_BASE64BINARY[]; static const XMLCh fgDT_HEXBINARY[]; static const XMLCh fgDT_FLOAT[]; static const XMLCh fgDT_DOUBLE[]; static const XMLCh fgDT_URIREFERENCE[]; static const XMLCh fgDT_ANYURI[]; static const XMLCh fgDT_QNAME[]; static const XMLCh fgDT_NORMALIZEDSTRING[]; static const XMLCh fgDT_ANYSIMPLETYPE[]; static const XMLCh fgRegEx_XOption[]; static const XMLCh fgRedefIdentifier[]; static const int fgINT_MIN_VALUE; static const int fgINT_MAX_VALUE; enum { EMPTY_SET = 0, SUBSTITUTION = 1, EXTENSION = 2, RESTRICTION = 4, LIST = 8, UNION = 16, ENUMERATION = 32 }; // group orders enum { CHOICE = 0, SEQUENCE= 1, ALL = 2 }; enum { UNBOUNDED = -1, NILLABLE = 1, ABSTRACT = 2, FIXED = 4 }; }; #endif /** * End of file SchemaSymbols.hpp */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: hfi_xrefpage.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-02-20 09: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): _______________________________________ * * ************************************************************************/ #include <precomp.h> #include "hfi_xrefpage.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_ce.hxx> #include <toolkit/hf_title.hxx> #include "hfi_navibar.hxx" #include "hfi_typetext.hxx" #include "hi_env.hxx" namespace { const String C_sTitleStart("uses of "); const String C_sCRLF("\n"); const String C_sDevMan("References in Developers Guide"); } // anonymous namespace HF_IdlXrefs::HF_IdlXrefs( Environment & io_rEnv, Xml::Element & o_rOut, const String & i_prefix, const client & i_ce ) : HtmlFactory_Idl(io_rEnv, &o_rOut), rContentDirectory(*new Html::Paragraph), pClient(&i_ce) { produce_Main(i_prefix, i_ce); } HF_IdlXrefs::~HF_IdlXrefs() { } void HF_IdlXrefs::Write_ManualLinks( const client & i_ce ) const { const StringVector & rLinks2Refs = i_ce.Secondaries().Links2RefsInManual(); if ( rLinks2Refs.size() == 0 ) { rContentDirectory << C_sDevMan << new Html::LineBreak << C_sCRLF; return; } rContentDirectory >> *new Html::Link("#devmanrefs") << C_sDevMan << new Html::LineBreak << C_sCRLF; HF_SubTitleTable aList(CurOut(), "devmanrefs", C_sDevMan, 1); Xml::Element & rOutCell = aList.Add_Row() >>* new Html::TableCell; csv_assert(rLinks2Refs.size() % 2 == 0); for ( StringVector::const_iterator it = rLinks2Refs.begin(); it != rLinks2Refs.end(); ++it ) { Xml::Element & rLink = rOutCell >> *new Html::Link( Env().Link2Manual(*it)); if ( (*(it+1)).empty() ) // HACK KORR_FUTURE // Research what happens with manual links which contain normal characters // in non-utf-8 texts. And research, why utfF-8 does not work here. rLink << new Xml::XmlCode(*it); else // HACK KORR_FUTURE, see above. rLink << new Xml::XmlCode( *(it+1) ); rOutCell << new Html::LineBreak << C_sCRLF; ++it; } // end for CurOut() << new Html::HorizontalLine(); } void HF_IdlXrefs::Produce_List( const char * i_title, const char * i_label, ce_list & i_iterator ) const { if (NOT i_iterator) { rContentDirectory << i_title << new Html::LineBreak << C_sCRLF; return; } csv_assert(*i_label == '#'); rContentDirectory >> *new Html::Link(i_label) << i_title << new Html::LineBreak << C_sCRLF; HF_SubTitleTable aList(CurOut(), i_label+1, i_title, 1); Xml::Element & rOutCell = aList.Add_Row() >>* new Html::TableCell; HF_IdlTypeText aTypeWriter(Env(), rOutCell, true, pClient); for ( ce_list & it = i_iterator; it; ++it ) { aTypeWriter.Produce_byData(*it); rOutCell << new Html::LineBreak; } // end for CurOut() << new Html::HorizontalLine(); } void HF_IdlXrefs::produce_Main( const String & i_prefix, const client & i_ce ) const { make_Navibar(i_ce); HF_TitleTable aTitle(CurOut()); aTitle.Produce_Title( StreamLock(200)() << C_sTitleStart << i_prefix << " " << i_ce.LocalName() << c_str ); aTitle.Add_Row() << &rContentDirectory; rContentDirectory >> *new Html::Link( StreamLock(200)() << i_ce.LocalName() << ".html" << c_str ) >> *new Html::Bold << "back to " << i_prefix << " " << i_ce.LocalName(); rContentDirectory << new Html::LineBreak << new Html::LineBreak << C_sCRLF; CurOut() << new Html::HorizontalLine(); } void HF_IdlXrefs::make_Navibar( const client & i_ce ) const { HF_IdlNavigationBar aNaviBar(Env(), CurOut()); aNaviBar.Produce_CeXrefsMainRow(i_ce); CurOut() << new Html::HorizontalLine(); } <commit_msg>INTEGRATION: CWS adc8 (1.4.4); FILE MERGED 2004/07/02 11:04:12 np 1.4.4.1: #i26261#<commit_after>/************************************************************************* * * $RCSfile: hfi_xrefpage.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-07-12 15:30:13 $ * * 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): _______________________________________ * * ************************************************************************/ #include <precomp.h> #include "hfi_xrefpage.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_ce.hxx> #include <ary/idl/i_gate.hxx> #include <ary/idl/ip_ce.hxx> #include <toolkit/hf_title.hxx> #include "hfi_navibar.hxx" #include "hfi_typetext.hxx" #include "hi_env.hxx" namespace { const String C_sTitleStart("uses of "); const String C_sCRLF("\n"); const String C_sDevMan("References in Developers Guide"); } // anonymous namespace HF_IdlXrefs::HF_IdlXrefs( Environment & io_rEnv, Xml::Element & o_rOut, const String & i_prefix, const client & i_ce ) : HtmlFactory_Idl(io_rEnv, &o_rOut), rContentDirectory(*new Html::Paragraph), pClient(&i_ce) { produce_Main(i_prefix, i_ce); } HF_IdlXrefs::~HF_IdlXrefs() { } void HF_IdlXrefs::Write_ManualLinks( const client & i_ce ) const { const StringVector & rLinks2Refs = i_ce.Secondaries().Links2RefsInManual(); if ( rLinks2Refs.size() == 0 ) { rContentDirectory << C_sDevMan << new Html::LineBreak << C_sCRLF; return; } rContentDirectory >> *new Html::Link("#devmanrefs") << C_sDevMan << new Html::LineBreak << C_sCRLF; HF_SubTitleTable aList(CurOut(), "devmanrefs", C_sDevMan, 1); Xml::Element & rOutCell = aList.Add_Row() >>* new Html::TableCell; csv_assert(rLinks2Refs.size() % 2 == 0); for ( StringVector::const_iterator it = rLinks2Refs.begin(); it != rLinks2Refs.end(); ++it ) { Xml::Element & rLink = rOutCell >> *new Html::Link( Env().Link2Manual(*it)); if ( (*(it+1)).empty() ) // HACK KORR_FUTURE // Research what happens with manual links which contain normal characters // in non-utf-8 texts. And research, why utfF-8 does not work here. rLink << new Xml::XmlCode(*it); else // HACK KORR_FUTURE, see above. rLink << new Xml::XmlCode( *(it+1) ); rOutCell << new Html::LineBreak << C_sCRLF; ++it; } // end for } void HF_IdlXrefs::Produce_List( const char * i_title, const char * i_label, ce_list & i_iterator ) const { if (NOT i_iterator) { rContentDirectory << i_title << new Html::LineBreak << C_sCRLF; return; } csv_assert(*i_label == '#'); rContentDirectory >> *new Html::Link(i_label) << i_title << new Html::LineBreak << C_sCRLF; HF_SubTitleTable aList(CurOut(), i_label+1, i_title, 1); Xml::Element & rOutCell = aList.Add_Row() >>* new Html::TableCell; HF_IdlTypeText aTypeWriter(Env(), rOutCell, true, pClient); for ( ce_list & it = i_iterator; it; ++it ) { aTypeWriter.Produce_byData(*it); rOutCell << new Html::LineBreak; } // end for } void HF_IdlXrefs::Produce_Tree( const char * i_title, const char * i_label, const client & i_ce, F_GET_SUBLIST i_sublistcreator ) const { dyn_ce_list pResult; (*i_sublistcreator)(pResult, i_ce); if (NOT (*pResult).operator bool()) { rContentDirectory << i_title << new Html::LineBreak << C_sCRLF; return; } csv_assert(*i_label == '#'); rContentDirectory >> *new Html::Link(i_label) << i_title << new Html::LineBreak << C_sCRLF; HF_SubTitleTable aList(CurOut(), i_label+1, i_title, 1); Xml::Element & rOut = aList.Add_Row() >>* new Html::TableCell >> *new csi::xml::AnElement("pre") << new csi::html::StyleAttr("font-family:monospace;"); recursive_make_ListInTree( rOut, 0, i_ce, *pResult, i_sublistcreator ); } void HF_IdlXrefs::produce_Main( const String & i_prefix, const client & i_ce ) const { make_Navibar(i_ce); HF_TitleTable aTitle(CurOut()); aTitle.Produce_Title( StreamLock(200)() << C_sTitleStart << i_prefix << " " << i_ce.LocalName() << c_str ); aTitle.Add_Row() << &rContentDirectory; rContentDirectory >> *new Html::Link( StreamLock(200)() << i_ce.LocalName() << ".html" << c_str ) >> *new Html::Bold << "back to " << i_prefix << " " << i_ce.LocalName(); rContentDirectory << new Html::LineBreak << new Html::LineBreak << C_sCRLF; CurOut() << new Html::HorizontalLine(); } void HF_IdlXrefs::make_Navibar( const client & i_ce ) const { HF_IdlNavigationBar aNaviBar(Env(), CurOut()); aNaviBar.Produce_CeXrefsMainRow(i_ce); CurOut() << new Html::HorizontalLine(); } void HF_IdlXrefs::recursive_make_ListInTree( Xml::Element & o_rDisplay, uintt i_level, const client & i_ce, ce_list & i_iterator, F_GET_SUBLIST i_sublistcreator ) const { const char * sLevelIndentation = " "; HF_IdlTypeText aTypeWriter(Env(), o_rDisplay, true, &i_ce); for ( ; i_iterator.operator bool(); ++i_iterator ) { for (uintt i = 0; i < i_level; ++i) { o_rDisplay << sLevelIndentation; } // end for aTypeWriter.Produce_byData(*i_iterator); o_rDisplay << C_sCRLF; dyn_ce_list pResult; const client & rCe = Env().Gate().Ces().Find_Ce(*i_iterator); (*i_sublistcreator)(pResult, rCe); if ( (*pResult).operator bool() ) { recursive_make_ListInTree( o_rDisplay, i_level + 1, rCe, *pResult, i_sublistcreator ); } } // end for } <|endoftext|>
<commit_before><commit_msg>UVa 1207 solved<commit_after><|endoftext|>
<commit_before>/// @author Владимир Керимов #pragma once #include <data/api> #include <data/stdfwd> #include <cstdint> namespace data { /// Base type for any data type class DATA_API object { public: /// Create null-object object(); /// Base scalar destructor ~object(); /// Create with copy of data from another object object(object const& another); /// Copy data from another object object& operator = (object const& another); /// Create with data moved from r-value reference object(object&& temporary); /// Move data from r-value reference object& operator = (object&& temporary); /// Get object as value of specified type template <typename value_type> value_type as() const; /// Implicit cast to boolean operator bool() const; /// Implicit cast to 64-bit signed integer operator int64_t() const; /// Implicit cast to 32-bit signed integer operator int32_t() const; /// Implicit cast to 16-bit signed integer operator int16_t() const; /// Implicit cast to 8-bit signed integer operator int8_t() const; /// Implicit cast to 64-bit unsigned integer operator uint64_t() const; /// Implicit cast to 32-bit unsigned integer operator uint32_t() const; /// Implicit cast to 16-bit unsigned integer operator uint16_t() const; /// Implicit cast to 8-bit unsigned integer operator uint8_t() const; /// Implicit cast to single-precision floating-point value operator float() const; /// Implicit cast to double-precision floating-point value operator double() const; /// Implicit cast to fixed-point decimal value operator decimal() const; /// Implicit cast to text operator text() const; /// Implicit cast to byte-character null-terminated string pointer operator char const*() const; /// Implicit cast to wide-character null-terminated string pointer operator wchar_t const*() const; /// Implicit cast to byte-character standard string container operator std::string() const; /// Implicit cast to wide-character standard string container operator std::wstring() const; /// Clone data into new object object clone() const; /// Check is object null bool is_null() const; /// Create object of null value object(std::nullptr_t); /// Create object of logical value object(bool value); /// Create object of 8-bit signed integer object(int8_t value); /// Create object of 16-bit signed integer object(int16_t value); /// Create object of 32-bit signed integer object(int32_t value); /// Create object of 64-bit signed integer object(int64_t value); /// Create object of 8-bit unsigned integer object(uint8_t value); /// Create object of 16-bit unsigned integer object(uint16_t value); /// Create object of 32-bit unsigned integer object(uint32_t value); /// Create object of 64-bit unsigned integer object(uint64_t value); /// Create object of single precision floating point value object(float value); /// Create object of double precision floating point value object(double value); /// Create object of ANSI string object(char const* value); /// Create object of wide character string object(wchar_t const* value); /// Create object of standard container of ANSI string object(std::string const& value); /// Create object of standard container of wide character string object(std::wstring const& value); /// Create object of function object(std::function<object(object const& arguments)> const value); /// Indexing by constant object object operator [] (object const& id) const; /// Indexing by non-constant object object& operator [] (object const& index); /// Call functor as constant object with constant arguments object operator () (object const& arguments) const; /// Add another object to this object operator + (object const& another) const; /// Subtract another object from this object operator - (object const& another) const; /// Multiply this object to another object operator * (object const& another) const; /// Divide this object to another object operator / (object const& another) const; /// Unary plus object operator + () const; /// Unary minus object operator - () const; /// Size of object presented collection size_t size() const; /// Iterator of the beginning of collection presented by object iterator begin(); /// Iterator of the beginning of collection presented by object iterator end(); /// Constant iterator of the beginning of collection presented by object const_iterator begin() const; /// Constant iterator of the beginning of collection presented by object const_iterator end() const; /// Constant iterator of the beginning of collection presented by object const_iterator cbegin() const; /// Constant iterator of the beginning of collection presented by object const_iterator cend() const; /// Find element of collection by key and return iterator to it iterator find(object const& key); /// Find element of collection by key and return constant iterator to it const_iterator find(object const& key) const; /// Find element of collection by predicate and return iterator to it iterator find(std::function<void(object& elem)> const& predicate); /// Find element of collection by predicate and return constant iterator to it const_iterator find(std::function<void(object const& elem)> const& predicate) const; /// Apply unary operation to each element in collection and store the results object unary_operation(std::function<object(object& elem)> const& operation); /// Apply unary operation to each element in collection and store the results object unary_operation(std::function<object(object const& elem)> const& operation) const; /// Apply unary operation to each element in collection and store the results object binary_operation(object& another, std::function<object(object& mine, object& their)> const& operation); /// Apply unary operation to each element in collection and store the results object binary_operation(object const& another, std::function<object(object const& mine, object const& their)> const& operation) const; /// Execute the function represented by object object operator()(object const& arguments) const; /// Apply unary operation to each element in collection and store the results object binary_operation(object const& another, std::function<object(object const& mine, object const& their)> const& operation) const; protected: /// Base object data class class data; /// Constant of max available size for data static const int data_max_size = DATA_MAX_SIZE; /// Address of buffer char* buffer(); /// Create object by derived data object(data* derived_data); /// Create object by prepared_data object(data&& prepared_data); /// Scalar data storage template <typename value_type> class scalar_data; public: /// Pointer to the data data* data_ptr(); /// Constant pointer to the data data const* data_ptr() const; private: /// Reference to the base object::data data* m_data; /// Data buffer must be greater size than any possible data char m_buffer[data_max_size]; /// Destruct data void destruct(); }; // --- additional declarations part --- // /// Write object into the byte stream DATA_API std::ostream& operator << (std::ostream& output, object const& value); /// Read object from the byte stream DATA_API std::istream& operator >> (std::istream& input, object& value); /// Representation of null constant DATA_API extern const object null; // data::object template <typename value_type> value_type object::as() const { static_assert(false, "Not supported type to get object as the type specified."); } /// Get object as value of boolean type template <> DATA_API bool object::as() const; /// Get object as 8-bit signed integer value template <> DATA_API int8_t object::as() const; /// Get object as 16-bit signed integer value template <> DATA_API int16_t object::as() const; /// Get object as 32-bit signed integer value template <> DATA_API int32_t object::as() const; /// Get object as 64-bit signed integer value template <> DATA_API int64_t object::as() const; /// Get object as 8-bit unsigned integer value template <> DATA_API uint8_t object::as() const; /// Get object as 16-bit unsigned integer value template <> DATA_API uint16_t object::as() const; /// Get object as 32-bit unsigned integer value template <> DATA_API uint32_t object::as() const; /// Get object as 64-bit unsigned integer value template <> DATA_API uint64_t object::as() const; /// Get object as single-precision floating-point value template <> DATA_API float object::as() const; /// Get object as double-precision floating-point value template <> DATA_API double object::as() const; /// Get object as decimal fixed-point value template <> DATA_API decimal object::as() const; /// Get object as text template <> DATA_API text object::as() const; /// Get object as pointer to byte character string template <> DATA_API char const* object::as() const; /// Get object as pointer to wide character string template <> DATA_API wchar_t const* object::as() const; /// Get object as standard byte character string template <> DATA_API std::string object::as() const; /// Get object as stardard wide character string template <> DATA_API std::wstring object::as() const; } // sine qua non <commit_msg>Removed previously wrong merged code.<commit_after>/// @author Владимир Керимов #pragma once #include <data/api> #include <data/stdfwd> #include <cstdint> namespace data { /// Base type for any data type class DATA_API object { public: /// Create null-object object(); /// Base scalar destructor ~object(); /// Create with copy of data from another object object(object const& another); /// Copy data from another object object& operator = (object const& another); /// Create with data moved from r-value reference object(object&& temporary); /// Move data from r-value reference object& operator = (object&& temporary); /// Get object as value of specified type template <typename value_type> value_type as() const; /// Implicit cast to boolean operator bool() const; /// Implicit cast to 64-bit signed integer operator int64_t() const; /// Implicit cast to 32-bit signed integer operator int32_t() const; /// Implicit cast to 16-bit signed integer operator int16_t() const; /// Implicit cast to 8-bit signed integer operator int8_t() const; /// Implicit cast to 64-bit unsigned integer operator uint64_t() const; /// Implicit cast to 32-bit unsigned integer operator uint32_t() const; /// Implicit cast to 16-bit unsigned integer operator uint16_t() const; /// Implicit cast to 8-bit unsigned integer operator uint8_t() const; /// Implicit cast to single-precision floating-point value operator float() const; /// Implicit cast to double-precision floating-point value operator double() const; /// Implicit cast to fixed-point decimal value operator decimal() const; /// Implicit cast to text operator text() const; /// Implicit cast to byte-character null-terminated string pointer operator char const*() const; /// Implicit cast to wide-character null-terminated string pointer operator wchar_t const*() const; /// Implicit cast to byte-character standard string container operator std::string() const; /// Implicit cast to wide-character standard string container operator std::wstring() const; /// Clone data into new object object clone() const; /// Check is object null bool is_null() const; /// Create object of null value object(std::nullptr_t); /// Create object of logical value object(bool value); /// Create object of 8-bit signed integer object(int8_t value); /// Create object of 16-bit signed integer object(int16_t value); /// Create object of 32-bit signed integer object(int32_t value); /// Create object of 64-bit signed integer object(int64_t value); /// Create object of 8-bit unsigned integer object(uint8_t value); /// Create object of 16-bit unsigned integer object(uint16_t value); /// Create object of 32-bit unsigned integer object(uint32_t value); /// Create object of 64-bit unsigned integer object(uint64_t value); /// Create object of single precision floating point value object(float value); /// Create object of double precision floating point value object(double value); /// Create object of ANSI string object(char const* value); /// Create object of wide character string object(wchar_t const* value); /// Create object of standard container of ANSI string object(std::string const& value); /// Create object of standard container of wide character string object(std::wstring const& value); /// Create object of function object(std::function<object(object const& arguments)> const value); /// Indexing by constant object object operator [] (object const& id) const; /// Indexing by non-constant object object& operator [] (object const& index); /// Call functor as constant object with constant arguments object operator () (object const& arguments) const; /// Add another object to this object operator + (object const& another) const; /// Subtract another object from this object operator - (object const& another) const; /// Multiply this object to another object operator * (object const& another) const; /// Divide this object to another object operator / (object const& another) const; /// Unary plus object operator + () const; /// Unary minus object operator - () const; /// Size of object presented collection size_t size() const; /// Iterator of the beginning of collection presented by object iterator begin(); /// Iterator of the beginning of collection presented by object iterator end(); /// Constant iterator of the beginning of collection presented by object const_iterator begin() const; /// Constant iterator of the beginning of collection presented by object const_iterator end() const; /// Constant iterator of the beginning of collection presented by object const_iterator cbegin() const; /// Constant iterator of the beginning of collection presented by object const_iterator cend() const; /// Find element of collection by key and return iterator to it iterator find(object const& key); /// Find element of collection by key and return constant iterator to it const_iterator find(object const& key) const; /// Find element of collection by predicate and return iterator to it iterator find(std::function<void(object& elem)> const& predicate); /// Find element of collection by predicate and return constant iterator to it const_iterator find(std::function<void(object const& elem)> const& predicate) const; /// Apply unary operation to each element in collection and store the results object unary_operation(std::function<object(object& elem)> const& operation); /// Apply unary operation to each element in collection and store the results object unary_operation(std::function<object(object const& elem)> const& operation) const; /// Apply unary operation to each element in collection and store the results object binary_operation(object& another, std::function<object(object& mine, object& their)> const& operation); /// Apply unary operation to each element in collection and store the results object binary_operation(object const& another, std::function<object(object const& mine, object const& their)> const& operation) const; protected: /// Base object data class class data; /// Constant of max available size for data static const int data_max_size = DATA_MAX_SIZE; /// Address of buffer char* buffer(); /// Create object by derived data object(data* derived_data); /// Create object by prepared_data object(data&& prepared_data); /// Scalar data storage template <typename value_type> class scalar_data; public: /// Pointer to the data data* data_ptr(); /// Constant pointer to the data data const* data_ptr() const; private: /// Reference to the base object::data data* m_data; /// Data buffer must be greater size than any possible data char m_buffer[data_max_size]; /// Destruct data void destruct(); }; // --- additional declarations part --- // /// Write object into the byte stream DATA_API std::ostream& operator << (std::ostream& output, object const& value); /// Read object from the byte stream DATA_API std::istream& operator >> (std::istream& input, object& value); /// Representation of null constant DATA_API extern const object null; // data::object template <typename value_type> value_type object::as() const { static_assert(false, "Not supported type to get object as the type specified."); } /// Get object as value of boolean type template <> DATA_API bool object::as() const; /// Get object as 8-bit signed integer value template <> DATA_API int8_t object::as() const; /// Get object as 16-bit signed integer value template <> DATA_API int16_t object::as() const; /// Get object as 32-bit signed integer value template <> DATA_API int32_t object::as() const; /// Get object as 64-bit signed integer value template <> DATA_API int64_t object::as() const; /// Get object as 8-bit unsigned integer value template <> DATA_API uint8_t object::as() const; /// Get object as 16-bit unsigned integer value template <> DATA_API uint16_t object::as() const; /// Get object as 32-bit unsigned integer value template <> DATA_API uint32_t object::as() const; /// Get object as 64-bit unsigned integer value template <> DATA_API uint64_t object::as() const; /// Get object as single-precision floating-point value template <> DATA_API float object::as() const; /// Get object as double-precision floating-point value template <> DATA_API double object::as() const; /// Get object as decimal fixed-point value template <> DATA_API decimal object::as() const; /// Get object as text template <> DATA_API text object::as() const; /// Get object as pointer to byte character string template <> DATA_API char const* object::as() const; /// Get object as pointer to wide character string template <> DATA_API wchar_t const* object::as() const; /// Get object as standard byte character string template <> DATA_API std::string object::as() const; /// Get object as stardard wide character string template <> DATA_API std::wstring object::as() const; } // sine qua non <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include "median.h" using namespace std; int main () { srand (time(NULL)); MedianList a; for (int i=0; i<100000; i++) { int r = rand() % 100000 + 0; a.insert(r); } cout<<a.getMedian(); return 0; } <commit_msg>Add average time calculation<commit_after>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <vector> #include "median.h" #define ITER 10000 using namespace std; clock_t insertTime = 0, deleteTime = 0, starting_time; void printAverageTime() { cout<<"Average insertion time: " <<((double)insertTime/ITER)/CLOCKS_PER_SEC<<endl; cout<<"Average deletion time: " <<((double)deleteTime/ITER)/CLOCKS_PER_SEC<<endl; } int main (void) { vector<int> values; srand (time(NULL)); MedianList container; /* Insert values to container and calculate insertion time */ for (int i=0; i<ITER; i++) { int r = rand() % 10000 + 137; values.push_back(r); starting_time = clock(); container.insert(r); insertTime += clock() - starting_time; } cout<<"median: "<<container.getMedian()<<endl; /* Delete all values from container and calculate deletion time */ while (!values.empty()) { starting_time = clock(); container.remove(values.back()); deleteTime += clock() - starting_time; values.pop_back(); } printAverageTime(); return 0; } <|endoftext|>
<commit_before><commit_msg>Build fix.<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Nathan Binkert */ #include "arch/arm/stacktrace.hh" #include <string> #include "arch/arm/isa_traits.hh" #include "arch/arm/vtophys.hh" #include "base/bitfield.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/thread_context.hh" #include "mem/fs_translating_port_proxy.hh" #include "sim/system.hh" using namespace std; namespace ArmISA { ProcessInfo::ProcessInfo(ThreadContext *_tc) : tc(_tc) { Addr addr = 0; FSTranslatingPortProxy &vp = tc->getVirtProxy(); if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_size", addr)) panic("thread info not compiled into kernel\n"); thread_info_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_size", addr)) panic("thread info not compiled into kernel\n"); task_struct_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_task", addr)) panic("thread info not compiled into kernel\n"); task_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_pid", addr)) panic("thread info not compiled into kernel\n"); pid_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_comm", addr)) panic("thread info not compiled into kernel\n"); name_off = vp.readGtoH<int32_t>(addr); } Addr ProcessInfo::task(Addr ksp) const { Addr base = ksp & ~0x1fff; if (base == ULL(0xffffffffc0000000)) return 0; Addr tsk; FSTranslatingPortProxy &vp = tc->getVirtProxy(); tsk = vp.readGtoH<Addr>(base + task_off); return tsk; } int ProcessInfo::pid(Addr ksp) const { Addr task = this->task(ksp); if (!task) return -1; uint16_t pd; FSTranslatingPortProxy &vp = tc->getVirtProxy(); pd = vp.readGtoH<uint16_t>(task + pid_off); return pd; } string ProcessInfo::name(Addr ksp) const { Addr task = this->task(ksp); if (!task) return "unknown"; char comm[256]; CopyStringOut(tc, comm, task + name_off, sizeof(comm)); if (!comm[0]) return "startup"; return comm; } StackTrace::StackTrace() : tc(0), stack(64) { } StackTrace::StackTrace(ThreadContext *_tc, const StaticInstPtr &inst) : tc(0), stack(64) { trace(_tc, inst); } StackTrace::~StackTrace() { } void StackTrace::trace(ThreadContext *_tc, bool is_call) { } bool StackTrace::isEntry(Addr addr) { return false; } bool StackTrace::decodeStack(MachInst inst, int &disp) { return false; } bool StackTrace::decodeSave(MachInst inst, int &reg, int &disp) { return false; } /* * Decode the function prologue for the function we're in, and note * which registers are stored where, and how large the stack frame is. */ bool StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func, int &size, Addr &ra) { return false; } #if TRACING_ON void StackTrace::dump() { DPRINTFN("------ Stack ------\n"); DPRINTFN(" Not implemented\n"); } #endif } <commit_msg>arm: Fix some style issues in stacktrace.cc.<commit_after>/* * Copyright (c) 2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Nathan Binkert */ #include "arch/arm/stacktrace.hh" #include <string> #include "arch/arm/isa_traits.hh" #include "arch/arm/vtophys.hh" #include "base/bitfield.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/thread_context.hh" #include "mem/fs_translating_port_proxy.hh" #include "sim/system.hh" namespace ArmISA { ProcessInfo::ProcessInfo(ThreadContext *_tc) : tc(_tc) { Addr addr = 0; FSTranslatingPortProxy &vp = tc->getVirtProxy(); if (!tc->getSystemPtr()->kernelSymtab->findAddress( "thread_info_size", addr)) { panic("thread info not compiled into kernel\n"); } thread_info_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress( "task_struct_size", addr)) { panic("thread info not compiled into kernel\n"); } task_struct_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress( "thread_info_task", addr)) { panic("thread info not compiled into kernel\n"); } task_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress( "task_struct_pid", addr)) { panic("thread info not compiled into kernel\n"); } pid_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress( "task_struct_comm", addr)) { panic("thread info not compiled into kernel\n"); } name_off = vp.readGtoH<int32_t>(addr); } Addr ProcessInfo::task(Addr ksp) const { Addr base = ksp & ~0x1fff; if (base == ULL(0xffffffffc0000000)) return 0; Addr tsk; FSTranslatingPortProxy &vp = tc->getVirtProxy(); tsk = vp.readGtoH<Addr>(base + task_off); return tsk; } int ProcessInfo::pid(Addr ksp) const { Addr task = this->task(ksp); if (!task) return -1; uint16_t pd; FSTranslatingPortProxy &vp = tc->getVirtProxy(); pd = vp.readGtoH<uint16_t>(task + pid_off); return pd; } std::string ProcessInfo::name(Addr ksp) const { Addr task = this->task(ksp); if (!task) return "unknown"; char comm[256]; CopyStringOut(tc, comm, task + name_off, sizeof(comm)); if (!comm[0]) return "startup"; return comm; } StackTrace::StackTrace() : tc(0), stack(64) { } StackTrace::StackTrace(ThreadContext *_tc, const StaticInstPtr &inst) : tc(0), stack(64) { trace(_tc, inst); } StackTrace::~StackTrace() { } void StackTrace::trace(ThreadContext *_tc, bool is_call) { } bool StackTrace::isEntry(Addr addr) { return false; } bool StackTrace::decodeStack(MachInst inst, int &disp) { return false; } bool StackTrace::decodeSave(MachInst inst, int &reg, int &disp) { return false; } /* * Decode the function prologue for the function we're in, and note * which registers are stored where, and how large the stack frame is. */ bool StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func, int &size, Addr &ra) { return false; } #if TRACING_ON void StackTrace::dump() { DPRINTFN("------ Stack ------\n"); DPRINTFN(" Not implemented\n"); } #endif } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef HEADER_GUARD_CHANGE_H #define HEADER_GUARD_CHANGE_H #include <boost/optional.hpp> #include <functional> #include <memory> #include <string> #include <vector> namespace vick { class contents; /*! * \file change.hh * * \brief Defines the change class, representing a change from one * `contents` to another. */ /*! * \class change change.hh "change.hh" * \brief Represents a change from one `contents` to another * * It allows for virtual dispath on undoing, redoing, and regeneration * of a textual edit to the buffer. `undo` will put the contents in * the state it was before the edit. `redo` will put the contents in * the state it was after the edit. `regenerate` generates a new * change at the new position in the buffer, or acting on the new * buffer state that must be manually `redo`ne on the contents. * * \see contents */ struct change { change() = default; virtual ~change() = default; /*! * \brief Return true if you edit the `contents` * * Basically allows controll over whether it should be "undone". */ virtual bool is_overriding() const noexcept = 0; /*! * \brief Undoes this edit */ virtual void undo(contents&) = 0; /*! * \brief Performs this edit again (Use after an undo) */ virtual void redo(contents&) = 0; /*! * \brief Generates a change that will act over the new contents */ virtual std::shared_ptr<change> regenerate(const contents&) const = 0; /*! * \brief Calls regenerate and then calls redo on the result and * returns the regenerated change. */ std::shared_ptr<change> regenerate_and_apply(contents& cont); }; } #endif <commit_msg>`vick::change` copy {constructor,operator} deleted<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef HEADER_GUARD_CHANGE_H #define HEADER_GUARD_CHANGE_H #include <boost/optional.hpp> #include <functional> #include <memory> #include <string> #include <vector> namespace vick { class contents; /*! * \file change.hh * * \brief Defines the change class, representing a change from one * `contents` to another. */ /*! * \class change change.hh "change.hh" * \brief Represents a change from one `contents` to another * * It allows for virtual dispath on undoing, redoing, and regeneration * of a textual edit to the buffer. `undo` will put the contents in * the state it was before the edit. `redo` will put the contents in * the state it was after the edit. `regenerate` generates a new * change at the new position in the buffer, or acting on the new * buffer state that must be manually `redo`ne on the contents. * * \see contents */ struct change { change() = default; virtual ~change() = default; /*! * \brief Return true if you edit the `contents` * * Basically allows controll over whether it should be "undone". */ virtual bool is_overriding() const noexcept = 0; /*! * \brief Undoes this edit */ virtual void undo(contents&) = 0; /*! * \brief Performs this edit again (Use after an undo) */ virtual void redo(contents&) = 0; /*! * \brief Generates a change that will act over the new contents */ virtual std::shared_ptr<change> regenerate(const contents&) const = 0; /*! * \brief Calls regenerate and then calls redo on the result and * returns the regenerated change. */ std::shared_ptr<change> regenerate_and_apply(contents& cont); private: change(const change&) = delete; change& operator=(const change&) = delete; }; } #endif <|endoftext|>
<commit_before><commit_msg>fix_interpolation<commit_after><|endoftext|>
<commit_before>#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include "StoreImageModule.hpp" using namespace std; using namespace uipf; // executes the Module /* input is a std::map of input resources, the names are described in the module meta description params is a std::map of input paramaeters, the names are described in the module meta description ouput is a std::map of output resources, the names are described in the module meta description context is a container providing access to the current environment, allowing to open windows, write to logger etc... */ void StoreImageModule::run(map<string, Data::ptr& >& input, map<string, string>& params, map<string, Data::ptr >& output) const { using namespace cv; Matrix* oMatrix = getData<Matrix>(input,"image"); if (oMatrix) { std::string strFilename = getParam<std::string>(params,"filename","noname.png"); imwrite( strFilename.c_str(), oMatrix->getContent() ); } } std::string StoreImageModule::name() const { return "storeImage"; } MetaData StoreImageModule::getMetaData() const { map<string, DataDescription> input = { {"image", DataDescription(MATRIX, "the image to save.") } }; map<string, ParamDescription> params = { {"filename", ParamDescription("file name of the file to save to.") } // TODO cover more parameters from http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imwrite, e.g. store as PNG or JPEG }; return MetaData( "Store an image to a file.", input, map<string, DataDescription>(), // no outputs params ); } <commit_msg>introduced quality-parameter connected to filetype<commit_after>#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include "StoreImageModule.hpp" using namespace std; namespace uipf { // executes the Module /* input is a std::map of input resources, the names are described in the module meta description params is a std::map of input paramaeters, the names are described in the module meta description ouput is a std::map of output resources, the names are described in the module meta description context is a container providing access to the current environment, allowing to open windows, write to logger etc... */ void StoreImageModule::run(map<string, Data::ptr& >& input, map<string, string>& params, map<string, Data::ptr >& output) const { using namespace cv; using namespace utils; Matrix* oMatrix = getData<Matrix>(input,"image"); if (oMatrix) { std::string strFilename = getParam<std::string>(params,"filename","noname.png"); int nQuality = getParam<int>(params,"quality",-1); if (nQuality != -1) { std::vector<int> compression_params; if (endswith(strFilename,"jpeg") || endswith(strFilename,"jpg")) compression_params.push_back(CV_IMWRITE_JPEG_QUALITY); else if (endswith(strFilename,"png")) compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); else if (endswith(strFilename,"bmp") || endswith(strFilename,"ppm") || endswith(strFilename,"pgm")) compression_params.push_back(CV_IMWRITE_PXM_BINARY); compression_params.push_back(nQuality); try { imwrite(strFilename.c_str(), oMatrix->getContent(), compression_params); } catch (runtime_error& ex) { LOG_E( "Exception converting image"); } } imwrite( strFilename.c_str(), oMatrix->getContent() ); } } std::string StoreImageModule::name() const { return "storeImage"; } MetaData StoreImageModule::getMetaData() const { map<string, DataDescription> input = { {"image", DataDescription(MATRIX, "the image to save.") } }; map<string, ParamDescription> params = { {"filename", ParamDescription("file name of the file to save to. imageformat is derived by fileending automatically.") }, {"quality", ParamDescription("compression quality (optional)") } }; return MetaData( "Store an image to a file.", input, map<string, DataDescription>(), // no outputs params ); } }//namespace <|endoftext|>
<commit_before>#include "encoding/ganglion.h" #include <opencv2/imgproc.hpp> #include "core/exception.h" #include "ts/ts.h" using namespace cv; class DiffOfGaussians2dSqTest : public ::testing::Test { protected: virtual void SetUp() { radius_ = 13; scale_ = 1.f; to_.Init(radius_, scale_, true); } DiffOfGaussians2dSq to_; ///< test object int radius_; ///< kernel radius float scale_; ///< scale }; TEST_F(DiffOfGaussians2dSqTest, InvalidInit) { EXPECT_THROW(to_.Init(0, 1, true), ExceptionBadDims); EXPECT_THROW(to_.Init(-1, 1, true), ExceptionBadDims); } TEST_F(DiffOfGaussians2dSqTest, KernelProperties) { Mat kernel = to_.Kernel(); EXPECT_EQ(1, kernel.rows % 2) << "No. of rows must be odd"; EXPECT_EQ(1, kernel.cols % 2) << "No. of columns must be odd"; EXPECT_MAT_DIMS_EQ(kernel, Size2i(radius_*2+1, radius_*2+1)); EXPECT_MAT_TYPE(kernel, CV_32F); EXPECT_MAT_EQ(kernel, kernel.t()); } TEST_F(DiffOfGaussians2dSqTest, Kernel) { Mat kernel = to_.Kernel(); Mat mid_row = kernel.row(radius_); Mat mid_col = kernel.row(radius_); } TEST_F(DiffOfGaussians2dSqTest, OnOff) { DiffOfGaussians2dSq to2; to2.Init(radius_, scale_, false); EXPECT_MAT_EQ(to_.Kernel(), -to2.Kernel()); } <commit_msg>add tests around DoG kernel<commit_after>#include "encoding/ganglion.h" #include <opencv2/imgproc.hpp> #include "core/exception.h" #include "ts/ts.h" using namespace cv; class DiffOfGaussians2dSqTest : public ::testing::Test { protected: virtual void SetUp() { radius_ = 13; scale_ = 1.f; center_on_ = true; to_.Init(radius_, scale_, center_on_); } DiffOfGaussians2dSq to_; ///< test object int radius_; ///< kernel radius float scale_; ///< scale bool center_on_; ///< center on surround off }; TEST_F(DiffOfGaussians2dSqTest, InvalidInit) { EXPECT_THROW(to_.Init(0, 1, true), ExceptionBadDims); EXPECT_THROW(to_.Init(-1, 1, true), ExceptionBadDims); } TEST_F(DiffOfGaussians2dSqTest, KernelProperties) { Mat kernel = to_.Kernel(); EXPECT_EQ(1, kernel.rows % 2) << "No. of rows must be odd"; EXPECT_EQ(1, kernel.cols % 2) << "No. of columns must be odd"; EXPECT_MAT_DIMS_EQ(kernel, Size2i(radius_*2+1, radius_*2+1)); EXPECT_MAT_TYPE(kernel, CV_32F); EXPECT_MAT_EQ(kernel, kernel.t()); Mat kernel_flipped; flip(kernel, kernel_flipped, 0); EXPECT_MAT_EQ(kernel, kernel_flipped); flip(kernel, kernel_flipped, 1); EXPECT_MAT_EQ(kernel, kernel_flipped); flip(kernel.t(), kernel_flipped, 1); EXPECT_MAT_EQ(kernel, kernel_flipped); } TEST_F(DiffOfGaussians2dSqTest, Kernel) { Mat kernel = to_.Kernel(); Mat1f mid_row = kernel.row(radius_); Mat1f mid_col = kernel.col(radius_); EXPECT_MAT_EQ(mid_col, mid_row.t()); double min_val, max_val; int min_idx[2] = {-1, -1}; int max_idx[2] = {-1, -1}; minMaxIdx(mid_row, &min_val, &max_val, min_idx, max_idx); EXPECT_NE(max_val, min_val); EXPECT_GT(max_val, 0); EXPECT_EQ(max_idx[1], kernel.cols/2); EXPECT_LT(min_val, 0); EXPECT_GE(mid_row(0), min_val); EXPECT_GE(mid_row(mid_row.cols-1), min_val); EXPECT_TRUE(max_idx[2]-abs(max_idx[2]-min_idx[2]) < kernel.cols/3); } TEST_F(DiffOfGaussians2dSqTest, OnOff) { DiffOfGaussians2dSq to2; to2.Init(radius_, scale_, false); EXPECT_MAT_EQ(to_.Kernel(), -to2.Kernel()); } <|endoftext|>
<commit_before><commit_msg>`World::set_active_scene`: add `const` modifier to function parameter.<commit_after><|endoftext|>
<commit_before><commit_msg>Localization: fix the crash that gps message is ealier than imu message<commit_after><|endoftext|>
<commit_before>/*! \file * * \brief Python exports for math * \author Benjamin Pritchard (ben@bennyp.org) */ #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include "bpmodule/math/Factorial.hpp" using namespace boost::python; //! \todo Export exact casts? Or have the equivalent with python? namespace bpmodule { namespace math { namespace export_python { BOOST_PYTHON_MODULE(math) { def("Factorial", Factorial); def("FactorialF", FactorialF); def("FactorialD", FactorialD); def("DoubleFactorial", DoubleFactorial); def("DoubleFactorialF", DoubleFactorialF); def("DoubleFactorialD", DoubleFactorialD); def("Double2nm1Factorial", Double2nm1Factorial); def("Double2nm1FactorialF", Double2nm1FactorialF); def("Double2nm1FactorialD", Double2nm1FactorialD); } } // close namespace export_python } // close namespace math } // close namespace bpmodule <commit_msg>Convert math module<commit_after>/*! \file * * \brief Python exports for math * \author Benjamin Pritchard (ben@bennyp.org) */ #include "bpmodule/python_helper/Pybind11.hpp" #include "bpmodule/math/Factorial.hpp" //! \todo Export exact casts? Or have the equivalent with python? namespace bpmodule { namespace math { namespace export_python { PYBIND11_PLUGIN(math) { pybind11::module m("math", "Some common math operations"); m.def("Factorial", Factorial); m.def("FactorialF", FactorialF); m.def("FactorialD", FactorialD); m.def("DoubleFactorial", DoubleFactorial); m.def("DoubleFactorialF", DoubleFactorialF); m.def("DoubleFactorialD", DoubleFactorialD); m.def("Double2nm1Factorial", Double2nm1Factorial); m.def("Double2nm1FactorialF", Double2nm1FactorialF); m.def("Double2nm1FactorialD", Double2nm1FactorialD); return m.ptr(); } } // close namespace export_python } // close namespace math } // close namespace bpmodule <|endoftext|>
<commit_before>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file This file implements a clang-tidy tool. /// /// This tool uses the Clang Tooling infrastructure, see /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html /// for details on setting it up with LLVM source tree. /// //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "clang/Tooling/CommonOptionsParser.h" using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; static cl::OptionCategory ClangTidyCategory("clang-tidy options"); static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::extrahelp ClangTidyHelp( "Configuration files:\n" " clang-tidy attempts to read configuration for each source file from a\n" " .clang-tidy file located in the closest parent directory of the source\n" " file. If any configuration options have a corresponding command-line\n" " option, command-line option takes precedence. The effective\n" " configuration can be inspected using -dump-config.\n\n"); const char DefaultChecks[] = "*," // Enable all checks, except these: "-clang-analyzer-alpha*," // Too many false positives. "-llvm-include-order," // Not implemented yet. "-google-*,"; // Doesn't apply to LLVM. static cl::opt<std::string> Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n" "prefix. Globs are processed in order of appearance\n" "in the list. Globs without '-' prefix add checks\n" "with matching names to the set, globs with the '-'\n" "prefix remove checks with matching names from the\n" "set of enabled checks.\n" "This option's value is appended to the value read\n" "from a .clang-tidy file, if any."), cl::init(""), cl::cat(ClangTidyCategory)); static cl::opt<std::string> HeaderFilter("header-filter", cl::desc("Regular expression matching the names of the\n" "headers to output diagnostics from. Diagnostics\n" "from the main file of each translation unit are\n" "always displayed.\n" "Can be used together with -line-filter.\n" "This option overrides the value read from a\n" ".clang-tidy file."), cl::init(""), cl::cat(ClangTidyCategory)); static cl::opt<std::string> LineFilter("line-filter", cl::desc("List of files with line ranges to filter the\n" "warnings. Can be used together with\n" "-header-filter. The format of the list is a JSON\n" "array of objects:\n" " [\n" " {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n" " {\"name\":\"file2.h\"}\n" " ]"), cl::init(""), cl::cat(ClangTidyCategory)); static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<bool> ListChecks("list-checks", cl::desc("List all enabled checks and exit. Use with\n" "-checks='*' to list all available checks."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<bool> DumpConfig("dump-config", cl::desc("Dumps configuration in the YAML format to stdout."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<bool> AnalyzeTemporaryDtors( "analyze-temporary-dtors", cl::desc("Enable temporary destructor-aware analysis in\n" "clang-analyzer- checks.\n" "This option overrides the value read from a\n" ".clang-tidy file."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<std::string> ExportFixes( "export-fixes", cl::desc("YAML file to store suggested fixes in. The\n" "stored fixes can be applied to the input source\n" "code with clang-apply-replacements."), cl::value_desc("filename"), cl::cat(ClangTidyCategory)); static void printStats(const clang::tidy::ClangTidyStats &Stats) { if (Stats.errorsIgnored()) { llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings ("; StringRef Separator = ""; if (Stats.ErrorsIgnoredNonUserCode) { llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code"; Separator = ", "; } if (Stats.ErrorsIgnoredLineFilter) { llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter << " due to line filter"; Separator = ", "; } if (Stats.ErrorsIgnoredNOLINT) { llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT"; Separator = ", "; } if (Stats.ErrorsIgnoredCheckFilter) llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter << " with check filters"; llvm::errs() << ").\n"; if (Stats.ErrorsIgnoredNonUserCode) llvm::errs() << "Use -header-filter='.*' to display errors from all " "non-system headers.\n"; } } int main(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory); clang::tidy::ClangTidyGlobalOptions GlobalOptions; if (std::error_code Err = clang::tidy::parseLineFilter(LineFilter, GlobalOptions)) { llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n"; llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); return 1; } clang::tidy::ClangTidyOptions FallbackOptions; FallbackOptions.Checks = DefaultChecks; FallbackOptions.HeaderFilterRegex = HeaderFilter; FallbackOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors; clang::tidy::ClangTidyOptions OverrideOptions; if (Checks.getNumOccurrences() > 0) OverrideOptions.Checks = Checks; if (HeaderFilter.getNumOccurrences() > 0) OverrideOptions.HeaderFilterRegex = HeaderFilter; if (AnalyzeTemporaryDtors.getNumOccurrences() > 0) OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors; auto OptionsProvider = llvm::make_unique<clang::tidy::FileOptionsProvider>( GlobalOptions, FallbackOptions, OverrideOptions); std::string FileName = OptionsParser.getSourcePathList().front(); std::vector<std::string> EnabledChecks = clang::tidy::getCheckNames(OptionsProvider->getOptions(FileName)); // FIXME: Allow using --list-checks without positional arguments. if (ListChecks) { llvm::outs() << "Enabled checks:"; for (auto CheckName : EnabledChecks) llvm::outs() << "\n " << CheckName; llvm::outs() << "\n\n"; return 0; } if (DumpConfig) { llvm::outs() << clang::tidy::configurationAsText( clang::tidy::ClangTidyOptions::getDefaults() .mergeWith(OptionsProvider->getOptions(FileName))) << "\n"; return 0; } if (EnabledChecks.empty()) { llvm::errs() << "Error: no checks enabled.\n"; llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); return 1; } std::vector<clang::tidy::ClangTidyError> Errors; clang::tidy::ClangTidyStats Stats = clang::tidy::runClangTidy( std::move(OptionsProvider), OptionsParser.getCompilations(), OptionsParser.getSourcePathList(), &Errors); clang::tidy::handleErrors(Errors, Fix); if (!ExportFixes.empty() && !Errors.empty()) { std::error_code EC; llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None); if (EC) { llvm::errs() << "Error opening output file: " << EC.message() << '\n'; return 1; } clang::tidy::exportReplacements(Errors, OS); } printStats(Stats); return 0; } namespace clang { namespace tidy { // This anchor is used to force the linker to link the LLVMModule. extern volatile int LLVMModuleAnchorSource; static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource; // This anchor is used to force the linker to link the GoogleModule. extern volatile int GoogleModuleAnchorSource; static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource; // This anchor is used to force the linker to link the MiscModule. extern volatile int MiscModuleAnchorSource; static int MiscModuleAnchorDestination = MiscModuleAnchorSource; } // namespace tidy } // namespace clang <commit_msg>Moved main() to the clang::tidy namespace, no functional changes.<commit_after>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file This file implements a clang-tidy tool. /// /// This tool uses the Clang Tooling infrastructure, see /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html /// for details on setting it up with LLVM source tree. /// //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "clang/Tooling/CommonOptionsParser.h" using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; static cl::OptionCategory ClangTidyCategory("clang-tidy options"); static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::extrahelp ClangTidyHelp( "Configuration files:\n" " clang-tidy attempts to read configuration for each source file from a\n" " .clang-tidy file located in the closest parent directory of the source\n" " file. If any configuration options have a corresponding command-line\n" " option, command-line option takes precedence. The effective\n" " configuration can be inspected using -dump-config.\n\n"); const char DefaultChecks[] = "*," // Enable all checks, except these: "-clang-analyzer-alpha*," // Too many false positives. "-llvm-include-order," // Not implemented yet. "-google-*,"; // Doesn't apply to LLVM. static cl::opt<std::string> Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n" "prefix. Globs are processed in order of appearance\n" "in the list. Globs without '-' prefix add checks\n" "with matching names to the set, globs with the '-'\n" "prefix remove checks with matching names from the\n" "set of enabled checks.\n" "This option's value is appended to the value read\n" "from a .clang-tidy file, if any."), cl::init(""), cl::cat(ClangTidyCategory)); static cl::opt<std::string> HeaderFilter("header-filter", cl::desc("Regular expression matching the names of the\n" "headers to output diagnostics from. Diagnostics\n" "from the main file of each translation unit are\n" "always displayed.\n" "Can be used together with -line-filter.\n" "This option overrides the value read from a\n" ".clang-tidy file."), cl::init(""), cl::cat(ClangTidyCategory)); static cl::opt<std::string> LineFilter("line-filter", cl::desc("List of files with line ranges to filter the\n" "warnings. Can be used together with\n" "-header-filter. The format of the list is a JSON\n" "array of objects:\n" " [\n" " {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n" " {\"name\":\"file2.h\"}\n" " ]"), cl::init(""), cl::cat(ClangTidyCategory)); static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<bool> ListChecks("list-checks", cl::desc("List all enabled checks and exit. Use with\n" "-checks='*' to list all available checks."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<bool> DumpConfig("dump-config", cl::desc("Dumps configuration in the YAML format to stdout."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<bool> AnalyzeTemporaryDtors( "analyze-temporary-dtors", cl::desc("Enable temporary destructor-aware analysis in\n" "clang-analyzer- checks.\n" "This option overrides the value read from a\n" ".clang-tidy file."), cl::init(false), cl::cat(ClangTidyCategory)); static cl::opt<std::string> ExportFixes( "export-fixes", cl::desc("YAML file to store suggested fixes in. The\n" "stored fixes can be applied to the input source\n" "code with clang-apply-replacements."), cl::value_desc("filename"), cl::cat(ClangTidyCategory)); namespace clang { namespace tidy { static void printStats(const ClangTidyStats &Stats) { if (Stats.errorsIgnored()) { llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings ("; StringRef Separator = ""; if (Stats.ErrorsIgnoredNonUserCode) { llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code"; Separator = ", "; } if (Stats.ErrorsIgnoredLineFilter) { llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter << " due to line filter"; Separator = ", "; } if (Stats.ErrorsIgnoredNOLINT) { llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT"; Separator = ", "; } if (Stats.ErrorsIgnoredCheckFilter) llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter << " with check filters"; llvm::errs() << ").\n"; if (Stats.ErrorsIgnoredNonUserCode) llvm::errs() << "Use -header-filter='.*' to display errors from all " "non-system headers.\n"; } } int clangTidyMain(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory); ClangTidyGlobalOptions GlobalOptions; if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) { llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n"; llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); return 1; } ClangTidyOptions FallbackOptions; FallbackOptions.Checks = DefaultChecks; FallbackOptions.HeaderFilterRegex = HeaderFilter; FallbackOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors; ClangTidyOptions OverrideOptions; if (Checks.getNumOccurrences() > 0) OverrideOptions.Checks = Checks; if (HeaderFilter.getNumOccurrences() > 0) OverrideOptions.HeaderFilterRegex = HeaderFilter; if (AnalyzeTemporaryDtors.getNumOccurrences() > 0) OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors; auto OptionsProvider = llvm::make_unique<FileOptionsProvider>( GlobalOptions, FallbackOptions, OverrideOptions); std::string FileName = OptionsParser.getSourcePathList().front(); ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName); std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions); // FIXME: Allow using --list-checks without positional arguments. if (ListChecks) { llvm::outs() << "Enabled checks:"; for (auto CheckName : EnabledChecks) llvm::outs() << "\n " << CheckName; llvm::outs() << "\n\n"; return 0; } if (DumpConfig) { llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults() .mergeWith(EffectiveOptions)) << "\n"; return 0; } if (EnabledChecks.empty()) { llvm::errs() << "Error: no checks enabled.\n"; llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true); return 1; } std::vector<ClangTidyError> Errors; ClangTidyStats Stats = runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(), OptionsParser.getSourcePathList(), &Errors); handleErrors(Errors, Fix); if (!ExportFixes.empty() && !Errors.empty()) { std::error_code EC; llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None); if (EC) { llvm::errs() << "Error opening output file: " << EC.message() << '\n'; return 1; } exportReplacements(Errors, OS); } printStats(Stats); return 0; } // This anchor is used to force the linker to link the LLVMModule. extern volatile int LLVMModuleAnchorSource; static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource; // This anchor is used to force the linker to link the GoogleModule. extern volatile int GoogleModuleAnchorSource; static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource; // This anchor is used to force the linker to link the MiscModule. extern volatile int MiscModuleAnchorSource; static int MiscModuleAnchorDestination = MiscModuleAnchorSource; } // namespace tidy } // namespace clang int main(int argc, const char **argv) { return clang::tidy::clangTidyMain(argc, argv); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlversion.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2005-02-21 16:35:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _XMLOFF_XMLVERSION_HXX #define _XMLOFF_XMLVERSION_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTREVISIONLISTPERSISTENCE_HPP_ #include <com/sun/star/document/XDocumentRevisionListPersistence.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_REVISIONTAG_HPP_ #include <com/sun/star/util/RevisionTag.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #include <cppuhelper/implbase1.hxx> #ifndef _XMLOFF_XMLICTXT_HXX #include <xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmlexp.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmltoken.hxx> #endif // ------------------------------------------------------------------------ class XMLVersionListExport : public SvXMLExport { private: const com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& maVersions; public: XMLVersionListExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& rVersions, const rtl::OUString &rFileName, com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler > &rHandler ); virtual ~XMLVersionListExport() {} sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ); void _ExportAutoStyles() {} void _ExportMasterStyles () {} void _ExportContent() {} }; // ------------------------------------------------------------------------ class XMLVersionListImport : public SvXMLImport { private: com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& maVersions; protected: // This method is called after the namespace map has been updated, but // before a context for the current element has been pushed. virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); public: // #110897# XMLVersionListImport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& rVersions ); ~XMLVersionListImport() throw(); com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& GetList() { return maVersions; } }; // ------------------------------------------------------------------------ class XMLVersionListContext : public SvXMLImportContext { private: XMLVersionListImport & rLocalRef; public: XMLVersionListContext( XMLVersionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~XMLVersionListContext(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); }; // ------------------------------------------------------------------------ class XMLVersionContext: public SvXMLImportContext { private: XMLVersionListImport& rLocalRef; static sal_Bool ParseISODateTimeString( const rtl::OUString& rString, com::sun::star::util::DateTime& rDateTime ); public: XMLVersionContext( XMLVersionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~XMLVersionContext(); }; // ------------------------------------------------------------------------ class XMLVersionListPersistence : public ::cppu::WeakImplHelper1< ::com::sun::star::document::XDocumentRevisionListPersistence > { public: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::util::RevisionTag > SAL_CALL load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL store( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage, const ::com::sun::star::uno::Sequence< ::com::sun::star::util::RevisionTag >& List ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); }; ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL XMLVersionListPersistence_getSupportedServiceNames() throw(); ::rtl::OUString SAL_CALL XMLVersionPersistence_getImplementationName() throw(); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL XMLVersionListPersistence_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & ) throw( ::com::sun::star::uno::Exception ); #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.126); FILE MERGED 2005/09/05 14:38:17 rt 1.2.126.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlversion.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:21:56 $ * * 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 _XMLOFF_XMLVERSION_HXX #define _XMLOFF_XMLVERSION_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTREVISIONLISTPERSISTENCE_HPP_ #include <com/sun/star/document/XDocumentRevisionListPersistence.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_REVISIONTAG_HPP_ #include <com/sun/star/util/RevisionTag.hpp> #endif #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif #include <cppuhelper/implbase1.hxx> #ifndef _XMLOFF_XMLICTXT_HXX #include <xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmlexp.hxx> #endif #ifndef _XMLOFF_XMLIMP_HXX #include <xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmltoken.hxx> #endif // ------------------------------------------------------------------------ class XMLVersionListExport : public SvXMLExport { private: const com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& maVersions; public: XMLVersionListExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& rVersions, const rtl::OUString &rFileName, com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler > &rHandler ); virtual ~XMLVersionListExport() {} sal_uInt32 exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ); void _ExportAutoStyles() {} void _ExportMasterStyles () {} void _ExportContent() {} }; // ------------------------------------------------------------------------ class XMLVersionListImport : public SvXMLImport { private: com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& maVersions; protected: // This method is called after the namespace map has been updated, but // before a context for the current element has been pushed. virtual SvXMLImportContext *CreateContext( sal_uInt16 nPrefix, const ::rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); public: // #110897# XMLVersionListImport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& rVersions ); ~XMLVersionListImport() throw(); com::sun::star::uno::Sequence < com::sun::star::util::RevisionTag >& GetList() { return maVersions; } }; // ------------------------------------------------------------------------ class XMLVersionListContext : public SvXMLImportContext { private: XMLVersionListImport & rLocalRef; public: XMLVersionListContext( XMLVersionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~XMLVersionListContext(); virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); }; // ------------------------------------------------------------------------ class XMLVersionContext: public SvXMLImportContext { private: XMLVersionListImport& rLocalRef; static sal_Bool ParseISODateTimeString( const rtl::OUString& rString, com::sun::star::util::DateTime& rDateTime ); public: XMLVersionContext( XMLVersionListImport& rImport, sal_uInt16 nPrefix, const rtl::OUString& rLocalName, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > & xAttrList ); ~XMLVersionContext(); }; // ------------------------------------------------------------------------ class XMLVersionListPersistence : public ::cppu::WeakImplHelper1< ::com::sun::star::document::XDocumentRevisionListPersistence > { public: virtual ::com::sun::star::uno::Sequence< ::com::sun::star::util::RevisionTag > SAL_CALL load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL store( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage, const ::com::sun::star::uno::Sequence< ::com::sun::star::util::RevisionTag >& List ) throw (::com::sun::star::io::IOException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); }; ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL XMLVersionListPersistence_getSupportedServiceNames() throw(); ::rtl::OUString SAL_CALL XMLVersionPersistence_getImplementationName() throw(); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL XMLVersionListPersistence_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & ) throw( ::com::sun::star::uno::Exception ); #endif <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "arch/io/blocker_pool.hpp" #include <string.h> __thread int thread_is_blocker_pool_thread = 0; // IO thread function void* blocker_pool_t::event_loop(void *arg) { thread_is_blocker_pool_thread = 1; blocker_pool_t *parent = reinterpret_cast<blocker_pool_t*>(arg); // Disable signals on this thread. This ensures that signals like SIGINT are // handled by one of the main threads. { sigset_t sigmask; int res = sigfillset(&sigmask); guarantee_err(res == 0, "Could not get a full sigmask"); res = pthread_sigmask(SIG_SETMASK, &sigmask, NULL); guarantee_xerr(res == 0, res, "Could not block signal"); } while (true) { // Wait for an IO command or shutdown command. The while-loop guards against spurious // wakeups. system_mutex_t::lock_t or_lock(&parent->or_mutex); while (parent->outstanding_requests.empty() && !parent->shutting_down) { parent->or_cond.wait(&parent->or_mutex); } if (parent->shutting_down) { // or_lock's destructor gets called, so everything is OK. return NULL; } else { // Grab a request job_t *request = parent->outstanding_requests.front(); parent->outstanding_requests.erase(parent->outstanding_requests.begin(), parent->outstanding_requests.begin() + 1); // Unlock the mutex manually instead of waiting for its destructor so that other jobs // will get to proceed or_lock.unlock(); // Perform the request. It may block. This is the raison d'etre for blocker_pool_t. request->run(); // Notify that the request is done { system_mutex_t::lock_t ce_lock(&parent->ce_mutex); parent->completed_events.push_back(request); } // It seems critical for performance that we release ce_lock *before* we write to the signal! // This is probably because the kernel thinks "hey, somebody is blocking on the signal. // Now that it has been written to, that thread will want to handle it, so let's wake it up." // If we don't have ce_lock released at that point, the following happens: // The signalled thread immediately has to acquire ce_lock, so the kernel has to yield control // again. Only after an additional scheduler roundtrip, we get control again and can release the ce_lock. parent->ce_signal.wakey_wakey(); } } } blocker_pool_t::blocker_pool_t(int nthreads, linux_event_queue_t *_queue) : threads(nthreads), shutting_down(false), queue(_queue) { // Start the worker threads for (size_t i = 0; i < threads.size(); ++i) { int res = pthread_create(&threads[i], NULL, &blocker_pool_t::event_loop, reinterpret_cast<void*>(this)); guarantee_xerr(res == 0, res, "Could not create blocker-pool thread."); } // Register with event queue so we get the completion events queue->watch_resource(ce_signal.get_notify_fd(), poll_event_in, this); } blocker_pool_t::~blocker_pool_t() { // Deregister with the event queue queue->forget_resource(ce_signal.get_notify_fd(), this); /* Send out the order to shut down */ { system_mutex_t::lock_t or_lock(&or_mutex); shutting_down = true; /* It is an error to shut down the blocker pool while requests are still out */ rassert(outstanding_requests.size() == 0); or_cond.broadcast(); } /* Wait for stuff to actually shut down */ for (size_t i = 0; i < threads.size(); ++i) { int res = pthread_join(threads[i], NULL); guarantee_xerr(res == 0, res, "Could not join blocker-pool thread."); } } void blocker_pool_t::do_job(job_t *job) { system_mutex_t::lock_t or_lock(&or_mutex); outstanding_requests.push_back(job); or_cond.signal(); } void blocker_pool_t::on_event(DEBUG_VAR int event) { rassert(event == poll_event_in); ce_signal.consume_wakey_wakeys(); // So pipe doesn't get backed up std::vector<job_t *> local_completed_events; { system_mutex_t::lock_t ce_lock(&ce_mutex); local_completed_events.swap(completed_events); } for (size_t i = 0; i < local_completed_events.size(); ++i) { local_completed_events[i]->done(); } } bool i_am_in_blocker_pool_thread() { return thread_is_blocker_pool_thread == 1; } <commit_msg>Made the blocker pool specify the stack size for blocker pool threads to be the same as COROUTINE_STACK_SIZE (which is 128 KB).<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #include "arch/io/blocker_pool.hpp" #include <string.h> __thread int thread_is_blocker_pool_thread = 0; // IO thread function void* blocker_pool_t::event_loop(void *arg) { thread_is_blocker_pool_thread = 1; blocker_pool_t *parent = reinterpret_cast<blocker_pool_t*>(arg); // Disable signals on this thread. This ensures that signals like SIGINT are // handled by one of the main threads. { sigset_t sigmask; int res = sigfillset(&sigmask); guarantee_err(res == 0, "Could not get a full sigmask"); res = pthread_sigmask(SIG_SETMASK, &sigmask, NULL); guarantee_xerr(res == 0, res, "Could not block signal"); } while (true) { // Wait for an IO command or shutdown command. The while-loop guards against spurious // wakeups. system_mutex_t::lock_t or_lock(&parent->or_mutex); while (parent->outstanding_requests.empty() && !parent->shutting_down) { parent->or_cond.wait(&parent->or_mutex); } if (parent->shutting_down) { // or_lock's destructor gets called, so everything is OK. return NULL; } else { // Grab a request job_t *request = parent->outstanding_requests.front(); parent->outstanding_requests.erase(parent->outstanding_requests.begin(), parent->outstanding_requests.begin() + 1); // Unlock the mutex manually instead of waiting for its destructor so that other jobs // will get to proceed or_lock.unlock(); // Perform the request. It may block. This is the raison d'etre for blocker_pool_t. request->run(); // Notify that the request is done { system_mutex_t::lock_t ce_lock(&parent->ce_mutex); parent->completed_events.push_back(request); } // It seems critical for performance that we release ce_lock *before* we write to the signal! // This is probably because the kernel thinks "hey, somebody is blocking on the signal. // Now that it has been written to, that thread will want to handle it, so let's wake it up." // If we don't have ce_lock released at that point, the following happens: // The signalled thread immediately has to acquire ce_lock, so the kernel has to yield control // again. Only after an additional scheduler roundtrip, we get control again and can release the ce_lock. parent->ce_signal.wakey_wakey(); } } } blocker_pool_t::blocker_pool_t(int nthreads, linux_event_queue_t *_queue) : threads(nthreads), shutting_down(false), queue(_queue) { // Start the worker threads for (size_t i = 0; i < threads.size(); ++i) { pthread_attr_t attr; int res = pthread_attr_init(&attr); guarantee_xerr(res == 0, res, "pthread_attr_init failed."); // The coroutine stack size should be enough for blocker pool stacks. Right // now that's 128 KB. static_assert(COROUTINE_STACK_SIZE == 131072, "Expecting COROUTINE_STACK_SIZE to be 131072. If you changed " "it, please double-check whether the value is appropriate for " "blocker pool threads."); // Disregard failure -- we'll just use the default stack size if this somehow // fails. UNUSED int ignored_res = pthread_attr_setstacksize(&attr, COROUTINE_STACK_SIZE); res = pthread_create(&threads[i], NULL, &blocker_pool_t::event_loop, reinterpret_cast<void*>(this)); guarantee_xerr(res == 0, res, "Could not create blocker-pool thread."); res = pthread_attr_destroy(&attr); guarantee_xerr(res == 0, res, "pthread_attr_destroy failed."); } // Register with event queue so we get the completion events queue->watch_resource(ce_signal.get_notify_fd(), poll_event_in, this); } blocker_pool_t::~blocker_pool_t() { // Deregister with the event queue queue->forget_resource(ce_signal.get_notify_fd(), this); /* Send out the order to shut down */ { system_mutex_t::lock_t or_lock(&or_mutex); shutting_down = true; /* It is an error to shut down the blocker pool while requests are still out */ rassert(outstanding_requests.size() == 0); or_cond.broadcast(); } /* Wait for stuff to actually shut down */ for (size_t i = 0; i < threads.size(); ++i) { int res = pthread_join(threads[i], NULL); guarantee_xerr(res == 0, res, "Could not join blocker-pool thread."); } } void blocker_pool_t::do_job(job_t *job) { system_mutex_t::lock_t or_lock(&or_mutex); outstanding_requests.push_back(job); or_cond.signal(); } void blocker_pool_t::on_event(DEBUG_VAR int event) { rassert(event == poll_event_in); ce_signal.consume_wakey_wakeys(); // So pipe doesn't get backed up std::vector<job_t *> local_completed_events; { system_mutex_t::lock_t ce_lock(&ce_mutex); local_completed_events.swap(completed_events); } for (size_t i = 0; i < local_completed_events.size(); ++i) { local_completed_events[i]->done(); } } bool i_am_in_blocker_pool_thread() { return thread_is_blocker_pool_thread == 1; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // Date: Tue Jul 28 18:14:40 CST 2015 #include "butil/time.h" #include "butil/memory/singleton_on_pthread_once.h" #include "bvar/reducer.h" #include "bvar/detail/sampler.h" #include "bvar/passive_status.h" #include "bvar/window.h" namespace bvar { namespace detail { const int WARN_NOSLEEP_THRESHOLD = 2; // Combine two circular linked list into one. struct CombineSampler { void operator()(Sampler* & s1, Sampler* s2) const { if (s2 == NULL) { return; } if (s1 == NULL) { s1 = s2; return; } s1->InsertBeforeAsList(s2); } }; // Call take_sample() of all scheduled samplers. // This can be done with regular timer thread, but it's way too slow(global // contention + log(N) heap manipulations). We need it to be super fast so that // creation overhead of Window<> is negliable. // The trick is to use Reducer<Sampler*, CombineSampler>. Each Sampler is // doubly linked, thus we can reduce multiple Samplers into one cicurlarly // doubly linked list, and multiple lists into larger lists. We create a // dedicated thread to periodically get_value() which is just the combined // list of Samplers. Waking through the list and call take_sample(). // If a Sampler needs to be deleted, we just mark it as unused and the // deletion is taken place in the thread as well. class SamplerCollector : public bvar::Reducer<Sampler*, CombineSampler> { public: SamplerCollector() : _created(false) , _stop(false) , _cumulated_time_us(0) { create_sampling_thread(); } ~SamplerCollector() { if (_created) { _stop = true; pthread_join(_tid, NULL); _created = false; } } private: // Support for fork: // * The singleton can be null before forking, the child callback will not // be registered. // * If the singleton is not null before forking, the child callback will // be registered and the sampling thread will be re-created. // * A forked program can be forked again. static void child_callback_atfork() { butil::get_leaky_singleton<SamplerCollector>()->after_forked_as_child(); } void create_sampling_thread() { const int rc = pthread_create(&_tid, NULL, sampling_thread, this); if (rc != 0) { LOG(FATAL) << "Fail to create sampling_thread, " << berror(rc); } else { _created = true; pthread_atfork(NULL, NULL, child_callback_atfork); } } void after_forked_as_child() { _created = false; create_sampling_thread(); } void run(); static void* sampling_thread(void* arg) { static_cast<SamplerCollector*>(arg)->run(); return NULL; } static double get_cumulated_time(void* arg) { return static_cast<SamplerCollector*>(arg)->_cumulated_time_us / 1000.0 / 1000.0; } private: bool _created; bool _stop; int64_t _cumulated_time_us; pthread_t _tid; }; #ifndef UNIT_TEST static PassiveStatus<double>* s_cumulated_time_bvar = NULL; static bvar::PerSecond<bvar::PassiveStatus<double> >* s_sampling_thread_usage_bvar = NULL; #endif void SamplerCollector::run() { #ifndef UNIT_TEST // NOTE: // * Following vars can't be created on thread's stack since this thread // may be adandoned at any time after forking. // * They can't created inside the constructor of SamplerCollector as well, // which results in deadlock. if (s_cumulated_time_bvar == NULL) { s_cumulated_time_bvar = new PassiveStatus<double>(get_cumulated_time, this); } if (s_sampling_thread_usage_bvar == NULL) { s_sampling_thread_usage_bvar = new bvar::PerSecond<bvar::PassiveStatus<double> >( "bvar_sampler_collector_usage", s_cumulated_time_bvar, 10); } #endif butil::LinkNode<Sampler> root; int consecutive_nosleep = 0; while (!_stop) { int64_t abstime = butil::gettimeofday_us(); Sampler* s = this->reset(); if (s) { s->InsertBeforeAsList(&root); } int nremoved = 0; int nsampled = 0; for (butil::LinkNode<Sampler>* p = root.next(); p != &root;) { // We may remove p from the list, save next first. butil::LinkNode<Sampler>* saved_next = p->next(); Sampler* s = p->value(); s->_mutex.lock(); if (!s->_used) { s->_mutex.unlock(); p->RemoveFromList(); delete s; ++nremoved; } else { s->take_sample(); s->_mutex.unlock(); ++nsampled; } p = saved_next; } bool slept = false; int64_t now = butil::gettimeofday_us(); _cumulated_time_us += now - abstime; abstime += 1000000L; while (abstime > now) { ::usleep(abstime - now); slept = true; now = butil::gettimeofday_us(); } if (slept) { consecutive_nosleep = 0; } else { if (++consecutive_nosleep >= WARN_NOSLEEP_THRESHOLD) { consecutive_nosleep = 0; LOG(WARNING) << "bvar is busy at sampling for " << WARN_NOSLEEP_THRESHOLD << " seconds!"; } } } } Sampler::Sampler() : _used(true) {} Sampler::~Sampler() {} void Sampler::schedule() { *butil::get_leaky_singleton<SamplerCollector>() << this; } void Sampler::destroy() { _mutex.lock(); _used = false; _mutex.unlock(); } } // namespace detail } // namespace bvar <commit_msg>not register pthread_atfork in child process<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // Date: Tue Jul 28 18:14:40 CST 2015 #include "butil/time.h" #include "butil/memory/singleton_on_pthread_once.h" #include "bvar/reducer.h" #include "bvar/detail/sampler.h" #include "bvar/passive_status.h" #include "bvar/window.h" namespace bvar { namespace detail { const int WARN_NOSLEEP_THRESHOLD = 2; // Combine two circular linked list into one. struct CombineSampler { void operator()(Sampler* & s1, Sampler* s2) const { if (s2 == NULL) { return; } if (s1 == NULL) { s1 = s2; return; } s1->InsertBeforeAsList(s2); } }; // True iff pthread_atfork was called. The callback to atfork works for child // of child as well, no need to register in the child again. static bool registered_atfork = false; // Call take_sample() of all scheduled samplers. // This can be done with regular timer thread, but it's way too slow(global // contention + log(N) heap manipulations). We need it to be super fast so that // creation overhead of Window<> is negliable. // The trick is to use Reducer<Sampler*, CombineSampler>. Each Sampler is // doubly linked, thus we can reduce multiple Samplers into one cicurlarly // doubly linked list, and multiple lists into larger lists. We create a // dedicated thread to periodically get_value() which is just the combined // list of Samplers. Waking through the list and call take_sample(). // If a Sampler needs to be deleted, we just mark it as unused and the // deletion is taken place in the thread as well. class SamplerCollector : public bvar::Reducer<Sampler*, CombineSampler> { public: SamplerCollector() : _created(false) , _stop(false) , _cumulated_time_us(0) { create_sampling_thread(); } ~SamplerCollector() { if (_created) { _stop = true; pthread_join(_tid, NULL); _created = false; } } private: // Support for fork: // * The singleton can be null before forking, the child callback will not // be registered. // * If the singleton is not null before forking, the child callback will // be registered and the sampling thread will be re-created. // * A forked program can be forked again. static void child_callback_atfork() { butil::get_leaky_singleton<SamplerCollector>()->after_forked_as_child(); } void create_sampling_thread() { const int rc = pthread_create(&_tid, NULL, sampling_thread, this); if (rc != 0) { LOG(FATAL) << "Fail to create sampling_thread, " << berror(rc); } else { _created = true; if (!registered_atfork) { registered_atfork = true; pthread_atfork(NULL, NULL, child_callback_atfork); } } } void after_forked_as_child() { _created = false; create_sampling_thread(); } void run(); static void* sampling_thread(void* arg) { static_cast<SamplerCollector*>(arg)->run(); return NULL; } static double get_cumulated_time(void* arg) { return static_cast<SamplerCollector*>(arg)->_cumulated_time_us / 1000.0 / 1000.0; } private: bool _created; bool _stop; int64_t _cumulated_time_us; pthread_t _tid; }; #ifndef UNIT_TEST static PassiveStatus<double>* s_cumulated_time_bvar = NULL; static bvar::PerSecond<bvar::PassiveStatus<double> >* s_sampling_thread_usage_bvar = NULL; #endif void SamplerCollector::run() { #ifndef UNIT_TEST // NOTE: // * Following vars can't be created on thread's stack since this thread // may be adandoned at any time after forking. // * They can't created inside the constructor of SamplerCollector as well, // which results in deadlock. if (s_cumulated_time_bvar == NULL) { s_cumulated_time_bvar = new PassiveStatus<double>(get_cumulated_time, this); } if (s_sampling_thread_usage_bvar == NULL) { s_sampling_thread_usage_bvar = new bvar::PerSecond<bvar::PassiveStatus<double> >( "bvar_sampler_collector_usage", s_cumulated_time_bvar, 10); } #endif butil::LinkNode<Sampler> root; int consecutive_nosleep = 0; while (!_stop) { int64_t abstime = butil::gettimeofday_us(); Sampler* s = this->reset(); if (s) { s->InsertBeforeAsList(&root); } int nremoved = 0; int nsampled = 0; for (butil::LinkNode<Sampler>* p = root.next(); p != &root;) { // We may remove p from the list, save next first. butil::LinkNode<Sampler>* saved_next = p->next(); Sampler* s = p->value(); s->_mutex.lock(); if (!s->_used) { s->_mutex.unlock(); p->RemoveFromList(); delete s; ++nremoved; } else { s->take_sample(); s->_mutex.unlock(); ++nsampled; } p = saved_next; } bool slept = false; int64_t now = butil::gettimeofday_us(); _cumulated_time_us += now - abstime; abstime += 1000000L; while (abstime > now) { ::usleep(abstime - now); slept = true; now = butil::gettimeofday_us(); } if (slept) { consecutive_nosleep = 0; } else { if (++consecutive_nosleep >= WARN_NOSLEEP_THRESHOLD) { consecutive_nosleep = 0; LOG(WARNING) << "bvar is busy at sampling for " << WARN_NOSLEEP_THRESHOLD << " seconds!"; } } } } Sampler::Sampler() : _used(true) {} Sampler::~Sampler() {} void Sampler::schedule() { *butil::get_leaky_singleton<SamplerCollector>() << this; } void Sampler::destroy() { _mutex.lock(); _used = false; _mutex.unlock(); } } // namespace detail } // namespace bvar <|endoftext|>
<commit_before>#include "c4/storage/raw.test.hpp" #include "c4/storage/raw.hpp" #include "c4/test.hpp" #include "c4/allocator.hpp" C4_BEGIN_NAMESPACE(c4) C4_BEGIN_NAMESPACE(stg) TEST(raw_fixed, instantiation) { using ci = Counting< int >; { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw_fixed< ci, 10 > rf; EXPECT_EQ(rf.capacity(), 10); } ch.check_all_delta(0, 0, 0); } { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw_fixed< ci, 11 > rf; EXPECT_EQ(rf.capacity(), 11); } ch.check_all_delta(0, 0, 0); } } TEST(raw, instantiation) { using ci = Counting< int >; { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw< ci > rf; EXPECT_EQ(rf.capacity(), 0); } ch.check_all_delta(0, 0, 0); } { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw< ci > rf(10); EXPECT_EQ(rf.capacity(), 10); } //WIP ch.check_all_delta(1, 10 * sizeof(int), 10 * sizeof(int)); } { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw< ci > rf(16); EXPECT_EQ(rf.capacity(), 16); } //WIP ch.check_all_delta(1, 16 * sizeof(int), 16 * sizeof(int)); } } TEST(raw_paged, instantiation) { using ci = Counting< int >; size_t ps; { AllocationCountsChecker ch; { raw_paged< ci > rf; ps = rf.page_size(); EXPECT_EQ(rf.capacity(), 0); EXPECT_EQ(rf.num_pages(), 0); } //WIP ch.check_all_delta(0, 0, 0); } { raw_paged< ci > rf(1); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged< ci > rf(2 * ps - 1); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged< ci > rf(2 * ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged< ci > rf(2 * ps + 1); EXPECT_EQ(rf.capacity(), 3 * ps); EXPECT_EQ(rf.num_pages(), 3); } } TEST(raw_paged_rt, instantiation) { using ci = Counting< int >; { raw_paged_rt< ci > rf; EXPECT_EQ(rf.capacity(), 0); EXPECT_EQ(rf.num_pages(), 0); EXPECT_EQ(rf.page_size(), 256); // the default } for(size_t ps : {32, 64, 128}) { { raw_paged_rt< ci > rf(1, ps); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged_rt< ci > rf(ps - 1, ps); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged_rt< ci > rf(ps, ps); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged_rt< ci > rf(ps + 1, ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged_rt< ci > rf(2 * ps - 1, ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged_rt< ci > rf(2 * ps, ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged_rt< ci > rf(2 * ps + 1, ps); EXPECT_EQ(rf.capacity(), 3 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 3); } } } C4_END_NAMESPACE(stg) C4_END_NAMESPACE(c4) <commit_msg>raw storage: add tests to ensure there are no leaks when inheriting from raw storage containers<commit_after>#include "c4/storage/raw.test.hpp" #include "c4/storage/raw.hpp" #include "c4/test.hpp" #include "c4/allocator.hpp" C4_BEGIN_NAMESPACE(c4) C4_BEGIN_NAMESPACE(stg) //----------------------------------------------------------------------------- TEST(raw_fixed, instantiation) { using ci = Counting< int >; { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw_fixed< ci, 10 > rf; EXPECT_EQ(rf.capacity(), 10); } ch.check_all_delta(0, 0, 0); } { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw_fixed< ci, 11 > rf; EXPECT_EQ(rf.capacity(), 11); } ch.check_all_delta(0, 0, 0); } } //----------------------------------------------------------------------------- TEST(raw, instantiation) { using ci = Counting< int >; { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw< ci > rf; EXPECT_EQ(rf.capacity(), 0); } ch.check_all_delta(0, 0, 0); } { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw< ci > rf(10); EXPECT_EQ(rf.capacity(), 10); } //WIP ch.check_all_delta(1, 10 * sizeof(int), 10 * sizeof(int)); } { AllocationCountsChecker ch; { auto cd = ci::check_ctors_dtors(0, 0); raw< ci > rf(16); EXPECT_EQ(rf.capacity(), 16); } //WIP ch.check_all_delta(1, 16 * sizeof(int), 16 * sizeof(int)); } } //----------------------------------------------------------------------------- template< class T > struct raw_inheriting : public raw< T > { using raw< T >::raw; }; TEST(raw, inheriting) { using ci = Counting< raw_inheriting< int > >; { auto cd = ci::check_ctors_dtors(1, 1); { ci rf(10); EXPECT_EQ(rf.obj.capacity(), 10); } } } //----------------------------------------------------------------------------- TEST(raw_paged, instantiation) { using ci = Counting< int >; size_t ps; { AllocationCountsChecker ch; { raw_paged< ci > rf; ps = rf.page_size(); EXPECT_EQ(rf.capacity(), 0); EXPECT_EQ(rf.num_pages(), 0); } //WIP ch.check_all_delta(0, 0, 0); } { raw_paged< ci > rf(1); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged< ci > rf(2 * ps - 1); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged< ci > rf(2 * ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged< ci > rf(2 * ps + 1); EXPECT_EQ(rf.capacity(), 3 * ps); EXPECT_EQ(rf.num_pages(), 3); } } //----------------------------------------------------------------------------- TEST(raw_paged_rt, instantiation) { using ci = Counting< int >; { raw_paged_rt< ci > rf; EXPECT_EQ(rf.capacity(), 0); EXPECT_EQ(rf.num_pages(), 0); EXPECT_EQ(rf.page_size(), 256); // the default } for(size_t ps : {32, 64, 128}) { { raw_paged_rt< ci > rf(1, ps); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged_rt< ci > rf(ps - 1, ps); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged_rt< ci > rf(ps, ps); EXPECT_EQ(rf.capacity(), ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 1); } { raw_paged_rt< ci > rf(ps + 1, ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged_rt< ci > rf(2 * ps - 1, ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged_rt< ci > rf(2 * ps, ps); EXPECT_EQ(rf.capacity(), 2 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 2); } { raw_paged_rt< ci > rf(2 * ps + 1, ps); EXPECT_EQ(rf.capacity(), 3 * ps); EXPECT_EQ(rf.page_size(), ps); EXPECT_EQ(rf.num_pages(), 3); } } } //----------------------------------------------------------------------------- template< class T > struct raw_inheriting_paged : public raw_paged< T > { using raw_paged< T >::raw_paged; }; TEST(raw_paged, inheriting) { using ci = Counting< raw_inheriting_paged< int > >; { auto cd = ci::check_ctors_dtors(1, 1); { ci rf(10); EXPECT_EQ(rf.obj.capacity(), 256); } } } //----------------------------------------------------------------------------- template< class T > struct raw_inheriting_paged_rt : public raw_paged_rt< T > { using raw_paged_rt< T >::raw_paged_rt; }; TEST(raw_paged_rt, inheriting) { using ci = Counting< raw_inheriting_paged_rt< int > >; { auto cd = ci::check_ctors_dtors(1, 1); { ci rf(10); EXPECT_EQ(rf.obj.capacity(), 256); } } } C4_END_NAMESPACE(stg) C4_END_NAMESPACE(c4) <|endoftext|>
<commit_before>#ifndef CAFFE_LAYER_FACTORY_HPP_ #define CAFFE_LAYER_FACTORY_HPP_ #include <string> #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/vision_layers.hpp" namespace caffe { // A function to get a specific layer from the specification given in // LayerParameter. Ideally this would be replaced by a factory pattern, // but we will leave it this way for now. template <typename Dtype> Layer<Dtype>* GetLayer(const LayerParameter& param) { const string& name = param.name(); const LayerParameter_LayerType& type = param.type(); switch (type) { case LayerParameter_LayerType_ACCURACY: return new AccuracyLayer<Dtype>(param); case LayerParameter_LayerType_ABSVAL: return new AbsValLayer<Dtype>(param); case LayerParameter_LayerType_ARGMAX: return new ArgMaxLayer<Dtype>(param); case LayerParameter_LayerType_BNLL: return new BNLLLayer<Dtype>(param); case LayerParameter_LayerType_CONCAT: return new ConcatLayer<Dtype>(param); case LayerParameter_LayerType_CONVOLUTION: return new ConvolutionLayer<Dtype>(param); case LayerParameter_LayerType_DATA: return new DataLayer<Dtype>(param); case LayerParameter_LayerType_DROPOUT: return new DropoutLayer<Dtype>(param); case LayerParameter_LayerType_DUMMY_DATA: return new DummyDataLayer<Dtype>(param); case LayerParameter_LayerType_EUCLIDEAN_LOSS: return new EuclideanLossLayer<Dtype>(param); case LayerParameter_LayerType_ELTWISE: return new EltwiseLayer<Dtype>(param); case LayerParameter_LayerType_FLATTEN: return new FlattenLayer<Dtype>(param); case LayerParameter_LayerType_HDF5_DATA: return new HDF5DataLayer<Dtype>(param); case LayerParameter_LayerType_HDF5_OUTPUT: return new HDF5OutputLayer<Dtype>(param); case LayerParameter_LayerType_HINGE_LOSS: return new HingeLossLayer<Dtype>(param); case LayerParameter_LayerType_IMAGE_DATA: return new ImageDataLayer<Dtype>(param); case LayerParameter_LayerType_IM2COL: return new Im2colLayer<Dtype>(param); case LayerParameter_LayerType_INFOGAIN_LOSS: return new InfogainLossLayer<Dtype>(param); case LayerParameter_LayerType_INNER_PRODUCT: return new InnerProductLayer<Dtype>(param); case LayerParameter_LayerType_LRN: return new LRNLayer<Dtype>(param); case LayerParameter_LayerType_MEMORY_DATA: return new MemoryDataLayer<Dtype>(param); case LayerParameter_LayerType_MVN: return new MVNLayer<Dtype>(param); case LayerParameter_LayerType_MULTINOMIAL_LOGISTIC_LOSS: return new MultinomialLogisticLossLayer<Dtype>(param); case LayerParameter_LayerType_POOLING: return new PoolingLayer<Dtype>(param); case LayerParameter_LayerType_POWER: return new PowerLayer<Dtype>(param); case LayerParameter_LayerType_RELU: return new ReLULayer<Dtype>(param); case LayerParameter_LayerType_SIGMOID: return new SigmoidLayer<Dtype>(param); case LayerParameter_LayerType_SIGMOID_CROSS_ENTROPY_LOSS: return new SigmoidCrossEntropyLossLayer<Dtype>(param); case LayerParameter_LayerType_SLICE: return new SliceLayer<Dtype>(param); case LayerParameter_LayerType_SOFTMAX: return new SoftmaxLayer<Dtype>(param); case LayerParameter_LayerType_SOFTMAX_LOSS: return new SoftmaxWithLossLayer<Dtype>(param); case LayerParameter_LayerType_SPLIT: return new SplitLayer<Dtype>(param); case LayerParameter_LayerType_TANH: return new TanHLayer<Dtype>(param); case LayerParameter_LayerType_WINDOW_DATA: return new WindowDataLayer<Dtype>(param); case LayerParameter_LayerType_NONE: LOG(FATAL) << "Layer " << name << " has unspecified type."; default: LOG(FATAL) << "Layer " << name << " has unknown type " << type; } // just to suppress old compiler warnings. return (Layer<Dtype>*)(NULL); } template Layer<float>* GetLayer(const LayerParameter& param); template Layer<double>* GetLayer(const LayerParameter& param); } // namespace caffe #endif // CAFFE_LAYER_FACTORY_HPP_ <commit_msg>fix layer_factory.cpp bug: there should be no ifdefs<commit_after>#include <string> #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/vision_layers.hpp" namespace caffe { // A function to get a specific layer from the specification given in // LayerParameter. Ideally this would be replaced by a factory pattern, // but we will leave it this way for now. template <typename Dtype> Layer<Dtype>* GetLayer(const LayerParameter& param) { const string& name = param.name(); const LayerParameter_LayerType& type = param.type(); switch (type) { case LayerParameter_LayerType_ACCURACY: return new AccuracyLayer<Dtype>(param); case LayerParameter_LayerType_ABSVAL: return new AbsValLayer<Dtype>(param); case LayerParameter_LayerType_ARGMAX: return new ArgMaxLayer<Dtype>(param); case LayerParameter_LayerType_BNLL: return new BNLLLayer<Dtype>(param); case LayerParameter_LayerType_CONCAT: return new ConcatLayer<Dtype>(param); case LayerParameter_LayerType_CONVOLUTION: return new ConvolutionLayer<Dtype>(param); case LayerParameter_LayerType_DATA: return new DataLayer<Dtype>(param); case LayerParameter_LayerType_DROPOUT: return new DropoutLayer<Dtype>(param); case LayerParameter_LayerType_DUMMY_DATA: return new DummyDataLayer<Dtype>(param); case LayerParameter_LayerType_EUCLIDEAN_LOSS: return new EuclideanLossLayer<Dtype>(param); case LayerParameter_LayerType_ELTWISE: return new EltwiseLayer<Dtype>(param); case LayerParameter_LayerType_FLATTEN: return new FlattenLayer<Dtype>(param); case LayerParameter_LayerType_HDF5_DATA: return new HDF5DataLayer<Dtype>(param); case LayerParameter_LayerType_HDF5_OUTPUT: return new HDF5OutputLayer<Dtype>(param); case LayerParameter_LayerType_HINGE_LOSS: return new HingeLossLayer<Dtype>(param); case LayerParameter_LayerType_IMAGE_DATA: return new ImageDataLayer<Dtype>(param); case LayerParameter_LayerType_IM2COL: return new Im2colLayer<Dtype>(param); case LayerParameter_LayerType_INFOGAIN_LOSS: return new InfogainLossLayer<Dtype>(param); case LayerParameter_LayerType_INNER_PRODUCT: return new InnerProductLayer<Dtype>(param); case LayerParameter_LayerType_LRN: return new LRNLayer<Dtype>(param); case LayerParameter_LayerType_MEMORY_DATA: return new MemoryDataLayer<Dtype>(param); case LayerParameter_LayerType_MVN: return new MVNLayer<Dtype>(param); case LayerParameter_LayerType_MULTINOMIAL_LOGISTIC_LOSS: return new MultinomialLogisticLossLayer<Dtype>(param); case LayerParameter_LayerType_POOLING: return new PoolingLayer<Dtype>(param); case LayerParameter_LayerType_POWER: return new PowerLayer<Dtype>(param); case LayerParameter_LayerType_RELU: return new ReLULayer<Dtype>(param); case LayerParameter_LayerType_SIGMOID: return new SigmoidLayer<Dtype>(param); case LayerParameter_LayerType_SIGMOID_CROSS_ENTROPY_LOSS: return new SigmoidCrossEntropyLossLayer<Dtype>(param); case LayerParameter_LayerType_SLICE: return new SliceLayer<Dtype>(param); case LayerParameter_LayerType_SOFTMAX: return new SoftmaxLayer<Dtype>(param); case LayerParameter_LayerType_SOFTMAX_LOSS: return new SoftmaxWithLossLayer<Dtype>(param); case LayerParameter_LayerType_SPLIT: return new SplitLayer<Dtype>(param); case LayerParameter_LayerType_TANH: return new TanHLayer<Dtype>(param); case LayerParameter_LayerType_WINDOW_DATA: return new WindowDataLayer<Dtype>(param); case LayerParameter_LayerType_NONE: LOG(FATAL) << "Layer " << name << " has unspecified type."; default: LOG(FATAL) << "Layer " << name << " has unknown type " << type; } // just to suppress old compiler warnings. return (Layer<Dtype>*)(NULL); } template Layer<float>* GetLayer(const LayerParameter& param); template Layer<double>* GetLayer(const LayerParameter& param); } // namespace caffe <|endoftext|>
<commit_before> #include "journal/player.hpp" #include <list> #include <string> #include <thread> #include <vector> #include "benchmark/benchmark.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "journal/method.hpp" #include "journal/profiles.hpp" #include "journal/recorder.hpp" #include "ksp_plugin/interface.hpp" #include "serialization/journal.pb.h" namespace principia { namespace journal { void BM_PlayForReal(benchmark::State& state) { while (state.KeepRunning()) { Player player( R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20171112-193041)"); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } } } BENCHMARK(BM_PlayForReal); class PlayerTest : public ::testing::Test { protected: PlayerTest() : test_info_(testing::UnitTest::GetInstance()->current_test_info()), test_case_name_(test_info_->test_case_name()), test_name_(test_info_->name()), plugin_(interface::principia__NewPlugin("MJD0", "MJD0", 0)) {} template<typename Profile> bool RunIfAppropriate(serialization::Method const& method_in, serialization::Method const& method_out_return, Player& player) { return player.RunIfAppropriate<Profile>(method_in, method_out_return); } ::testing::TestInfo const* const test_info_; std::string const test_case_name_; std::string const test_name_; std::unique_ptr<ksp_plugin::Plugin> plugin_; }; TEST_F(PlayerTest, PlayTiny) { // Do the recording in a separate thread to make sure that it activates using // a different static variable than the one in the plugin dynamic library. std::thread recorder([this]() { Recorder* const r(new Recorder(test_name_ + ".journal.hex")); Recorder::Activate(r); { Method<NewPlugin> m({"MJD1", "MJD2", 3}); m.Return(plugin_.get()); } { const ksp_plugin::Plugin* plugin = plugin_.get(); Method<DeletePlugin> m({&plugin}, {&plugin}); m.Return(); } Recorder::Deactivate(); }); recorder.join(); Player player(test_name_ + ".journal.hex"); // Replay the journal. int count = 0; while (player.Play()) { ++count; } EXPECT_EQ(2, count); } TEST_F(PlayerTest, DISABLED_Benchmarks) { benchmark::RunSpecifiedBenchmarks(); } TEST_F(PlayerTest, DISABLED_Debug) { // An example of how journaling may be used for debugging. You must set // |path| and fill the |method_in| and |method_out_return| protocol buffers. std::string path = R"(\\venezia.mockingbirdnest.com\Namespaces\Public\Public Mockingbird\Principia\Crashes\1628\JOURNAL.20171122-074220)"; // NOLINT Player player(path); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } LOG(ERROR) << count << " journal entries in total"; LOG(ERROR) << "Last successful method in:\n" << player.last_method_in().DebugString(); LOG(ERROR) << "Last successful method out/return: \n" << player.last_method_out_return().DebugString(); #if 0 serialization::Method method_in; { auto* extension = method_in.MutableExtension( serialization::FutureWait::extension); auto* in = extension->mutable_in(); in->set_future(8318272064); } serialization::Method method_out_return; { auto* extension = method_out_return.MutableExtension( serialization::FutureWait::extension); } LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString(); CHECK(RunIfAppropriate<FutureWait>(method_in, method_out_return, player)); #endif } } // namespace journal } // namespace principia <commit_msg>Journal for Christoffel.<commit_after> #include "journal/player.hpp" #include <list> #include <string> #include <thread> #include <vector> #include "benchmark/benchmark.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "journal/method.hpp" #include "journal/profiles.hpp" #include "journal/recorder.hpp" #include "ksp_plugin/interface.hpp" #include "serialization/journal.pb.h" namespace principia { namespace journal { void BM_PlayForReal(benchmark::State& state) { while (state.KeepRunning()) { Player player( R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20171216-145412)"); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } } } BENCHMARK(BM_PlayForReal); class PlayerTest : public ::testing::Test { protected: PlayerTest() : test_info_(testing::UnitTest::GetInstance()->current_test_info()), test_case_name_(test_info_->test_case_name()), test_name_(test_info_->name()), plugin_(interface::principia__NewPlugin("MJD0", "MJD0", 0)) {} template<typename Profile> bool RunIfAppropriate(serialization::Method const& method_in, serialization::Method const& method_out_return, Player& player) { return player.RunIfAppropriate<Profile>(method_in, method_out_return); } ::testing::TestInfo const* const test_info_; std::string const test_case_name_; std::string const test_name_; std::unique_ptr<ksp_plugin::Plugin> plugin_; }; TEST_F(PlayerTest, PlayTiny) { // Do the recording in a separate thread to make sure that it activates using // a different static variable than the one in the plugin dynamic library. std::thread recorder([this]() { Recorder* const r(new Recorder(test_name_ + ".journal.hex")); Recorder::Activate(r); { Method<NewPlugin> m({"MJD1", "MJD2", 3}); m.Return(plugin_.get()); } { const ksp_plugin::Plugin* plugin = plugin_.get(); Method<DeletePlugin> m({&plugin}, {&plugin}); m.Return(); } Recorder::Deactivate(); }); recorder.join(); Player player(test_name_ + ".journal.hex"); // Replay the journal. int count = 0; while (player.Play()) { ++count; } EXPECT_EQ(2, count); } TEST_F(PlayerTest, DISABLED_Benchmarks) { benchmark::RunSpecifiedBenchmarks(); } TEST_F(PlayerTest, DISABLED_Debug) { // An example of how journaling may be used for debugging. You must set // |path| and fill the |method_in| and |method_out_return| protocol buffers. std::string path = R"(\\venezia.mockingbirdnest.com\Namespaces\Public\Public Mockingbird\Principia\Crashes\1628\JOURNAL.20171122-074220)"; // NOLINT Player player(path); int count = 0; while (player.Play()) { ++count; LOG_IF(ERROR, (count % 100'000) == 0) << count << " journal entries replayed"; } LOG(ERROR) << count << " journal entries in total"; LOG(ERROR) << "Last successful method in:\n" << player.last_method_in().DebugString(); LOG(ERROR) << "Last successful method out/return: \n" << player.last_method_out_return().DebugString(); #if 0 serialization::Method method_in; { auto* extension = method_in.MutableExtension( serialization::FutureWait::extension); auto* in = extension->mutable_in(); in->set_future(8318272064); } serialization::Method method_out_return; { auto* extension = method_out_return.MutableExtension( serialization::FutureWait::extension); } LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString(); CHECK(RunIfAppropriate<FutureWait>(method_in, method_out_return, player)); #endif } } // namespace journal } // namespace principia <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include <algorithm> #include <limits> #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_scenario.h" // NOINT #include "modules/perception/proto/perception_obstacle.pb.h" #include "modules/planning/proto/planning_config.pb.h" #include "cyber/common/log.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_pre_stop.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_stop.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_creep.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_intersection_cruise.h" namespace apollo { namespace planning { namespace scenario { namespace stop_sign_protected { using common::TrajectoryPoint; using common::time::Clock; using hdmap::HDMapUtil; using hdmap::StopSignInfo; using hdmap::StopSignInfoConstPtr; using StopSignLaneVehicles = std::unordered_map<std::string, std::vector<std::string>>; void StopSignUnprotectedScenario::Init() { if (init_) { return; } Scenario::Init(); if (!GetScenarioConfig()) { AERROR << "fail to get scenario specific config"; return; } const std::string stop_sign_overlap_id = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.object_id; if (stop_sign_overlap_id.empty()) { return; } context_.stop_sign_id = stop_sign_overlap_id; next_stop_sign_ = HDMapUtil::BaseMap().GetStopSignById( hdmap::MakeMapId(stop_sign_overlap_id)); if (!next_stop_sign_) { AERROR << "Could not find stop sign: " << stop_sign_overlap_id; return; } GetAssociatedLanes(*next_stop_sign_); init_ = true; } apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> StopSignUnprotectedScenario::s_stage_factory_; void StopSignUnprotectedScenario::RegisterStages() { if (!s_stage_factory_.Empty()) { s_stage_factory_.Clear(); } s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_PRE_STOP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedPreStop(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_STOP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedStop(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_CREEP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedCreep(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_INTERSECTION_CRUISE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedIntersectionCruise(config); }); } std::unique_ptr<Stage> StopSignUnprotectedScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config); if (ptr) { ptr->SetContext(&context_); } return ptr; } bool StopSignUnprotectedScenario::IsTransferable( const Scenario& current_scenario, const common::TrajectoryPoint& ego_point, const Frame& frame) const { const std::string stop_sign_overlap_id = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.object_id; if (stop_sign_overlap_id.empty()) { return false; } const auto& reference_line_info = frame.reference_line_info().front(); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double stop_sign_overlap_start_s = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.start_s; const double adc_distance_to_stop_sign = stop_sign_overlap_start_s - adc_front_edge_s; const double adc_speed = common::VehicleStateProvider::Instance()->linear_velocity(); const uint32_t time_distance = static_cast<uint32_t>(ceil( adc_distance_to_stop_sign / adc_speed)); switch (current_scenario.scenario_type()) { case ScenarioConfig::LANE_FOLLOW: case ScenarioConfig::CHANGE_LANE: case ScenarioConfig::SIDE_PASS: case ScenarioConfig::APPROACH: return (time_distance <= config_.stop_sign_unprotected_config().start_stop_sign_timer()); case ScenarioConfig::STOP_SIGN_PROTECTED: return false; case ScenarioConfig::STOP_SIGN_UNPROTECTED: return true; case ScenarioConfig::TRAFFIC_LIGHT_LEFT_TURN_PROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_LEFT_TURN_UNPROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_RIGHT_TURN_PROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_RIGHT_TURN_UNPROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_GO_THROUGH: default: break; } return false; } /* * read scenario specific configs and set in context_ for stages to read */ bool StopSignUnprotectedScenario::GetScenarioConfig() { if (!config_.has_stop_sign_unprotected_config()) { AERROR << "miss scenario specific config"; return false; } context_.scenario_config.CopyFrom(config_.stop_sign_unprotected_config()); return true; } /* * get all the lanes associated/guarded by a stop sign */ int StopSignUnprotectedScenario::GetAssociatedLanes( const StopSignInfo& stop_sign_info) { context_.associated_lanes.clear(); std::vector<StopSignInfoConstPtr> associated_stop_signs; HDMapUtil::BaseMap().GetStopSignAssociatedStopSigns(stop_sign_info.id(), &associated_stop_signs); for (const auto stop_sign : associated_stop_signs) { if (stop_sign == nullptr) { continue; } const auto& associated_lane_ids = stop_sign->OverlapLaneIds(); for (const auto& lane_id : associated_lane_ids) { const auto lane = HDMapUtil::BaseMap().GetLaneById(lane_id); if (lane == nullptr) { continue; } const auto& stop_sign_overlaps = lane->stop_signs(); for (auto stop_sign_overlap : stop_sign_overlaps) { auto over_lap_info = stop_sign_overlap->GetObjectOverlapInfo(stop_sign.get()->id()); if (over_lap_info != nullptr) { context_.associated_lanes.push_back( std::make_pair(lane, stop_sign_overlap)); ADEBUG << "stop_sign: " << stop_sign_info.id().id() << "; associated_lane: " << lane_id.id() << "; associated_stop_sign: " << stop_sign.get()->id().id(); } } } } return 0; } } // namespace stop_sign_protected } // namespace scenario } // namespace planning } // namespace apollo <commit_msg>planning: scenario a minor fix to address code review comment<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include <algorithm> #include <limits> #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_scenario.h" // NOINT #include "modules/perception/proto/perception_obstacle.pb.h" #include "modules/planning/proto/planning_config.pb.h" #include "cyber/common/log.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_pre_stop.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_stop.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_creep.h" #include "modules/planning/scenarios/stop_sign_unprotected/stop_sign_unprotected_intersection_cruise.h" namespace apollo { namespace planning { namespace scenario { namespace stop_sign_protected { using common::TrajectoryPoint; using common::time::Clock; using hdmap::HDMapUtil; using hdmap::StopSignInfo; using hdmap::StopSignInfoConstPtr; using StopSignLaneVehicles = std::unordered_map<std::string, std::vector<std::string>>; void StopSignUnprotectedScenario::Init() { if (init_) { return; } Scenario::Init(); if (!GetScenarioConfig()) { AERROR << "fail to get scenario specific config"; return; } const std::string stop_sign_overlap_id = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.object_id; if (stop_sign_overlap_id.empty()) { return; } context_.stop_sign_id = stop_sign_overlap_id; next_stop_sign_ = HDMapUtil::BaseMap().GetStopSignById( hdmap::MakeMapId(stop_sign_overlap_id)); if (!next_stop_sign_) { AERROR << "Could not find stop sign: " << stop_sign_overlap_id; return; } GetAssociatedLanes(*next_stop_sign_); init_ = true; } apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> StopSignUnprotectedScenario::s_stage_factory_; void StopSignUnprotectedScenario::RegisterStages() { if (!s_stage_factory_.Empty()) { s_stage_factory_.Clear(); } s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_PRE_STOP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedPreStop(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_STOP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedStop(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_CREEP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedCreep(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_INTERSECTION_CRUISE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedIntersectionCruise(config); }); } std::unique_ptr<Stage> StopSignUnprotectedScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config); if (ptr) { ptr->SetContext(&context_); } return ptr; } bool StopSignUnprotectedScenario::IsTransferable( const Scenario& current_scenario, const common::TrajectoryPoint& ego_point, const Frame& frame) const { const std::string stop_sign_overlap_id = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.object_id; if (stop_sign_overlap_id.empty()) { return false; } const auto& reference_line_info = frame.reference_line_info().front(); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double stop_sign_overlap_start_s = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.start_s; const double adc_distance_to_stop_sign = stop_sign_overlap_start_s - adc_front_edge_s; const double adc_speed = common::VehicleStateProvider::Instance()->linear_velocity(); const uint32_t time_distance = static_cast<uint32_t>(ceil( adc_distance_to_stop_sign / adc_speed)); switch (current_scenario.scenario_type()) { case ScenarioConfig::LANE_FOLLOW: case ScenarioConfig::CHANGE_LANE: case ScenarioConfig::SIDE_PASS: case ScenarioConfig::APPROACH: return (time_distance <= config_.stop_sign_unprotected_config().start_stop_sign_timer()); case ScenarioConfig::STOP_SIGN_PROTECTED: return false; case ScenarioConfig::STOP_SIGN_UNPROTECTED: return true; case ScenarioConfig::TRAFFIC_LIGHT_LEFT_TURN_PROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_LEFT_TURN_UNPROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_RIGHT_TURN_PROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_RIGHT_TURN_UNPROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_GO_THROUGH: default: break; } return false; } /* * read scenario specific configs and set in context_ for stages to read */ bool StopSignUnprotectedScenario::GetScenarioConfig() { if (!config_.has_stop_sign_unprotected_config()) { AERROR << "miss scenario specific config"; return false; } context_.scenario_config.CopyFrom(config_.stop_sign_unprotected_config()); return true; } /* * get all the lanes associated/guarded by a stop sign */ int StopSignUnprotectedScenario::GetAssociatedLanes( const StopSignInfo& stop_sign_info) { context_.associated_lanes.clear(); std::vector<StopSignInfoConstPtr> associated_stop_signs; HDMapUtil::BaseMap().GetStopSignAssociatedStopSigns(stop_sign_info.id(), &associated_stop_signs); for (const auto stop_sign : associated_stop_signs) { if (stop_sign == nullptr) { continue; } const auto& associated_lane_ids = stop_sign->OverlapLaneIds(); for (const auto& lane_id : associated_lane_ids) { const auto lane = HDMapUtil::BaseMap().GetLaneById(lane_id); if (lane == nullptr) { continue; } for (const auto& stop_sign_overlap : lane->stop_signs()) { auto over_lap_info = stop_sign_overlap->GetObjectOverlapInfo(stop_sign.get()->id()); if (over_lap_info != nullptr) { context_.associated_lanes.push_back( std::make_pair(lane, stop_sign_overlap)); ADEBUG << "stop_sign: " << stop_sign_info.id().id() << "; associated_lane: " << lane_id.id() << "; associated_stop_sign: " << stop_sign.get()->id().id(); } } } } return 0; } } // namespace stop_sign_protected } // namespace scenario } // namespace planning } // namespace apollo <|endoftext|>